Solved

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

Posted on 2004-10-13
19
267 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
  • 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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 55 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 20 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

839 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