so let's say I have the current XML file.
<?xml version="1.0" encoding="UTF-8"?>
<config>
<apps>
<app name="app1">
<url>someUrl</url>
<username>user1</username>
<password>qwerty123</password>
</app>
<app name="app2">
<url>someUrl</url>
<username>user2</username>
<password>asdasdasd</password>
</app>
<app name="app3">
<url>someUrl</url>
<username>user3</username>
<password>123456789</password>
</app>
</apps>
</config>
I've searched far and wide on how to edit the first password (qwerty123) to something else and then save the file, but I just can't find the proper solution.
Does anyone here have an idea on how can I do that?
Example solution with DOM parser:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<config>\n" +
" <apps>\n" +
" <app name=\"app1\">\n" +
" <url>someUrl</url>\n" +
" <username>user1</username>\n" +
" <password>qwerty123</password>\n" +
" </app>\n" +
" <app name=\"app2\">\n" +
" <url>someUrl</url>\n" +
" <username>user2</username>\n" +
" <password>asdasdasd</password>\n" +
" </app>\n" +
" <app name=\"app3\">\n" +
" <url>someUrl</url>\n" +
" <username>user3</username>\n" +
" <password>123456789</password>\n" +
" </app>\n" +
" </apps>\n" +
"</config>";
//here use your InputStream for example from file
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();
doc.getElementsByTagName("password").item(0).getFirstChild().setNodeValue("new content");
//here use your outputStream for example file output stream
OutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(doc);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer()
.transform(xmlSource, outputTarget);
//when you replace output stream with file output stream remove this, as this line is only for debugging
System.out.println(new String(((ByteArrayOutputStream) outputStream).toByteArray()));
Maybe you can do that:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<config>\r\n" +
" <apps>\r\n" +
" <app name=\"app1\">\r\n" +
" <url>someUrl</url>\r\n" +
" <username>user1</username>\r\n" +
" <password>qwerty123</password>\r\n" +
" </app>\r\n" +
" <app name=\"app2\">\r\n" +
" <url>someUrl</url>\r\n" +
" <username>user2</username>\r\n" +
" <password>asdasdasd</password>\r\n" +
" </app>\r\n" +
" <app name=\"app3\">\r\n" +
" <url>someUrl</url>\r\n" +
" <username>user3</username>\r\n" +
" <password>123456789</password>\r\n" +
" </app>\r\n" +
" </apps>\r\n" +
"</config>";
try {
SOAPMessage message = MessageFactory.newInstance().createMessage(null,new ByteArrayInputStream(xml.getBytes()));
System.out.println(message.getSOAPPart().getElementsByTagName("password").item(0).getTextContent());
message.getSOAPPart().getElementsByTagName("password").item(0).setTextContent("NewPassword");
System.out.println(message.getSOAPPart().getElementsByTagName("password").item(0).getTextContent());
StringWriter messageString = new StringWriter();
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(message.getSOAPPart()),
new StreamResult(messageString));
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.xml", true), "utf-8"));
writer.write(messageString.toString());
writer.newLine();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Or you can just use the Marshaller and Unmarshaller, if you want I'll explain how to do it this way.
Related
I am writing a bot to auto purchase items on a website (zalando).
Everything goes well from login to adding items to shopping cart but at the very end it doesn't work anyomore. It sends this error:
{ "edge_error": "halt", "ref_id": "18.57c51102.1663765843.299fc0e", "wait": 60, "feedback": { "email": true, "url": "", "recaptcha": { "enabled": false, "type": 0, "sitekey": "" } }}
I think it has something to do with their protection or just me missing a header or cookie or a delay... I honestly have no clue anymore
This is the code I use in the end (to checkout and generate a paypal link (post response)):
public void makePostJsonRequest(WebDriver driver, String eTag, String checkoutID)
{
retrieveCookiesMap(driver);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("https://www.zalando.be/api/checkout/buy-now");
postRequest.setHeader("authority", "www.zalando.be");
postRequest.setHeader("accept", "application/json");
postRequest.setHeader("accept-language", "en-US,en;q=0.9");
postRequest.setHeader("content-type", "application/json");
postRequest.setHeader("cookie", "language-preference=nl;" +
" Zalando-Client-Id=" + cookiesMap.get("Zalando-Client-Id") + ";" +
" ncx=f;" +
" _gcl_au=" + cookiesMap.get("_gcl_au") + ";" +
" sqt_cap=" + cookiesMap.get("sqt_cap") + ";" +
" _ga=" + cookiesMap.get("_ga") + ";" +
" _gid=" + cookiesMap.get("_gid") + ";" +
" bm_sz=" + cookiesMap.get("bm_sz") + ";" +
" ak_bms=" + cookiesMap.get("ak_bms") + ";" +
" _gat_zalga=1;" +
" mpulseinject=false;" +
" frsx=" + cookiesMap.get("frsx") + ";" +
" zsa=" + cookiesMap.get("zsa") + ";" +
" zsr=" + cookiesMap.get("zsr") + ";" +
" zsi=" + cookiesMap.get("zsi") + ";" +
" bm_sv=" + cookiesMap.get("bm_sv") + ";" +
" _abck=" + cookiesMap.get("_abck") + ";");
postRequest.setHeader("origin", "https://www.zalando.be");
postRequest.setHeader("referer", "https://www.zalando.be/checkout/confirm");
postRequest.setHeader("sec-ch-ua", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"");
postRequest.setHeader("sec-ch-ua-mobile", "?0");
postRequest.setHeader("sec-ch-ua-platform", "\"Linux\"");
postRequest.setHeader("sec-fetch-dest", "empty");
postRequest.setHeader("sec-fetch-mode", "cors");
postRequest.setHeader("sec-fetch-site", "same-origin");
postRequest.setHeader("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36");
postRequest.setHeader("x-xsrf-token", cookiesMap.get("frsx"));
postRequest.setHeader("x-zalando-checkout-app", "web");
postRequest.setHeader("x-zalando-footer-mode", "desktop");
postRequest.setHeader("x-zalando-header-mode", "desktop");
eTag = StringUtils.chop(eTag);
eTag += "\\";
String jsonString = "{\"checkoutId\":\"" + checkoutID + "\"," +
"\"eTag\":" + "\"\\" + eTag + "\"" + "\"" + "}";
System.out.println(jsonString);
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(builder.toString());
System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}
This means that Akamai (the provider that zalando uses for bot protection), has detected and stopped your request because it detected you as a bot. To avoid this "stop" you MUST send a valid _abck cookie, generated by passing sensor data to the zalando akamai endpoint( you can find using chrome devtools and analyzing the requests )
i am creating a .jar file to plug into a java connector on bpm.
the idea is for the .jar to generate a pdf from html which is using images from a Image folder and send as an email attachment.
the PDF sends ok with the html and the images when ran from eclipse, soon as i export the .jar and try to use it outside of eclipse it doesnt show the images
System.out.println("I am about to get resource image001");
BufferedImage imageone = ImageIO.read(new FileInputStream("Images/image001.jpg"));
File outputfile = new File("Images/image001.jpg");
ImageIO.write(imageone, "jpg", outputfile);
System.out.println("image 1 " + outputfile.toURL());
String one = "Images/image001.jpg";
System.out.println("got image 1");
System.out.println("I am about to get rousrce image002");
//BufferedImage bufferedImage2 = ImageIO.read(jamesNew.class.getResource("/Images/image002.gif"));
BufferedImage imagwtwo = ImageIO.read(new FileInputStream("Images/image002.gif"));
File outputfile1 = new File("image002.gif");
ImageIO.write(imagwtwo, "gif", outputfile1);
System.out.println("image 2 " + outputfile1.toURL());
String two = "Images/image002.gif";
System.out.println("got image 2");
System.out.println("I am about to get rousrce image003");
//BufferedImage bufferedImage3 = ImageIO.read(jamesNew.class.getResource("/Images/image003.gif"));
BufferedImage imagwthree = ImageIO.read(new FileInputStream("Images/image003.gif"));
File outputfile2 = new File("image003.gif");
ImageIO.write(imagwthree, "gif", outputfile2);
System.out.println("image 3 " + outputfile2.toURL());
String three = "Images/image003.gif";
System.out.println("got image 3");
System.out.println("I am about to get rousrce image004");
//BufferedImage bufferedImage4 = ImageIO.read(jamesNew.class.getResource("/Images/image006.gif"));
BufferedImage imagefour = ImageIO.read(new FileInputStream("Images/image006.gif"));
File outputfile3 = new File("image006.gif");
ImageIO.write(imagefour, "gif", outputfile3);
System.out.println("image 4 " + outputfile3.toURL());
String four = "Images/image006.gif";
System.out.println("got image 4");
System.out.println("I am about to get rousrce image005");
//BufferedImage bufferedImage5 = ImageIO.read(jamesNew.class.getResource("/Images/logo1.png"));
BufferedImage imagwfive = ImageIO.read(new FileInputStream("Images/logo1.png"));
File outputfile4 = new File("logo1.png");
ImageIO.write(imagwfive, "png", outputfile4);
System.out.println("image 5 " + outputfile4.toURL());
String five = "Images/logo1.png";
System.out.println("got image 5");
System.out.println("CLASS PATHS SET..........");
String named = null;
String total = null;
String completehtml1 = null;
String style = "<style type=\""+"text/css" + "\" >" + ".centerImage { text-align:center; display:block; } </style>";
String feed = "<html><body>";
System.out.println("STRINGS SET..........");
completehtml = feed + style + "<div style=\"text-align:center;\">" + "<img src=\"" + outputfile + "\" />" + "<p></p>" + "<img src=\"" + outputfile1 + "\" + style=\"width:400px;height:150px;" + "\" />" + "<p><h3 style=\"text-align:center;"+"\">" + "THIS IS TO CERTIFY" + "</h3></p>" + "<p><h3 style=\"text-align:center;"+"\">"+ user + "</h3></p>" + "<p>" + "</p>" + "<p>" + "<img src=\"" + outputfile2 + "\" />" + "</p>" + "<p>" + "</p>" + "<p><h3 style=\"text-align:center;"+"\">"+ dateTXT + " " + date + "</h3></p>" + "<p><h3 style=\"text-align:center;"+"\">" + "SIGNED" + "</h3></p>" + "<p>" + "</p>" + "<p>" + "<img src=\"" + outputfile3 + "\" + style=\"width:150px;height:150px;"+"\" />" + "</p>" + "<p>" + "</p>" + "<p>" + "<img src=\"" + outputfile4 + "\" />" + "</p>" + "<p></p>" + "<p></p>" + "</div>" + htmlend;
total = completehtml + named + completehtml1 + htmlend;
System.out.println("complete HTML" + completehtml);
System.out.println("STARTED!!!");
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
ObjectOutputStream file = new ObjectOutputStream(baos1);
Document document = new Document();
PdfWriter pdfwriter = PdfWriter.getInstance(document, baos1);
document.open();
System.out.println("DOCUMENT OPEN");
document.addAuthor("James Parish");
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
worker.parseXHtml(pdfwriter, document, new StringReader(completehtml));
// worker.parseXHtml(pdfwriter, document, new FileInputStream("Images/image001.jpg"));
System.out.println("NEW PARAGRAPH");
System.out.println("PARAGRAPH ADDED");
document.close();
System.out.println("CLOSED DOCUMENT!");
file.close();
System.out.println("CLOSED FILE");
System.out.println("pdf is" + file);
System.out.println("ENDED!!!");
Email from = new Email(msgfrom);
Email to = new Email(msgto);
Content content = new Content("text/plain", msgbody);
Mail mail = new Mail(from, subject, to, content);
ByteArrayOutputStream fileData = null;
byte[] testing = baos1.toByteArray();
try {
fileData = baos1;
Attachments attachments3 = new Attachments();
Base64 x = new Base64();
String imageDataString = Base64.encodeBase64String(testing);
attachments3.setContent(imageDataString);
attachments3.setType("application/pdf");//"application/pdf"
attachments3.setFilename("Certificate.pdf");
attachments3.setDisposition("attachment");
attachments3.setContentId("Banner");
mail.addAttachments(attachments3);
System.out.println("BASE64 ENCODED ATTACHMENT " + imageDataString);
I have written the below code to parse a string in java but its not printing out a blank message.
How can I get specific parts from a SOAP message and get their values?
I want to get the error and the message in the request.
String xml = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<S:Body>"
+ "<ns2:processResponse xmlns:ns2=\"http://ws.xxxxx.com/\">"
+ "<response><direction>response</direction>"
+ "<reference>09FG10021008111306320</reference>"
+ "<amount>0.0</amount>"
+ "<totalFailed>0</totalFailed>"
+ "<totalSuccess>0</totalSuccess>"
+ "<error>1</error>"
+ "<message>Invalid</message>"
+ "<otherReference>6360e28990c743a3b3234</otherReference>"
+ "<action>FT</action>"
+ "<openingBalance>0.0</openingBalance>"
+ "<closingBalance>0.0</closingBalance>"
+ "</response>"
+ "</ns2:processResponse>"
+ "</S:Body>"
+ "</S:Envelope>\n";
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xml);
Document doc = null;
Element root = null;
Element meta = null;
Element error = null;
Element status_message = null;
String status_code= "";
String message = "";
try
{
doc = builder.build(in);
root = doc.getRootElement();
meta = root.getChild("processResponse").getChild("response");
error = meta.getChild("error");
status_message = meta.getChild("message");
status_code = error.getText();
message = status_message.getText();
}catch (Exception e)
{
// do what you want
}
System.out.println("status_code: " + status_code + "\nmessage: " + message);
The response being generated is
status_code:
message:
You are making some mistakes in your code while picking up elements in xml. You can use this code and check,
public static void main(String[] args) {
String xml = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<S:Body>"
+ "<ns2:processResponse xmlns:ns2=\"http://ws.xxxxx.com/\">"
+ "<response><direction>response</direction>" + "<reference>09FG10021008111306320</reference>"
+ "<amount>0.0</amount>" + "<totalFailed>0</totalFailed>" + "<totalSuccess>0</totalSuccess>"
+ "<error>1</error>" + "<message>Invalid</message>"
+ "<otherReference>6360e28990c743a3b3234</otherReference>" + "<action>FT</action>"
+ "<openingBalance>0.0</openingBalance>" + "<closingBalance>0.0</closingBalance>" + "</response>"
+ "</ns2:processResponse>" + "</S:Body>" + "</S:Envelope>\n";
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xml);
Document doc = null;
Element root = null;
Element error = null;
Element status_message = null;
String status_code = "";
String message = "";
try {
doc = builder.build(in);
root = doc.getRootElement();
Element body = root.getChild("Body", Namespace.getNamespace("S", "http://schemas.xmlsoap.org/soap/envelope/"));
Element processResponse = body.getChild("processResponse", Namespace.getNamespace("ns2", "http://ws.xxxxx.com/"));
Element response = processResponse.getChild("response");
error = response.getChild("error");
status_message = response.getChild("message");
status_code = error.getText();
message = status_message.getText();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("status_code: " + status_code + "\nmessage: " + message);
}
For me this is giving following output,
status_code: 1
message: Invalid
I want to write to a file in Android, but it results in the following error:
java.lang.IllegalArgumentException: File C:/Users/Senior/Downloads/Gps_location-master/DenverCrimeDataVisualization/app/src/main/res/raw/neighborhood_id_location.json contains a path separator
private void writeToFile() {
try {
OutputStreamWriter outputStreamWriter =
new OutputStreamWriter(new FileOutputStream(new File(getExternalFilesDir(null), "neighborhood_id_location.json")));
outputStreamWriter.write("[");
for (int i = 0; i < geo_lat.length; i++) {
// Maybe:
outputStreamWriter.write("{\"lat\" : " + geo_lat[0] + ", \"lng\" : " + geo_lon[0] + "}");
// Or:
}
outputStreamWriter.write("]");
outputStreamWriter.close();
outputStreamWriter.write("["+"{"+"Latitude" + geo_lat[0] + "," +"Longtitude"+ geo_lon[0] +"}" +"]");
outputStreamWriter.close();
}
I am trying to parse a XML string into org.w3c.dom.Document object.
I have looked at solutions provided here, here and a few other blogs that give a variation of the same solution. But the Document object's #Document variable is always null and nothing gets parsed.
Here is the XML file
XMLMappingValidator v = new XMLMappingValidator("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<mapping>\n" +
"<container>\n" +
"<source-container>c:\\stem.csv</source-container>\n" +
"<source-type>CSV_FILE</source-type>\n" +
"<target-container>db</target-container>\n" +
"<target-type>MySQL_TABLE</target-type>\n" +
"</container>\n" +
"<entity>\n" +
"<source-entity>stem</source-entity>\n" +
"<target-entity>tbl_stem</target-entity>\n" +
"</entity>\n" +
"<attributes>\n" +
"<attribute>\n" +
"<datatype>SMALLINT</datatype>\n" +
"<source-attribute>id</source-attribute>\n" +
"<target-attribute>id</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>VARCHAR</datatype>\n" +
"<source-attribute>name</source-attribute>\n" +
"<target-attribute>name</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>TEXT</datatype>\n" +
"<source-attribute>body</source-attribute>\n" +
"<target-attribute>body</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>DATETIME</datatype>\n" +
"<source-attribute>date</source-attribute>\n" +
"<target-attribute>date</target-attribute>\n" +
"</attribute>\n" +
"<attribute>\n" +
"<datatype>VARCHAR</datatype>\n" +
"<source-attribute>info</source-attribute>\n" +
"<target-attribute>info</target-attribute>\n" +
"</attribute>\n" +
"</attributes>\n" +
"</mapping>");
The constructor XMLMappingValidator object's code is as follows
public class XMLMappingValidator {
private Document xml;
public XMLMappingValidator (String xmlString) throws
IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.xml =
builder.parse(new InputSource(new StringReader(xmlString)));
}
public Document getXML() {
return xml;
}
}
When I call v.getXML().toString() I get [#document: null]
Clearly, the parse is failing. But I don't understand why.
Any suggestions/help is greatly appreciated.