Changeset 9085


Ignore:
Timestamp:
2005-02-17T16:21:16+13:00 (19 years ago)
Author:
mdewsnip
Message:

Replaced all hard-wired Unix-style path separators with File.separator, by Matthew Whyte. Also removed a whole lot of unused code.

Location:
trunk/gli/src/org/greenstone/gatherer/gems
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/gli/src/org/greenstone/gatherer/gems/GEMS.java

    r9079 r9085  
    670670            if(result == 0) {
    671671                msm.save();
    672 
    673672            }
    674673        }
     
    839838
    840839        setLocation((config.screen_size.width - ADD_OR_EDIT_ATTRIBUTE_SIZE.width) / 2, (config.screen_size.height - ADD_OR_EDIT_ATTRIBUTE_SIZE.height) / 2);
    841    
    842            
    843            // create dom object for language_Box
    844             //GEMSLanguageManager GemsLangManager = new GEMSLanguageManager("/home/arosmain/gsdl/gli/classes/xml/languages.xml");
     840
    845841        GEMSLanguageManager GemsLangManager = new GEMSLanguageManager(Configuration.gsdl_path + File.separator + "gli" + File.separator + "classes" + File.separator + "xml" + File.separator + "languages.xml");
    846842       
     
    854850           String code = Configuration.getLanguage();
    855851           language_box.setSelectedItem(code);
    856            //System.out.println(code);
    857852        }
    858853
     
    10141009           
    10151010       }// end currattr == GEMSnode.set
    1016        
    10171011       value.setText(prevValue);
    1018        
    10191012       }
    10201013
     
    15381531        }
    15391532                else{
    1540                    
    15411533                       JOptionPane.showMessageDialog(self, Dictionary.get("GEMS.Set_Already_Exists"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
    1542          
    15431534                }
    15441535               
     
    15511542                    String anitem = existingSetJComboBox.getSelectedItem().toString();
    15521543                   
    1553                    // if(msm.getSet(namespace_str) == null) {
    15541544                    if(a_set_exists_with_this_namespace(namespace_field.getText()) == false){
    1555        
    15561545                        //setup to read the filename from mds file
    1557                          String [] items = anitem.split("#%");
     1546            String [] items = anitem.split("#%");
    15581547                        try {
    1559 
    1560             FileInputStream fstream = new FileInputStream(items[1].trim());
    1561             BufferedReader in = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
    1562 
    1563                         FileOutputStream out;
    1564                         PrintWriter p;
    1565                         //setup to write to filename from existing file
    1566                         try {
    1567                         out = new FileOutputStream(Utility.METADATA_DIR + "/"+ namespace_str + ".mds");
    1568             OutputStreamWriter pout = new OutputStreamWriter(out, "UTF8");
    1569                         p = new PrintWriter(pout);
    1570 
    1571             while(in.ready()){
    1572                 String nextline = in.readLine();
    1573 
    1574                             if(nextline.matches(".+namespace=\".+\".*") == true)
    1575                 {
    1576                     nextline = nextline.replaceFirst("namespace=\".+\"","namespace=\"" + namespace_str+ "\"");                         
     1548                FileInputStream fstream = new FileInputStream(items[1].trim());
     1549                BufferedReader in = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
     1550               
     1551                FileOutputStream out;
     1552                PrintWriter p;
     1553                //setup to write to filename from existing file
     1554                try {
     1555                out = new FileOutputStream(Utility.METADATA_DIR + File.separator+ namespace_str + ".mds");
     1556                OutputStreamWriter pout = new OutputStreamWriter(out, "UTF8");
     1557                p = new PrintWriter(pout);
     1558               
     1559                while(in.ready()){
     1560                    String nextline = in.readLine();
     1561                   
     1562                    if(nextline.matches(".+namespace=\".+\".*") == true) {
     1563                    nextline = nextline.replaceFirst("namespace=\".+\"","namespace=\"" + namespace_str+ "\"");                         
     1564                    }
     1565                    else {
     1566                    nextline = nextline.replaceFirst(">.+</Name>",">" + name_str + "</Name>");
     1567                    }
     1568                    p.print(nextline + "\n");
    15771569                }
    1578                             else
    1579                 {
    1580                     nextline = nextline.replaceFirst(">.+</Name>",">" + name_str + "</Name>");
    1581                 }
    1582                
    1583                             p.print(nextline + "\n");
    1584                         }
    1585                         p.close();
    1586                        
    1587                         MetadataSet loadedset = msm.loadMetadataSet(new File(Utility.METADATA_DIR + "/" + namespace_str + ".mds"));
    1588                          model.add(null, loadedset, GEMSNode.SET);
    1589                         }
    1590                         catch(Exception e){
    1591                             System.out.println("Print file error");
    1592 
    1593                         }
    1594 
     1570                p.close();
     1571               
     1572                MetadataSet loadedset = msm.loadMetadataSet(new File(Utility.METADATA_DIR + File.separator + namespace_str + ".mds"));
     1573                model.add(null, loadedset, GEMSNode.SET);
     1574                }
     1575                catch(Exception e){
     1576                System.out.println("Print file error");
     1577                }
    15951578                        }
    15961579                        catch(Exception e){
     
    16001583                    }//msm.getset(namespacE) == null
    16011584                    else{
    1602                        
    1603                       JOptionPane.showMessageDialog(self, Dictionary.get("GEMS.Set_Already_Exists"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
     1585            JOptionPane.showMessageDialog(self, Dictionary.get("GEMS.Set_Already_Exists"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
    16041586                    }
    1605              setVisible(false);
     1587            setVisible(false);
    16061588                }
    1607 
    16081589        } //if(source == ok_button)
    16091590        else if(source == cancel_button) {
     
    16441625        center_pane.setOpaque(false);
    16451626
    1646    
    16471627        JPanel boxes_pane = new JPanel();
    16481628
     
    18091789            }
    18101790            ignore = false;
    1811                    
    18121791            atLeastOneSetChanged= true;
    18131792        }
     
    20141993        else
    20151994        {
    2016             name_field.setText(current_set.getName()); //getName() doesn't work properly. Need to update MetadataSet.java
    2017             //getName() only doesn't work when the name is exactly the same as the namespace.
     1995            name_field.setText(current_set.getName());
    20181996            namespace_field.setText(current_set.getNamespace());
    20191997            setVisible(true); //Show the dialog
    2020         }
    2021            
     1998        }   
    20221999        source = null;
    20232000    }
    20242001   
    2025 
    20262002    public void dispose() {
    20272003        cancel_button = null;
     
    20302006        super.dispose();
    20312007    }
    2032 
    20332008    }
    20342009
     
    21762151    }
    21772152   
    2178 
    21792153    public void dispose() {
    21802154        cancel_button = null;
     
    21832157        super.dispose();
    21842158    }
    2185 
    21862159    }
    21872160
  • trunk/gli/src/org/greenstone/gatherer/gems/MSMUtils.java

    r9077 r9085  
    4141 */
    4242public class MSMUtils {
    43     /** Used to order metadata according to set standard element order then alphabetically by value. */
    44     // static private MetadataComparator METADATA_COMPARATOR = new MetadataComparator();
    45     /** An element of the enumeration of type filter. */
    46     static public int NONE = 0;
    47     /** An element of the enumeration of type filter. */
    48     static public int VALUES = 1;
    49     /** An element of the enumeration of type filter. */
    50     static public int ALIASES = 2;
    51     /** An element of the enumeration of type filter. */
    52     static public int BOTH = 3;
    53     /** The character used to separate name space from metadata element. */
    54     static public char NS_SEP= '.';
    55     /** The character used to separate subfields from metadata element. */
    56     static public String SF_SEP= "^";
     43    static public int NONE = 0;     //An element of the enumeration of type filter.
     44    static public int VALUES = 1;   //An element of the enumeration of type filter.
     45    static public int ALIASES = 2;  //An element of the enumeration of type filter.
     46    static public int BOTH = 3;     //An element of the enumeration of type filter.
     47    static public char NS_SEP= '.'; //The character used to separate name space from metadata element.
     48    static public char SF_SEP= '^'; //The character used to separate subfields from metadata element.
     49
    5750    /** Method to add one node as a child of another, after migrating into the target document.
    5851     * @param parent The <strong>Node</strong> we are inserting into.
     
    122115
    123116
    124     /** A method for comparing two AssignedValues trees. This compares not only the Subject hierarchies but also the values themselves.
    125      * @param avt A <strong>Node</strong> which is the root of an AssignedValues tree.
    126      * @param bvt The <strong>Node</strong> which is the root of the tree we wish to compare it to.
    127      * @return <i>true</i> if the two trees are equal, <i>false</i> otherwise.
    128      */
    129     static final private boolean assignedValuesEqual(Node avt, Node bvt) {
    130     if(avt == null && bvt == null) {
    131         return true; // Both are null so both are equal.
    132     }
    133     else if(avt == null || bvt == null) {
    134                 // One is null and the other isn't.
    135         return false;
    136     }
    137     else {
    138         Hashtable a_map = new Hashtable();
    139         getValueMappings(avt, null, a_map);
    140         Hashtable b_map = new Hashtable();
    141         getValueMappings(bvt, null, b_map);
    142         if(a_map.size() == b_map.size()) {
    143         /** @TODO - Figure out what to do now. */
    144         return true;
    145         }
    146     }
    147     return false;
    148     }
    149     /** A method for comparing two attribute nodes of type Node not Attr as you might think. Attr objects are used to describe the attributes of tags themselves, while in a metadata set we intend attribute nodes to describe qualities of metadata elements. It's just confusing because the two systems (DOM model and Dublin Core) are quite similar.
    150      * @param an A <strong>Node</strong> representing some attribute of an element.
    151      * @param bn The <strong>Node</strong> we wish to compare it to.
    152      * @return <i>true</i> if and only if the attributes are equal.
    153      */
    154     static final public boolean attributesEqual(Node an, Node bn) {
    155     // Check we are comparing apples and apples...
    156     if(an.getNodeName().equals("Attribute") && bn.getNodeName().equals("Attribute")) {
    157         Element ae = (Element) an;
    158         Element be = (Element) bn;
    159                 // Ensure we are comparing the same type of attribute.
    160         if(ae.getAttribute("name").equals(be.getAttribute("name"))) {
    161         // And finally retrieve and compare the values.
    162         if(getValue(ae).equals(getValue(be))) {
    163             // We have a match.
    164             return true;
    165         }
    166         }
    167     }
    168     // And if anything goes wrong we can't be dealing with equal attributes.
    169     return false;
    170     }
    171 
    172     /** Remove all of the child nodes from a certain node. */
    173     static final public void clear(Node parent) {
    174     while(parent.hasChildNodes()) {
    175         parent.removeChild(parent.getFirstChild());
    176     }
    177     }
    178 
    179     /** Method to compare two metadata elements (of type Element, which is bound to get more than a bit confusing) for equality. This test may only check the structural (ie pretty much unchanging) consistancy, or may include the AssignedValue tree as well (which will be different for each collection I'd imagine).
    180      * @param a_set The <strong>MetadataSet</strong> a comes from.
    181      * @param ae An <strong>Element</strong>.
    182      * @param b_set The <strong>MetadataSet</strong> b comes from.
    183      * @param be The <strong>Element</strong> to compare it to.
    184      * @param values <i>true</i> if the AssignedValues tree should also be compared, <i>false</i> otherwise.
    185      * @return <i>true</i> if the elements are equal, <i>false</i> otherwise.
    186      */
    187     static final public boolean elementsEqual(MetadataSet a_set, Element ae, MetadataSet b_set, Element be, boolean values) {
    188     // Compare Element Attr(ibutes) within the DOM, not to be confused with comparing element attributes in a Dublin Core sense...
    189     NamedNodeMap aas = ae.getAttributes();
    190     NamedNodeMap bas = be.getAttributes();
    191     // For each attribute in a...
    192     for(int i = 0; i < aas.getLength(); i++) {
    193         Attr aa = (Attr)aas.item(i);
    194                 // Try to retrieve an attribute of the same name from b.
    195         Attr ba = (Attr)bas.getNamedItem(aa.getNodeName());
    196                 // Now if there was no such attribute, or if the values for the
    197                 // two attributes are different the structures different.
    198         if(ba == null || (!aa.getValue().equals(ba.getValue()))) {
    199         //ystem.err.println("Attributes are not equal");
    200         return false;
    201         }
    202     }
    203     // Quickest test of children is to see we have the same number in
    204     // each. Remember to modify for missing AssignedValues which have
    205     // nothing to do with structure.
    206     int anc = getAttributeCount(ae);
    207     int bnc = getAttributeCount(be);
    208     if(anc != bnc) {
    209         return false;
    210     }
    211     // Now we compare the child nodes of the two Elements taking into
    212     // account three special cases...
    213     // 1. We don't test the AssignedValues element here.
    214     // 2. Remember OptionList node.
    215     // 3. The Attributes of each metadata element.
    216     // For each child node of a.
    217     for(Node an = ae.getFirstChild(); an !=null; an =an.getNextSibling()) {
    218         if(an.getNodeName().equals("OptionList")) {
    219         //ystem.err.println("Matching OptionLists.");
    220         Node bn = getNodeFromNamed(be, "OptionList");
    221         if(bn == null || !optionListsEqual(an, bn)) {
    222             //ystem.err.println("OptionLists are not equal");
    223             return false;
    224         }
    225         }
    226                 // Matching attributes.
    227         else if(an.getNodeName().equals("Attribute")) {
    228         //ystem.err.println("Matching Attributes.");
    229         boolean matched = false;
    230         for(Node bn = be.getFirstChild(); bn != null && !matched;
    231             bn = bn.getNextSibling()) {
    232             if(bn.getNodeName().equals("Attribute")) {
    233             matched = attributesEqual(an, bn);
    234             }
    235         }
    236         if(!matched) {
    237             //ystem.err.println("Cannot match attribute.");
    238             return false;
    239         }
    240         }
    241     }
    242     // Finally, if we've been asked to compares value trees (for some unknown reason) go ahead and compare them too.
    243     if(values) {
    244         GValueModel avt = a_set.getValueTree(new ElementWrapper(ae));
    245         GValueModel bvt = b_set.getValueTree(new ElementWrapper(be));
    246         return assignedValuesEqual(avt.getDocument().getDocumentElement(), bvt.getDocument().getDocumentElement());
    247     }
    248     // If we've got this far the elements match!
    249     return true;
    250     }   
    251     /** This method extracts the assigned value trees details, if any, from a certain element and stores them in an array ready to be passed as arguments to the Dictionary.
    252      * @param element The <strong>Element</strong> whose values we wish to view.
    253      * @return A <strong>String[]</strong> containing the details of the assigned values tree.
    254      * @see org.greenstone.gatherer.Dictionary
    255      */
    256     static final public String[] getAssignedValuesDetails(MetadataSet mds, Element element) {
    257     String details[] = null;
    258     //Node avt = getNodeFromNamed(element, "AssignedValues");
    259     GValueModel avt = mds.getValueTree(new ElementWrapper(element));
    260     if(avt != null) {
    261         Hashtable mapping = new Hashtable();
    262         getValueMappings(avt.getDocument().getDocumentElement(), null, mapping);
    263         ArrayList values = new ArrayList(mapping.keySet());
    264         Collections.sort(values);
    265         details = new String[1];
    266         for(int i = 0; i < values.size(); i++) {
    267         if(details[0] == null) {
    268             details[0] = "   " + values.get(i);
    269         }
    270         else {
    271             details[0] = details[0] + "\n   " + values.get(i);
    272         }
    273         }
    274         mapping = null;
    275         values = null;
    276     }
    277     avt = null;
    278     return details;
    279     }
    280 
    281117    /** Retrieve all of the attributes for the given element as a tree set. Note that this requires significant manipulation if the source is a multilingual optimized metadata set.
    282118     * @param element the Element whose attributes we wish to catalog
     
    305141                }
    306142        else if(some_element_name.equals(StaticStrings.LANGUAGE_ELEMENT)) {
    307                     ///Added by Attila on Nov 05 04
    308             //System.out.println(some_element_name +  "<- some_element nodes' value"); //debug
    309                    
    310143            String language_code = some_element.getAttribute(StaticStrings.CODE_ATTRIBUTE);
    311144            NodeList attribute_elements = some_element.getElementsByTagName(StaticStrings.ATTRIBUTE_ELEMENT);
     
    317150                               
    318151                               if(enabled_langs[k].trim().compareTo(some_element.getAttributes().item(0).getNodeValue().toString()) == 0){
    319                      
    320                                  attribute_tree.add(new Attribute(attribute_element.getAttribute(StaticStrings.NAME_ATTRIBUTE), language_code, MSMUtils.getValue(attribute_element)));
    321                      attribute_element = null;
    322                                  
    323                                  break;
     152                   attribute_tree.add(new Attribute(attribute_element.getAttribute(StaticStrings.NAME_ATTRIBUTE), language_code, MSMUtils.getValue(attribute_element)));
     153                   attribute_element = null;
     154                   
     155                   break;
    324156                               }
    325                                //else {
    326                                //    System.out.println(enabled_langs[k].trim().toString() + some_element.getAttributes().item(0).getNodeValue().toString());
    327                               // }
    328                            
    329157                            }
    330                         //  enabled_languages_split[k].toLowerCase().trim();
    331              
    332                            
    333                        // if(match_exit_flag == false)
    334                             // break;
    335                         //add language specific attr's:
    336             //attribute_tree.add(new Attribute(attribute_element.getAttribute(StaticStrings.NAME_ATTRIBUTE), language_code, MSMUtils.getValue(attribute_element)));
    337             attribute_element = null;
    338             }
     158                attribute_element = null;
     159           }
    339160            attribute_elements = null;
    340161            language_code = null;
     
    347168    }
    348169
    349     /** Method to count the number of Attribute nodes under a certain Element. This ignores other nodes such as #text, OptionList and AssignedValues nodes.
    350      * @param element The <strong>Element</strong> whose attributes you want to count.
    351      * @return An <i>int</i> which is the number of attribute nodes.
    352      */
    353     static final private int getAttributeCount(Node element) {
    354     int count = 0;
    355     for(Node n = element.getFirstChild(); n != null;
    356         n = n.getNextSibling()) {
    357         if(n.getNodeName().equals("Attribute")) {
    358         count++;
    359         }
    360     }
    361     return count;
    362     }
    363 
    364     /** This method is a slight variation on getNodeNamed in that it is especially written to retrieve the attribute Nodes of a certain name present under the given element.
    365      * @param element The target element <strong>Node</strong>.
    366      * @param name The name of the attribute you wish to return.
    367      * @return An <strong>Element[]</strong> containing the attributes you requested, or <i>null</i> if no such attributes exists.
    368      */
    369     static final public Element[] getAttributeNodesNamed(Node element, String name) {
    370     Element attributes[] = null;
    371     for(Node n = element.getFirstChild(); n != null; n = n.getNextSibling()) {
    372         if(n.getNodeName().equals("Attribute")) {
    373         Element e = (Element)n;
    374         if(e.getAttribute("name").equals(name)) {
    375             if(attributes == null) {
    376             attributes = new Element[1];
    377             attributes[0] = e;
    378             }
    379             else {
    380             Element temp[] = attributes;
    381             attributes = new Element[temp.length + 1];
    382             System.arraycopy(temp, 0, attributes, 0, temp.length);
    383             attributes[temp.length] = e;
    384             temp = null;
    385             }
    386         }
    387         e = null;
    388         }
    389     }
    390     return attributes;
    391     }
    392170
    393171    /** Method to construct an elements description by retrieving the correct attribute.
     
    411189    return description.toString();
    412190    }
     191
    413192
    414193    /** Retrieve the value for the requested attribute in the required language. Once again this method must be aware of the differences between the old metadata sets and the new multilingual optimized ones.
     
    486265            target_name_str = null;
    487266        }
    488         //else {
    489         ///ystem.err.println("Second level");
    490         //}
    491267        attribute_element = null;
    492268        }
    493269        attribute_elements = null;
    494 
    495270    }
    496271    document = null;
     
    498273    }
    499274
    500     /*************************************************************************/
     275
     276
    501277    /** Method to construct an elements fully qualified name. Note that this is different from a nodes identifier. Think of name as a short, unique reference to a metadata element, whereas identifier can be much longer, language specific and non-unique.
    502278     * @param element An <strong>Element</strong> whose name we are interested in.
     
    507283
    508284    }
    509     /*************************************************************************/
     285
     286
    510287    /** Method to construct an elements fully qualified name. Note that this is different from a nodes identifier. Think of name as a short, unique reference to a metadata element, whereas identifier can be much longer, language specific and non-unique.
    511288     * @param element An <strong>Element</strong> whose name we are interested in.
     
    548325    } // static public String getFullName(Element element)
    549326
     327
    550328    /**
    551329       Method to get an element's name, not including its namespace.
     
    584362    return identifier;
    585363    }
    586 
    587364
    588365
     
    602379    return child;
    603380    }
     381
     382
    604383    /** Look for the occurances 'field' of the element and return it if found.
    605384     * @return An <i>int</i> which matches the number in the occurances attribute of the element, or 0 if no such attribute.
     
    618397    return count;
    619398    }   
    620     /** This method extracts the option list details, if any, from a certain element and stores them in an array ready to be passed as arguments to the <strong>Dictionary</strong>.
    621      * @param element The <strong>Element</strong> whose option list we wish to view.
    622      * @return A <strong>String[]</strong> containing the details of the option list.
    623      * TODO implement.
    624      * @see org.greenstone.gatherer.Dictionary
    625      */
    626     static final public String[] getOptionListDetails(Element element) {
    627     return null;
    628     }
    629 
    630 
    631     /** This method extracts the structural details from a certain element and stores them in an array, all ready for passing to the <strong>Dictionary</strong>.
    632      * @param element The <Strong>Element</strong> whose details we wish to gather.
    633      * @return A <strong>String[]</strong> containing the structural details.
    634      */
    635     static final public String[] getStructuralDetails(MetadataSet mds, Element element) {
    636     String details[] = new String[4];
    637     //Element root = (Element)element.getParentNode();
    638     //details[0] = root.getAttribute("name");
    639     //details[1] = root.getAttribute("namespace");
    640     details[0] = mds.getName();
    641     details[1] = mds.getNamespace();
    642     details[2] = getFullName(element);
    643     details[3] = null;
    644     // Get attributes
    645     Vector attributes = new Vector();
    646     for(Node n=element.getFirstChild(); n!=null; n=n.getNextSibling()) {
    647         if(n.getNodeName().equals("Attribute")) {
    648         Element temp = (Element)n;
    649         attributes.add(temp.getAttribute("name") + "=" + getValue(n));
    650         }
    651     }
    652     // Sort attributes
    653     Collections.sort(attributes);
    654     // Add attributes to details.
    655     for(int i = 0; i < attributes.size(); i++) {
    656         if(details[3] == null) {
    657         details[3] = "   " + attributes.get(i);
    658         }
    659         else {
    660         details[3] = details[3] + "\n   " + attributes.get(i);
    661         }
    662     }
    663     return details;
    664     }
     399
    665400
    666401    /** Method to retrieve the value of a given node (not the assigned values tree!).
     
    687422    return "";
    688423    }
     424
    689425
    690426    /** Method to traverse the given value tree, and build up a hashtable of mappings between the value path key names and the Subject nodes of the tree.
     
    717453    }
    718454    }
     455
     456
    719457    /** Parses the value tree template file.
    720458     * @return The Document parsed.
     
    723461    return Utility.parse(GEMS.METADATA_VALUE_TEMPLATE, true);
    724462    }
     463
    725464
    726465    /** Determine if the named attribute is language specific for this collection. This information is found in a DOM attribute of the document element, as a comma separated list of attribute names.
     
    748487    }
    749488
    750     /** Determine if the given document is a legacy MDS or a new multilingual one. The easiest way to tell is whether there is a language_dependent attribute in the document element.
    751      * @param document the Document to test
    752      * @return true if this is an old mds, false otherwise
    753      * @see org.greenstone.gatherer.util.StaticStrings#LANGUAGEDEPENDENT_ATTRIBUTE
    754      * @see org.greenstone.gatherer.util.StaticStrings#EMPTY_STR
    755      */
    756     static private boolean isLegacyMDS(Document document) {
    757     ///ystem.err.println("isLegacyMDS(): l_d = " + document.getDocumentElement().getAttribute(StaticStrings.LANGUAGEDEPENDENT_ATTRIBUTE));
    758     return (document.getDocumentElement().getAttribute(StaticStrings.LANGUAGEDEPENDENT_ATTRIBUTE)).equals(StaticStrings.EMPTY_STR);
    759     }
    760 
    761     /** Method to compare two OptionsLists for equality.
    762      * @param al A <strong>Node</strong> which represents an OptionList.
    763      * @param bl The <strong>Node</strong> we wish to test against.
    764      * @return A <i>boolean</i> which is <i>true</i> if the two option lists are equal, <i>false</i> otherwise.
    765      * TODO Implementation
    766      */
    767     static final private boolean optionListsEqual(Node al, Node bl) {
    768     // Compare the 'restricted' attribute of the two lists.
    769     Element ae = (Element) al;
    770     Element be = (Element) bl;
    771     if(!ae.getAttribute("restricted").equals
    772        (be.getAttribute("restricted"))) {
    773         return false;
    774     }
    775     // Compare the Values under each list.
    776     for(Node an = al.getFirstChild(); an != null;
    777         an = an.getNextSibling()){
    778         if(an.getNodeName().equals("Value")) {
    779         boolean matched = false;
    780         for(Node bn = bl.getFirstChild(); bn != null && !matched;
    781             bn = bn.getNextSibling()) {
    782             if(bn.getNodeName().equals("Value")) {
    783             matched = valuesEqual(an, bn);
    784             }
    785         }
    786         if(!matched) {
    787             return false;
    788         }
    789         }
    790     }
    791     return true;
    792     }
    793489
    794490    /** A method to remove a specific attribute element from an element. This attribute must match in name, language and in value before being removed. Note that this method supports both legacy and multilingual optimized versions of the mds.
     
    891587    }
    892588
     589
    893590    /** can only be used to set the english value */
    894591    static final public void setIdentifier(Node element, String value) {
     
    906603    }
    907604    }
     605
     606
    908607    /** Set the value of the element attribute occurances.
    909608     * @param element The <strong>Element</strong> to change.
     
    914613    element.setAttribute("occurances", new_value.toString());
    915614    }
     615
    916616
    917617    /** Set the #text node value of some element.
     
    928628    }
    929629
     630
    930631    /** This method also traverses the tree, but this one is used to gather all the values and aliases at once, and to 'prune' the tree if necessary.
    931632     * @param current The current root <strong>Node</strong> of this AssignedValues tree subtree.
     
    966667    }
    967668
    968     /** This method is used to systematically merge two AssignedValues tree. Both trees have their current values mapped, then the new tree is searched for key paths that don't exist in the current tree. If such a key is found, the Subject <strong>Node</strong> it maps to is retrieved and then imported and added to whatever was the closest available node (in terms of tree path) in the current tree.
    969      * @param a_set The MetadataSet from which the Element a came from.
    970      * @param a The Element at the root of the current AssignedValues tree.
    971      * @param b_set The MetadataSet from which the Element b came from.
    972      * @param b The root Element of the tree that is being merged.
    973      * @return A <i>boolean</i> which is <i>true</i> if the trees merged without error, <i>false</i> otherwise.
    974      */
    975     static final public boolean updateValueTree(MetadataSet a_set, Element a, MetadataSet b_set, Element b) {
    976     GValueModel avt = a_set.getValueTree(new ElementWrapper(a));
    977     GValueModel bvt = b_set.getValueTree(new ElementWrapper(b));
    978     // If neither element even has a value tree, we're all done.
    979     if(avt == null && bvt == null) {
    980         avt = null;
    981         bvt = null;
    982         return true;
    983     }
    984     // If the new element has no value tree then nothing needs to be done.
    985     else if(avt != null && bvt == null) {
    986         avt = null;
    987         bvt = null;
    988         return true;
    989     }
    990     // If only the new element has a value tree, then add all of its values
    991     // immediately.
    992     else if(avt == null && bvt != null) {
    993         a_set.addValueTree(new ElementWrapper(a), bvt);
    994         avt = null;
    995         bvt = null;
    996         return true;
    997     }
    998     // We have both trees for both elements, time to merge.
    999     else {
    1000         Document document = avt.getDocument();
    1001         Hashtable a_map = new Hashtable();
    1002         getValueMappings(document.getDocumentElement(), null, a_map);
    1003         Hashtable b_map = new Hashtable();
    1004         getValueMappings(bvt.getDocument().getDocumentElement(), null, b_map);
    1005                 // For each new entry in b_map
    1006         for(Enumeration b_keys = b_map.keys(); b_keys.hasMoreElements(); ) {
    1007         String b_key = (String)b_keys.nextElement();
    1008         // Test if there is already an entry in a_map.
    1009         if(!a_map.containsKey(b_key)) {
    1010             // If not, search through a_map for the longest match.
    1011             Node target = document.getDocumentElement();
    1012             String last_match = null;
    1013             for(Enumeration a_keys = a_map.keys();
    1014             a_keys.hasMoreElements(); ) {
    1015             String a_key = (String)a_keys.nextElement();
    1016             if(b_key.startsWith(a_key)) {
    1017                 if(last_match == null || a_key.length() > last_match.length()) {
    1018                 last_match = a_key;
    1019                 target = (Node)a_map.get(a_key);
    1020                 }
    1021             }
    1022             a_key = null;
    1023             }
    1024             // Now import the node at b_key and add it to target.
    1025             Node subtree = (Node)b_map.get(b_key);
    1026             subtree = document.importNode(subtree, true);
    1027             // Find the node to insert before...
    1028             String name = getValue(subtree);
    1029             Node move = null;
    1030             for(Node n = target.getFirstChild(); n != null && move == null; n = n.getNextSibling()) {
    1031             if(n.getNodeName().equals("Subject")) {
    1032                 if(name.compareTo(getValue(n)) <= 0) {
    1033                 move = n;
    1034                 }
    1035             }
    1036             }
    1037             if(move == null) {
    1038             target.appendChild(subtree);
    1039             }
    1040             else {
    1041             target.insertBefore(subtree, move);
    1042             }
    1043             target = null;
    1044             last_match = null;
    1045             subtree = null;
    1046             name = null;
    1047             move = null;
    1048         }
    1049         b_key = null;
    1050         }
    1051         document = null;
    1052         a_map = null;
    1053         b_map = null;
    1054         avt = null;
    1055         bvt = null;
    1056         return true;
    1057     }
    1058     }
     669
     670    /** Determine if the given document is a legacy MDS or a new multilingual one. The easiest way to tell is whether there is a language_dependant attribute in the document element.
     671     * @param document the Document to test
     672     * @return true if this is an old mds, false otherwise
     673     * @see org.greenstone.gatherer.util.StaticStrings#LANGUAGEDEPENDANT_ATTRIBUTE
     674     * @see org.greenstone.gatherer.util.StaticStrings#EMPTY_STR
     675     */
     676    static private boolean isLegacyMDS(Document document) {
     677    ///ystem.err.println("isLegacyMDS(): l_d = " + document.getDocumentElement().getAttribute(StaticStrings.LANGUAGEDEPENDANT_ATTRIBUTE));
     678    return (document.getDocumentElement().getAttribute(StaticStrings.LANGUAGEDEPENDENT_ATTRIBUTE)).equals(StaticStrings.EMPTY_STR);
     679    }
     680
     681
     682    /** Remove all of the child nodes from a certain node. */
     683    static final public void clear(Node parent) {
     684    while(parent.hasChildNodes()) {
     685        parent.removeChild(parent.getFirstChild());
     686    }
     687    }
     688 
    1059689
    1060690    /** Method to determine if two Value nodes are equal.
     
    1076706    return false;
    1077707    }
    1078 
    1079     /** A comparator for sorting metadata element-value pairs into their standard order (elements) then alphabetical order (values). */
    1080 //     static final private class MetadataComparator
    1081 //  implements Comparator {
    1082 //  /** Compares its two arguments for order. */
    1083 //  public int compare(Object o1, Object o2) {
    1084 //      int result = 0;
    1085 //      ElementWrapper e1 = null;
    1086 //      ElementWrapper e2 = null;
    1087 //      String v1 = null;
    1088 //      String v2 = null;
    1089 //      if(o1 instanceof Metadata && o2 instanceof Metadata) {
    1090 //      Metadata m1 = (Metadata) o1;
    1091 //      Metadata m2 = (Metadata) o2;
    1092 //      ///ystem.err.println("MSMUtils.compare(" + m1 + ", " + m2 + ") = ");
    1093 //      e1 = m1.getElement();
    1094 //      e2 = m2.getElement();
    1095 //      v1 = m1.getValue().toLowerCase();
    1096 //      v2 = m2.getValue().toLowerCase();
    1097 //      }
    1098 //      else if(o1 instanceof ElementWrapper && o2 instanceof ElementWrapper) {
    1099 //      e1 = (ElementWrapper) o1;
    1100 //      e2 = (ElementWrapper) o2;
    1101 //      }
    1102 //      if(e1 != null && e2 != null) {
    1103 //      // First we compare the namespaces
    1104 //      result = e1.getNamespace().compareTo(e2.getNamespace());
    1105 //      if(result == 0 && Gatherer.c_man != null && Gatherer.c_man.ready() && e1.getNamespace() != null) {
    1106 //          // Now, given both elements are in the same set, we compare the element ordering using methods in MetadataSet
    1107 //          MetadataSet set = Gatherer.c_man.getCollection().msm.getSet(e1.getNamespace());
    1108 //          ///ystem.err.print("MetadataSet.compare(" + e1 + ", " + e2 + ") = ");
    1109 //          if(set != null) {
    1110 //          result = set.compare(e1.getElement(), e2.getElement());
    1111 //          ///ystem.err.println(result);
    1112 //          if(result == 0 && v1 != null && v2 != null) {
    1113 //              // Finally we compare the values alphabetically.
    1114 //              result = v1.compareTo(v2);
    1115 //          }
    1116 //          }
    1117 //          else {
    1118 //          return 0;
    1119 //          }
    1120 //      }
    1121 //      }
    1122 //      else {
    1123 //      result = o1.toString().compareTo(o2.toString());
    1124 //      }
    1125 //      ///ystem.err.println("Result: " + result);
    1126 //      return result;
    1127 //  }
    1128          
    1129 //  /** Indicates whether some other object is "equal to" this Comparator. */
    1130 //  public boolean equals(Object obj) {
    1131 //      return compare(this, obj) == 0;
    1132 //  }
    1133 //     }
    1134708}
  • trunk/gli/src/org/greenstone/gatherer/gems/MetadataSetManager.java

    r9036 r9085  
    5959 */
    6060public class MetadataSetManager {
    61 
    62     /** The character used to separate name space from metadata element. */
    63     static public char NS_SEP= '.';
    64     /** The character used to separate subfields from metadata element. */
    65     static public String SF_SEP= "#";
    66 
    67     /** The name of the hidden, or system, metadata set. */
    68     static final public String HIDDEN = "hidden";
     61    static final public String HIDDEN = "hidden"; //The name of the hidden, or system, metadata set.
    6962    static final public int MAX_LOADED_SETS = 64;
    7063    static public CollectionManager col_man = null;
    71     /** A mapping from metadata namespace to metadata set. */
    72     static private Hashtable mds_hashtable = new Hashtable();
     64    static private Hashtable mds_hashtable = new Hashtable(); //A mapping from metadata namespace to metadata set.
    7365    public GEMS gemsptr;
    7466   
    75     /** The profiler is responsible for remembering what actions a user has requested when importing metadata, so as to prevent the user needlessly re-entering this information for each import. */
    76     // public MSMProfiler profiler = null;
    77 
    7867
    7968    /** Constructor. */
     
    9281    mds.setAttribute("lastchanged", Utility.getDateString() + " - " + user_name + " on " + machine_name);
    9382    // And the remaining attributes.
    94     //mds.setAttribute("name", name);
    9583    mds.setAttribute("namespace", namespace);
    9684    // Add the name element.
     
    10391    return mds;
    10492    }
     93
    10594
    10695    /**
     
    134123
    135124
    136     public Vector getVectorSets() {   
    137         Vector sets = new Vector();
    138        
    139         File metadata_directory = new File(Utility.METADATA_DIR);
    140     if (metadata_directory.exists()) {
    141         // Load just those .mds files in this directory, and return them
    142         File[] directory_files = metadata_directory.listFiles();
    143         for (int i = 0; i < directory_files.length; i++) {
    144         File child_file = directory_files[i];
    145         if (!child_file.isDirectory() && child_file.getName().endsWith(".mds")) {
    146             System.err.println("Found mds file: " + child_file);
    147             MetadataSet metadata_set = loadMetadataSet(child_file);
    148                   //  metadata_set.getName();
    149                     sets.add(new String(child_file.toString() + " ^ " + metadata_set.getName()));
    150             //model.add(null, metadata_set, GEMSNode.SET);
    151         }
    152         }
    153     }
    154         return sets;
    155     }
    156     public Object [] getVectorSetsToStringArray() {
    157        
    158         return getSets().toArray();   
    159     }
    160125    /** Add a value tree to a given metadata element represented as a GValueModel
    161126     * @param model The <strong>GValueTree</strong> model
     
    188153    return getElements(all, false);
    189154    }
     155
    190156
    191157    /** Used to get all the elements in this manager.
     
    217183    }
    218184
     185
    219186    /** Retrieve a metadata element by its index.
    220187     * @param index The specified index as an int.
     
    229196    return result;
    230197    }
     198
    231199    /** Retrieve a metadata element by looking at the current metadata element. Note that this 'index' element may now be disconnected from the DOM model, so we have to reload the target element by the string method.
    232200     * @param element The possibly out-of-data MetadataElement.
     
    236204    return getElement(element.toString());
    237205    }
     206
    238207    /** Retrieve a metadata element by its fully qualified name.
    239208     * @param name The elements name as a String.
    240209     * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
    241210     */
     211
    242212    public ElementWrapper getElement(String name) {
    243213    return getElement(name, false);
     
    254224    String element = null;
    255225    // First we seperate off what set it is in, where we have '<set><namespace_separator><element>'.
    256     if(name.indexOf(NS_SEP) != -1) {
    257         String namespace = name.substring(0, name.indexOf(NS_SEP));
     226    if(name.indexOf(MSMUtils.NS_SEP) != -1) {
     227        String namespace = name.substring(0, name.indexOf(MSMUtils.NS_SEP));
    258228        // Retrieve the correct set if possible.
    259229        set = (MetadataSet)mds_hashtable.get(namespace);
    260230        namespace = null;
    261231        // Now retrieve the element name.
    262         element = name.substring(name.indexOf(NS_SEP) + 1);
     232        element = name.substring(name.indexOf(MSMUtils.NS_SEP) + 1);
    263233    }
    264234    // If we are looking for a perfect match, we can assume that no namespace means extracted metadata
     
    270240    if(set != null) {
    271241        // Now we have a set we are ready to locate the requested element. Break the remaining element name down by the subfield separator, attempting to retrieve the element indicated by each step.
    272         if(element.indexOf(SF_SEP) != -1) {
    273         StringTokenizer tokenizer = new StringTokenizer(element, SF_SEP);
     242        if(element.indexOf(MSMUtils.SF_SEP) != -1) {
     243        StringTokenizer tokenizer = new StringTokenizer(element, new Character(MSMUtils.SF_SEP).toString());
    274244        // Has to be at least two tokens
    275245        if(tokenizer.countTokens() >= 2) {
     
    285255        tokenizer = null;
    286256        }
    287         // No subfields - much easier.
     257        // No subelements - much easier.
    288258        if(result == null) {
    289259        ///ystem.err.print("Trying to match element " + element +"?");
     
    299269    return result;
    300270    }
     271
    301272    /** Retrieve a certain named element from a certain named set.
    302273     * @param set The metadata set whose element you want.
     
    312283    }
    313284
     285
    314286    /** Retrieve the named metadata set.
    315287     * @param name The sets name as a String.
     
    320292        return (MetadataSet) mds_hashtable.get(namespace);
    321293    }
    322 //  else if(name.equals(HIDDEN)) {
    323 //      return createHidden();
    324 //  }
    325294    return null;
    326295    }
     
    383352        //Now check our metadata.set's namespace to see if it is already loaded in all_sets
    384353        for(int p = 0 ; p < i; p++) {
    385  
    386                 if(metadata_set.getFile().compareTo(all_sets[p]) == 0) {
    387                    // System.err.println("Not loading set: "+ metadata_set.getNamespace() + " is already loaded.\n");
    388                    // JOptionPane.showMessageDialog(self, Dictionary.get("MEM.Cannot_Add_Elements_To_Greenstone_MDS"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
    389                     gemsptr.warn_cant_load_set();
    390                    
    391                     return null;
    392                  }
    393                
     354        if(metadata_set.getFile().compareTo(all_sets[p]) == 0) {
     355        gemsptr.warn_cant_load_set();
     356        return null;
     357        }
    394358        }
    395359   
    396360        //check if this metadata set belongs to a collection
    397         //if so, then change the metadata set's name in the interface to (collection) dublic core...
    398      // System.out.println(new String("asdfd" + metadata_set.getFile().separator));
     361        //if so, then change the metadata set's name in the interface to (collection) dublin core...
    399362    String sep = new String(metadata_set.getFile().separator);
    400        StringTokenizer st = new StringTokenizer(metadata_set.getFile().toString(), sep);
    401        String colName = new String("");
    402        
     363    StringTokenizer st = new StringTokenizer(metadata_set.getFile().toString(), sep);
     364    String colName = new String("");
     365   
    403366        while ( st.hasMoreTokens() )
    404367        {
    405368           if(st.nextToken().compareTo("collect") == 0) {
    406             colName = st.nextToken(); 
    407            // metadata_set.old_filename = metadata_set.getName();
    408            // metadata_set.setName(new String("(" + colName + ") " + metadata_set.getName()) );
    409             break;
     369           colName = st.nextToken(); 
     370           break;
    410371           }   
    411372        }
    412373
    413         //Actual set loading code(if it gets this far-Attila
    414     //**************
    415     //mds_hashtable.put(metadata_set.getNamespace(), metadata_set);
    416374    if (colName.equals("")) {
    417         //mds_hashtable.put(colName+":"+metadata_set.getNamespace(), metadata_set);
    418375        mds_hashtable.put(metadata_set.getNamespace(), metadata_set);
    419376    } else {
     
    423380    return metadata_set;
    424381    }
     382
    425383
    426384    /**
     
    449407
    450408
    451  /**
     409    /**
    452410       Rename the metadata element.
    453411       @param oldElement An <strong>ElementWrapper</strong> we wish to rename
     
    471429    }
    472430
    473 /*Following write() and write() and save() were taken from msm/metadatasetmanager.java and converted to
    474  *the gems standard
    475  */
     431
     432    /*Following write() and write() and save() were taken from msm/metadatasetmanager.java and converted to
     433     *the gems standard
     434     */
    476435     private void write(ElementWrapper element, GValueModel model, String etc_dir) {
    477436    try {
     
    503462    w.write(buffer, 0, buffer.length);
    504463    }
    505  public void save() {
    506      // Create the correct file to save these sets to...
    507      //File file = new File(Gatherer.self.getCollectionMetadata());
    508      //File file = new File(GEMS.config.gsdl_path + "/gli/metadata");
    509      File file = new File(Utility.METADATA_DIR);
    510 
    511      
    512      if (!file.exists()) {
    513      //DebugStream.println("trying to save a collection and the metadata directory does not exist - creating it!");
    514      System.out.println("trying to save a collection and the metadata directory does not exist - creating it!");
    515      
    516      file.mkdir();
    517      }
    518      // And make back ups of all existing metadata set files.
    519      File temp[] = file.listFiles();
    520      
    521      //Null ptr exception here? Didnt see it, -Attila
    522      /*for(int i = temp.length - 1; i >= 0; i--) {
    523      // System.out.println("Itter: " + i);
    524      if(temp[i].getName().endsWith(".mds") ) {
    525      File backup = new File(temp[i].getAbsolutePath() + "~bak");
    526                
    527                 //System.out.println(temp[i].getAbsolutePath()+ "asdf\n backupfile:"+ backup.toString());
    528                
    529                
    530         //backup.deleteOnExit();
    531                
    532         if(!temp[i].renameTo(backup)) {
    533             DebugStream.println("Error in MetadataSetManager.save(): FileRenamedException");
    534                     System.out.println("Error in MetadataSetManager.save(): FileRenamedException");
    535         }
    536         }
    537     }*/
    538      // Now save the latest versions of the metadata sets.
    539      for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
    540      String namespace = (String) keys.nextElement();
    541      MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
    542             //
    543             //col_man.loadCollection(GEMS.config.getString("general.open_collection",true));
    544             //
    545      try {
    546          // this won't work if we have collection metadata open
    547          //File mds_file = new File(file, set.getNamespace() + ".mds");
    548                
    549                 //set.setName(set.old_filename);
    550                
    551                 //set has not changed(or has been recently saved
    552              
    553              
    554              /*
    555                 if(set.getSetChanged() == false){
    556                   continue;   
    557                 }*/
    558                
    559          // just use the existing file path
    560          File mds_file = set.getFile();
    561                 //System.out.println(mds_file.toString() + "a\n");
    562                //Saves the DOM obj that set.getDocument returns to mds_file name
    563                // set.getF
    564                // System.out.println(keys.toString());
    565                
    566                
    567             // System.out.println("::: " + mds_file.toString());
    568          XMLTools.writeXMLFile(mds_file, set.getDocument());
    569              
    570              set.setSetChanged(false);
    571          //What does setfile do?
    572          //set.setFile(mds_file);
    573          //}
    574         // Now for each element attempt to save its value tree.
    575         //NodeList elements = set.getElements();
    576         //for(int i = elements.getLength() - 1; i >= 0; i--) {
    577           //  ElementWrapper value_element = new ElementWrapper((Element)elements.item(i));
    578             //if(value_element.hasValueTree()) {
    579             //GValueModel value_tree = set.getValueTree(value_element);
    580             //if(value_tree != null) {
    581                 //File value_file = new File(file, value_element.getName() + ".mdv");
    582                 ///ystem.err.println("Saving value file: " + value_file.toString());
    583                 //Utility.export(value_tree.getDocument(), value_file);
    584                 // If this is a hierarchy element, write hierarchy file.
    585                 //if(value_element.getNamespace().equals(MetadataSetManager.HIDDEN) || value_tree.isHierarchy()) {
    586                 //System.out.println("Val Tree: " +value_file.toString() + "\n");
    587                                // value_element.
    588                                // System.out.println(col_man.getCollectionEtc() + "<--getColEtc\n");
    589                           //      write(value_element, value_tree, new String("/home/arosmain/gsdl/gli/"));
    590                 //}
    591             //}
    592             //}
    593                     //System.out.println("Val element: "+value_element.toString() + "\n");
    594         //}
     464
     465    public void save() {
     466    File file = new File(Utility.METADATA_DIR);
     467       
     468    if (!file.exists()) {
     469        System.out.println("trying to save a collection and the metadata directory does not exist - creating it!");
     470       
     471        file.mkdir();
     472    }
     473    // And make back ups of all existing metadata set files.
     474    File temp[] = file.listFiles();
     475   
     476    // Now save the latest versions of the metadata sets.
     477    for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
     478        String namespace = (String) keys.nextElement();
     479        MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
     480        try {
     481        // just use the existing file path
     482        File mds_file = set.getFile();
     483        XMLTools.writeXMLFile(mds_file, set.getDocument());
     484        set.setSetChanged(false);
    595485        }
    596486        catch (Exception error) {
     
    598488        }
    599489    }
    600     //profiler.save();
    601     }
     490    }
     491   
    602492    public void removeSet(MetadataSet set) {
    603493    mds_hashtable.remove(set.getNamespace());
    604494        File f =  set.getFile();
    605495        f.delete();
    606         //System.out.println(f.toString() + Utility.METADATA_DIR);
    607     // fireSetChanged(set);
    608496    }
    609497}
Note: See TracChangeset for help on using the changeset viewer.