OpenLDAP and Octet String.

Hi all, I had a new problem with my jsp's applications that must connect to a openLDAP server.
I resolve the connection and the search problems, as I said in other post.
Now the problem is that I must use the connection for authenticate the simple user.
I discovery that I can do that using the dn parameter.
The problem is that if I would do it I should do too much connections because I must do:
1)connect with the admin user;
2) search the dn value of the user that is trying to connect using the username's value that I receive withe login's form;
3) close the connection;
4) and finnally reconnect to the ldap server with thenew credentials!
I don't like this solution so I'm here because I would know if there are some thing to do for take the value of a octet string on a ldap server.
The alternative is "traslate" the string with the password write on my login's form in the same format of userPassword's field.
I know that the octet string is a byte's array and I try to cast my string in a bye's array and compare with the other with the method contains() but it retunes false.
I find this topic:
http://forums.sun.com/thread.jspa?threadID=721595&messageID=4162046
but there are two problems:
1) as I said I don't know how get the value of a octet string's field;
2) the code of for's cycle five me a compilers' error and I never seen a for's cycle withe the string so I don't know how I can traslate it in a classic for's cycle...
Some one can help me?
Thanks inadvance.

First I use the contaims() method.
Second i insert as value to control the string casts in byte's array with the method getBytes().
Than it returns true!

Similar Messages

  • Problem with OpenLDAP and JNDI

    I'm having problem working with OpenLDAP and JNDI.
    First I have changed LDAP's slapd.conf file:
    suffix          "dc=antipodes,dc=com"
    rootdn          cn=Manager,dc=antipodes,dc=com
    directory     "C:/Program Files/OpenLDAP/data"
    rootpw          secret
    schemacheck offthan i used code below, to create root context:
    package test;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.naming.NameAlreadyBoundException;
    import javax.naming.directory.*;
    import java.util.*;
    public class MakeRoot {
         final static String ldapServerName = "localhost";
         final static String rootdn = "cn=Manager,dc=antipodes,dc=com";
         final static String rootpass = "secret";
         final static String rootContext = "dc=antipodes,dc=com";
         public static void main( String[] args ) {
                   // set up environment to access the server
                   Properties env = new Properties();
                   env.put( Context.INITIAL_CONTEXT_FACTORY,
                              "com.sun.jndi.ldap.LdapCtxFactory" );
                   env.put( Context.PROVIDER_URL, "ldap://" + ldapServerName + "/" );
                   env.put( Context.SECURITY_PRINCIPAL, rootdn );
                   env.put( Context.SECURITY_CREDENTIALS, rootpass );
                   try {
                             // obtain initial directory context using the environment
                             DirContext ctx = new InitialDirContext( env );
                             // now, create the root context, which is just a subcontext
                             // of this initial directory context.
                             ctx.createSubcontext( rootContext );
                   } catch ( NameAlreadyBoundException nabe ) {
                             System.err.println( rootContext + " has already been bound!" );
                   } catch ( Exception e ) {
                             System.err.println( e );
    }this worked fine, I could see that by using "LDAP Browser/Editor".
    and then I tried to create group with code:
    package test;
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    public class MakeGroup
         public static void main (String[] args)
              Hashtable env = new Hashtable();
              String adminName = "cn=Manager,dc=antipodes,dc=com";
              String adminPassword = "secret";
              String ldapURL = "ldap://127.0.0.1:389";
              String groupName = "CN=Evolution,OU=Research,DC=antipodes,DC=com";
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL,ldapURL);
              try {
                   // Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   // Create attributes to be associated with the new group
                        Attributes attrs = new BasicAttributes(true);
                   attrs.put("objectClass","group");
                   attrs.put("samAccountName","Evolution");
                   attrs.put("cn","Evolution");
                   attrs.put("description","Evolutionary Theorists");
                   //group types from IAds.h
                   int ADS_GROUP_TYPE_GLOBAL_GROUP = 0x0002;
                   int ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = 0x0004;
                   int ADS_GROUP_TYPE_LOCAL_GROUP = 0x0004;
                   int ADS_GROUP_TYPE_UNIVERSAL_GROUP = 0x0008;
                   int ADS_GROUP_TYPE_SECURITY_ENABLED = 0x80000000;
                   attrs.put("groupType",Integer.toString(ADS_GROUP_TYPE_UNIVERSAL_GROUP + ADS_GROUP_TYPE_SECURITY_ENABLED));
                   // Create the context
                   Context result = ctx.createSubcontext(groupName, attrs);
                   System.out.println("Created group: " + groupName);
                   ctx.close();
              catch (NamingException e) {
                   System.err.println("Problem creating group: " + e);
    }got the error code: Problem creating group: javax.naming.directory.InvalidAttributeIdentifierException: [LDAP: error code 17 - groupType: attribute type undefined]; remaining name 'CN=Evolution,OU=Research,DC=antipodes,DC=com'
    I tried by creating organizational unit "ou=Research" from "LDAP Browser/Editor", and then running the same code -> same error.
    also I have tried code for adding users:
    package test;
    import java.util.Hashtable;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import javax.naming.*;
    import javax.net.ssl.*;
    import java.io.*;
    public class MakeUser
         public static void main (String[] args)
              Hashtable env = new Hashtable();
              String adminName = "cn=Manager,dc=antipodes,dc=com";
              String adminPassword = "secret";
              String userName = "cn=Albert Einstein,ou=Research,dc=antipodes,dc=com";
              String groupName = "cn=All Research,ou=Research,dc=antipodes,dc=com";
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL, "ldap://127.0.0.1:389");
              try {
                   // Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   // Create attributes to be associated with the new user
                        Attributes attrs = new BasicAttributes(true);
                   //These are the mandatory attributes for a user object
                   //Note that Win2K3 will automagically create a random
                   //samAccountName if it is not present. (Win2K does not)
                   attrs.put("objectClass","user");
                        attrs.put("samAccountName","AlbertE");
                   attrs.put("cn","Albert Einstein");
                   //These are some optional (but useful) attributes
                   attrs.put("giveName","Albert");
                   attrs.put("sn","Einstein");
                   attrs.put("displayName","Albert Einstein");
                   attrs.put("description","Research Scientist");
                        attrs.put("userPrincipalName","[email protected]");
                        attrs.put("mail","[email protected]");
                   attrs.put("telephoneNumber","999 123 4567");
                   //some useful constants from lmaccess.h
                   int UF_ACCOUNTDISABLE = 0x0002;
                   int UF_PASSWD_NOTREQD = 0x0020;
                   int UF_PASSWD_CANT_CHANGE = 0x0040;
                   int UF_NORMAL_ACCOUNT = 0x0200;
                   int UF_DONT_EXPIRE_PASSWD = 0x10000;
                   int UF_PASSWORD_EXPIRED = 0x800000;
                   //Note that you need to create the user object before you can
                   //set the password. Therefore as the user is created with no
                   //password, user AccountControl must be set to the following
                   //otherwise the Win2K3 password filter will return error 53
                   //unwilling to perform.
                        attrs.put("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED+ UF_ACCOUNTDISABLE));
                   // Create the context
                   Context result = ctx.createSubcontext(userName, attrs);
                   System.out.println("Created disabled account for: " + userName);
                   //now that we've created the user object, we can set the
                   //password and change the userAccountControl
                   //and because password can only be set using SSL/TLS
                   //lets use StartTLS
                   StartTlsResponse tls = (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
                   tls.negotiate();
                   //set password is a ldap modfy operation
                   //and we'll update the userAccountControl
                   //enabling the acount and force the user to update ther password
                   //the first time they login
                   ModificationItem[] mods = new ModificationItem[2];
                   //Replace the "unicdodePwd" attribute with a new value
                   //Password must be both Unicode and a quoted string
                   String newQuotedPassword = "\"Password2000\"";
                   byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
                   mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
                   mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED)));
                   // Perform the update
                   ctx.modifyAttributes(userName, mods);
                   System.out.println("Set password & updated userccountControl");
                   //now add the user to a group.
                        try     {
                             ModificationItem member[] = new ModificationItem[1];
                             member[0]= new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", userName));
                             ctx.modifyAttributes(groupName,member);
                             System.out.println("Added user to group: " + groupName);
                        catch (NamingException e) {
                              System.err.println("Problem adding user to group: " + e);
                   //Could have put tls.close()  prior to the group modification
                   //but it seems to screw up the connection  or context ?
                   tls.close();
                   ctx.close();
                   System.out.println("Successfully created User: " + userName);
              catch (NamingException e) {
                   System.err.println("Problem creating object: " + e);
              catch (IOException e) {
                   System.err.println("Problem creating object: " + e);               }
    }same error.
    I haven't done any chages to any schema manually.
    I know I'm missing something crucial but have no idea what. I have tried many other code from tutorials from net, but they are all very similar and throwing the same error I showed above.
    thanks in advance for help.

    I've solved this.
    The problem was that all codes were using classes from Microsoft Active Directory, and they are not supported in OpenLDAP (microsoft.schema in OpenLDAP is just for info). Due to this some fields are not the same in equivalent classes ("user" and "person").
    so partial code for creating user in root would be:
    import java.util.Hashtable;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import javax.naming.*;
    import javax.net.ssl.*;
    import java.io.*;
    public class MakeUser
         public static void main (String[] args)
              Hashtable env = new Hashtable();
              String adminName = "cn=Manager,dc=antipodes,dc=com";
              String adminPassword = "secret";
              String userName = "cn=Albert Einstein,ou=newgroup,dc=antipodes,dc=com";
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL, "ldap://127.0.0.1:389");
              try {
                   // Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   // Create attributes to be associated with the new user
                        Attributes attrs = new BasicAttributes(true);
                                  attrs.put("objectClass","user");
                   attrs.put("cn","Albert Einstein");
                   attrs.put("userPassword","Nale");
                   attrs.put("sn","Einstein");
                   attrs.put("description","Research Scientist");
                   attrs.put("telephoneNumber","999 123 4567");
                   // Create the context
                   Context result = ctx.createSubcontext(userName, attrs);
                   System.out.println("Successfully created User: " + userName);
              catch (NamingException e) {
                   System.err.println("Problem creating object: " + e);
    }hope this will help anyone.

  • Null and empty string not being the same in object?

    Hello,
    I know that null and empty string are interpreted the same in oracle.
    However I discovered the strange behaviour concerning user defined objects:
    create or replace
    TYPE object AS OBJECT (
    value VARCHAR2(2000)
    declare
    xml xmltype;
    obj object;
    begin
    obj := object('abcd');
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    obj.value := '';
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    obj.value := null;
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    end;
    When creating xml from object, all not-null fields are transformed into xml tag.
    I supposed that obj.value being either '' or null will lead to the same result.
    However this is output from Oracle 9i:
    <OBJECT_ID><VALUE>abcd</VALUE></OBJECT_ID>
    <OBJECT_ID><VALUE></VALUE></OBJECT_ID>
    <OBJECT_ID/>
    Oracle 10g behaves as expected:
    <OBJECT><VALUE>abcd</VALUE></OBJECT>
    <OBJECT/>
    <OBJECT/>
    However Oracle 9i behaviour leads me to the conclusion that oracle
    must somehow distinguish between empty string and null in user defined objects...
    Can someone clarify this behaviour?
    Thus is it possible to test if object's field is empty or null?

    However Oracle 9i behaviour leads me to the conclusion that oracle
    must somehow distinguish between empty string and null in user defined objects...
    Can someone clarify this behaviour?
    Thus is it possible to test if object's field is empty or null?A lot of "fixes" were done, relating to XML in 10g and the XML functionality of 9i was known to be buggy.
    I think you can safely assume that null and empty strings are treated the same by Oracle regardless. If you're using anything less than 10g, it's not supported any more anyway, so upgrade. Don't rely on any assumptions that may appear due to bugs.

  • Difference in Null and Empty String

    Hi,
    I have been wondering about the difference between Null and Empty String in Java. So I wrote a small program like this:
    public class CompareEmptyAndNullString {
         public static void main(String args[]) {
              String sNull = null;
              String sEmpty = "";
              try {
                   if (sNull.equalsIgnoreCase(sEmpty)) {
                        System.out.println("Null and Empty Strings are Equal");
                   } else {
                        System.out.println("Null and Empty Strings are Equal");
              } catch (Exception e) {
                   e.printStackTrace();
    This program throws Exception: java.lang.NullPointerException
         at practice.programs.CompareEmptyAndNullString.main(CompareEmptyAndNullString.java:10)
    Now if I change the IF Clause to if (sEmpty.equalsIgnoreCase(sNull)) then the Program outputs this: Null and Empty Strings are Equal
    Can anyone explain why this would happen ?
    Thanks in Advance !!

    JavaProwler wrote:
    Saish,
    Whether you do any of the following code, the JUnit Test always passes: I mean he NOT Sign doesnt make a difference ...
    assert (! "".equals(null));
    assert ("".equals(null));
    You probably have assertions turned off. Note the the assert keyword has nothing to do with JUnit tests.
    I think that older versions of JUnit, before assert was a language keyword (which started in 1.4 or 1.5), had a method called assert. Thus, if you have old-style JUnit tests, they might still compile, but the behavior is completely different from what it was in JUnit, and has nothing to do with JUnit at all.
    If you turn assertions on (-ea flag in the JVM command line, I think), the second one will throw AssertionError.

  • What is difference between Null String and Empty String ?

    Hi
    Just i have little confusion that the difference bet'n NULL String and Empty String ..
    Please clear my doubte.
    Thankx

    For the same reason I think it's okay to say "null
    String" and "empty String "as long as you know they
    really mean "null String reference" and "empty String
    object" respectively. Crap. It's only okay to say that as long as *the one you're talking to" knows what it really means. Whether you know it or not is absolutely irrelevant. And there is hardly any ambiguity about the effects that a statement like "assign an object to a reference" brings. "Null String" differs in that way.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • VARCHAR2:: How to differnciate between NULL and empty string '' ?

    Hello to all,
    I'm looking for a possibility to differnciate between NULL and empty string '' in column of type VARCHAR2.
    I have an application relying on that there is a difference between NULL and ''.
    Is it possible to configure ORACLE in some way ?
    Thanx in advance,
    Thomas

    try check if a varchar variable has an empty string
    by checking its lengthAnd that would accomplish what? But see for yourself:
    DECLARE
      v_test VARCHAR2(10);
    BEGIN
      v_test := '';
      DBMS_OUTPUT.put_line(LENGTH(v_test));
      v_test := NULL;
      DBMS_OUTPUT.put_line(LENGTH(v_test));
    END; C.

  • What is the difference between String Constant and Empty String Constant

    What is the difference between string constant which does not contain any value and the Empty string constant?
    While testing a VI which contain a normal string constant in VI analyzer, it gives error to change string constant with the empty string constant?
    Please Reply
    prabhakant
    Regards
    Prabhakant Patil

    Readability.
    Functionally, they are the same. From a coding standpoint, the Empty String Constant is unambiguous.
    It is empty and will always be; good for initialization. Also, because you can not type a value into and Empty String Constant, someone would need to conciously replace it to set a 'default' value that is something other than NULL.
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness

  • Difference between String and final String

    Hi friends,
    This is Ramana. Can u suggest me in this Question
    What is the difference between String and final String? Means
    String str="hai";
    final String str="hai";
    Regards,
    Ramana.

    *******REPEAT POST***********
    We already answered your question why post in a different section?
    http://forum.java.sun.com/thread.jspa?threadID=5201549

  • On-Screen Keyboard and a String Control

    I am experiencing some odd behavior when I use the On-Screen keyboard (OSK) and a string control.
    I am developing a application that will need to use the OSK to enter in some data on a touch screen monitor with no physical keyboard. I have a Event-Driven State Machine set up to the Key Down event when a word/characters are entered and the user presses the Enter Key on the OSK. I noticed if I probe the VKey wire wuen I press the Enter Key on the OSK, it comes across as a Return press. No big deal I thought, just see if the Return Key is pressed and continue on.
    When I went to test my program, I noticed that my values were displaying as if nothing was entered. Digging a little further, I noticed that my original data is still there if I press the Backspace Key and remove the Return command. Probing the string wire within the string control indicates that that the value comes back as a empty string in my string control even though my entire string is physically still there. I can press the backspace key (deleting the carriage return) and see my original text. What I think is happening is when I press the Return Key on the OSK, it inserts something and moves my text either up or down and when I use the property node to extract the data within the string control, I get a empty string.
    How have you gotten around this? I'd like to hear your solutions.
    Solved!
    Go to Solution.

    Since you marked Jarle's message as the solution, I hope it means your happy and he's helped you solve your problem.
    I had never seen the OSK app before.  It looks like it can be very useful, but these other issues like how to programmatically get into it, or out of it with a task kill seem like they are a bit of a hack to work with something that shows so much promise.
    If these issues are too big, consider making your home pop-up keyboard as a LabVIEW VI.  It would be a little bit of work, but not so bad.  I've made a pop-up numeric keyboard that I've used in a few apps of mine.  Of course that is fewer keys to layout and deal with.  And I didn't need decimals for what I was doing so I didn't have to program that which adds a little complication.
    A pop-up keyboard might actually be easier, other than having 3-4 times the number of keys depending on how many symbols you need to deal with, and if you need to deal with CAPS, or CAPS lock or whatever.
    There is also a chance that someone may have done something already.  A google search might find something.  It is likely in the NI community if it exists.  If you can find something that works or is close to what you want, it might be better than using this OSK executable.
    Just some ideas to toss out there.

  • Difference between public void, private void and public string

    Hi everyone,
    My 1st question is how do you know when to use public void, private void and public string? I am mightily cofuse with this.
    2ndly, Can anybody explain to me on following code snippet:
    Traceback B0;//the starting point  of Traceback
    // Traceback objects
    abstract class Traceback {
      int i, j;                     // absolute coordinates
    // Traceback2 objects for simple gap costs
    class Traceback2 extends Traceback {
      public Traceback2(int i, int j)
      { this.i = i; this.j = j; }
    }And using the code above is the following allowed:
    B[0] = new Traceback2(i-1, 0);
    Any replies much appreciated. Thank you.

    1)
    public and private are access modifiers,
    void and String return type declarations.
    2)
    It's called "inheritance", and "bad design" as well.
    You should read the tutorials, you know?

  • I would like to do a program that have one string control and one string indicator, any character that I type in the string control in the same time it will be appear in another string (indicator). How can help me?

    I would like to do a program that have one string control and one string indicator, any character that I type in the string control in the same time it will be appear in another string (indicator). How can help me?

    Why not use an event
    Add a While Loop, inside the loop add the Event Sructure.
    Now in the event structure selecd the String Controls.value change event to
    react
    and the new value inside the event that you get,( connect to the String
    indicator box.
    On Sun, 10 Aug 2003 15:58:47 -0500 (CDT), WiltonFilho wrote:
    > I would like to do a program that have one string control and one
    > string indicator, any character that I type in the string control in
    > the same time it will be appear in another string (indicator). How can
    > help me?
    >
    > I would like to do a program that have one string control and one
    > string indicator, any character that I type in the string control in
    > the same time it will be appear in another string (indicator). How can
    > help me?
    >
    Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • Search and replace string formatting

    Hi,
    I am trying to do a search and replace formatting of a string.
    In the example I am looking for string "PASSED" but it must also start with usbflash and some number + PASSED.
    I can't get the format to have a number from 1-99. The number of replacements should add up to 6 in this case. I have tried with \d for any number, and I also tried [1-99].
    Solved!
    Go to Solution.

    Right click on the Search And Replace String function.  There is an option to use Regular Expressions.  Then give this a try.
    EDIT: You will need to set the Replace All input to TRUE.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Match Pattern.png ‏12 KB

  • Search and replace string problems

    Hi to all,
    I have problem with Search and replace string function. It shows me a wrong Value (Number) from 15 to 100 is everything OK (15=0, 30=1, 45=2, 100=3), but after 100 ........
    Take look in VI and if you have any ideas post them please
    THX
    Igor 
    Attachments:
    indexing.vi ‏10 KB

    there will be no 15115 string, but 15 or 115 and 15 is 0, 115 is 4. Anyway, i have changed string input format and now its working THX for your help
    Attachments:
    indexing.vi ‏10 KB

  • Search and Replace String throwing the wrong error message with regexp?

    This came up in a LAVA thread, and I'm not sure if there's a bug here or not. When using Search and Replace string, and using a regular expression of [(G[b|i])], LabVIEW throws error -4622, "There is an unmatched parenthesis in a regular expression."  There are obviously no unmatched parenthesis in that expression, so it seems to me that the wrong error is being thrown. I'm just not sure if that's a syntactically valid regexp. The problem seems to be with nesting [ ]'s inside ( )'s inside [ ]'s. I've tried a couple of regexp resources on the Web, and one suggests it's valid, while the other seems to think it isn't.
    Message Edited by eaolson on 03-13-2007 10:33 AM
    Attachments:
    ATML_StandardUnit2.vi ‏10 KB
    regexp.png ‏5 KB

    adambrewster wrote:
    I think your regexp is invalid.
    In regexps, brackets are not the same as parentheses.  Parens are for grouping, while brackets are for matching one of a class of characters.  Brackets can not be nested.
    If the regexp is replaced with [G[bi]], there is no error, so it's not a matter of nested brackets. I couldn't find anything on the PCRE man page that forbids nested brackets specifically, but it makes sense.
    Your expression "[(G[bi])]", therefore parses as a character class which matches '(', 'G', '[', 'b', or 'i' followed by an unmatched paren, and an unmatched bracket.
    I don't believe that's the case. Replace the regexp with [(Gbi)], and the error goes away. So it's not a matter of the '(' being literal, and then encountering a ')' without a matching '('.
    daveTW wrote:
    what string exactly you want to replace? I think the round braces are not right in this case, since they mark partial matches which are given back by "match regular expression". But you don't want to extract parts of the string, you want to replace them (or delete, with empty <replace string>). So if you leave the outer [( ... )] then your RegEx means all strings with either "Gb" or "Gi".
    It's not my regular expression. A poster at LAVA was having problems with one of his (a truly frightening one), and this seemed to be the element that was causing the problem. I'm pretty sure that the originator of the regexp meant to use G(b|i), which seems like a complicated way of matching "Gb" or "Gi", if you ask me.

Maybe you are looking for