Getting a subset of string from multivalue field SSJS - xpages

In an XPage bound to a document I have a multivalue field containing email addresses. I simply wish to loop through the email addresses and return a subset of addresses which contain mydomain. To then use them in 'recipient' field for emailing.
Seems straight forward, but I receive the following error, even though 'typeof()' returns strings. I can't seem to get away from the [JavaScript Object]. Tried toString() and all sorts. Any help is appreciated.
Error message
Error while executing JavaScript computed expression
Script interpreter error[TypeError] Error calling method 'includes(string)' on an object of type 'String [JavaScript Object]'
JavaScript code
var array = documentContract.getItemValueArray("EmailAddress")
var result = "";
for (var i=0; i<array.length; i++) {
if ( array[i].includes("#mydomain.com")) {
result = result + array[i] + "\n";}
}
return result;

The error message says that includes is not an available method on the string object.
You can use #Contains:
if (#Contains(array[i], "#mydomain.com")) {

Gotta love Formula language:
evaluate('#Trim(#Left(EmailAddress, "#mydomain.com"))+"#mydomain.com"', documentContract)
Watch out for uppercase and no mydomain at all. Maybe the evaluate isn't even necessary, it might just function in SSJS without it.

Related

Is it possible to get the name of variable in Groovy?

I would like to know if it is possible to retrieve the name of a variable.
For example if I have a method:
def printSomething(def something){
//instead of having the literal String something, I want to be able to use the name of the variable that was passed
println('something is: ' + something)
}
If I call this method as follows:
def ordinary = 58
printSomething(ordinary)
I want to get:
ordinary is 58
On the other hand if I call this method like this:
def extraOrdinary = 67
printSomething(extraOrdinary)
I want to get:
extraOrdinary is 67
Edit
I need the variable name because I have this snippet of code which runs before each TestSuite in Katalon Studio, basically it gives you the flexibility of passing GlobalVariables using a katalon.features file. The idea is from: kazurayam/KatalonPropertiesDemo
#BeforeTestSuite
def sampleBeforeTestSuite(TestSuiteContext testSuiteContext) {
KatalonProperties props = new KatalonProperties()
// get appropriate value for GlobalVariable.hostname loaded from katalon.properties files
WebUI.comment(">>> GlobalVariable.G_Url default value: \'${GlobalVariable.G_Url}\'");
//gets the internal value of GlobalVariable.G_Url, if it's empty then use the one from katalon.features file
String preferedHostname = props.getProperty('GlobalVariable.G_Url')
if (preferedHostname != null) {
GlobalVariable.G_Url = preferedHostname;
WebUI.comment(">>> GlobalVariable.G_Url new value: \'${preferedHostname}\'");
} else {
WebUI.comment(">>> GlobalVariable.G_Url stays unchanged");
}
//doing the same for other variables is a lot of duplicate code
}
Now this only handles 1 variable value, if I do this for say 20 variables, that is a lot of duplicate code, so I wanted to create a helper function:
def setProperty(KatalonProperties props, GlobalVariable var){
WebUI.comment(">>> " + var.getName()" + default value: \'${var}\'");
//gets the internal value of var, if it's null then use the one from katalon.features file
GlobalVariable preferedVar = props.getProperty(var.getName())
if (preferedVar != null) {
var = preferedVar;
WebUI.comment(">>> " + var.getName() + " new value: \'${preferedVar}\'");
} else {
WebUI.comment(">>> " + var.getName() + " stays unchanged");
}
}
Here I just put var.getName() to explain what I am looking for, that is just a method I assume.
Yes, this is possible with ASTTransformations or with Macros (Groovy 2.5+).
I currently don't have a proper dev environment, but here are some pointers:
Not that both options are not trivial, are not what I would recommend a Groovy novice and you'll have to do some research. If I remember correctly either option requires a separate build/project from your calling code to work reliable. Also either of them might give you obscure and hard to debug compile time errors, for example when your code expects a variable as parameter but a literal or a method call is passed. So: there be dragons. That being said: I have worked a lot with these things and they can be really fun ;)
Groovy Documentation for Macros
If you are on Groovy 2.5+ you can use Macros. For your use-case take a look at the #Macro methods section. Your Method will have two parameters: MacroContext macroContext, MethodCallExpression callExpression the latter being the interesting one. The MethodCallExpression has the getArguments()-Methods, which allows you to access the Abstract Syntax Tree Nodes that where passed to the method as parameter. In your case that should be a VariableExpression which has the getName() method to give you the name that you're looking for.
Developing AST transformations
This is the more complicated version. You'll still get to the same VariableExpression as with the Macro-Method, but it'll be tedious to get there as you'll have to identify the correct MethodCallExpression yourself. You start from a ClassNode and work your way to the VariableExpression yourself. I would recommend to use a local transformation and create an Annotation. But identifying the correct MethodCallExpression is not trivial.
no. it's not possible.
however think about using map as a parameter and passing name and value of the property:
def printSomething(Map m){
println m
}
printSomething(ordinary:58)
printSomething(extraOrdinary:67)
printSomething(ordinary:11,extraOrdinary:22)
this will output
[ordinary:58]
[extraOrdinary:67]
[ordinary:11, extraOrdinary:22]

TypeError: Cannot read property 'substring' of undefined

Written in node.js file
The function is returning the error:
Returns the ACE occupation exhibit identifier
Example of originalID: 46R-002-30BroadJour12_01-12_11
Expected output: 46R-002
/*This function is returning the error:
Cannot read property 'substring' of undefined*/
function splitID(originalID){
var aceid = originalID.substring(0,7);
return aceid;
}
//1. Get the ace exhibit occupation id for each of them and put it in a parallel array.
for (var row in values) {
//split the 5th column using our function
var output = splitID(row[4]);
var result = getOccupation(output);
//now we add the split output to our occupation array.
occupationsToInsert.append(result);
}
If you may refer to the documentation here at MDN, it advises against using for...in for looping over the arrays because it does not give consistent values on return. It rather iterates on the enumerable properties of the concerned object passed to it.
In other words, for (var row in values) would not iterate over each individual rows as expected, but rather the enumerable properties of the values list.
So, for your const array, you can find the enumerable properties by simply doing
Object.getOwnPropertyNames(values)
which would return you the following list :
["0", "length"]
You're essentially trying to access the fourth element of this array which doesn't exist, and thereby it is undefined, causing the error you observe.
The error is telling you the exact problem: originalID is undefined. In your for loop, row[4] is resulting in an undefined value. Verify your values array contains what you are expecting.

Alfresco slingshot search numberFound and totalRecords number different

I'm using Alfresco 5.0.d
I see in the search json result (with firebug console panel) that in addition to result items , 2 other properties are returned : numberFound and totalRecords. It seems that Alfresco search engine considers numberFound as total items found.
So it display "numberFound results founded" to user.
The problem is that numberFound is not equals to totalRecords.
I see that totalRecords is the correct number of search result (in fact search always return totalRecords number of items).
So i decided to see in the webscript that performs search (alfresco-remote-api-5.0.d.jar\alfresco\templates\webscripts\org\alfresco\slingshot\search\search.lib.js).
We can easly see that the numberFound property comes from this statement
var rs = search.queryResultSet(queryDef);
var numberFound = rs.meta.numberFound ;
About totalRecords property, it comes from the same statement but a little bit different:
var totalRecords = rs.nodes.length
which is the correct value of number of item really found.
So is it an Alfresco api bug?
If no , is it possible that error comes from my query parameters?
Can someone explains me what does mean the numberFound property?
Thank you.
Below is the URL of java file which is getting called when you are executing search.queryResultSet(queryDef) code.
you can refer below method in the java file.It is adding all the things.
https://svn.alfresco.com/repos/alfresco-open-mirror/alfresco/HEAD/root/projects/repository/source/java/org/alfresco/repo/jscript/Search.java
public Scriptable queryResultSet() //This is java method which is getting called.
Below is the code which is written for what you are getting in result.
meta:
{
numberFound: long, // total number found in index, or -1 if not known or not supported by this resultset
facets:
{ // facets are returned for each field as requested in the SearchParameters fieldfacets
field:
{ // each field contains a map of facet to value
facet: value,
},
}
}

What is wrong in this LINQ Query, getting compile error

I have a list AllIDs:
List<IAddress> AllIDs = new List<IAddress>();
I want to do substring operation on a member field AddressId based on a character "_".
I am using below LINQ query but getting compilation error:
AllIDs= AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_"))
.Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_")))
.ToList();
Error:
Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<MyCompany.Common.Users.IAddress>'
AllIDs is a list of IAddress but you are selecting a string. The compiler is complaining it cannot convert a List<string> to a List<IAddress>. Did you mean the following instead?
var substrings = AllIDs.Where(...).Select(...).ToList();
If you want to put them back into Address objects (assuming you have an Address class in addition to your IAddress interface), you can do something like this (assuming the constructor for Address is in place):
AllIDs = AllIDs.Where(...).Select(new Address(s.AddressID.Substring(s.AddressID.IndexOf("_")))).ToList();
You should also look at using query syntax for LINQ instead of method syntax, it can clean up and improve the readability of a lot of queries like this. Your original (unmodified) query is roughly equivalent to this:
var substrings = from a in AllIDs
let id = a.AddressId
let idx = id.IndexOf("_")
where id.Length >= idx
select id.Substring(idx);
Though this is really just a style thing, and this compiles to the same thing as the original. One slight difference is that you only have to call String.IndexOf() one per entry, instead of twice per entry. let is your friend.
Maybe this?
var boundable =
from s id in AllIDs
where s.AddressId.Length >= s.AddressId.IndexOf("_")
select new { AddressId = s.AddressId.Substring(s.AddressId.IndexOf("_")) };
boundable = boundable.ToList();

getSubmittedValue() vs. getValue()

Is that correct:
When I query a value before validation (or if validation failed) I have to use getSubmittedValue();. Once the value is validated, even if I query it in another validation later in the page/control I have to use .getValue(); since getSubmittedValue(); returns null after successful validation?
This xsnippet makes it easier to handle this. It allows you to just call getComponentValue("inputText1") to get either value or submittedValue.
Here's the function for reference:
function getComponentValue(id){
  var field = getComponent(id);
  var value = field.getSubmittedValue();
  if( null == value ){
         // else not yet submitted
         value = field.getValue();
  }
 
  return value
}
There's a slightly easier way: if you're just expecting a simple single-value String, just call:
var compare = firstField.getValueAsString();
Otherwise, call:
var compare = com.ibm.xsp.util.FacesUtil.convertValue(facesContext, firstField);
The former calls the latter anyway, but is obviously a terser syntax. This does what you're looking for and more:
If the value hasn't yet been validated, returns the submitted value
If validation has already passed, returns the value after it's already been processed by any converters and / or content filters, so particularly in cases where you're trying to compare two field values, this should ensure that both values have been properly trimmed, etc., and is therefore less likely to return a false positive than just comparing the raw submitted values.
Found the answer here. So when you want to ensure that 2 text fields have the same value (use case: please repeat your email) and the first box already has a validation that might fail, you need to use submittedValue unless it is null, then you use the value. Code in the validation expression for the second field looks like this:
var firstField = getComponent("inputText1");
var compare = firstField.getSubmittedValue() || firstField.getValue();
compare == value;
You have to love it.

Resources