?
Solved

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

Posted on 2004-10-13
19
Medium Priority
?
270 Views
Last Modified: 2012-05-05
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.
0
Comment
Question by:sdesar
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 8
  • 3
19 Comments
 
LVL 6

Expert Comment

by:manuel_m
ID: 12301674
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
 

Author Comment

by:sdesar
ID: 12301779
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
 
LVL 1

Expert Comment

by:axemaster
ID: 12301969
What are you trying to do - remove duplicates?  How do you know what the replace string is?
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 6

Expert Comment

by:manuel_m
ID: 12302185
try it on your own.

we are not here to solve your complete problem... :)
0
 

Author Comment

by:sdesar
ID: 12302450
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
 
LVL 1

Assisted Solution

by:axemaster
axemaster earned 220 total points
ID: 12302611
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
 

Author Comment

by:sdesar
ID: 12303214
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 12303430
you have to take the jdom.jar inside of the .zip file not the jdom-1.0.zip itself.

greets
Manuel

0
 
LVL 6

Accepted Solution

by:
manuel_m earned 80 total points
ID: 12303436
i think axemaster should receive the points anyway.
maybe you can split the points, that would nice 2 ;)
0
 

Author Comment

by:sdesar
ID: 12303503
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 12303625
try

javac -classpath C:\J2sdk1.4.2_04\lib\jdom-1.0\build\jdom.jar Q_21167053.java
0
 

Author Comment

by:sdesar
ID: 12303718
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
 

Author Comment

by:sdesar
ID: 12303860
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
 

Author Comment

by:sdesar
ID: 12303947
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 12307175
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 12307531
this will output the doc in the formattedoutput.xml file

xmlout.output(doc, new FileWriter("formattedoutput.xml"));
0
 
LVL 1

Expert Comment

by:axemaster
ID: 12311146
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
 

Author Comment

by:sdesar
ID: 12311544
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 12311785
no problem, and thanks for the points :)

Manuel
0

Featured Post

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month10 days, 6 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question