0

I have the following string which is generated by an external program (OpenVAS) and returned to my program successfully as a string.

<create_target_response id="b4c8de55-94d8-4e08-b20e-955f97a714f1" status_text="OK, resource created" status="201"></create_target_response>

I am trying to split the string to give me the "b4c8d....14f1" without the inverted commas. I have tried all sorts of escape methods and keep getting the else method "String does not contain a Target ID". I have tried removing the IF statement checking for the string, but continue to have the same issue. The goal is to get my id string into jTextField6. String Lob contains the full string as above.

     if (Lob.contains("id=\"")){
      // put the split here
           String[] parts = Lob.split("id=\"");
           String cut1 = parts[1];

           String[] part2 = cut1.split("\"");
           String TaskFinal = part2[0];

           jTextField6.setText(TaskFinal);

      }
       else {
           throw new IllegalArgumentException("String does not contain a Target ID");
       }

  } catch (IOException e) {
     e.printStackTrace();
  }

It seems I only need to escape the " and not the = (Java kicks up an error if i do)

Thanks in advance

EDIT: Code as it stands now using jSoup lib - The 'id' string won't display. Any ideas? Thanks

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
          String TargIP = jTextField1.getText(); // Get IP Address
          String TargName = jTextField5.getText(); // Get Target Name
          String Vag = "8d32ad99-ac84-4fdc-b196-2b379f861def";
          String Lob = "";

  final String dosCommand = "cmd /c omp -u admin -w admin --xml=\"<create_target><name>" + TargName + "</name><hosts>" + TargIP + "</hosts></create_target>\"";
  3</comment><config id='daba56c8-73ec-11df-a475-002264764cea'/><target id='" + Vag + "'/></create_task>\"";
  final String location = "C:\\";
  try {
     final Process process = Runtime.getRuntime().exec(
        dosCommand + " " + location);
     final InputStream in = process.getInputStream();
     int ch;
     while((ch = in.read()) != -1) {
        System.out.print((char)ch);
       Lob = String.valueOf((char)ch);
       jTextArea2.append(Lob);


     }

  } catch (IOException e) {
     e.printStackTrace();
  }
           String id = Jsoup.parse(Lob).getAllElements().attr("id");
     System.out.println(id); // This doesn't output? 
}
Remotejon
  • 35
  • 9

5 Answers5

1

This will get you your job id more easily:

int idStart = Lob.indexOf("id=")+("id=\"").length();
System.out.println(Lob.substring(idStart,Lob.indexOf("\"",idStart)));
SANN3
  • 9,459
  • 6
  • 61
  • 97
  • Might want to mention that 4 happens to be the length of `id="` (or better yet, make that string a variable and use it's `.length()`) -- less magic numbers to remember when coming back to the code in a week. – Philipp Reichart Feb 21 '14 at 10:59
1

Split on the basis of ". You can get all the key values.

String str = "<create_target_response id=\"b4c8de55-94d8-4e08-b20e-955f97a714f1\" status_text=\"OK, resource created\" status=\"201\"></create_target_response>";
String[] tokens = str.split("\\\"");
System.out.println(tokens[1]);
System.out.println(tokens[5]);

output:

b4c8de55-94d8-4e08-b20e-955f97a714f1
201
Rahul
  • 3,479
  • 3
  • 16
  • 28
  • I don't understand why you have changed the 'str' string. OpenVAS does not include these backspaces when sending the XML to my program? – Remotejon Feb 22 '14 at 12:00
  • The double quote `"` is used in Java to signify the begin and end of a string value. If you want a literal `"` in your string, it has to be escaped as `\"`, see the section on ["Escape Sequences" in The Java Tutorial](http://docs.oracle.com/javase/tutorial/java/data/characters.html) for more. – Philipp Reichart Feb 23 '14 at 15:54
0

This is a lot simpler than you're making it, to my mind. First, split on space, then check if an = is present. If it is, split on the =, and finally remove the " from the second token.

The tricky bit is the spaces inside of the "". This will require some regular expressions, which you can work out from this question.

Example

String input; // Assume this contains the whole string.
String pattern; // Have fun working out the regex.

String[] values = input.split(pattern);

for(String value : values)
{
    if(value.contains("=")) {
        String[] pair = value.split("=");
        String key = pair[0];
        String value = pair[1].replaceAll("\"");

        // Do something with the values.
    }
}

Advantage of my approach

Is that provided the input follows the format of key="value" key="value", you can parse anything that comes through, rather than hard coding the name of the attributes.

And if this is XML..

Then use an XML parser. There is a good (awesome) answer that explains why you shouldn't be using Stringmanipulation to parse XML/HTML. Here is the answer.

Community
  • 1
  • 1
christopher
  • 26,815
  • 5
  • 55
  • 89
0

You can use a regex to extract what is needed; what is more, it looks like the value of id is a UUID. Therefore:

private static final Pattern PATTERN
    = Pattern.compile("\\bid=\"([^\"]+)\"");

// In code...
public String getId(final String input)
{
    final Matcher m = PATTERN.matcher(input);
    if (!m.find())
        throw new IllegalArgumentException("String does not contain a Target ID");
    final String uuid = m.group(1);
    try {
        UUID.fromString(uuid);

    } catch (IllegalArgumentException ignored) {
        throw new IllegalArgumentException("String does not contain a Target ID");
    }

    return uuid;
}
fge
  • 119,121
  • 33
  • 254
  • 329
0

Everyone's telling you to use an XML parser (and they're right) but noone's showing you how.

Here goes:

String lob = ...

Using Jsoup from http://jsoup.org, actually an HTML parser but also handles XML neatly:

String id = Jsoup.parse(lob).getAllElements().attr("id");
// b4c8de55-94d8-4e08-b20e-955f97a714f1

With built-in Java XML APIs, less concise but no addtional libraries:

Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
    .parse(new InputSource(new StringReader(lob)));
String id = dom.getDocumentElement().getAttribute("id");
// b4c8de55-94d8-4e08-b20e-955f97a714f1
Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65