Solved

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

Posted on 2004-10-13
19
269 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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 
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

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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 about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

724 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