How to search for a duplicate string and search and replace the string in java?

1. Open the outputX.xml file
2. Search for any duplicate "names" in userpath=
    Example- sam
3. Find the first occurance of that duplicate name
   Example - String sNewPath = userpath="Users\grouping-users\gr-ost\sam"
4. Search and Replace the all the other userpath strings with sPath
   Example - userpath="Users\grouping-users\gr-ose-browseit\sam"  will be userpath="Users\grouping-users\gr-ost\sam"

This is the xml file "outputX.xml"
<OrganiseUsers> <sync />
<move source="Users\LDAP Users\alex" target="Users\grouping-users\gr-ost" />
<move source="Users\LDAP Users\sam" target="Users\grouping-users\gr-ost" />
<move source="Users\LDAP Users\matt" target="Users\grouping-users\gr-ost" />
<move source="Users\LDAP Users\sara" target="Users\grouping-users\gr-ost" />
<move source="Users\LDAP Users\nicole" target="Users\grouping-users\gr-ost" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\matt" role="Editor" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\nicole" role="Editor" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\alex" role="Reviewer" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\sam" role="Reviewer" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\sara" role="Administrator" />
<move source="Users\LDAP Users\pasquini" target="Users\grouping-users\gr-ose-browseit" />
<move source="Users\LDAP Users\sam" target="Users\grouping-users\gr-ose-browseit" />
<changerole projects="mon_visdev_test" userpath="Users\grouping-users\gr-ose-browseit\sam" role="Administrator" />
<changerole projects="mon_visdev_test" userpath="Users\grouping-users\gr-ose-browseit\ricky" role="Administrator" />
</OrganiseUsers>


Please provide the java code to do the above search and replace

Thanks

Eagerly awaiting a response.
sdesarAsked:
Who is Participating?
 
manuel_mConnect With a Mentor Commented:
i think axemaster should receive the points anyway.
maybe you can split the points, that would nice 2 ;)
0
 
manuel_mCommented:
to open the xml file and get the document.

try {
            // Build the document with SAX and Xerces, no validation
            SAXBuilder builder = new SAXBuilder();
            // Create the document
            Document doc = builder.build(new File(filename));

            // get the root element of the document
            Element root = doc.getRootElement();

            // now compare the AttributeValue of "userpath" with your string and replace it if it is found

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

try it yourself first:
you have to search for the attribute "userpath" in all elements or in specific elements. if you have the element, get the value of the element and compare the string. Replace if you need.
After this you can write the xml file back (see links)

look in the JDOM Api how to search the attribute of an element
http://www.jdom.org/docs/apidocs/index.html

here you have some examples how to process with jdom
http://www.jdom.org/downloads/docs.html
0
 
sdesarAuthor Commented:
Hello,
Thanks for the quick response.

I need to know how to find the duplicate string for userpath= within the XML file
I don't know the duplicate name - in the example it is sam, but there could be other duplicate names.
Thereore, could you please provide code on how to serach for the duplicate name "sam" and do the following ....

2. Search for any duplicate "names" in userpath=
    Example- sam
3. Find the first occurance of that duplicate name
   Example - String sNewPath = userpath="Users\grouping-users\gr-ost\sam"
4. Search and Replace the all the other userpath strings with sPath
   Example - userpath="Users\grouping-users\gr-ose-browseit\sam"  will be userpath="Users\grouping-users\gr-ost\sam"


Thanks

Eagery awaiting a response


0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
axemasterCommented:
What are you trying to do - remove duplicates?  How do you know what the replace string is?
0
 
manuel_mCommented:
try it on your own.

we are not here to solve your complete problem... :)
0
 
sdesarAuthor Commented:
1.  This is what the XML file looks like -
<OrganiseUsers> <sync />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\alex" role="Reviewer" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\sam" role="Reviewer" />
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\sara" role="Administrator" />
<changerole projects="mon_visdev_test" userpath="Users\grouping-users\gr-ose-browseit\sam" role="Administrator" />
<changerole projects="mon_visdev_test" userpath="Users\grouping-users\gr-ose-browseit\ricky" role="Administrator" />
</OrganiseUsers>

2.  I would like some code that finds a duplicate "name" in the userpath="...."  
Example - "sam" is a duplicate in two places -
Maybe a regrex that looks for userpath=".....\name" and if it is  same
Example -
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\sam" role="Reviewer" />
<changerole projects="mon_visdev_test" userpath="Users\grouping-users\gr-ose-browseit\sam" role="Administrator" />


3.  Repalce all the instances of userpath with the the first userpath
Example -
<changerole projects="mansonTest_v2" userpath="Users\grouping-users\gr-ost\sam" role="Reviewer" />
<changerole projects="mon_visdev_test" userpath="Users\grouping-users\gr-ost\sam" role="Administrator" />

0
 
axemasterConnect With a Mentor Commented:
This does it with JDOM.   http://www.jdom.org/

/*
 * Created on Oct 13, 2004
 */
package org.timshea.expertsexchange;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * @author Tim Shea
 */
public class Q_21167053 {

      public static void main(String[] args) throws Exception {
            
            HashMap map = new HashMap();
            
            Pattern pat = Pattern.compile(".*\\\\(.*)");
            
            SAXBuilder sb =  new SAXBuilder();
            Document doc = sb.build("Q_21167053.xml");
            Element root = doc.getRootElement();
            List list = root.getChildren();
            for( Iterator iter = list.iterator(); iter.hasNext(); ) {
                  Element e = (Element) iter.next();
                  Attribute a = e.getAttribute("userpath");
                  if( a == null ) {
                        continue;
                  }
                  String userpath = a.getValue();
                  Matcher match = pat.matcher(userpath);
                  if( !match.matches() ) {
                        continue;                  
                  }
                  String username = match.group(1);
                  if( userpath != null && username != null ) {
                        System.out.println(e.getName() + " " + username + " " + userpath);
                        if( map.containsKey(username)) {
                              // FOUND A DUPLICATE
                              a.setValue( (String) map.get(username) );
                              System.out.println("Reused " + map.get(username));            
                        }
                        else {
                              System.out.println("put " + username + " " + userpath);            
                              map.put(username, userpath);
                        }
                  }
            }
            
            // Write out the updated document to stdout
            
            XMLOutputter xmlout = new XMLOutputter(Format.getPrettyFormat());
            xmlout.output(doc, System.out);
            
      }
}
0
 
sdesarAuthor Commented:
Thanks for the code.
I did not have jdom.
so I  installed on a Windows machine.

And I installed it at this location -
C:\j2sdk1.4.2_04\lib\jdom-1.0.zip

And I added 'jdom-1.0.zip' to the classpath -
C:\J2sdk1.4.2_04\bin;C:\J2sdk1.4.2_04\lib\classes12.zip;C:\J2sdk1.4.2_04\lib\oci_nt9203.zip;C:\J2sdk1.4.2_04\lib\sql9201.zip;C:\J2sdk1.4.2_04\lib\jdom-1.0.zip

I added the above code in this location -
C:\j2sdk1.4.2_04\demo\ Q_21167053.java

and when I complie it -
C:\j2sdk1.4.2_04\demo>javac Q_21167053.java

This is the error I get

C:\j2sdk1.4.2_04\demo>javac Q_21167053.java
Q_21167053.java:12: package org.jdom does not exist
import org.jdom.Attribute;
                ^
Q_21167053.java:13: package org.jdom does not exist
import org.jdom.Document;
                ^
Q_21167053.java:14: package org.jdom does not exist
import org.jdom.Element;
                ^
Q_21167053.java:15: package org.jdom.input does not exist
import org.jdom.input.SAXBuilder;
                      ^
Q_21167053.java:16: package org.jdom.output does not exist
import org.jdom.output.Format;
                       ^
Q_21167053.java:17: package org.jdom.output does not exist
import org.jdom.output.XMLOutputter;
                       ^
Q_21167053.java:30: cannot resolve symbol
symbol  : class SAXBuilder
location: class org.timshea.expertsexchange.Q_21167053
          SAXBuilder sb =  new SAXBuilder();
          ^
Q_21167053.java:30: cannot resolve symbol
symbol  : class SAXBuilder
location: class org.timshea.expertsexchange.Q_21167053
          SAXBuilder sb =  new SAXBuilder();


Please advise.



PS. I am increasing points because of this new addition to the question

awaiting a response.

Thanks
0
 
manuel_mCommented:
you have to take the jdom.jar inside of the .zip file not the jdom-1.0.zip itself.

greets
Manuel

0
 
sdesarAuthor Commented:
I followed the instructions once I unzipped jdom and ran build.sh  and I found the jdom.jar here -
C:\J2sdk1.4.2_04\lib\jdom-1.0\build\jdom.jar

So I updated the class path as follows -
C:\J2sdk1.4.2_04\bin;C:\J2sdk1.4.2_04\lib\classes12.zip;C:\J2sdk1.4.2_04\lib\oci_nt9203.zip;C:\J2sdk1.4.2_04\lib\sql9201.zip;C:\J2sdk1.4.2_04\lib\jdom-1.0\build\jdom.jar

And now when I try this -
C:\j2sdk1.4.2_04\demo>javac Q_21167053.java

I still get the same error -

Q_21167053.java:12: package org.jdom does not exist
import org.jdom.Attribute;
                ^
Q_21167053.java:13: package org.jdom does not exist
import org.jdom.Document;
                ^
Q_21167053.java:14: package org.jdom does not exist
import org.jdom.Element;

Eagerly awaiting a response...
0
 
manuel_mCommented:
try

javac -classpath C:\J2sdk1.4.2_04\lib\jdom-1.0\build\jdom.jar Q_21167053.java
0
 
sdesarAuthor Commented:
Thanks - I got the code to compile.

Now I get this error..

C:\j2sdk1.4.2_04>.\bin\java -cp .\demo;.\lib\ojdbc14.jar;.\lib\jdom-1.0\build.jar Q_21167053
Exception in thread "main" java.lang.NoClassDefFoundError: org/jdom/input/SAXBuilder
        at Q_21167053.main(Q_21167053.java:30)


Its this line 30  - SAXBuilder sb =  new SAXBuilder();


Awaiting a response
0
 
sdesarAuthor Commented:
Thanks all - I got the code to compile and run ..


C:\j2sdk1.4.2_04>.\bin\java -cp .\demo;.\lib\ojdbc14.jar;.\lib\jdom-1.0\build\jdom.jar Q_21167053

I will check it out to make sure it works as I requested.

Thanks
0
 
sdesarAuthor Commented:
Awesome thanks axemaster.. the code works  great,

instead of outputting the xml to system.out can i change it tooutput it to a file-
xmlout.output(doc, formattedoutput.xml);

Please advise.

Thanks
0
 
manuel_mCommented:
look here: http://www.jdom.org/downloads/docs.html

there you find an answer to your question. But it is possible to output the xml in a file formattedoutput.xml with Outputformatter i think.
0
 
manuel_mCommented:
this will output the doc in the formattedoutput.xml file

xmlout.output(doc, new FileWriter("formattedoutput.xml"));
0
 
axemasterCommented:
Yes you can use any writer.  I used System.out just as an example.  I usually do something like this:

File outputFile = new File("yourfilename");
FileOutputStream fos = new FileOutputStream(outputFile);
printXML(doc, fos);
fos.close();


      /**
       * Send the pretty XML document to any output stream.
       *
       * @param doc                  XML Document
       * @param os                  Output stream to receive pretty XML document
       * @throws Exception
       */
      public void printXML(Document doc, OutputStream os) throws Exception {
            XMLOutputter xmlout = new XMLOutputter(Format.getPrettyFormat());
            xmlout.output(doc, os);
      }



0
 
sdesarAuthor Commented:
Thanks a million for all the help.
Here are the excellent points for 'axemaster' - for the code and
manuel_m   for helping with classpath

Thanks!
0
 
manuel_mCommented:
no problem, and thanks for the points :)

Manuel
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.