Announcement

Collapse
No announcement yet.

Puzzling Javascript Error in Regexp on Mirth 1.8.2.4472

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Puzzling Javascript Error in Regexp on Mirth 1.8.2.4472

    Hi All!

    I have a file called testfile.dat in our appliance's /folders/outbox folder that contains one line of data: "none\n". The file size is reported as 5 bytes and includes the 0x0A (newline) character.

    I have a simple javascript script that reads the file and uses a regular expression in an attempt to remove the 0x0a newline character after which it compares that value to one extracted from the mirthdb database in the channel's source area. Here is the script:

    Code:
    var thevalue = msg['max'].toString();
    var cont = FileUtil.read('/folders/outbox/testfile.dat');
    var trimmed = cont.replace(/\s+$/g, "");
    if (trimmed == "none")
    {
        connectorMap.put('ourvalue',thevalue);
    }
    else if (trimmed == thevalue)
    {
        connectorMap.put('ourvalue',trimmed + "Equal" + thevalue);
    }
    else
    {
        connectorMap.put('ourvalue',trimmed + "NotEqual" + thevalue);
    }
    I receive the following error:

    Code:
    FAILURE: Error evaluating transformer
    MirthJavascriptTransformerException
    
    CHANNEL:
    test-sql
    CONNECTOR:
    Destination 1
    SCRIPT SOURCE:
    
    SOURCE CODE:
    
    7: function doFilter() { phase = 'filter'; return true; }function doTransform() { phase = 'transformer'; logger = Packages.org.apache.log4j.Logger.getLogger(phase);
    8: 
    9: 
    10: var thevalue = msg['max'].toString();
    11: var cont = FileUtil.read('/folders/outbox/testfile.dat');
    12: var trimmed = cont.replace(/\s+$/g, "");
    13: if (trimmed == "none")
    14: {
    15:     connectorMap.put('ourvalue',thevalue);
    16: }
    LINE NUMBER:
    12
    DETAILS:
    The choice of Java constructor replace matching JavaScript argument types (function,string) is ambiguous; candidate constructors are: 
        class java.lang.String replace(char,char)
        class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence)
    I'm assuming something is incorrect with my regular expression. If the regexp is OK does Mirth 1.8.2.4472 have any issues with regular expressions in a string.replace?

    Bob D.
    Bob Dilworth
    University of Toledo Medical Center
    Toledo, Ohio

  • #2
    Try:

    var cont = new String(FileUtil.read('/folders/outbox/testfile.dat'));

    or

    cont.toString().replace(/\s+$/g, "");

    Comment


    • #3
      Re: Puzzling Javascript Error in Regexp on Mirth 1.8.2.4472

      Originally posted by apatwa View Post
      Try:

      var cont = new String(FileUtil.read('/folders/outbox/testfile.dat'));

      or

      cont.toString().replace(/\s+$/g, "");
      Thanks for the suggestions! I tried them both together as well as separately with the same results: I receive the same runtime channel error I provided in my original posting.

      To make absolutely sure that my regex is correct I wrote a little stand-alone Perl script on my Linux box to do the same thing and this regex works fine: s/\s*$//g; However, when I used the same syntax in the javascript step like this: cont.replace(/\s*$/g, ""); I still receive the same error. For grins I also tried: cont.replace(/\s*$//g, ""); and cont.replace(/\s*$/, ""); which also didn't work.

      I even tried separating out the regex itself into a variable and using that variable in the string.replace like this:

      Code:
      var cont = new String(FileUtil.read('/folders/outbox/testfile.dat'));
      var patt = "/\s*$/g";
      var trimmed = cont.toString().replace(patt, "");
      The channel error went away but the the newline remained at the end of the string.

      Does anyone out there have a working string.replace that uses a regex they'd be willing to share?

      Bob D.
      Last edited by bdilworth; 10-14-2010, 07:10 AM. Reason: corrected fat finger error in code
      Bob Dilworth
      University of Toledo Medical Center
      Toledo, Ohio

      Comment


      • #4
        Try

        Code:
        var trimmed = cont.replace("/\s+$/g", "");
        I think the regex needs to be a string. You may also need to escape the '\' with a '\\', i.e.

        Code:
        var trimmed = cont.replace("/\\s+$/g", "");

        Comment


        • #5
          To handle new lines, you want to do .replace(/\n|\r/g, '');

          Comment


          • #6
            Re: Puzzling Javascript Error in Regexp on Mirth 1.8.2.4472

            Thanks again for the new suggestions! I tried them all a variety of ways still to no avail. Here's the variations I tried based on the most recent suggestions. Please note that I did not run all these variations at the same time! :-) Each of the vairations did not error but they also did not remove the newline at the end of the string:

            Code:
            var cont = FileUtil.read('/folders/outbox/testfile.dat');
            
            var trimmed = cont.replace("/\n$/", '');
            var trimmed = cont.replace("/\\n$/", '');
            var trimmed = cont.replace("/\\s+$/", '');
            var trimmed = cont.replace("/\s+$/", '');
            I also discovered that if one does not surround the regex with double quotes it errors off when it runs. Looks like the double quotes around the regex are indeed needed?

            For grins I also tried them all in Mirth 1.8.1 with exactly the same results.

            Any other thoughts or suggestions or is there some sort of bug in the javascript implementation in Mirth 1.8.1 and 1.8.2?

            Bob D.
            Bob Dilworth
            University of Toledo Medical Center
            Toledo, Ohio

            Comment


            • #7
              FileUtil.read returns a java string. The replace function you are trying to use is for a javascript string. You could change your code to this to ensure you have a javascript string:
              Code:
              var cont = FileUtil.read('/folders/outbox/testfile.dat') + "";
              Or you can use the java replace function instead.
              Daniel Svanstedt
              Software Engineer
              Mirth Corporation

              Want professional services, support, and enterprise or virtual appliances? It's all available from the Mirth Corporation:
              Mirth Support | Mirth Training | Mirth Appliances | Online Training | Developer Q&A

              Don't forget, Mirth Support gives you access to all of our online training videos, and silver support gives you access to developer Q&As!

              Comment


              • #8
                Originally posted by dans View Post
                FileUtil.read returns a java string. The replace function you are trying to use is for a javascript string. You could change your code to this to ensure you have a javascript string:
                Code:
                var cont = FileUtil.read('/folders/outbox/testfile.dat') + "";
                Hi Daniel!

                Thank you SO much for the tip!!!! Adding the + "" to the end of the FileUtil.read did the trick. The regular expression worked great once I did that:

                Code:
                var cont = FileUtil.read('/folders/outbox/testfile.dat') + "";
                var trimmed = cont.replace(/\s+$/g, "");
                Thanks again!!!!!!!!!!!!!!!!!!

                Bob D.
                Bob Dilworth
                University of Toledo Medical Center
                Toledo, Ohio

                Comment


                • #9
                  I don't intend to necro an old thread but I'm curious as to why appending "" to the string is necessary. I'm especially curious because I had a working regex in this function.

                  Code:
                  function replaceSingleQuote(object){
                  	for (property in object) {
                  		var propertyString = object[property];
                  		var regex = /\'/g;
                  		// var subString = "''";
                  		if (typeof object[property] === "string") {
                  			object[property] = propertyString.replace(regex,"''");
                  		}
                  	}
                  }
                  Through doing some refactoring of the code the function changed to this and the regex no longer works without throwing that error:

                  Code:
                  function replaceSingleQuote(string){
                  	/* appending string with "" is necessary to avoid this error: The choice of Java method java.lang.String.replace matching JavaScript argument types (function,string) is ambiguous; candidate methods are: */
                  	string = string + "";
                  	var regex = /\'/g;
                  	return string.replace(regex,"''");
                  The only thing that I can tell that changed in a meaningful way is that I changed object to string. The function is now used more appropriately as a utility function called by others to reformat a string while they iterate through an object instead of iterating through the object itself.

                  Thanks in advance for helping me understand this.
                  Last edited by bassicallychris; 08-16-2019, 06:46 AM.

                  Comment


                  • #10
                    As the error implies, the java.lang.String.replace and String.prototype.replace methods don't behave in the same way.

                    In many cases, java and javascript strings can be used interchangeably, with Rhino converting them automatically based on context. Invoking the replace method is one of the cases where it can't do that.

                    Any time you do string concatenation in Rhino, it will result in a javascript string, even if you are concatenating two Java Strings.

                    A more explicit way to convert them to the desired type is to do the following:

                    Code:
                    function replaceSingleQuote(string){
                    	// force to javascript string
                    	string = String(string);
                    	var regex = /'/g;
                    	return string.replace(regex,"''"); // returns a javascript string
                    }
                    or

                    Code:
                    function replaceSingleQuote(string){
                    	// force to java String
                    	string = new java.lang.String(string);
                    	var regex = "'";
                    	return string.replaceAll(regex,"''"); // returns a java String
                    }

                    Comment


                    • #11
                      Thank you for the explanation! That makes a lot of sense to me, I'm still fuzzy on why the distinction needed to be made when using a variable that directly represents a string passed to the function vs. not needed when iterationing through an object passed to the function resulting in using
                      Code:
                      object[property]
                      which also directly represents a string.

                      Comment


                      • #12
                        When using typeof on a js primitive string it returns 'string'. typeof on an instance of java.lang.String will return 'object'.

                        Comment


                        • #13
                          This makes sense, I think my initial message caused confusion because in reality I was using the string variable without appending ` "" ` to it but I believe I've still understood this.

                          To confirm, there are JavaScript and Java replace functions that are written differently and Rhino doesn't know which one to use unless the string is explicitly defined as either a JS or Java string. When performing the typeof evaluation you're letting Rhino know that you're using a JS string but if you just feed it a string it doesn't know which replace function to use.

                          Comment


                          • #14
                            If you pass a javascript regular expression as the first parameter, it will work if you're calling it on a javascript string, and it won't work on a java string, because it's expecting either a char or CharSequence as the first parameter, and Rhino can't tell which one you meant to call.

                            If you pass strings as both parameters, it will work because both the java and js methods behave the same way in this case, and the javascript strings will get converted to CharSequences when called on a java string, so it's not ambiguous like when passing a regex.

                            Comment

                            Working...
                            X