Collator compare doubt

I am using the java collator compare to sort strings alphabetically.
The input strings are:
1)Google home Page
2)Yahoo Home page
3)orkut Home Page
After this the lines are circulary shifted and then sorted.
After sorting i am getting the following output.
Google home Page
home Page Google
Home Page orkut
Home page Yahoo
orkut Home Page
Page Google home
Page orkut Home
page Yahoo Home
Yahoo Home page
Shouldn't p become before P?
My understanding is that collator compare does a natural language comparator. So it should sort like a<A<b<B<c<C........z<Z
(i.e a less than A less than b less than B...)
The comparator i am using is
Collections.sort(arrayList,new Comparator() {
public int compare(Object o1, Object o2)
Collator myCollator = Collator.getInstance();
myCollator.setStrength(Collator.TERTIARY);
String str1 = (String)o1.toString();
String str2 = (String)o2.toString();
return myCollator.compare(str1,str2);
Is there anything wrong in the way I am using the comparator or is my understanding of the way collator works is wrong?
I tried setting the locale also..but no difference.
Message was edited by:
n.santhosh

Read the How Should I Compare String Objects tip for information on how a
Collator works.The statement made there that alphabetic differences are "primary" is what I
was getting at. The OP's output is exactly what you would expect from an
alphabetic ordering of strings.
But the OP wants
page Yahoo Home < Page Google Home
notwithstanding the fact that Y > G.
It looks like the wrong things are being compared. Instead of comparing
strings (sequences of letters - I realise Collator doesn't exactly do that),
phrases (sequences of strings) should be compared. Something along
the lines ofstatic int comparePhrase(List<String> phr1, List<String> phr2) {
    int sz1 = phr1.size();
    int sz2 = phr2.size();
    if(sz1 == 0 && sz2 == 0) return 0;
    if(sz1 == 0) return -1;
    if(sz2 == 0) return 1;
        // coll is a Collator instance
    int ret = coll.compare(phr1.get(0), phr2.get(0));
    if(ret != 0) return ret;
    return comparePhrase(phr1.subList(1, sz1), phr2.subList(1, sz2));
}

Similar Messages

  • Chinese Charactor sorting in List using Comparator and Collator

    I've used Collator.sort method with Locale.TRADITIONAL_CHINESE Locale to sort an ArrayList which contains a list of Chinese charactor. But it seems that the ordering is not based on stroke.
    Here is the coding for compare methods whose class implements java.util.Comparator
         public int compare(Object obj1, Object obj2){
              String string1 = (String)obj1;
              String string2 = (String)obj2;
              int compareResult = 0;
              Locale locale = locale = Locale.TRADITIONAL_CHINESE;
              Collator collator = Collator.getInstance(locale);
              compareResult = collator.compare(string1, string2);
              return compareResult;
    Could any one have exprience on it???
    Thanks,

    The resulted sequence
    "\u59cb\u6587\u65bc\u6709\u6c0f\u6f22\u7136\u7565\u7fa9\u800c\u81f3\u8a31\u8aaa\u91cd\u97f3"follows the traditional ordering of the Kangxi radicals within the limit of CJK Unified Ideographs.
    The following may be more flexible.
    import java.util.*;
    import java.io.*;
    import java.text.*;
    public class CharSort implements Comparator{
    java.text.RuleBasedCollator collator; // you can set your rules for the instance "collator"
    CharSort(){
      collator = (RuleBasedCollator)java.text.Collator.getInstance(java.util.Locale.TAIWAN);//try testing various locales
    public void doSort(String str) throws java.io.IOException{
    java.text.CollationKey[] keys = new java.text.CollationKey[str.length()];
    for(int i=0;i<keys.length;i++){
         keys[i] = collator.getCollationKey(str.substring(i,i+1));
    java.util.Arrays.sort(keys, this);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("cjk.txt"), "UTF8"));
    for(int i=0;i<keys.length;i++){
             bw.write(keys.getSourceString());
    bw.newLine();
    bw.close();
    public int compare(Object c1, Object c2) throws IllegalArgumentException{
    if((c1 instanceof CollationKey) &&(c2 instanceof CollationKey)){
    return collator.compare(((CollationKey)c1).getSourceString(), ((CollationKey)c2).getSourceString());
    }else throw new IllegalArgumentException();
    public boolean equals(Object c1, Object c2){
    if(this.compare(c1,c2)==0) return true;
    else return false;
    public static void main(String[] args) throws java.lang.Exception{
    CharSort chSort = new CharSort();
    String str = "\u81f3\u6f22\u8a31\u6c0f\u59cb\u6709\u8aaa\u6587\u7136\u91cd\u7fa9\u800c\u7565\u65bc\u97f3";
    chSort.doSort(str);

  • Sorting with Comparator, wrong order?

    Hello,
    i've a string array, and every string in this array in form of "Firstname [MiddleName] LastName". After i sort the array i get "List A" below, but i expect to get "List B". All "Alp"s must be together like dictionary order, isn't it? What cause this?
    Regards,
    List A:
    Alp BBBBB
    Alper KKKKK
    Alper SSSSSS
    Alp KKKKKKK
    Alp OOOO
    Alp ÖÖÖÖÖÖÖÖÖ
    Alptu&#287; VVVVV
    Alp YYYYY KKKKK
    Alp YYYYYYYYYY
    List B
    Alp BBBBB
    Alp KKKKKKK
    Alp OOOO
    Alp ÖÖÖÖÖÖÖÖÖ
    Alp YYYYY KKKKK
    Alp YYYYYYYYYY
    Alper KKKKK
    Alper SSSSSS
    Alptu&#287; VVVVV
    Code
    import java.text.Collator;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Locale;
    public class sort {
        static final Comparator<String> x = new Comparator<String>() {
            public int compare(String o1, String o2) {
                return Collator.getInstance(new Locale("tr", "TR")).compare(o1, o2);
        public static void main(String[] args) {
            String[] snames={
                     "Alp BBBBB",
                     "Alper KKKKK",
                     "Alper SSSSSS",
                     "Alp KKKKKKK",
                     "Alp OOOO",
                     "Alp ÖÖÖÖÖÖÖÖÖ",
                     "Alptu&#287; VVVVV",
                     "Alp YYYYY KKKKK",
                     "Alp YYYYYYYYYY"};
            List lsnames=Arrays.asList(snames);
            Collections.sort(lsnames, x);
            System.out.println(lsnames.toString().replaceAll(",", "\n"));
    }

    static final Comparator<String> x = new Comparator<String>()
            final private Collator collator = Collator.getInstance(new Locale("tr", "TR"));
            final private Pattern splitterPattern = Pattern.compile("\\s+");
            public int compare(String o1, String o2)
                try
                    final String[] fields1 = splitterPattern.split(o1, 2);
                    final String[] fields2 = splitterPattern.split(o2, 2);
                    for (int i = 0; i < 2; i++)
                        final int v = collator.compare(fields1, fields2[i]);
    if (v != 0)
    return v;
    } catch (Exception e)
    // Possibly nothing to do here but, depending on how
    // fatal one views it, one could throw
    // an unchecked exception, just print a stack
    // trace or totally ignore the exception.
    // Since this is probably a system error, my
    // preference is for
    throw new Error("Problem in comparator", e);
    return -1;
    public static void main(String[] args)
    String[] snames =
    "Alp BBBBB",
    "Alper KKKKK",
    "Alper SSSSSS",
    "Alp KKKKKKK",
    "Alp OOOO",
    "Alp ÖÖÖÖÖÖÖÖÖ",
    "Alptu&#287; VVVVV",
    "Alp YYYYY KKKKK",
    "Alp YYYYYYYYYY"
    List<String> lsnames = Arrays.asList(snames);
    Collections.sort(lsnames, x);
    System.out.println(lsnames.toString().replaceAll(",", "\n"));
    }Edited by: sabre150 on Jan 6, 2009 10:37 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Comparing time including AM and PM

    Hi,
    In my project, if a customer calls an agent,his time matches with the server time.If the calling time is between 9.00 AM to 6.00 PM the welcome message will be played.If the calling time is between 6.00 PM to 9.00 Am,the message agents logged off should be played.I tried the following.
    import java.util.*;
    import java.lang.Object;
    import java.text.Collator;
    public class CurrentTime{
      public static void main(String[] args){
        Calendar calendar = new GregorianCalendar();
        String am_pm;
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
      //  int second = calendar.get(Calendar.SECOND);
        if(calendar.get(Calendar.AM_PM) == 0)
          am_pm = "AM";
        else
          am_pm = "PM";
      String time= "Current Time : " + hour + ":" + minute + " " + am_pm;
        System.out.println(time);
        Collator myCollator = Collator.getInstance();
          if(( myCollator.compare(time, "9.00 AM") > 0 ) && (myCollator.compare(time, "6.00 PM") < 0))
                    System.out.println("welcome");
    }Here i have checked whether my time 11.49 AM > 9.00 AM and 11.49 AM < 6.00 PM.But nothing is displayed.because it is not taking the AM and PM.It is just comparing 11.49 < 6.00.How can i compare the AM and PM?please help me to solve this.
    Thanks

    myCollator.compare(time, "9.00 AM")Doesn't a Collator compare strings? "11.49 AM" < "9.00 AM" because "1" < "9". Calendars implement Comparable so compare them instead. Or use before() and after().
    Edited by: pbrockway2 on Aug 13, 2008 7:31 PM
    Edited by: pbrockway2 on Aug 13, 2008 7:35 PM
    Or get the hour and compare it to 6 or 9.

  • This is a stumper of a problem

    This is quite a specialised problem and i hope someone can help me
    I am writing a jsp web page to display information from a ldap directory. It works fine except i need to specify where the program is to search the ldap tree. When i specify no location i.e. "" the program works perfectly but when i specify a location such as i.e. "cn=Radiation,cn=Documentation" tomcat returns an error that doesnt exactly explain whats happening the main error line reads
    org.apache.jasper.JasperException: ld.Connection.getDocument(Ljava/lang/String;)Ljava/util/ArrayList;The must stumping part of this problem is that the program runs in jbuilder when i specify a location but not on tomcat, i find this strange as jbuilder runs it in tomcat to run it!!!
    The code for the jsp page is this
    <?xml version="1.0" encoding="utf-8"?>
    <?xml-stylesheet type="text/xsl" *******"?>
    <%@ page contentType="application/xml" %>
    <%@ page import="java.util.*" %>
    <%@ page import="javax.naming.*" %>
    <%@ page import="ld.*" %>
    <%@ page import="biz.osoft.escies.*" %>
    <%
    long start = System.currentTimeMillis();
    %>
    <html xml:lang="en">
    <head>
      <title>Escies Conference Documents</title>
      <identifier>*****</identifier>
      <date><%=new java.sql.Date(System.currentTimeMillis())%></date>
      <contributor>webmaster</contributor>
      <subject>Titles and description of Documents</subject>
      <description>Titles and description of Documents</description>
      <script type="text/javascript">
            function PrintAuthor(anAuthor)
                alert (anAuthor);
         function PrintDescription(aDescription)
                alert (aDescription)
         function PrintKeywords(aKeyword)
                alert (aKeyword)
      </script>
    <style type="text/css" >
    div.scroll {height: 3ex; overflow: auto;}
    </style>
    </head>
    <body>
      <h1>Documents</h1>
      <br clear="all" />
      <index>
    <%
    Connection ldap = new Connection();
    String DocumentLocation = new String("cn=Irradiation,cn=Radiation,cn=Documentation");
    ArrayList doc = ldap.getDocument(DocumentLocation);
    String ldapLocation = new String();
    String ldapLoc= new String();
    String nextLdapLocation = new String();
    String ldapPosition = new String();
    %>
    <%/*StringTokenizer st = new StringTokenizer(ldapPosition,",");
    ArrayList a = new ArrayList();
    while (st.hasMoreTokens())a.add(st.nextToken());
    Object [] backwards = a.toArray();
    int l = backwards.length;
    String forwards = "";
    for (int j = l-1; j>=0; j--){
         backwards [j] = ((String) backwards [j]).substring(3);
         forwards += backwards[j];
         if (j>0){forwards += " ";}
         }*/%>
    <%
    for (int n=0; n <  doc.size(); n++){
         LDAPDocument identifier = (LDAPDocument)doc.get(n);
            ldapLoc=identifier.getCnString();
            ldapLoc=ldapLoc.substring((ldapLoc.indexOf(",")+1));
         if(doc.size()-1>=(n+1)){
         LDAPDocument nextIdentifier = (LDAPDocument)doc.get(n+1);
            nextLdapLocation=nextIdentifier.getCnString();
            nextLdapLocation=nextLdapLocation.substring((nextLdapLocation.indexOf(",")+1));
         }else{nextLdapLocation="";}
         //ldapGroup=identifier.getCnString();
         //ldapGroup=ldapGroup.substring((ldapGroup.indexOf(",")+1),ldapGroup.indexOf(ldapPosition)-1);
         ldapPosition=ldapLoc;
         StringTokenizer st = new StringTokenizer(ldapPosition,",");
         ArrayList a = new ArrayList();
         while (st.hasMoreTokens())a.add(st.nextToken());
         Object [] backwards = a.toArray();
         int l = backwards.length;
         String forwards = "";
         for (int j = l-1; j>=0; j--){
              backwards [j] = ((String) backwards [j]).substring(3);
              forwards += backwards[j];
              if (j>0){
                   forwards += " ";
    %>
    <%if (ldapLoc.matches(ldapLocation)!=true){%>
    <group heading ="<%=forwards%>">
    <item>
      <table>
    <col width = "55%" />
    <col width = "10%" />
    <col width = "15%" />
    <col width = "15%" />
    <col width = "5%" />
        <tr>
          <th>Document Title</th>
          <th>Document Author</th>
          <th>Document Description</th>
          <th>Document Keywords</th>
          <th>Document Location</th>
        </tr>
    <%}%>
    <%ldapLocation=ldapLoc;%>
         <tr><div class="scroll">
             <td valign="top">
              <%=ldap.convertToXML(identifier.getIdentifier())%>
             </td>
             <td valign="top">
              <a href="javascript:PrintAuthor('<%=ldap.convertToXML(identifier.getAuthor())%>')">Author</a>
             </td>
             <td valign ="top">
              <a href="javascript:PrintDescription('<%=ldap.convertToXML(identifier.getDescription())%>')">Description</a>
             </td>
             <td valign ="top">
              <a href="javascript:PrintKeywords('<%=ldap.convertToXML(identifier.getKeywords())%>')">KeyWords</a>
             </td>
             <td valign = "top">
              <a href="<%=ldap.convertToXML(identifier.getLocation())%>">GO</a>
             </td>
         </div>
         </tr>
    <%if (ldapLoc.matches(nextLdapLocation)!=true){%>
    </table>
    </item>
    </group>
    <%}%>
    <%//ldapLocation=ldapLoc;%>
    <%
    %>
      </index>
    <%
    ldap.close();
    %>
    </body>
    </html>and the class that the jsp page is using is this
    package ld;
    import java.util.*;
    import java.util.ArrayList;
    import java.io.*;
    import javax.naming.*;
    import javax.naming.directory.*;
    import javax.naming.NamingException;
    public class Connection{
       public DirContext ctx = null;
       public Connection() throws javax.naming.NamingException{
       Hashtable env = new Hashtable();
       env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
       env.put(Context.PROVIDER_URL, "*********");
       env.put(Context.SECURITY_AUTHENTICATION,"simple");
       env.put(Context.SECURITY_PRINCIPAL,"*****"); // specify the username
       env.put(Context.SECURITY_CREDENTIALS,"*****");           // specify the password
       try{
         ctx = new InitialDirContext(env);
       }catch(Exception a){System.out.println(a);}
       public ArrayList getDocument() throws NamingException{
         int n=0;
         ArrayList document = new ArrayList();
         String[] attrIDs = {"cn"};
         SearchControls ctls = new SearchControls();
         ctls.setReturningAttributes(attrIDs);
         ctls.setReturningObjFlag(true);
         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
         String filter = "(documentIdentifier=*)";
         try{
           NamingEnumeration e = ctx.search("", filter, ctls);
           System.out.println("Search performed");
           document = formatResults(e);
           System.out.println("finished formatresults method");
           Collections.sort(document, new DocumentComparator());
           System.out.println("finished sorting alphabethically");
         }catch(Exception f){System.out.println("exception caught "+f);}
         for (n=0;n<document.size();n++){
            System.out.println(document.get(n));
         System.out.println("closing context");
         ctx.close();
       return document;
       public ArrayList getDocument(String argument) throws NamingException{
            int n=0;
            ArrayList document = new ArrayList();
            String[] attrIDs = {"cn"};
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(attrIDs);
            ctls.setReturningObjFlag(true);
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = "(documentIdentifier=*)";
            try{
              NamingEnumeration e = ctx.search(argument, filter, ctls);
              System.out.println("Search performed");
              document = formatResults(e ,argument);
              System.out.println("finished formatresults method");
              //Collections.sort(document, new DocumentComparator());
            }catch(Exception f){System.out.println("fault line 68 : "+f);}
            //for (n=0;n<document.size();n++){
            //   System.out.println(document.get(n));
           System.out.println("closing context");
            ctx.close();
          return document;
       public ArrayList formatResults (NamingEnumeration eneration, String argument) throws Exception{
         ArrayList document = new ArrayList();
         int n=0;
         System.out.println("Starting while loop line 81");
         try{
         while (eneration.hasMore()){
         System.out.println("line 87");
          String aVal = eneration.nextElement().toString();
          System.out.println("line 89");
          aVal = aVal.substring(0,aVal.indexOf(":"));
          System.out.println(aVal);
          aVal +=",";
          aVal +=argument;
          System.out.println(aVal);
          System.out.println("line 91");
          document.add(getIdentifier(aVal));
          System.out.println("line 93");
          System.out.println(document.size());
          for (n=0; n<document.size(); n++){
             System.out.println(document.get(n));
          }catch (NamingException e){
          e.printStackTrace();
          }System.out.println("ending while loop line 101");
          System.out.println("number of locations in document - : "+document.size());
          return document;
       public ArrayList formatResults (NamingEnumeration eneration) throws Exception{
         ArrayList document = new ArrayList();
         int n=0;
         System.out.println("Starting while loop line 81");
         try{
         while (eneration.hasMore()){
         System.out.println("line 87");
          String aVal = eneration.nextElement().toString();
          System.out.println("line 89");
          aVal = aVal.substring(0,aVal.indexOf(":"));
          System.out.println(aVal);
          System.out.println("line 91");
          document.add(getIdentifier(aVal));
          System.out.println("line 93");
          System.out.println(document.size());
          for (n=0; n<document.size(); n++){
             System.out.println(document.get(n));
          }catch (NamingException e){
          e.printStackTrace();
          }System.out.println("ending while loop line 101");
          System.out.println("number of locations in document - : "+document.size());
          return document;
       public void close() throws NamingException{
         if(ctx != null)ctx.close();
       public LDAPDocument getIdentifier(String baseDN) throws NamingException{
          String TEST = new String();
          int test = 0;
          String ldapLoc = new String();
          LDAPDocument doc = new LDAPDocument();
          System.out.println(baseDN);
          Attributes attrs = ctx.getAttributes(baseDN);
          NamingEnumeration e = attrs.getIDs();
          System.out.println("while loop starting line 125");
          while (e.hasMore()){
             try{
                String id = e.nextElement().toString();
                doc.setCnString(baseDN);
                if (id.equals("cn"))
                   doc.setName(attrs.get(id).get().toString());
                if (id.equals("documentIdentifier"))
                   doc.setIdentifier(attrs.get(id).get().toString());
                if (id.equals("description"))
                   doc.setDescription(attrs.get(id).get().toString());
                if (id.equals("documentAuthor"))
                   doc.setAuthor(attrs.get(id).get().toString());
                if (id.equals("keyWords"))
                   doc.setKeywords(attrs.get(id).get().toString());
                if (id.equals("documentLocation")) {
                   doc.setLocation(attrs.get(id).get().toString());
             }catch(Exception b){System.out.println("exception is : "+b);}
             System.out.println("while loop finished line 144");
         }return doc;
       public static String convertToXML(String s) {
        return convertToXML(s, false);
      public static String convertToXML(String s, boolean replaceLineEndings) {
        if (s != null) {
          s = s.replaceAll("&", "&");
          s = s.replaceAll("<", "<");
          s = s.replaceAll(">", ">");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          if (replaceLineEndings)
            s = s.replaceAll("\n", "<br />");
        return s;
    class DocumentComparator implements Comparator {
         java.text.Collator collator = java.text.Collator.getInstance();
         public int compare (Object d1, Object d2){
            return collator.compare(((LDAPDocument) d1).getLdapLocation(),((LDAPDocument) d2).getLdapLocation());
    }I know this is a tough problem but even if i get a post saying that someone cant see anything wrong it would help

    oh and this is the full error list given by tomcat
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: ld.Connection.getDocument(Ljava/lang/String;)Ljava/util/ArrayList;
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:248)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    root cause
    javax.servlet.ServletException: ld.Connection.getDocument(Ljava/lang/String;)Ljava/util/ArrayList;
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:533)
         at org.apache.jsp._136_jsp._jspService(_136_jsp.java:214)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:204)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    Apache Tomcat/4.1.18does this mean anything to anyone cos it means nothing to me
    cheers

  • Weblogic Portal 9.2 LDAP user listing resulting in NullPointer

    Hi,
    I have configured Weblogic Portal 9.2 to use an LDAPAuthenticator, when I use the Admin Console I can see the Novel Groups and Novel Users fine. When I select "User Management" menu item in the Admin tool where you set the Entitlements etc.. I get a null pointer exception but can see the Novel Groups fine. Is this a bug?
    The exception starts with...
    java.lang.NullPointerException
         at sun.text.UCharacterIterator.<init>(UCharacterIterator.java:46)
         at sun.text.UCharacterIterator.getInstance(UCharacterIterator.java:71)
         at sun.text.Normalizer.setText(Normalizer.java:1045)
         at java.text.CollationElementIterator.setText(CollationElementIterator.java:479)
         at java.text.RuleBasedCollator.compare(RuleBasedCollator.java:401)
         at java.text.Collator.compare(Collator.java:297)
         at java.util.Arrays.mergeSort(Arrays.java:1284)
         at java.util.Arrays.mergeSort(Arrays.java:1296)
         at java.util.Arrays.mergeSort(Arrays.java:1296)
         at java.util.Arrays.mergeSort(Arrays.java:1295)
         at java.util.Arrays.mergeSort(Arrays.java:1295)
         at java.util.Arrays.sort(Arrays.java:1223)
         at java.util.Collections.sort(Collections.java:159)
         at com.bea.p13n.usermgmt.query.UGQueryResult.reSort(UGQueryResult.java:132)
         at com.bea.p13n.usermgmt.query.UGQueryResult.<init>(UGQueryResult.java:48)
         at com.bea.p13n.usermgmt.query.internal.UserPagedResult.<init>(UserPagedResult.java:31)
         at com.bea.p13n.usermgmt.hierarchy.AtnGroupManager.queryUser(AtnGroupManager.java:231)
    The strange thing is that firstly I can see the Novel Groups but not the users, and can see both Groups and Users in the normal administration console. This tells me that the LDAPAuthenticator is connecting up correctly.

    This problem occured because the user filter entry was not filled in when putting in the ldap provider settings on the weblogic console. The portal admin console gives a null pointer when listing all users but when using the normal weblogic console it lists the Novel users alright.

  • How to determine the maximum prefix of two CharSequences efficiently?

    I have the following problem. I need a unicode friendly mechanism for determining the maximum prefix of 2 CharacterSequences. I've come up with the following code which appears to do the job, but which requires up to ([number of codepoints in smaller sequence] * 2) + 1 memory allocations. These memory allocations are rather irksome since I plan on calling this method extremely many times. The code I came up with looks like:
    private static int getLengthOfMaxCommonPrefix(CharSequence str1, CharSequence str2, Collator collator) {
        if ((str1 == null) || (str2 == null)) { return 0; }
        if (Character.codePointCount(str1, 0, str1.length()) > Character.codePointCount(str2, 0, str2.length())) {
          CharSequence tmp = str1;
          str1 = str2;
          str2 = tmp;
        // @todo get rid of memory allocation
        char[] charArray = new char[4];
        int i = 0;
        for (int size = Character.codePointCount(str1, 0, str1.length()); i < size; i++) {
          Character.toChars(Character.codePointAt(str1, i), charArray, 0);
          Character.toChars(Character.codePointAt(str2, i), charArray, 2);
           // @todo get rid of memory allocation
          String char1Str = new String(charArray, 0, 2);
          // @todo get rid of memory allocation
          String char2Str = new String(charArray, 2, 2);
          if (collator.compare(char1Str, char2Str) != 0) {
            return i;
        return i;
      }Am I overlooking an API that would allow me have this same functionality without memory allocations? If not, would it be reasonable to request that the Java Collator API be updated to have:
    Collator.compare(int codepoint1, int codepoint2)which would eliminate the need for these memory allocations. The only reason I would suggest this change is that more than a few pieces of my other code involving unicode has the same problem. Also, when looking over the API it seems that
    static Character.toString(char c)exists, but the following method doesn't:
    static Character.toString(int codepoint)which would at least minimize some of the ugliness in the above code and be in keeping with the other APIs under Character.
    Edited by: APBrusseau on Feb 10, 2008 11:23 PM
    Edited by: APBrusseau on Feb 10, 2008 11:24 PM
    Edited by: APBrusseau on Feb 10, 2008 11:29 PM
    Edited by: APBrusseau on Feb 10, 2008 11:45 PM
    Edited by: APBrusseau on Feb 10, 2008 11:46 PM
    Edited by: APBrusseau on Feb 10, 2008 11:48 PM

    But still, surely just walking character by character through the strings and comparing them (using your collator) will do?
        char[] c1 = new char[1];
        char[] c2 = new char[1];
        // swap longest/shortest string, etc.
        // for each char {
            c1[0] = cs1.charAt(n);
            c2[0] = cs2.charAt(n);
            s1 = new String(c1);
            s2 = new String(c2);
            // use collator to compare
        // }The only thing I don't know is whether there are collators which look at sequences of characters. For example, I think in Unicode, you can have an 'a' followed by a 'add an accent to the previous character' character, which would obviously impact on the collation order.
    In which case, something like
        // for n = 1 .. length of shortest {
            int result = collator.compare(cs1.subSequence(0, n).toString(), cs2.subSequence(0, n).toString());
            if (result != 0) {
                return result;
        // equal to length of shortest string. Make decision based on length.This might be efficient, or not, depending on the implementation of CharSequence. String, for example, has a very efficient subSequence() method.

  • Table Sorting: How is firstVisibleRow being affected?

    Dears,
    I'm confused at table sorting using Tablesorter.java.
    When sorting, how does Tablesorter affect the firstVisibleRow of the table?
    In the "[Working with tables|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/90ac0015-d1c5-2a10-d788-aed89990811d]" sample SDN provided, when press "sorting asending" or "sort descending", the table's first visible row changes automatically.
    I didn't understand why firstVisibleRow changed to be so. And I don't know how the firstVisibleRow will change to be.
    I checked the code of Tablesorter, and I also tried to debug into it, but didn't find any track.
    Any word is appreciated. Thanks in advance.
    Edited by: gangtee gangtee on May 2, 2008 4:59 PM

    Attached is Tablesorter.java
    package com.sap.tc.webdynpro.tests.utils;
    import java.text.Collator;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.StringTokenizer;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractDropDownByIndex;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractDropDownByKey;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractInputField;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractTableColumn;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDCaption;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDCheckBox;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDLink;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDProgressIndicator;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDRadioButton;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTable;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableCellEditor;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableColumn;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableColumnGroup;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTextEdit;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTextView;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.WDTableColumnSortDirection;
    import com.sap.tc.webdynpro.progmodel.api.IWDAction;
    import com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent;
    import com.sap.tc.webdynpro.progmodel.api.IWDNode;
    import com.sap.tc.webdynpro.progmodel.api.IWDNodeElement;
    import com.sap.tc.webdynpro.progmodel.api.IWDViewElement;
    import com.sap.tc.webdynpro.services.sal.localization.api.WDResourceHandler;
    * Helper class that makes a Web Dynpro table UI element sortable (column-wise).
    public final class TableSorter {
          * @param table
          * @param sortAction
          * @param comparators
         public TableSorter(IWDTable table, IWDAction sortAction, Map comparators) {
              init(table, sortAction, comparators, null);
         public TableSorter(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns) {
              init(table, sortAction, comparators, sortableColumns);
          * Initialisation stuff
         private void init(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns){
              this.table = table;
              if(sortableColumns == null){
                   sortableCols = null;
              }else{
                   sortableCols = new HashMap();
                   for (int i = 0; i < sortableColumns.length; i++) {
                        sortableCols.put(sortableColumns<i>, sortableColumns<i>);
              // sanity checks
              if (sortAction == null)
                   throw new IllegalArgumentException("Sort action must be given");
              if (table == null)
                   throw new IllegalArgumentException("Table must be given");
              if (table.bindingOfDataSource() == null)
                   throw new IllegalArgumentException(
                        "Data source of table with id '" + table.getId() + "' must be bound");
              // make the columns sortable
              String dataSourcePrefix = table.bindingOfDataSource() + ".";
              setComparatorsForColumns(dataSourcePrefix, table.iterateGroupedColumns(), comparators);
              //set up the table properties
              table.setOnSort(sortAction);
              table.mappingOfOnSort().addSourceMapping(IWDTable.IWDOnSort.COL, "selectedColumn");
              table.mappingOfOnSort().addSourceMapping(IWDTable.IWDOnSort.DIRECTION, "sortDirection");     
          * Try to make the given columns sortable (recusivly, if necessary)
         private void setComparatorsForColumns(String dataSourcePrefix, Iterator columnIterator, Map comparators){
              int index = 0;
              for (Iterator it = columnIterator; it.hasNext(); ++index) { // for every column: try to make it bindable
                   IWDAbstractTableColumn abstractColumn = (IWDAbstractTableColumn) it.next();
                   if(abstractColumn instanceof IWDTableColumn){
                        IWDTableColumn column = (IWDTableColumn)abstractColumn;
                        if(sortableCols == null || sortableCols.containsKey(column.getId())){
                             //try to make this column sortable
                             Comparator comparator = null;
                             if (comparators != null){
                                  comparator = (Comparator)comparators.get(column.getId());
                             NodeElementByAttributeComparator elementComparator = null;     
                             if (comparator instanceof NodeElementByAttributeComparator) {
                                  // the easy one, attribute and ordering are given
                                  elementComparator = (NodeElementByAttributeComparator)comparator;
                             } else { // attribute must be determined
                                  String bindingOfPrimaryProperty = bindingOfPrimaryProperty(column.getTableCellEditor());
                                  if (bindingOfPrimaryProperty == null || !bindingOfPrimaryProperty.startsWith(dataSourcePrefix)){
                                       //no attribute found or outside of data source
                                       column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                                       continue;
                                  String attributeName = bindingOfPrimaryProperty.substring(dataSourcePrefix.length());
                                  Collection subnodes = new ArrayList();
                                  if (attributeName.indexOf('.') >= 0){
                                       //attribute not immediately below data source
                                       String[] tokens = tokenize (attributeName, ".");
                                       for(int i=0; i<tokens.length-1; i++){
                                            subnodes.add(tokens<i>);
                                       attributeName = tokens[tokens.length-1];
                                  if(subnodes.size() == 0){
                                       elementComparator = new NodeElementByAttributeComparator(attributeName, comparator);
                                  }else{
                                       elementComparator = new NodeElementByAttributeComparator(attributeName, comparator, subnodes);
                             // set up internal data structures
                             comparatorForColumn.put(column, elementComparator);
                             //set sort state
                             column.setSortState(WDTableColumnSortDirection.NONE);
                        }else{
                             //column should not be sortable
                             column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                   }else if (abstractColumn instanceof IWDTableColumnGroup){
                        //it's just a column group -> try to bind the columns of the column group
                        IWDTableColumnGroup columnGroup = (IWDTableColumnGroup)abstractColumn;
                        setComparatorsForColumns(dataSourcePrefix, columnGroup.iterateColumns(), comparators);
          * Tokenizes the input string according to the given delimiters. The delimiters will be left out.
          * Example: tokenize("Hello_World", "_") results ["Hello", "World"]
         private String[] tokenize (String input, String delim){
              StringTokenizer tokenizer = new StringTokenizer(input, delim);
              String[] tokens = new String[tokenizer.countTokens()];
              int index = 0;
              while(tokenizer.hasMoreTokens()){
                   tokens[index] = tokenizer.nextToken();
                   index++;
              return tokens;
          * This method must be called from the event handler of this table sorter's
          * sort action. It performs the actual sort operation.
         public void sort(IWDCustomEvent wdEvent, IWDNode dataSource) {
              // find the things we need
              String columnId = wdEvent.getString("selectedColumn");
              String direction = wdEvent.getString("sortDirection");
              IWDTableColumn column = (IWDTableColumn) table.getView().getElement(columnId);
              NodeElementByAttributeComparator elementComparator = (NodeElementByAttributeComparator) comparatorForColumn.get(column);
              if (elementComparator == null){
                   //not a sortable column
                   column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                   return;
              // sorting
              elementComparator.setSortDirection(WDTableColumnSortDirection.valueOf(direction));
              dataSource.sortElements(elementComparator);
          * Returns the binding of the given table cell editor's property that is
          * considered "primary" or <code>null</code> if no such binding exists or no
          * such property can be determined.
         private static final String bindingOfPrimaryProperty(IWDTableCellEditor editor) {
              return editor instanceof IWDViewElement ? bindingOfPrimaryProperty((IWDViewElement) editor) : null;
          * Returns the binding of the given view element's property that is
          * considered "primary" or <code>null</code> if no such binding exists or no
          * such property can be determined.
         private static final String bindingOfPrimaryProperty(IWDViewElement element) {
              if (element instanceof IWDAbstractDropDownByIndex)
                   return ((IWDAbstractDropDownByIndex) element).bindingOfTexts();
              if (element instanceof IWDAbstractDropDownByKey)
                   return ((IWDAbstractDropDownByKey) element).bindingOfSelectedKey();
              if (element instanceof IWDAbstractInputField)
                   return ((IWDAbstractInputField) element).bindingOfValue();
              if (element instanceof IWDCaption)
                   return ((IWDCaption) element).bindingOfText();
              if (element instanceof IWDCheckBox)
                   return ((IWDCheckBox) element).bindingOfChecked();
              if (element instanceof IWDLink)
                   return ((IWDLink) element).bindingOfText();
              if (element instanceof IWDProgressIndicator)
                   return ((IWDProgressIndicator) element).bindingOfPercentValue();
              if (element instanceof IWDRadioButton)
                   return ((IWDRadioButton) element).bindingOfSelectedKey();
              if (element instanceof IWDTextEdit)
                   return ((IWDTextEdit) element).bindingOfValue();
              if (element instanceof IWDTextView)
                   return ((IWDTextView) element).bindingOfText();
              return null;
          * Instance of a comparator according to the ordering imposed by the
          * implementation of <code>Comparable</code>.
         private static final Comparator DEFAULT = new Comparator() {
               * Compares the given objects according to the ordering imposed by the first
               * ones <code>compareTo(Object)</code> function. Furthermore, <code>null</code>
               * is treated to be less than any object.
               * @see java.lang.Comparable#compareTo(java.lang.Object)
               * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
              public int compare(Object o1, Object o2) {
                   if (o1 == null && o2 == null)
                        return 0;
                   if (o1 == null)
                        return -1;
                   if (o2 == null)
                        return +1;
                   if (o1 instanceof Boolean && o2 instanceof Boolean)
                        return o1.toString().compareTo(o2.toString()); // false < true
                   if (o1 instanceof String && o2 instanceof String){
                        //Use a Collator for sorting according to the given Locale
                        Collator collate = Collator.getInstance(WDResourceHandler.getCurrentSessionLocale());
                        return collate.compare(o1, o2);                    
                   return ((Comparable) o1).compareTo((Comparable) o2);
          * Map of table column to comparator (<code>ReversableComparator</code>)
          * used for sorting that column (sortable columns only).
         private Map comparatorForColumn = new HashMap();
          * The table to be sorted.
         private IWDTable table = null;
          * Column-IDs of the columns, which should be sortable
         private Map sortableCols = null;
          * Generic comparator that compares node elements by a given attribute with
          * the help of a given comparator.
         public final class NodeElementByAttributeComparator implements Comparator {
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute according to the natural ordering of that attribute's
               * type (which must implement <code>java.lang.Comparable</code>).
              public NodeElementByAttributeComparator(String attributeName) {
                   this(attributeName, null, false, new ArrayList());
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute with the help of the given comparator. If no comparator
               * is given, the natural ordering of that attribute's type is used.
              public NodeElementByAttributeComparator(String attributeName, Comparator comparator) {
                   this(attributeName, comparator, false, new ArrayList());
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute either as objects (i.e. "in internal format") or as text
               * (i.e. "in external format") as indicated. The ordering is the natural
               * ordering of that attribute's type (which must implement
               * <code>java.lang.Comparable</code>) in case objects are compared or the
               * natural ordering of <code>java.lang.String</code> in case texts are compared.
              public NodeElementByAttributeComparator(String attributeName, boolean compareAsText) {
                   this(attributeName, null, compareAsText, new ArrayList());
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute according to the natural ordering of that attribute's
               * type (which must implement <code>java.lang.Comparable</code>). In addition it is possible
               * to define the path to a child node with the <code>java.util.Collection</code> subnodes.
               * (List of child node names in the correct order)
              public NodeElementByAttributeComparator(String attributeName, Collection subnodes) {
                   this(attributeName, null, false, subnodes);
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute with the help of the given comparator. If no comparator
               * is given, the natural ordering of that attribute's type is used. In addition it is possible
               * to define the path to a child node with the <code>java.util.Collection</code> subnodes.
               * (List of child node names in the correct order)
              public NodeElementByAttributeComparator(String attributeName, Comparator comparator, Collection subnodes) {
                   this(attributeName, comparator, false, subnodes);
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute either as objects (i.e. "in internal format") or as text
               * (i.e. "in external format") as indicated. The ordering is the natural
               * ordering of that attribute's type (which must implement
               * <code>java.lang.Comparable</code>) in case objects are compared or the
               * natural ordering of <code>java.lang.String</code> in case texts are compared. In addition it is possible
               * to define the path to a child node with the <code>java.util.Collection</code> subnodes.
               * (List of child node names in the correct order)
              public NodeElementByAttributeComparator(String attributeName, boolean compareAsText, Collection subnodes) {
                   this(attributeName, null, compareAsText, subnodes);
               * Internal constructor.
              private NodeElementByAttributeComparator(
                   String attributeName,
                   Comparator comparator,
                   boolean compareAsText,
                   Collection subNodes) {
                   if (attributeName == null)
                        throw new IllegalArgumentException("Attribute name must not be null");
                   if (comparator == null)
                        comparator = DEFAULT;
                   this.attributeName = attributeName;
                   this.comparator = comparator;
                   this.compareAsText = compareAsText;
                   this.sortDirection = true;
                   this.subNodes = subNodes;
               * Sets the sort direction of this comparator to the given direction. The comparator sort in ascending order by default.
               * @see com.sap.tc.webdynpro.clientserver.uielib.standard.api.WDTableColumnSortDirection
              public void setSortDirection(WDTableColumnSortDirection direction){
                   if(direction.equals(WDTableColumnSortDirection.UP)){
                        sortDirection = true;
                   }else if(direction.equals(WDTableColumnSortDirection.DOWN)){
                        sortDirection = false;
               * Compares the given objects which must be instances of <code>IWDNodeElement</code>
               * according to the values of the attribute given at construction time
               * with the help of the comparator given at construction time.
               * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
               * @see com.sap.tc.webdynpro.progmodel.api.IWDNodeElement
              public int compare(Object o1, Object o2) {
                   IWDNodeElement element1 = (IWDNodeElement) o1;
                   IWDNodeElement element2 = (IWDNodeElement) o2;
                   if(subNodes.size() > 0){
                        element1 = getSubNodeElement(element1, 0);
                        element2 = getSubNodeElement(element2, 0);
                   Object attributeValue1 = null;
                   Object attributeValue2 = null;
                   if(element1 != null){
                        attributeValue1 =
                             compareAsText
                                  ? element1.getAttributeAsText(attributeName)
                                  : element1.getAttributeValue(attributeName);
                   if(element2 != null){
                        attributeValue2 =
                             compareAsText
                                  ? element2.getAttributeAsText(attributeName)
                                  : element2.getAttributeValue(attributeName);
                   if(sortDirection){
                        return comparator.compare(attributeValue1, attributeValue2);
                   }else{
                        return comparator.compare(attributeValue2, attributeValue1);
               * Determines recursivly the child node, which have an attribute with the given name.
               * The path to this child node must be specified in the subnodes property of this comparator.
               * Start this method with index = 0.
              private IWDNodeElement getSubNodeElement(IWDNodeElement currentElement, int index){
                   if(currentElement == null || index >= subNodes.size()){
                        //end of recursion
                        return currentElement;
                   }else{
                        return getSubNodeElement(currentElement.node().getChildNode((String)subNodes.toArray()[index], currentElement.index()).getCurrentElement(), index+1);
                        //return getSubNodeElement(currentElement.node().getChildNode((String)subNodes.toArray()[index], currentElement.index()).getElementAt(0), index+1);
               * Name of the attribute used for comparisons.
              private final String attributeName;
               * Comparator used for comparing the attribute's values.
              private final Comparator comparator;
               * Indicates whether attribute values are compared as text (as opposed to
               * "as objects").
              private final boolean compareAsText;
               * Sort direction (true = ascending order, false = descending order)
              private boolean sortDirection;
               * List of child node names
               * (Description of the path from the given context node to the specified attribute)
              private Collection subNodes;

  • Table sorter

    Hi,
         i have to implement a table sorter in one of my webdypro application. I have done all the steps mentioned in one of the blog and have also imported TableSorter.java class. i am getting sorting icons in column headers. but on clicking icon nothing happens...i think there is some problem with the java class which i have imported. So can anybody provide the code of tablesorter.java class.
    Thanks in advance,
        Reena

    Hi Reena,
    Here is the code.Just change the package name.
    * Created on Sep 6, 2007
    * To change the template for this generated file go to
    * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
    package ibm.com.tradefund.utils;
    * @author Administrator
    * To change the template for this generated type comment go to
    * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
    import java.text.Collator;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.StringTokenizer;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractDropDownByIndex;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractDropDownByKey;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractInputField;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractTableColumn;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDCaption;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDCheckBox;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDLink;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDProgressIndicator;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDRadioButton;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTable;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableCellEditor;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableColumn;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableColumnGroup;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTextEdit;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTextView;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.WDTableColumnSortDirection;
    import com.sap.tc.webdynpro.progmodel.api.IWDAction;
    import com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent;
    import com.sap.tc.webdynpro.progmodel.api.IWDNode;
    import com.sap.tc.webdynpro.progmodel.api.IWDNodeElement;
    import com.sap.tc.webdynpro.progmodel.api.IWDViewElement;
    import com.sap.tc.webdynpro.services.sal.localization.api.WDResourceHandler;
    * Helper class that makes a Web Dynpro table UI element sortable (column-wise).
    public final class TableSorter {
          * @param table
          * @param sortAction
          * @param comparators
          * Creates a table sorter for the given table using the given sort action.
          * This constructor must be called from <code>wdDoModifyView()</code>, but
          * usually only when that hook is called for the first time. Store the newly
          * created instance in a context attribute with Java native type
          * <code>com.sap.tc.webdynpro.tests.utils.TableSorter</code>.
          * The given sort action's event handler will be bound to the <code>onSort</code>
          * event of the table and must at least call this table sorter's
          * <code>sort(wdEvent)</code> method.
          * Every column of the table is made sortable if possible according to the
          * following rules.
          * If a comparator is given for a column's ID and it is a
          * <code>NodeElementByAttributeComparator</code>, then that comparator defines
          * both the attribute and the ordering used to sort that column.
          * If any other comparator is given and an attribute can be determined from
          * that column's table cell editor, then that attribute is used to sort that
          * column according to the ordering imposed by the given comparator.
          * If no comparator is given but an attribute can be determined from
          * that column's table cell editor, then that attribute is used to sort that
          * column according to the natural ordering of that attribute's type.
          * Else that column is left untouched.
          * Additionally it is possible to define the sortable columns by their
          * TableColumn UI element ids.
          * @see sort()
          * @see NodeElementByAttributeComparator
          * @see com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTable
         public TableSorter(IWDTable table, IWDAction sortAction, Map comparators) {
              init(table, sortAction, comparators, null);
         public TableSorter(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns) {
              init(table, sortAction, comparators, sortableColumns);
          * Initialisation stuff
         private void init(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns){
              this.table = table;
              if(sortableColumns == null){
                   sortableCols = null;
              }else{
                   sortableCols = new HashMap();
                   for (int i = 0; i < sortableColumns.length; i++) {
                        sortableCols.put(sortableColumns<i>, sortableColumns<i>);
              // sanity checks
              if (sortAction == null)
                   throw new IllegalArgumentException("Sort action must be given");
              if (table == null)
                   throw new IllegalArgumentException("Table must be given");
              if (table.bindingOfDataSource() == null)
                   throw new IllegalArgumentException(
                        "Data source of table with id '" + table.getId() + "' must be bound");
              // make the columns sortable
              String dataSourcePrefix = table.bindingOfDataSource() + ".";
              //TODO: remove the following line since this method is not longer available in later releases
              setComparatorsForColumns(dataSourcePrefix, table.iterateColumns(), comparators);
              setComparatorsForColumns(dataSourcePrefix, table.iterateGroupedColumns(), comparators);
              //set up the table properties
              table.setOnSort(sortAction);
              table.mappingOfOnSort().addSourceMapping(IWDTable.IWDOnSort.COL, "selectedColumn");
              table.mappingOfOnSort().addSourceMapping(IWDTable.IWDOnSort.DIRECTION, "sortDirection");     
          * Try to make the given columns sortable (recusivly, if necessary)
         private void setComparatorsForColumns(String dataSourcePrefix, Iterator columnIterator, Map comparators){
              int index = 0;
              for (Iterator it = columnIterator; it.hasNext(); ++index) { // for every column: try to make it bindable
                   IWDAbstractTableColumn abstractColumn = (IWDAbstractTableColumn) it.next();
                   if(abstractColumn instanceof IWDTableColumn){
                        IWDTableColumn column = (IWDTableColumn)abstractColumn;
                        if(sortableCols == null || sortableCols.containsKey(column.getId())){
                             //try to make this column sortable
                             Comparator comparator = null;
                             if (comparators != null){
                                  comparator = (Comparator)comparators.get(column.getId());
                             NodeElementByAttributeComparator elementComparator = null;     
                             if (comparator instanceof NodeElementByAttributeComparator) {
                                  // the easy one, attribute and ordering are given
                                  elementComparator = (NodeElementByAttributeComparator)comparator;
                             } else { // attribute must be determined
                                  String bindingOfPrimaryProperty = bindingOfPrimaryProperty(column.getTableCellEditor());
                                  if (bindingOfPrimaryProperty == null || !bindingOfPrimaryProperty.startsWith(dataSourcePrefix)){
                                       //no attribute found or outside of data source
                                       column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                                       continue;
                                  String attributeName = bindingOfPrimaryProperty.substring(dataSourcePrefix.length());
                                  Collection subnodes = new ArrayList();
                                  if (attributeName.indexOf('.') >= 0){
                                       //attribute not immediately below data source
                                       String[] tokens = tokenize (attributeName, ".");
                                       for(int i=0; i<tokens.length-1; i++){
                                            subnodes.add(tokens<i>);
                                       attributeName = tokens[tokens.length-1];
                                  if(subnodes.size() == 0){
                                       elementComparator = new NodeElementByAttributeComparator(attributeName, comparator);
                                  }else{
                                       elementComparator = new NodeElementByAttributeComparator(attributeName, comparator, subnodes);
                             // set up internal data structures
                             comparatorForColumn.put(column, elementComparator);
                             //set sort state
                             column.setSortState(WDTableColumnSortDirection.NONE);
                        }else{
                             //column should not be sortable
                             column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                   }else if (abstractColumn instanceof IWDTableColumnGroup){
                        //it's just a column group -> try to bind the columns of the column group
                        IWDTableColumnGroup columnGroup = (IWDTableColumnGroup)abstractColumn;
                        setComparatorsForColumns(dataSourcePrefix, columnGroup.iterateColumns(), comparators);
          * Tokenizes the input string according to the given delimiters. The delimiters will be left out.
          * Example: tokenize("Hello_World", "_") results ["Hello", "World"]
         private String[] tokenize (String input, String delim){
              StringTokenizer tokenizer = new StringTokenizer(input, delim);
              String[] tokens = new String[tokenizer.countTokens()];
              int index = 0;
              while(tokenizer.hasMoreTokens()){
                   tokens[index] = tokenizer.nextToken();
                   index++;
              return tokens;
          * This method must be called from the event handler of this table sorter's
          * sort action. It performs the actual sort operation.
         public void sort(IWDCustomEvent wdEvent, IWDNode dataSource) {
              // find the things we need
              String columnId = wdEvent.getString("selectedColumn");
              String direction = wdEvent.getString("sortDirection");
              IWDTableColumn column = (IWDTableColumn) table.getView().getElement(columnId);
              NodeElementByAttributeComparator elementComparator = (NodeElementByAttributeComparator) comparatorForColumn.get(column);
              if (elementComparator == null){
                   //not a sortable column
                   column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                   return;
              // sorting
              elementComparator.setSortDirection(WDTableColumnSortDirection.valueOf(direction));
              dataSource.sortElements(elementComparator);
          * Returns the binding of the given table cell editor's property that is
          * considered "primary" or <code>null</code> if no such binding exists or no
          * such property can be determined.
         private static final String bindingOfPrimaryProperty(IWDTableCellEditor editor) {
              return editor instanceof IWDViewElement ? bindingOfPrimaryProperty((IWDViewElement) editor) : null;
          * Returns the binding of the given view element's property that is
          * considered "primary" or <code>null</code> if no such binding exists or no
          * such property can be determined.
         private static final String bindingOfPrimaryProperty(IWDViewElement element) {
              if (element instanceof IWDAbstractDropDownByIndex)
                   return ((IWDAbstractDropDownByIndex) element).bindingOfTexts();
              if (element instanceof IWDAbstractDropDownByKey)
                   return ((IWDAbstractDropDownByKey) element).bindingOfSelectedKey();
              if (element instanceof IWDAbstractInputField)
                   return ((IWDAbstractInputField) element).bindingOfValue();
              if (element instanceof IWDCaption)
                   return ((IWDCaption) element).bindingOfText();
              if (element instanceof IWDCheckBox)
                   return ((IWDCheckBox) element).bindingOfChecked();
              if (element instanceof IWDLink)
                   return ((IWDLink) element).bindingOfText();
              if (element instanceof IWDProgressIndicator)
                   return ((IWDProgressIndicator) element).bindingOfPercentValue();
              if (element instanceof IWDRadioButton)
                   return ((IWDRadioButton) element).bindingOfSelectedKey();
              if (element instanceof IWDTextEdit)
                   return ((IWDTextEdit) element).bindingOfValue();
              if (element instanceof IWDTextView)
                   return ((IWDTextView) element).bindingOfText();
              return null;
          * Instance of a comparator according to the ordering imposed by the
          * implementation of <code>Comparable</code>.
         private static final Comparator DEFAULT = new Comparator() {
               * Compares the given objects according to the ordering imposed by the first
               * ones <code>compareTo(Object)</code> function. Furthermore, <code>null</code>
               * is treated to be less than any object.
               * @see java.lang.Comparable#compareTo(java.lang.Object)
               * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
              public int compare(Object o1, Object o2) {
                   if (o1 == null && o2 == null)
                        return 0;
                   if (o1 == null)
                        return -1;
                   if (o2 == null)
                        return +1;
                   if (o1 instanceof Boolean && o2 instanceof Boolean)
                        return o1.toString().compareTo(o2.toString()); // false < true
                   if (o1 instanceof String && o2 instanceof String){
                        //Use a Collator for sorting according to the given Locale
                        Collator collate = Collator.getInstance(WDResourceHandler.getCurrentSessionLocale());
                        return collate.compare(o1, o2);                    
                   return ((Comparable) o1).compareTo((Comparable) o2);
          * Map of table column to comparator (<code>ReversableComparator</code>)
          * used for sorting that column (sortable columns only).
         private Map comparatorForColumn = new HashMap();
          * The table to be sorted.
         private IWDTable table = null;
          * Column-IDs of the columns, which should be sortable
         private Map sortableCols = null;
          * Generic comparator that compares node elements by a given attribute with
          * the help of a given comparator.
         public final class NodeElementByAttributeComparator implements Comparator {
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute according to the natural ordering of that attribute's
               * type (which must implement <code>java.lang.Comparable</code>).
              public NodeElementByAttributeComparator(String attributeName) {
                   this(attributeName, null, false, new ArrayList());
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute with the help of the given comparator. If no comparator
               * is given, the natural ordering of that attribute's type is used.
              public NodeElementByAttributeComparator(String attributeName, Comparator comparator) {
                   this(attributeName, comparator, false, new ArrayList());
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute either as objects (i.e. "in internal format") or as text
               * (i.e. "in external format") as indicated. The ordering is the natural
               * ordering of that attribute's type (which must implement
               * <code>java.lang.Comparable</code>) in case objects are compared or the
               * natural ordering of <code>java.lang.String</code> in case texts are compared.
              public NodeElementByAttributeComparator(String attributeName, boolean compareAsText) {
                   this(attributeName, null, compareAsText, new ArrayList());
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute according to the natural ordering of that attribute's
               * type (which must implement <code>java.lang.Comparable</code>). In addition it is possible
               * to define the path to a child node with the <code>java.util.Collection</code> subnodes.
               * (List of child node names in the correct order)
              public NodeElementByAttributeComparator(String attributeName, Collection subnodes) {
                   this(attributeName, null, false, subnodes);
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute with the help of the given comparator. If no comparator
               * is given, the natural ordering of that attribute's type is used. In addition it is possible
               * to define the path to a child node with the <code>java.util.Collection</code> subnodes.
               * (List of child node names in the correct order)
              public NodeElementByAttributeComparator(String attributeName, Comparator comparator, Collection subnodes) {
                   this(attributeName, comparator, false, subnodes);
               * Creates a new comparator for the given attribute name that compares values
               * of that attribute either as objects (i.e. "in internal format") or as text
               * (i.e. "in external format") as indicated. The ordering is the natural
               * ordering of that attribute's type (which must implement
               * <code>java.lang.Comparable</code>) in case objects are compared or the
               * natural ordering of <code>java.lang.String</code> in case texts are compared. In addition it is possible
               * to define the path to a child node with the <code>java.util.Collection</code> subnodes.
               * (List of child node names in the correct order)
              public NodeElementByAttributeComparator(String attributeName, boolean compareAsText, Collection subnodes) {
                   this(attributeName, null, compareAsText, subnodes);
               * Internal constructor.
              private NodeElementByAttributeComparator(
                   String attributeName,
                   Comparator comparator,
                   boolean compareAsText,
                   Collection subNodes) {
                   if (attributeName == null)
                        throw new IllegalArgumentException("Attribute name must not be null");
                   if (comparator == null)
                        comparator = DEFAULT;
                   this.attributeName = attributeName;
                   this.comparator = comparator;
                   this.compareAsText = compareAsText;
                   this.sortDirection = true;
                   this.subNodes = subNodes;
               * Sets the sort direction of this comparator to the given direction. The comparator sort in ascending order by default.
               * @see com.sap.tc.webdynpro.clientserver.uielib.standard.api.WDTableColumnSortDirection
              public void setSortDirection(WDTableColumnSortDirection direction){
                   if(direction.equals(WDTableColumnSortDirection.UP)){
                        sortDirection = true;
                   }else if(direction.equals(WDTableColumnSortDirection.DOWN)){
                        sortDirection = false;
               * Compares the given objects which must be instances of <code>IWDNodeElement</code>
               * according to the values of the attribute given at construction time
               * with the help of the comparator given at construction time.
               * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
               * @see com.sap.tc.webdynpro.progmodel.api.IWDNodeElement
              public int compare(Object o1, Object o2) {
                   IWDNodeElement element1 = (IWDNodeElement) o1;
                   IWDNodeElement element2 = (IWDNodeElement) o2;
                   if(subNodes.size() > 0){
                        element1 = getSubNodeElement(element1, 0);
                        element2 = getSubNodeElement(element2, 0);
                   Object attributeValue1 = null;
                   Object attributeValue2 = null;
                   if(element1 != null){
                        attributeValue1 =
                             compareAsText
                                  ? element1.getAttributeAsText(attributeName)
                                  : element1.getAttributeValue(attributeName);
                   if(element2 != null){
                        attributeValue2 =
                             compareAsText
                                  ? element2.getAttributeAsText(attributeName)
                                  : element2.getAttributeValue(attributeName);
                   if(sortDirection){
                        return comparator.compare(attributeValue1, attributeValue2);
                   }else{
                        return comparator.compare(attributeValue2, attributeValue1);
               * Determines recursivly the child node, which have an attribute with the given name.
               * The path to this child node must be specified in the subnodes property of this comparator.
               * Start this method with index = 0.
              private IWDNodeElement getSubNodeElement(IWDNodeElement currentElement, int index){
                   if(currentElement == null || index >= subNodes.size()){
                        //end of recursion
                        return currentElement;
                   }else{
                        return getSubNodeElement(currentElement.node().getChildNode((String)subNodes.toArray()[index], currentElement.index()).getCurrentElement(), index+1);
                        //return getSubNodeElement(currentElement.node().getChildNode((String)subNodes.toArray()[index], currentElement.index()).getElementAt(0), index+1);
               * Name of the attribute used for comparisons.
              private final String attributeName;
               * Comparator used for comparing the attribute's values.
              private final Comparator comparator;
               * Indicates whether attribute values are compared as text (as opposed to
               * "as objects").
              private final boolean compareAsText;
               * Sort direction (true = ascending order, false = descending order)
              private boolean sortDirection;
               * List of child node names
               * (Description of the path from the given context node to the specified attribute)
              private Collection subNodes;
    Re: Webdynpro Table: Column Header sort icon not visible
    Regards,
    Mithu

  • Alphanumeric Sorting

    Hi..
    I need to sort projects in an internal table.
    project(PROJ-PSPID).
    Suppose that in one internal table t_proj we have three entries
    EC-000293-A8
    EC-000293-A17
    EC-000293-A15
    Afther sorting ascending the ouput will be
    SORT t_proj Ascending.
    EC-000293-A15
    EC-000293-A17
    EC-000293-A8
    But my required output shoud be
    EC-000293-A8
    EC-000293-A15
    EC-000293-A17
    Can anyone pls help me in sorting like this
    Thanks in Advance
    Edited by: Sheeba Bhaskaran on Jan 9, 2008 12:15 PM
    Edited by: Sheeba Bhaskaran on Jan 9, 2008 12:16 PM

    Hi Sheeba,
    TableSorter.java code is here.
    create a java file in ur WD project in ur pacakages folder. let it be in subfolde 'com' of ur project's packages folder.
    then code is
    code
    package com;
    import java.sql.Date;
    import java.text.Collator;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.StringTokenizer;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractDropDownByIndex;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractDropDownByKey;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractInputField;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDAbstractTableColumn;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDCaption;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDCheckBox;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDLink;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDProgressIndicator;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDRadioButton;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTable;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableCellEditor;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableColumn;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTableColumnGroup;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTextEdit;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTextView;
    import com.sap.tc.webdynpro.clientserver.uielib.standard.api.WDTableColumnSortDirection;
    import com.sap.tc.webdynpro.progmodel.api.IWDAction;
    import com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent;
    import com.sap.tc.webdynpro.progmodel.api.IWDNode;
    import com.sap.tc.webdynpro.progmodel.api.IWDNodeElement;
    import com.sap.tc.webdynpro.progmodel.api.IWDViewElement;
    import com.sap.tc.webdynpro.services.sal.localization.api.WDResourceHandler;
    Helper class that makes a Web Dynpro table UI element sortable (column-wise).
    public final class TableSorter {
    @param table
    @param sortAction
    @param comparators
    Creates a table sorter for the given table using the given sort action.
    This constructor must be called from <code>wdDoModifyView()</code>, but
    usually only when that hook is called for the first time. Store the newly
    created instance in a context attribute with Java native type
    <code>com.sap.tc.webdynpro.tests.utils.TableSorter</code>.
    The given sort action's event handler will be bound to the <code>onSort</code>
    event of the table and must at least call this table sorter's
    <code>sort(wdEvent)</code> method.
    Every column of the table is made sortable if possible according to the
    following rules.
    If a comparator is given for a column's ID and it is a
    <code>NodeElementByAttributeComparator</code>, then that comparator defines
    both the attribute and the ordering used to sort that column.
    If any other comparator is given and an attribute can be determined from
    that column's table cell editor, then that attribute is used to sort that
    column according to the ordering imposed by the given comparator.
    If no comparator is given but an attribute can be determined from
    that column's table cell editor, then that attribute is used to sort that
    column according to the natural ordering of that attribute's type.
    Else that column is left untouched.
    Additionally it is possible to define the sortable columns by their
    TableColumn UI element ids.
    @see sort()
    @see NodeElementByAttributeComparator
    @see com.sap.tc.webdynpro.clientserver.uielib.standard.api.IWDTable
    public TableSorter(IWDTable table, IWDAction sortAction, Map comparators) {
    init(table, sortAction, comparators, null);
    public TableSorter(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns) {
    init(table, sortAction, comparators, sortableColumns);
    Initialisation stuff
    private void init(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns){
    this.table = table;
    if(sortableColumns == null){
    sortableCols = null;
    }else{
    sortableCols = new HashMap();
    for (int i = 0; i < sortableColumns.length; i++) {
    sortableCols.put(sortableColumns, sortableColumns);
    // sanity checks
    if (sortAction == null)
    throw new IllegalArgumentException("Sort action must be given");
    if (table == null)
    throw new IllegalArgumentException("Table must be given");
    if (table.bindingOfDataSource() == null)
    throw new IllegalArgumentException(
    "Data source of table with id '" + table.getId() + "' must be bound");
    // make the columns sortable
    String dataSourcePrefix = table.bindingOfDataSource() + ".";
    //TODO: remove the following line since this method is not longer available in later releases
    setComparatorsForColumns(dataSourcePrefix, table.iterateColumns(), comparators);
    setComparatorsForColumns(dataSourcePrefix, table.iterateGroupedColumns(), comparators);
    //set up the table properties
    table.setOnSort(sortAction);
    table.mappingOfOnSort().addSourceMapping(IWDTable.IWDOnSort.COL, "selectedColumn");
    table.mappingOfOnSort().addSourceMapping(IWDTable.IWDOnSort.DIRECTION, "sortDirection");
    Try to make the given columns sortable (recusivly, if necessary)
    private void setComparatorsForColumns(String dataSourcePrefix, Iterator columnIterator, Map comparators){
    int index = 0;
    for (Iterator it = columnIterator; it.hasNext(); ++index) { // for every column: try to make it bindable
    IWDAbstractTableColumn abstractColumn = (IWDAbstractTableColumn) it.next();
    if(abstractColumn instanceof IWDTableColumn){
    IWDTableColumn column = (IWDTableColumn)abstractColumn;
    if(sortableCols == null || sortableCols.containsKey(column.getId())){
    //try to make this column sortable
    Comparator comparator = null;
    if (comparators != null){
    comparator = (Comparator)comparators.get(column.getId());
    NodeElementByAttributeComparator elementComparator = null;
    if (comparator instanceof NodeElementByAttributeComparator) {
    // the easy one, attribute and ordering are given
    elementComparator = (NodeElementByAttributeComparator)comparator;
    } else { // attribute must be determined
    String bindingOfPrimaryProperty = bindingOfPrimaryProperty(column.getTableCellEditor());
    if (bindingOfPrimaryProperty == null || !bindingOfPrimaryProperty.startsWith(dataSourcePrefix)){
    //no attribute found or outside of data source
    column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
    continue;
    String attributeName = bindingOfPrimaryProperty.substring(dataSourcePrefix.length());
    Collection subnodes = new ArrayList();
    if (attributeName.indexOf('.') >= 0){
    //attribute not immediately below data source
    String[] tokens = tokenize (attributeName, ".");
    for(int i=0; i<tokens.length-1; i++){
    subnodes.add(tokens);
    attributeName = tokenshttp://tokens.length-1;
    if(subnodes.size() == 0){
    elementComparator = new NodeElementByAttributeComparator(attributeName, comparator);
    }else{
    elementComparator = new NodeElementByAttributeComparator(attributeName, comparator, subnodes);
    // set up internal data structures
    comparatorForColumn.put(column, elementComparator);
    //set sort state
    column.setSortState(WDTableColumnSortDirection.NONE);
    }else{
    //column should not be sortable
    column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
    }else if (abstractColumn instanceof IWDTableColumnGroup){
    //it's just a column group -> try to bind the columns of the column group
    IWDTableColumnGroup columnGroup = (IWDTableColumnGroup)abstractColumn;
    setComparatorsForColumns(dataSourcePrefix, columnGroup.iterateColumns(), comparators);
    Tokenizes the input string according to the given delimiters. The delimiters will be left out.
    Example: tokenize("Hello_World", "_") results \"Hello\", \"World\"
    private String[] tokenize (String input, String delim){
    StringTokenizer tokenizer = new StringTokenizer(input, delim);
    String[] tokens = new Stringhttp://tokenizer.countTokens();
    int index = 0;
    while(tokenizer.hasMoreTokens()){
    tokensindex = tokenizer.nextToken();
    index++;
    return tokens;
    This method must be called from the event handler of this table sorter's
    sort action. It performs the actual sort operation.
    public void sort(IWDCustomEvent wdEvent, IWDNode dataSource) {
    // find the things we need
    String columnId = wdEvent.getString("selectedColumn");
    String direction = wdEvent.getString("sortDirection");
    IWDTableColumn column = (IWDTableColumn) table.getView().getElement(columnId);
    NodeElementByAttributeComparator elementComparator = (NodeElementByAttributeComparator) comparatorForColumn.get(column);
    if (elementComparator == null){
    //not a sortable column
    column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
    return;
    // sorting
    elementComparator.setSortDirection(WDTableColumnSortDirection.valueOf(direction));
    dataSource.sortElements(elementComparator);
    Returns the binding of the given table cell editor's property that is
    considered "primary" or <code>null</code> if no such binding exists or no
    such property can be determined.
    private static final String bindingOfPrimaryProperty(IWDTableCellEditor editor) {
    return editor instanceof IWDViewElement ? bindingOfPrimaryProperty((IWDViewElement) editor) : null;
    Returns the binding of the given view element's property that is
    considered "primary" or <code>null</code> if no such binding exists or no
    such property can be determined.
    private static final String bindingOfPrimaryProperty(IWDViewElement element) {
    if (element instanceof IWDAbstractDropDownByIndex)
    return ((IWDAbstractDropDownByIndex) element).bindingOfTexts();
    if (element instanceof IWDAbstractDropDownByKey)
    return ((IWDAbstractDropDownByKey) element).bindingOfSelectedKey();
    if (element instanceof IWDAbstractInputField)
    return ((IWDAbstractInputField) element).bindingOfValue();
    if (element instanceof IWDCaption)
    return ((IWDCaption) element).bindingOfText();
    if (element instanceof IWDCheckBox)
    return ((IWDCheckBox) element).bindingOfChecked();
    if (element instanceof IWDLink)
    return ((IWDLink) element).bindingOfText();
    if (element instanceof IWDProgressIndicator)
    return ((IWDProgressIndicator) element).bindingOfPercentValue();
    if (element instanceof IWDRadioButton)
    return ((IWDRadioButton) element).bindingOfSelectedKey();
    if (element instanceof IWDTextEdit)
    return ((IWDTextEdit) element).bindingOfValue();
    if (element instanceof IWDTextView)
    return ((IWDTextView) element).bindingOfText();
    return null;
    Instance of a comparator according to the ordering imposed by the
    implementation of <code>Comparable</code>.
    private static final Comparator DEFAULT = new Comparator() {
    Compares the given objects according to the ordering imposed by the first
    ones <code>compareTo(Object)</code> function. Furthermore, <code>null</code>
    is treated to be less than any object.
    @see java.lang.Comparable#compareTo(java.lang.Object)
    @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
    public int compare(Object o1, Object o2) {
    if (o1 == null && o2 == null)
    return 0;
    if (o1 == null)
    return -1;
    if (o2 == null)
    return +1;
    if (o1 instanceof Boolean && o2 instanceof Boolean)
    return o1.toString().compareTo(o2.toString()); // false < true
    if (o1 instanceof String && o2 instanceof String){
    //Use a Collator for sorting according to the given Locale
    Collator collate = Collator.getInstance(WDResourceHandler.getCurrentSessionLocale());
    return collate.compare(o1, o2);
    return ((Comparable) o1).compareTo((Comparable) o2);
    Map of table column to comparator (<code>ReversableComparator</code>)
    used for sorting that column (sortable columns only).
    private Map comparatorForColumn = new HashMap();
    The table to be sorted.
    private IWDTable table = null;
    Column-IDs of the columns, which should be sortable
    private Map sortableCols = null;
    Generic comparator that compares node elements by a given attribute with
    the help of a given comparator.
    public final class NodeElementByAttributeComparator implements Comparator {
    Creates a new comparator for the given attribute name that compares values
    of that attribute according to the natural ordering of that attribute's
    type (which must implement <code>java.lang.Comparable</code>).
    public NodeElementByAttributeComparator(String attributeName) {
    this(attributeName, null, false, new ArrayList());
    Creates a new comparator for the given attribute name that compares values
    of that attribute with the help of the given comparator. If no comparator
    is given, the natural ordering of that attribute's type is used.
    public NodeElementByAttributeComparator(String attributeName, Comparator comparator) {
    this(attributeName, comparator, false, new ArrayList());
    Creates a new comparator for the given attribute name that compares values
    of that attribute either as objects (i.e. "in internal format") or as text
    (i.e. "in external format") as indicated. The ordering is the natural
    ordering of that attribute's type (which must implement
    <code>java.lang.Comparable</code>) in case objects are compared or the
    natural ordering of <code>java.lang.String</code> in case texts are compared.
    public NodeElementByAttributeComparator(String attributeName, boolean compareAsText) {
    this(attributeName, null, compareAsText, new ArrayList());
    Creates a new comparator for the given attribute name that compares values
    of that attribute according to the natural ordering of that attribute's
    type (which must implement <code>java.lang.Comparable</code>). In addition it is possible
    to define the path to a child node with the <code>java.util.Collection</code> subnodes.
    (List of child node names in the correct order)
    public NodeElementByAttributeComparator(String attributeName, Collection subnodes) {
    this(attributeName, null, false, subnodes);
    Creates a new comparator for the given attribute name that compares values
    of that attribute with the help of the given comparator. If no comparator
    is given, the natural ordering of that attribute's type is used. In addition it is possible
    to define the path to a child node with the <code>java.util.Collection</code> subnodes.
    (List of child node names in the correct order)
    public NodeElementByAttributeComparator(String attributeName, Comparator comparator, Collection subnodes) {
    this(attributeName, comparator, false, subnodes);
    Creates a new comparator for the given attribute name that compares values
    of that attribute either as objects (i.e. "in internal format") or as text
    (i.e. "in external format") as indicated. The ordering is the natural
    ordering of that attribute's type (which must implement
    <code>java.lang.Comparable</code>) in case objects are compared or the
    natural ordering of <code>java.lang.String</code> in case texts are compared. In addition it is possible
    to define the path to a child node with the <code>java.util.Collection</code> subnodes.
    (List of child node names in the correct order)
    public NodeElementByAttributeComparator(String attributeName, boolean compareAsText, Collection subnodes) {
    this(attributeName, null, compareAsText, subnodes);
    Internal constructor.
    private NodeElementByAttributeComparator(
    String attributeName,
    Comparator comparator,
    boolean compareAsText,
    Collection subNodes) {
    if (attributeName == null)
    throw new IllegalArgumentException("Attribute name must not be null");
    if (comparator == null)
    comparator = DEFAULT;
    this.attributeName = attributeName;
    this.comparator = comparator;
    this.compareAsText = compareAsText;
    this.sortDirection = true;
    this.subNodes = subNodes;
    Sets the sort direction of this comparator to the given direction. The comparator sort in ascending order by default.
    @see com.sap.tc.webdynpro.clientserver.uielib.standard.api.WDTableColumnSortDirection
    public void setSortDirection(WDTableColumnSortDirection direction){
    if(direction.equals(WDTableColumnSortDirection.UP)){
    sortDirection = true;
    }else if(direction.equals(WDTableColumnSortDirection.DOWN)){
    sortDirection = false;
    Compares the given objects which must be instances of <code>IWDNodeElement</code>
    according to the values of the attribute given at construction time
    with the help of the comparator given at construction time.
    @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
    @see com.sap.tc.webdynpro.progmodel.api.IWDNodeElement
    public int compare(Object o1, Object o2) {
    IWDNodeElement element1 = (IWDNodeElement) o1;
    IWDNodeElement element2 = (IWDNodeElement) o2;
    if(subNodes.size() > 0){
    element1 = getSubNodeElement(element1, 0);
    element2 = getSubNodeElement(element2, 0);
    Object attributeValue1 = null;
    Object attributeValue2 = null;
    if(element1 != null){
    attributeValue1 =
    compareAsText
    ? element1.getAttributeAsText(attributeName)
    : element1.getAttributeValue(attributeName);
    if(element2 != null){
    attributeValue2 =
    compareAsText
    ? element2.getAttributeAsText(attributeName)
    : element2.getAttributeValue(attributeName);
    if(sortDirection){
    return comparator.compare(attributeValue1, attributeValue2);
    }else{
    return comparator.compare(attributeValue2, attributeValue1);
    Determines recursivly the child node, which have an attribute with the given name.
    The path to this child node must be specified in the subnodes property of this comparator.
    Start this method with index = 0.
    private IWDNodeElement getSubNodeElement(IWDNodeElement currentElement, int index){
    if(currentElement == null || index >= subNodes.size()){
    //end of recursion
    return currentElement;
    }else{
    return getSubNodeElement(currentElement.node().getChildNode((String)subNodes.toArray()index, currentElement.index()).getCurrentElement(), index+1);
    //return getSubNodeElement(currentElement.node().getChildNode((String)subNodes.toArray()index, currentElement.index()).getElementAt(0), index+1);
    Name of the attribute used for comparisons.
    private final String attributeName;
    Comparator used for comparing the attribute's values.
    private final Comparator comparator;
    Indicates whether attribute values are compared as text (as opposed to
    "as objects").
    private final boolean compareAsText;
    Sort direction (true = ascending order, false = descending order)
    private boolean sortDirection;
    List of child node names
    (Description of the path from the given context node to the specified attribute)
    private Collection subNodes;
    [/code]
    kindly reward if helpful.
    cheers,
    Hema.

  • Unlock Gp Action Step

    In the following code I Get a  GP Process and complete the action .
    This works
         public String endGP(String processID, String recordID, String matNum) {
              Collator collator = Collator.getInstance();
              String retorno = "";
              int index = 0 ;
              try {
                   IGPRuntimeManager rtm = GPProcessFactory.getRuntimeManager();
                   IGPDesigntimeManager dtm = GPProcessFactory.getDesigntimeManager();
                   IGPUserContext userContext = getUserContext();
                   IGPProcessInstance process =
                        GPProcessFactory.getRuntimeManager().getProcessInstance(
                             processID,
                             userContext);
                   retorno = "no id " + process.getID();
                   IGPActivityInstance inst[] = process.getChildrenInformation();
                   boolean contabil = false;
                   for (int i = 0; i < inst.length; i++) {
                        IGPBlockInstance block =
                             GPProcessFactory.getRuntimeManager().getBlockInstance(
                                  processID,
                                  inst<i>.getID(),
                                  userContext);
                        IGPActivityInstance instBlock[] =
                             block.getChildrenInformation();
                        IGPActivityInstance actInst = null;
                        IGPActivityInstance activityToUpDate = null;
                        boolean readyToComplete = false;
                        for (int j = 0; j < instBlock.length; j++) {
         actInst = instBlock[j];
                             if (actInst.isBlock()) {
                                  IGPBlockInstance blockInstance =
                                       (IGPBlockInstance) actInst;
                                  IGPActivityInstance instParalelo[] =
                                       blockInstance.getChildrenInformation();
                             if (actInst.isAction()) {
                                                                IGPActionInstance action = (IGPActionInstance) actInst;
                                  IGPActivity activity = action.getTemplate();
                                  if (collator
                                       .compare(
                                            activity.getTitle(),
                                            "FIRSTSTEP")
                                       == 0 & action.getStatus().getCode() <= 5) {
                                       activityToUpDate = actInst;
                                       readyToComplete = true;
                                       contabil = true;
                                  } else {
                                       if (collator
                                            .compare(
                                                 activity.getTitle(),
                                                 "SECONDSTEP")
                                            == 0 & action.getStatus().getCode()
                   <= 5 & !readyToComplete) {
                                                      activityToUpDate = actInst;
                                            readyToComplete = true;
                        if (readyToComplete) {
                             //             messageMgr.reportSuccess("ready to complete");
                             IGPActionCompletionData completionData =
                                  GPProcessFactory
                                       .getRuntimeManager()
                                       .createActionCompletionData(
                                       processID,
                                       activityToUpDate.getID(),
                                       userContext);
                             IGPStructure out = completionData.getOutputStructure();
                             //                                                addStructure("centralFiscal_output");
                             out.addStructure("centralFiscal_output");
                             IGPStructure cfo = out.getStructure("centralFiscal_output");
                             if (contabil) {
                                  cfo.setAttributeValue(
                                       "step",
                                       "FISCAL@@" + recordID + "@@" + matNum);
                             } else {
                                  cfo.setAttributeValue(
                                       "step",
                                       "CENTRAL@@" + recordID + "@@" + matNum);
                             completionData.setState(IGPActionCompletionData.RESULT_STATE_COMPLETED_DONE_ONLY);
                             completionData.setType(IGPActionCompletionData.ACTIVITY_TYPE_BACKGROUND);
                                                 GPProcessFactory.getRuntimeManager().completeAction(completionData);
         retorno ="action : "+ activityToUpDate.getTemplate().getTitle()+ " is completed. ";
    }catch (Exception e) {
                   retorno ="Exception Finalize. "+ e.getLocalizedMessage()+ " : "+ e.getCause()+ " : "+ e.fillInStackTrace()+" : index : "+ index;
              return retorno;
              //@@end
    the first time this code runs  it ends the u201CFIRSTSTEPu201D .
    this works perfect.
    The problem is when we call this a second time to the end the u201CSECONDSTEPu201D.
    When we do this we get the following :
    "Exception Finalize. Object is locked : com.sap.caf.eu.gp.model.fnd.lock.AlreadyLockedException: Object is locked : com.sap.caf.eu.gp.exception.api.GPEngineException: Object is locked"
    My question to you ubergeeks: is there a way I can release this lock in orther to finish the u201CSECONDSTEPu201D . or am I mucking up something somewhere?
    Thank you in advance ,
    Guy

    I opened up a CSS message on this problem .
    the funny thing is if we end an action with the API then manually go into the portal and end the next action it works ,
    it seems only not to work when i try too end two consecutive actions .

  • Client compare using SCU0 - system load - doubt

    Hi
    I am planning to compare my Dev customization client with Production client. I will be using SCU0 for this activity. I will be performing application components for comparison.
    I have a query related to this,
    1. While performing client compare , what are the things that we need to take care? I know that we need authorization, RFC connections etc...
    2. What will be the load in source and target system? As the comparison will happen via RFC ,any precautionary measures need to be taken before the activity?
    Please share your experience on this regard.
    Best regards,
    VInodh.

    Hello,
    Run any client compare/copy procedure ie run test run .
    Hope It will give some results for y'r requirement , depends on the scenario !!
    Note: Points always encourage me to reply !!

  • XPath contains or compare with collation

    I intend to use the XPath contains which matches on whole words.
    Ex: contains ("abcd xyz","abc") should return false
    contains ("abc xyz","abc") should return true
    I understand that this can be done using collation.
    I have been trying to understand this by reading related documentation on w3.org but am not able to understand it.
    Can someone please help me with an example?
    Thanks,
    Rahul

    Try to use one of the following Data Structure classes which implements Set interface. Set interface does not contain duplicate elements which means that if e1.equals(e2) and then it does not take e2 into its storage.
    So try to use these classes;
        AbstractSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet

  • PoswerShell - Compare 2 x CSV files, only if data matches in column 1 add all data from file 2 to file 1 or output collated results

    OK, 1st the background...
    I have been provided a list of users of a particular group.
    We needed to know what computers (or IP's) the users are connected to...
    So, using Shared Folders, I have exported a list of all users connected to H drives (everyone on the domain) and I need to match their computernames (or IP) to the specific list of users I have...
    That gives me 2 x CSV files. 1 x master list of users, I list of all users PC or IP names.
    I need to be able to match the usernames on the master list (File1) with the usernames on File2 and append the computernames and connected times to File1 omitting the usernames that are not required...
    This is to determine what PC's the user is logged into and what site their computers are at.
    I also need to capture if they are logged into more than one computer (info is contained in File2)
    File1 Example:
    User
    FirstName
    LastName
    ADSite
    HDriveLocation
    HDriveLocationTS
    Office2010FAT
    XY123456
    BOB
    BUILDER
    LONDON 
    \\SERVER\%USERNAME%
    \\SERVER\USERNAME
    TRUE
    ABC09876
    JIM
    INYCRICKET 
    CHICAGO 
    \\SERVER\USERNAME
    \\SERVER\USERNAME
    TRUE
    ADD11223 
    SALLY
    METLARRY
    TOKYO
    \\SERVER\USERNAME
    \\SERVER\USERNAME
    FALSE
    File2 Example:
    User
    Computer
     Connected
    Idle
    XY123456 
    192.168.1.216 
    3 days 06:13:18
    0:00:03
    XY123456
    192.168.1.254 
    1 day 01:21:30
    23:08:39
    WXY46810 
    PCNAMEXYZ  
    6:44:19
    0:00:05
    I have found a PS script which "might" do what I need it to, but I haven't been able to "tweak" it right - it's omitting the details from File2 - http://powergui.org/thread.jspa?threadID=19522
    Also I can't figure out how to collect multiple computernames (that users are logged into) from File 2 and add this to File1
    Working with Powershell, but happy to consider any other options (EG: Excel, Macros, VBS, etc)
    Here's what I have got so far: (PS)
    $File1 = Import-Csv "C:\Users.csv"
    $File2 = Import-Csv "C:\Shares.csv"
    $Output = @()
    ForEach ($Item in $File1)
    { $Result = $File2 | Where { $Item.User -eq $_.User }
    $Output += New-Object PSObject -Property @{
    USER = $Item.User
    FirstName = $Item.FirstName
    LastName = $Item.LastName
    ADSite = $Item.ADSite
    Computer = $_.Computer
    Connected = $_.Connected
    Idle = $_.Idle
    Office2010FAT = $Item.Office2010FAT
    HDriveLocation = $Item.Connected
    HDriveLocationTS = $Item.Idle
    $Output | Select User,FirstName,LastName,ADSite,Computer,Connected,Idle,Office2010FAT,HDriveLocation,HDriveLocationTS | Export-Csv C:\Users\a1033965\Desktop\result.csv -NoTypeInformation
    However, the output I'm getting is missing the results from File2 and I NEED multiple computers listed if a user is logged into them:
    Current Output:
    USER
    FirstName
    LastName
    ADSite
    Computer
    Connected
     Idle 
    Office2010FAT
     HDriveLocation
     HDriveLocationTS
    XY123456
    BOB
    BUILDER
    LONDON
    TRUE
    ABC09876
    JIM
    INYCRICKET
    CHICAGO
    TRUE
    ADD11223 
    SALLY
    METLARRY
    TOKYO
    TRUE
    (TRUE is actually in the right column, under Office2010FAT as it should be - just doesn't look like it as I post this)
    Any help with this would be much appreciated. Cheers

    Please verify that your files look exactly like this:
    #file1 format
    User,FirstName,LastName,ADSite,HDriveLocation,HDriveLocationTS,Office2010FAT
    XY123456,BOB,BUILDER,LONDON,\\SERVER\%USERNAME%,\\SERVER\USERNAME,TRUE
    ABC09876,JIM,INYCRICKET,CHICAGO,\\SERVER\USERNAME,\\SERVER\USERNAME,TRUE
    ADD11223,SALLY,METLARRY,TOKYO,\\SERVER\USERNAME,\\SERVER\USERNAME,FALSE
    #file2 format
    User,Computer,Connected,Idle
    XY123456,192.168.1.216,3 days 06:13:18,0:00:03
    XY123456,192.168.1.254,1 day 01:21:30,23:08:39
    WXY46810,PCNAMEXYZ,6:44:19,0:00:05
    ¯\_(ツ)_/¯

  • Benefits of SAP Business Warehouse Reporting compared with the Query-tools?

    Hello experts,
    I've been creating reports with SAP Query tools, but been faced with few problems. First of all, there are restricted possibilities in terms of joining tables, and thus I cannot include all the data required for the report.
    One solution for this would have been to create separate queries and join the data together in Excel. The problem with this is that there exists no common field that would make sense as for a selection criterion. If the selection criterion is different in different queries, there is the danger of combining false data together, which would eventually result with distorted data. 
    So I was wondering, could anyone briefly tell me if SAP Business Warehouse reporting would solve these problems? And what other benefits would it provide compared with the SAP Query? I'd urgently need to know if it would be a beneficial investment for the company, since I haven't found solutions for the problems occurred in the creation of reports.
    Thank you in advance for you help!
    Maria

    The answers are yes - and thousands of companies have gone down this route
    Puttingin BW is a strategic aim of the comapny and not to be thought about and discussed in a BI forum such as this
    The costs of implementation and hardware will no doubt make your eyes water.
    To be quite honest SAP BI is a "no brainer" as most of the new e-SOA and new R3 modules reply on BW for their reporting needs

Maybe you are looking for