Resulting certificate on Signature has "&#13" how to remove them? - java

I'm using xades4j to sing an xml, everything works fine.
But on the resulting XML the X509Certificate looks something like this:
<ds:X509Certificate> MIIDUjCCAjqgAwIBAgIIYFxFM0GPYwowDQYJKoZIhvcNAQELBQAwKTEMMAoGA1UEAwwDRkVMMQww
CgYDVQQKDANTQVQxCzAJBgNVBAYTAkdUMB4XDTE4MTIxMDE1MTQyOFoXDTIwMTIwOTE1MTQyOFow
KDERMA8GA1UEAwwIODI1NzYyNTQxEzARBgNVBAoMCnNhdC5nb2IuZ3QwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQC6QTYY7yGtmikBaV6pNVee6WzNBToIr3jlFikbvZI4JD+4p0LJqten
</ds:X509Certificate>
How can I remove the "& #13;" from it?
The method that executes the signature is this one:
#Override
public DOMSource generarFirmaDigitalParaXML(Document xml, KeyingDataProvider keyingDataProvider, String nombreArchivoXmlOriginal) {
final Element rootElement = xml.getDocumentElement();
Element elementoAFirmar = null;
NodeList nodeList = xml.getElementsByTagName("dte:DatosEmision");
DOMSource source = null;
int lenght = nodeList.getLength();
for (int i = 0; i < lenght; i++) {
Node nNode = nodeList.item(i);
elementoAFirmar = (Element) nNode;
}
XadesBesSigningProfile profile = new XadesBesSigningProfile(keyingDataProvider);
try {
XadesSigner signer = profile.newSigner();
String atributoUtilizado = seleccionarAttributoComoId(elementoAFirmar, "ID");
if (atributoUtilizado != null) {
DataObjectDesc obj = new DataObjectReference("#" + elementoAFirmar.getAttribute(atributoUtilizado))
.withTransform(new EnvelopedSignatureTransform());
SignedDataObjects dataObjs = new SignedDataObjects().withSignedDataObject(obj);
signer.sign(dataObjs, rootElement);
xml.setXmlStandalone(true);
source = new DOMSource(xml);
} else {
throw new Exception("Atributo no encontrado en el XML");
}
} catch (Exception e) {
bitacora.log(Level.SEVERE, LOGGER, bitacora.obtenerStackTrace(e), true);
}
return source;
}

It took me a few hours to resolve it, but I've finally found the solution here: https://bugs.openjdk.java.net/browse/JDK-8264194
static {
System.setProperty("com.sun.org.apache.xml.internal.security.ignoreLineBreaks", "true");
}

Related

Reorganize XML using Java DOM - Hierarchy_Request_Error

I have a xml with following scheme structure
<test>
<testcase classname="TestsQuarantine.CreateUsers" name="Administrator"/>
<testcase classname="TestsQuarantine.Login" name="documentMailQuarantine"/>
<testcase classname="TestsClerk.CreateUsers" name="John"/>
</test>
I need to reorganize it to
<test>
<testsuite name="Quarantine">
<testcase classname="TestsQuarantine.CreateUsers" name="Administrator"/>
<testcase classname="TestsQuarantine.Login" name="documentMailQuarantine"/>
</testsuite>
<testsuite name="Clerk">
<testcase classname="TestsClerk.CreateUsers" name="John"/>
</testsuite>
</test>
At this point I'm reading the file to NodeList, iterate through it, create new root and try to switch it with original to achieve the structure that I need but I get following error
HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it
is not permitted.
happening in line that performs switch of roots and I'm out of ideas why it is so.. Here is my code:
File file = new File(fullPath);
List<Element> clerk = null,
quara = null,
misc = null;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("test");
Element root = doc.getDocumentElement(),
newRoot = doc.createElement("test");
clerk = new ArrayList<Element>();
quara = new ArrayList<Element>();
misc = new ArrayList<Element>();
for(int i=0; i < nodes.getLength(); i++) {
Element node = (Element) nodes.item(i);
if(node.getAttribute("classname").contains("Clerk")) {
clerk.add(node);
} else if(node.getAttribute("classname").contains("Quarantine")) {
quara.add(node);
} else {
misc.add(node);
}
}
if(clerk.isEmpty() == false) {
Element clerkSuite = doc.createElement("testsuite");
clerkSuite.setAttribute("name", "Clerk");
for(Element el : clerk) {
clerkSuite.appendChild(el);
}
newRoot.appendChild(clerkSuite);
}
if(quara.isEmpty() == false) {
Element quaraSuite = doc.createElement("testsuite");
quaraSuite.setAttribute("name", "Quarantine");
for(Element el : quara) {
quaraSuite.appendChild(el);
}
newRoot.appendChild(quaraSuite);
}
if(misc.isEmpty() == false) {
Element miscSuite = doc.createElement("testsuite");
miscSuite.setAttribute("name", "Miscellaneous");
for(Element el : misc) {
miscSuite.appendChild(el);
}
newRoot.appendChild(miscSuite);
}
root.getParentNode().replaceChild(newRoot, root);
DOMSource original = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult overritten = new StreamResult(fullPath);
transformer.transform(original, overritten);
} catch (Exception e) {
e.printStackTrace();
}
What do I have to change to make it work?
Your iteration over testcase nodes is incorrect. I changed that fragment to below one and Your code is working:
Node testNode = doc.getDocumentElement();
NodeList testCases= testNode.getChildNodes();
for(int i=0; i < testCases.getLength(); i++) {
Node n = testCases.item(i);
if (!(n instanceof Text)) {
Element testCase = (Element) n;
if (testCase.getAttribute("classname").contains("Clerk")) {
clerk.add(testCase);
} else if (testCase.getAttribute("classname").contains("Quarantine")) {
quara.add(testCase);
} else {
misc.add(testCase);
}
}
}

Java , XML User Verification Failure

I've been trying to make this work for longer than I'd like to say now and just can't figure out why it won't recognize the password,I get a null pointer exception on this line if (userPassword.getTextContent().equals(password)
Here is the method
public class XML {
public static boolean login(String email, String password) {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("data.xml");
Element root = document.getDocumentElement();
NodeList nList = root.getChildNodes();
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element users = (Element) nNode;
if (users.getNodeName().compareTo("users") == 0) {
NodeList userList = users.getChildNodes();
for (int j = 0; j < userList.getLength(); j++) {
Node userNode = userList.item(j);
NodeList AttributeList = userNode.getChildNodes();
Node userPassword = AttributeList.item(1);
Node userEmail = AttributeList.item(0);
if (userPassword.getTextContent().equals(password)
&& userEmail.getTextContent().equals(email)) {
return true;
}
}
}
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
}
return false;
}
Attribute nodes don't have text content but a value. You should use the following construct to retrieve it :
Node userNode = userList.item(j);
String attributeValue = userNode.getAttribute("attributeName")
Alternatively since you already have the attributes Nodes, you could cast them to org.w3c.dom.Attr and use their .getValue() method.

parse image in dom parser using jsoup in android

i am trying to get the rss feed of this website:
http://www.phonearena.com/feed
here is my domparser activity:
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName("item");
NodeList itemChildren = null;
Node currentItem = null;
Node currentChild = null;
int length = nl.getLength();
for (int i = 0; i < length; i++) {
currentItem = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentItem.getChildNodes();
int clength = nchild.getLength();
for (int j = 0; j < clength; j++) {
currentChild = nchild.item(j);
String theString = null;
String nodeName = currentChild.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
_feed.addItem(_item);
}
} catch (Exception e) {
}
return _feed;
}
}
everything is working fine except the image which i am trying to get through jsoup.
can anybody tell what i am doing wrong or missing?
The variable theString needs to be unescaped before passing it to Jsoup.
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Unescape then Parse the html description to get the image url
Element imgEle = Jsoup.parse( //
Parser.unescapeEntities( //
Parser.xmlParser().parseInput(theString, "").outerHtml(), //
true //
)) //
.select("img").first();
if (imgEle != null) {
_item.setImage(imgEle.attr("src"));
}
}

How can get node child tag from xml with dom (Java)

Took a long time searching and watching videos.
I'm trying to access the course subjects ID
This is my xml code
<list>
<Asignatura>
<id>1</id>
<nombre>Programación</nombre>
<curso>
<id>1</id>
<nombre>1º DAM</nombre>
<listaAsignaturas>
<Asignatura reference="../../.."/>
<Asignatura>
<id>2</id>
<nombre>Bases de datos</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>3</id>
<nombre>Formación y orientación laboral</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>4</id>
<nombre>Entornos de desarrollo</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
</listaAsignaturas>
</curso>
<listaAlumnos/>
</Asignatura>
</list>
And here my code in java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("./datos/Asignaturas.xml");
document.getDocumentElement().normalize();
NodeList Asignatura = document.getElementsByTagName("Asignatura");
for (int i = 0; i < Asignatura.getLength(); i++) {
Node c = Asignatura.item(i);
if (c.getNodeType() == Node.ELEMENT_NODE) {
Element elemento = (Element) c;
int id = Integer.parseInt(getValorHijo("id", elemento));
String nombre = getValorHijo("nombre", elemento);
//int idCurso = Integer.parseInt(getValorHijo("curso", elemento));
curso = new Curso();
curso.setId(idCurso);
curso = (Curso) FileXMLDAOFactory.getInstance().getCursoDAO().buscar(curso);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I have to say it works, pick up the ID and name of the subject.
But I can not pick up the ID or name of the course subject that is within.
Im not have idea how can get it :(
I tried a slighty different approach with the same xml input file with the following code.
public static void main(String[] args) {
List<Assignatura> assignaturas = new ArrayList<Assignatura>();
List<Curso> cursos = new ArrayList<Curso>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("datos.xml");
DocumentTraversal traversal = (DocumentTraversal) document;
NodeIterator iterator = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new ListAsignaturasFilter(), true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
Element el = (Element) n;
NodeList assignments = el.getElementsByTagName("Asignatura");
for(int i=0; i<assignments.getLength(); i++){
Node currentNode = assignments.item(i);
NodeList childs = currentNode.getChildNodes();
String id = getValorHijo(childs, "id");
String nombre = getValorHijo(childs, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
assignaturas.add(new Assignatura(id, nombre));
}
}
NodeIterator itCurso = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new CursoFilter(), true);
for (Node n = itCurso.nextNode(); n != null; n = itCurso.nextNode()) {
Element el = (Element) n;
NodeList cursos = el.getChildNodes();
String id = getValorHijo(cursos, "id");
String nombre = getValorHijo(cursos, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
cursos.add(new Curso(id, nombre));
}
for(Assignatura assignatura : assignaturas){
System.out.println(assignatura);
}
for(Curso curso : cursos){
System.out.println(curso);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private static String getValorHijo(NodeList childs, String data){
String search="";
if(childs.getLength()>0)
for(int j=0; j<childs.getLength(); j++){
if(childs.item(j).getNodeName().equals(data)){
return childs.item(j).getTextContent();
}
}
return search;
}
private static final class ListAsignaturasFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("listaAsignaturas")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
private static final class CursoFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("curso")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
As you can see I created two lists to memorize "Assignatura" an "Curso" object which are simple POJO with two attributes id and nombre. At the end of the main method I display the content of these lists and I've got the id and nombre information of element "Curso" besides all "Asignatura" elements. Hope this code help you !
Just for the record. The use of DOM was compulsory ? Because, it would have been easier to use JAXB.

How do I read in a file path from an XML file

I am trying to read in a file path from an XML file in java, but I am getting a file not found exception. I am not sure how to fix this. Any help would be appreciated.
This is the XML file:
<adapters>
<adapter>
<class>adapters.CSVFileAdapter</class>
<properties>
<property name="filename">C:\test.csv</property>
</properties>
</adapter>
<adapter>
<class>adapters.SNMPAdapter</class>
<properties>
<property name="target">10.100.85.135</property>
<property name="port">134</property>
</properties>
</adapter>
</adapters>
This is my java code:
public class XMLConfigurationReader {
public static List<String> load()
{
List<String> adpList = new ArrayList<String>();
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("C:/myProject/adapters.xml"));
doc.normalize();
NodeList rootNodes = doc.getElementsByTagName("adapters");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
rootNodes = rootElement.getElementsByTagName("class");
for(int k=0; k<rootNodes.getLength(); k++){
Node theAdapter = rootNodes.item(k);
Element adpElement = (Element) theAdapter;
adpList.add(adpElement.getTextContent());
}
rootNodes = doc.getElementsByTagName("properties");
for (int i = 0; i < rootNodes.getLength(); i++) { // loop for properties
Node nodeData = rootNodes.item(i);
Element elementColumnDetails = (Element) nodeData;
NodeList nodeListRow = elementColumnDetails.getElementsByTagName("property");
for (int j = 0; j < nodeListRow.getLength(); j++) { // loop for property
Node nodeRow = nodeListRow.item(j);
Element elementRow = (Element) nodeRow;
if(elementRow.getAttribute("property") != null){
String property = elementRow.getTextContent().trim();
}
}
}
}catch(ParserConfigurationException e){
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return adpList;
}
}
Problem with your code is in this line
adaptersList.item(0).getChildNodes().item(0).getNodeValue();
it should be replaced with
adaptersList.item(0).getTextContent();
in order to give you that pathname.
Firstly to read a file:
public class FileRead {
static String string = File.separator;
public static void main(String[] args) {
File file = new File("C:"+string+"myProject"+string+"adapters.xml");
System.out.println(file.getName());
}
}
Then try to test below code will help you to get file Name from xml:
NodeList nodeListData = xmlTableName.getElementsByTagName("properties");
for (int k = 0; k < nodeListData.getLength(); k++) { // loop for properties
Node nodeData = nodeListData.item(k);
Element elementColumnDetails = (Element) nodeData;
NodeList nodeListRow = elementColumnDetails.getElementsByTagName("property);
for (int l = 0; l < nodeListRow.getLength(); l++) { // loop for property
Node nodeRow = nodeListRow.item(l);
Element elementRow = (Element) nodeRow;
if(elementRow.getAttribute("filename")){
filePath = elementRow.getTextContent().trim();
}
}
}

Categories