⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 genericentity.java

📁 国外的一套开源CRM
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    /** Makes an XML Element object with an attribute for each field of the entity
     *@param document The XML Document that the new Element will be part of
     *@return org.w3c.dom.Element object representing this generic entity
     */
    public Element makeXmlElement(Document document) {
        return makeXmlElement(document, null);
    }

    /** Makes an XML Element object with an attribute for each field of the entity
     *@param document The XML Document that the new Element will be part of
     *@param prefix A prefix to put in front of the entity name in the tag name
     *@return org.w3c.dom.Element object representing this generic entity
     */
    public Element makeXmlElement(Document document, String prefix) {
        Element element = null;

        if (prefix == null) prefix = "";
        if (document != null) element = document.createElement(prefix + this.getEntityName());
        // else element = new ElementImpl(null, this.getEntityName());
        if (element == null) return null;

        Iterator modelFields = this.getModelEntity().getFieldsIterator();
        while (modelFields.hasNext()) {
            ModelField modelField = (ModelField) modelFields.next();
            String name = modelField.getName();
            String value = this.getString(name);

            if (value != null) {
                if (value.indexOf('\n') >= 0 || value.indexOf('\r') >= 0) {
                    UtilXml.addChildElementCDATAValue(element, name, value, document);
                } else {
                    element.setAttribute(name, value);
                }
            }
        }

        return element;
    }

    /** Writes XML text with an attribute or CDATA element for each field of the entity
     *@param writer A PrintWriter to write to
     *@param prefix A prefix to put in front of the entity name in the tag name
     */
    public void writeXmlText(PrintWriter writer, String prefix) {
        final int indent = 4;

        if (prefix == null) prefix = "";

        for (int i = 0; i < indent; i++) writer.print(' ');
        writer.print('<');
        writer.print(prefix);
        writer.print(this.getEntityName());

        // write attributes immediately and if a CDATA element is needed, put those in a Map for now
        Map cdataMap = new HashMap();

        Iterator modelFields = this.getModelEntity().getFieldsIterator();
        while (modelFields.hasNext()) {
            ModelField modelField = (ModelField) modelFields.next();
            String name = modelField.getName();
            String valueStr = this.getString(name);

            if (valueStr != null) {
                StringBuffer value = new StringBuffer(valueStr);
                boolean needsCdata = false;
                
                // check each character, if line-feed or carriage-return is found set needsCdata to true; also look for invalid characters
                for (int i = 0; i < value.length(); i++) {
                    char curChar = value.charAt(i);
                    /* Some common character for these invalid values, have seen these are mostly from MS Word, but may be part of some standard:
                     5 = ...
                     18 = apostrophe
                     19 = left quotation mark
                     20 = right quotation mark
                     22 = –
                     23 = -
                     25 = tm
                     * 
                     */                            
                    
                    switch (curChar) {
                    case '\'':
                        value.replace(i, i+1, "&apos;");
                        break;
                    case '"':
                        value.replace(i, i+1, "&quot;");
                        break;
                    case '&':
                        value.replace(i, i+1, "&amp;");
                        break;
                    case '<':
                        value.replace(i, i+1, "&lt;");
                        break;
                    case '>':
                        value.replace(i, i+1, "&gt;");
                        break;
                    case 0xA: // newline, \n
                        needsCdata = true;
                        break;
                    case 0xD: // carriage return, \r
                        needsCdata = true;
                        break;
                    case 0x9: // tab
                        // do nothing, just catch here so it doesn't get into the default
                        break;
                    case 0x5: // elipses (...)
                        value.replace(i, i+1, "...");
                        break;
                    case 0x12: // apostrophe
                        value.replace(i, i+1, "&apos;");
                        break;
                    case 0x13: // left quote
                        value.replace(i, i+1, "&quot;");
                        break;
                    case 0x14: // right quote
                        value.replace(i, i+1, "&quot;");
                        break;
                    case 0x16: // big(?) dash -
                        value.replace(i, i+1, "-");
                        break;
                    case 0x17: // dash -
                        value.replace(i, i+1, "-");
                        break;
                    case 0x19: // tm
                        value.replace(i, i+1, "tm");
                        break;
                    default:
                        if (curChar < 0x20) {
                            // if it is less that 0x20 at this point it is invalid because the only valid values < 0x20 are 0x9, 0xA, 0xD as caught above
                            Debug.logInfo("Removing invalid character [" + curChar + "] numeric value [" + (int) curChar + "] for field " + name + " of entity with PK: " + this.getPrimaryKey().toString(), module);
                            value.deleteCharAt(i);
                        }
                    }
                }
                
                if (needsCdata) {
                    cdataMap.put(name, value.toString());
                } else {
                    writer.print(' ');
                    writer.print(name);
                    writer.print("=\"");
                    // encode the value...
                    writer.print(value.toString());
                    writer.print("\"");
                }
            }
        }

        if (cdataMap.size() == 0) {
            writer.println("/>");
        } else {
            writer.println('>');

            Iterator cdataIter = cdataMap.entrySet().iterator();

            while (cdataIter.hasNext()) {
                Map.Entry entry = (Map.Entry) cdataIter.next();

                for (int i = 0; i < (indent << 1); i++) writer.print(' ');
                writer.print('<');
                writer.print((String) entry.getKey());
                writer.print("><![CDATA[");
                writer.print((String) entry.getValue());
                writer.print("]]></");
                writer.print((String) entry.getKey());
                writer.println('>');
            }

            // don't forget to close the entity.
            for (int i = 0; i < indent; i++) writer.print(' ');
            writer.print("</");
            writer.print(this.getEntityName());
            writer.println(">");
        }
    }

    /** Determines the equality of two GenericEntity objects, overrides the default equals
     *@param  obj  The object (GenericEntity) to compare this two
     *@return      boolean stating if the two objects are equal
     */
    public boolean equals(Object obj) {
        if (obj == null) return false;

        // from here, use the compareTo method since it is more efficient:
        try {
            return this.compareTo(obj) == 0;
        } catch (ClassCastException e) {
            return false;
        }
    }

    /** Creates a hashCode for the entity, using the default String hashCode and Map hashCode, overrides the default hashCode
     *@return    Hashcode corresponding to this entity
     */
    public int hashCode() {
        // divide both by two (shift to right one bit) to maintain scale and add together
        return getEntityName().hashCode() >> 1 + fields.hashCode() >> 1;
    }

    /** Creates a String for the entity, overrides the default toString
     *@return    String corresponding to this entity
     */
    public String toString() {
        StringBuffer theString = new StringBuffer();

        theString.append("[GenericEntity:");
        theString.append(getEntityName());
        theString.append(']');

        Iterator entries = fields.entrySet().iterator();
        Map.Entry anEntry = null;

        while (entries.hasNext()) {
            anEntry = (Map.Entry) entries.next();
            theString.append('[');
            theString.append(anEntry.getKey());
            theString.append(',');
            theString.append(anEntry.getValue());
            theString.append('(');
            theString.append(anEntry.getValue() != null ? anEntry.getValue().getClass().getName() : "");
            theString.append(')');
            theString.append(']');
        }
        return theString.toString();
    }

    /** Compares this GenericEntity to the passed object
     *@param obj Object to compare this to
     *@return int representing the result of the comparison (-1,0, or 1)
     */
    public int compareTo(Object obj) {
        // if null, it will push to the beginning
        if (obj == null) return -1;

        // rather than doing an if instanceof, just cast it and let it throw an exception if
        // it fails, this will be faster for the expected case (that it IS a GenericEntity)
        // if not a GenericEntity throw ClassCastException, as the spec says
        GenericEntity that = (GenericEntity) obj;

        int tempResult = this.entityName.compareTo(that.entityName);

        // if they did not match, we know the order, otherwise compare the primary keys
        if (tempResult != 0) return tempResult;

        // both have same entityName, should be the same so let's compare PKs
        int pksSize = modelEntity.getPksSize();

        for (int i = 0; i < pksSize; i++) {
            ModelField curField = modelEntity.getPk(i);
            Comparable thisVal = (Comparable) this.fields.get(curField.getName());
            Comparable thatVal = (Comparable) that.fields.get(curField.getName());

            if (thisVal == null) {
                if (thatVal == null)
                    tempResult = 0;
                // if thisVal is null, but thatVal is not, return 1 to put this earlier in the list
                else
                    tempResult = 1;
            } else {
                // if thatVal is null, put the other earlier in the list
                if (thatVal == null)
                    tempResult = -1;
                else
                    tempResult = thisVal.compareTo(thatVal);
            }
            if (tempResult != 0) return tempResult;
        }

        // okay, if we got here it means the primaryKeys are exactly the SAME, so compare the rest of the fields
        int nopksSize = modelEntity.getNopksSize();

        for (int i = 0; i < nopksSize; i++) {
            ModelField curField = modelEntity.getNopk(i);
            Comparable thisVal = (Comparable) this.fields.get(curField.getName());
            Comparable thatVal = (Comparable) that.fields.get(curField.getName());

            if (thisVal == null) {
                if (thatVal == null)
                    tempResult = 0;
                // if thisVal is null, but thatVal is not, return 1 to put this earlier in the list
                else
                    tempResult = 1;
            } else {
                // if thatVal is null, put the other earlier in the list
                if (thatVal == null)
                    tempResult = -1;
                else
                    tempResult = thisVal.compareTo(thatVal);
            }
            if (tempResult != 0) return tempResult;
        }

        // if we got here it means the two are exactly the same, so return tempResult, which should be 0
        return tempResult;
    }

    /** Clones this GenericEntity, this is a shallow clone & uses the default shallow HashMap clone
     *@return Object that is a clone of this GenericEntity
     */
    public Object clone() {
        GenericEntity newEntity = new GenericEntity(this);

        newEntity.setDelegator(internalDelegator);
        return newEntity;
    }

    // ---- Methods added to implement the Map interface: ----

    public Object remove(Object key) {
        return fields.remove(key);
    }

    public boolean containsKey(Object key) {
        return fields.containsKey(key);
    }

    public java.util.Set entrySet() {
        return fields.entrySet();
    }

    public Object put(Object key, Object value) {
        return this.set((String) key, value, true);
    }

    public void putAll(java.util.Map map) {
        this.setFields(map);
    }

    public void clear() {
        this.fields.clear();
    }

    public Object get(Object key) {
        try {
            return this.get((String) key);
        } catch (IllegalArgumentException e) {
            Debug.logWarning(e, "The field name (or key) [" + key + "] is not valid, printing IllegalArgumentException instead of throwing it because Map interface specification does not allow throwing that exception.", module);
            return null;
        }
    }

    public java.util.Set keySet() {
        return this.fields.keySet();
    }

    public boolean isEmpty() {
        return this.fields.isEmpty();
    }

    public java.util.Collection values() {
        return this.fields.values();
    }

    public boolean containsValue(Object value) {
        return this.fields.containsValue(value);
    }

    public int size() {
        return this.fields.size();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -