Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

In this page you can find the example usage for java.lang StringBuilder delete.

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:com.quinsoft.epamms.ZGlobal1_Operation.java

public int DecipherUsageKeyword(StringBuilder sbName, String openKey, String closeKey, StringBuilder sbKeyword,
        int keywordMaxLth, StringBuilder sbKeyValue, int keyValueMaxLth) {
    sbKeyword.setLength(0);/*w  w w. j  ava2s.  c  o  m*/
    sbKeyValue.setLength(0);
    int nLth = openKey.length();
    int nPos1 = sbName.indexOf(openKey);
    if (nPos1 >= 0) {
        int nPos2 = sbName.indexOf(closeKey, nPos1 + nLth);
        if (nPos2 >= 0) {
            String key = sbName.substring(nPos1 + nLth, nPos2);
            sbName.delete(nPos1, nPos2 + closeKey.length());
            sbKeyValue.append("(" + key + ")");
            int nPos = key.indexOf(' ', nLth);
            if (nPos > 0 && nPos < key.length() - 1) // ignore if space is leading or trailing
            {
                key = key.substring(0, nPos) + "#";
            }
            sbKeyword.append(key);
            sbName.insert(nPos1, "{{" + key + "}}");
            return 0;
        }
    }
    return -1;
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import data from a zip archive to a database table
 *
 * @param stmt               statement to use
 * @param zip                zip archive containing the zip entry
 * @param ze                 zip entry within the archive
 * @param xpath              xpath containing the entries to import
 * @param table              name of the table
 * @param executeInsertPhase execute the insert phase?
 * @param executeUpdatePhase execute the update phase?
 * @param updateColumns      columns that should be set to <code>null</code> in a first pass (insert)
 *                           and updated to the provided values in a second pass (update),
 *                           columns that should be used in the where clause have to be prefixed
 *                           with "KEY:", to assign a default value use the expression "columnname:default value",
 *                           if the default value is "@", it will be a negative counter starting at 0, decreasing.
 *                           If the default value starts with "%", it will be set to the column following the "%"
 *                           character in the first pass
 * @throws Exception on errors//from w w  w  .  j  av a2s .  com
 */
protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath,
        final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase,
        final String... updateColumns) throws Exception {
    //analyze the table
    final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2");
    StringBuilder sbInsert = new StringBuilder(500);
    StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null;
    if (rs == null)
        throw new IllegalArgumentException("Can not analyze table [" + table + "]!");
    sbInsert.append("INSERT INTO ").append(table).append(" (");
    final ResultSetMetaData md = rs.getMetaData();
    final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0
            ? new HashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0
            ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null;
    //preset to a referenced column (%column syntax)
    final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10)
            : null;
    final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null;
    final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>(
            md.getColumnCount() + (counters != null ? counters.size() : 0));
    int insertIndex = 1;
    int updateSetIndex = 1;
    int updateClauseIndex = 1;
    boolean first = true;
    for (int i = 0; i < md.getColumnCount(); i++) {
        final String currCol = md.getColumnName(i + 1).toLowerCase();
        if (updateColumns.length > 0) {
            boolean abort = false;
            for (String col : updateColumns) {
                if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) {
                    String value = col.substring(col.indexOf(':') + 1);
                    col = col.substring(0, col.indexOf(':'));
                    if ("@".equals(value)) {
                        if (currCol.equalsIgnoreCase(col)) {
                            counters.put(col, 0);
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                        }
                    } else if (value.startsWith("%")) {
                        if (currCol.equalsIgnoreCase(col)) {
                            presetRefColumns.put(col, value.substring(1));
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                            //                                System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1));
                        }
                    } else if (!presetColumns.containsKey(col))
                        presetColumns.put(col, value);
                }
                if (currCol.equalsIgnoreCase(col)) {
                    abort = true;
                    updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++));
                    break;
                }
            }
            if (abort)
                continue;
        }
        if (first) {
            first = false;
        } else
            sbInsert.append(',');
        sbInsert.append(currCol);
        insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
    }
    if (updateColumns.length > 0 && executeUpdatePhase) {
        sbUpdate.append("UPDATE ").append(table).append(" SET ");
        int counter = 0;
        for (String updateColumn : updateSetColumns.keySet()) {
            if (counter++ > 0)
                sbUpdate.append(',');
            sbUpdate.append(updateColumn).append("=?");
        }
        sbUpdate.append(" WHERE ");
        boolean hasKeyColumn = false;
        for (String col : updateColumns) {
            if (!col.startsWith("KEY:"))
                continue;
            hasKeyColumn = true;
            String keyCol = col.substring(4);
            for (int i = 0; i < md.getColumnCount(); i++) {
                if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol))
                    continue;
                updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++));
                sbUpdate.append(keyCol).append("=? AND ");
                break;
            }

        }
        if (!hasKeyColumn)
            throw new IllegalArgumentException("Update columns require a KEY!");
        sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND "
        //"shift" clause indices
        for (String col : updateClauseColumns.keySet()) {
            GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col);
            ci.index += (updateSetIndex - 1);
        }
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(key);
    }
    sbInsert.append(")VALUES(");
    for (int i = 0; i < insertColumns.size(); i++) {
        if (i > 0)
            sbInsert.append(',');
        sbInsert.append('?');
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(presetColumns.get(key));
    }
    sbInsert.append(')');
    if (DBG) {
        LOG.info("Insert statement:\n" + sbInsert.toString());
        if (updateColumns.length > 0)
            LOG.info("Update statement:\n" + sbUpdate.toString());
    }
    //build a map containing all nodes that require attributes
    //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data"
    final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5);
    for (String pElem : xpath.split("/")) {
        if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0))
            continue;
        List<String> att = new ArrayList<String>(5);
        for (String pAtt : pElem.split("@")) {
            if (!(pAtt.indexOf('=') > 0))
                continue;
            att.add(pAtt.substring(0, pAtt.indexOf('=')));
        }
        queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att);
    }
    final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString());
    final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase
            ? stmt.getConnection().prepareStatement(sbUpdate.toString())
            : null;
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            int counter;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            boolean insertMode = true;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                counter = 0;
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void processingInstruction(String target, String data) throws SAXException {
                if (target != null && target.startsWith("fx_")) {
                    if (target.equals("fx_mode"))
                        insertMode = "insert".equals(data);
                } else
                    super.processingInstruction(target, data);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                if (insertMode)
                    LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath
                            + "]");
                else
                    LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpath)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            private void pushPath(String qName, Attributes att) {
                if (att.getLength() > 0 && queryAttributes.containsKey(qName)) {
                    String curr = qName + "[";
                    boolean first = true;
                    final List<String> attList = queryAttributes.get(qName);
                    for (int i = 0; i < att.getLength(); i++) {
                        if (!attList.contains(att.getQName(i)))
                            continue;
                        if (first)
                            first = false;
                        else
                            curr += ',';
                        curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'";
                    }
                    curr += ']';
                    path.add(curr);
                } else
                    path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpath)) {
                    if (DBG)
                        LOG.info("Insert [" + xpath + "]: [" + data + "]");
                    inTag = false;
                    try {
                        if (insertMode) {
                            if (executeInsertPhase) {
                                processColumnSet(insertColumns, psInsert);
                                counter += psInsert.executeUpdate();
                            }
                        } else {
                            if (executeUpdatePhase) {
                                if (processColumnSet(updateSetColumns, psUpdate)) {
                                    processColumnSet(updateClauseColumns, psUpdate);
                                    counter += psUpdate.executeUpdate();
                                }
                            }
                        }
                    } catch (SQLException e) {
                        throw new SAXException(e);
                    } catch (ParseException e) {
                        throw new SAXException(e);
                    }
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            /**
             * Process a column set
             *
             * @param columns the columns to process
             * @param ps prepared statement to use
             * @return if data other than <code>null</code> has been set
             * @throws SQLException on errors
             * @throws ParseException on date/time conversion errors
             */
            private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps)
                    throws SQLException, ParseException {
                boolean dataSet = false;
                for (String col : columns.keySet()) {
                    ColumnInfo ci = columns.get(col);
                    String value = data.get(col);
                    if (insertMode && counters != null && counters.get(col) != null) {
                        final int newVal = counters.get(col) - 1;
                        value = String.valueOf(newVal);
                        counters.put(col, newVal);
                        //                            System.out.println("new value for " + col + ": " + newVal);
                    }
                    if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) {
                        value = data.get(presetRefColumns.get(col));
                        //                            System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]");
                    }

                    if (value == null)
                        ps.setNull(ci.index, ci.columnType);
                    else {
                        dataSet = true;
                        switch (ci.columnType) {
                        case Types.BIGINT:
                        case Types.NUMERIC:
                            if (DBG)
                                LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value));
                            ps.setBigDecimal(ci.index, new BigDecimal(value));
                            break;
                        case java.sql.Types.DOUBLE:
                            if (DBG)
                                LOG.info("Double " + ci.index + "->" + Double.parseDouble(value));
                            ps.setDouble(ci.index, Double.parseDouble(value));
                            break;
                        case java.sql.Types.FLOAT:
                        case java.sql.Types.REAL:
                            if (DBG)
                                LOG.info("Float " + ci.index + "->" + Float.parseFloat(value));
                            ps.setFloat(ci.index, Float.parseFloat(value));
                            break;
                        case java.sql.Types.TIMESTAMP:
                        case java.sql.Types.DATE:
                            if (DBG)
                                LOG.info("Timestamp/Date " + ci.index + "->"
                                        + FxFormatUtils.getDateTimeFormat().parse(value));
                            ps.setTimestamp(ci.index,
                                    new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime()));
                            break;
                        case Types.TINYINT:
                        case Types.SMALLINT:
                            if (DBG)
                                LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value));
                            ps.setInt(ci.index, Integer.valueOf(value));
                            break;
                        case Types.INTEGER:
                        case Types.DECIMAL:
                            try {
                                if (DBG)
                                    LOG.info("Long " + ci.index + "->" + Long.valueOf(value));
                                ps.setLong(ci.index, Long.valueOf(value));
                            } catch (NumberFormatException e) {
                                //Fallback (temporary) for H2 if the reported long is a big decimal (tree...)
                                ps.setBigDecimal(ci.index, new BigDecimal(value));
                            }
                            break;
                        case Types.BIT:
                        case Types.CHAR:
                        case Types.BOOLEAN:
                            if (DBG)
                                LOG.info("Boolean " + ci.index + "->" + value);
                            if ("1".equals(value) || "true".equals(value))
                                ps.setBoolean(ci.index, true);
                            else
                                ps.setBoolean(ci.index, false);
                            break;
                        case Types.LONGVARBINARY:
                        case Types.VARBINARY:
                        case Types.BLOB:
                        case Types.BINARY:
                            ZipEntry bin = zip.getEntry(value);
                            if (bin == null) {
                                LOG.error("Failed to lookup binary [" + value + "]!");
                                ps.setNull(ci.index, ci.columnType);
                                break;
                            }
                            try {
                                ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize());
                            } catch (IOException e) {
                                LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e);
                            }
                            break;
                        case Types.CLOB:
                        case Types.LONGVARCHAR:
                        case Types.VARCHAR:
                        case SQL_LONGNVARCHAR:
                        case SQL_NCHAR:
                        case SQL_NCLOB:
                        case SQL_NVARCHAR:
                            if (DBG)
                                LOG.info("String " + ci.index + "->" + value);
                            ps.setString(ci.index, value);
                            break;
                        default:
                            LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]");
                        }
                    }
                }
                return dataSet;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        handler.processingInstruction("fx_mode", "insert");
        parser.parse(zip.getInputStream(ze), handler);
        if (updateColumns.length > 0 && executeUpdatePhase) {
            handler.processingInstruction("fx_mode", "update");
            parser.parse(zip.getInputStream(ze), handler);
        }
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate);
    }
}

From source file:com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.java

protected void fillHostInfo(final Connection conn, final StartupRoutingCommand cmd) {
    final StringBuilder caps = new StringBuilder();
    try {//from ww  w.ja v a 2  s  . c o  m

        final Host host = Host.getByUuid(conn, _host.getUuid());
        final Host.Record hr = host.getRecord(conn);

        Map<String, String> details = cmd.getHostDetails();
        if (details == null) {
            details = new HashMap<String, String>();
        }

        String productBrand = hr.softwareVersion.get("product_brand");
        if (productBrand == null) {
            productBrand = hr.softwareVersion.get("platform_name");
        }
        details.put("product_brand", productBrand);
        details.put("product_version", _host.getProductVersion());
        if (hr.softwareVersion.get("product_version_text_short") != null) {
            details.put("product_version_text_short", hr.softwareVersion.get("product_version_text_short"));
            cmd.setHypervisorVersion(hr.softwareVersion.get("product_version_text_short"));

            cmd.setHypervisorVersion(_host.getProductVersion());
        }
        if (_privateNetworkName != null) {
            details.put("private.network.device", _privateNetworkName);
        }

        cmd.setHostDetails(details);
        cmd.setName(hr.nameLabel);
        cmd.setGuid(_host.getUuid());
        cmd.setPool(_host.getPool());
        cmd.setDataCenter(Long.toString(_dcId));
        for (final String cap : hr.capabilities) {
            if (cap.length() > 0) {
                caps.append(cap).append(" , ");
            }
        }
        if (caps.length() > 0) {
            caps.delete(caps.length() - 3, caps.length());
        }
        cmd.setCaps(caps.toString());

        cmd.setSpeed(_host.getSpeed());
        cmd.setCpuSockets(_host.getCpuSockets());
        cmd.setCpus(_host.getCpus());

        final HostMetrics hm = host.getMetrics(conn);

        long ram = 0;
        long dom0Ram = 0;
        ram = hm.getMemoryTotal(conn);
        final Set<VM> vms = host.getResidentVMs(conn);
        for (final VM vm : vms) {
            if (vm.getIsControlDomain(conn)) {
                dom0Ram = vm.getMemoryStaticMax(conn);
                break;
            }
        }

        ram = (long) ((ram - dom0Ram - _xsMemoryUsed) * _xsVirtualizationFactor);
        cmd.setMemory(ram);
        cmd.setDom0MinMemory(dom0Ram);

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Total Ram: " + ram + " dom0 Ram: " + dom0Ram);
        }

        PIF pif = PIF.getByUuid(conn, _host.getPrivatePif());
        PIF.Record pifr = pif.getRecord(conn);
        if (pifr.IP != null && pifr.IP.length() > 0) {
            cmd.setPrivateIpAddress(pifr.IP);
            cmd.setPrivateMacAddress(pifr.MAC);
            cmd.setPrivateNetmask(pifr.netmask);
        } else {
            cmd.setPrivateIpAddress(_host.getIp());
            cmd.setPrivateMacAddress(pifr.MAC);
            cmd.setPrivateNetmask("255.255.255.0");
        }

        pif = PIF.getByUuid(conn, _host.getPublicPif());
        pifr = pif.getRecord(conn);
        if (pifr.IP != null && pifr.IP.length() > 0) {
            cmd.setPublicIpAddress(pifr.IP);
            cmd.setPublicMacAddress(pifr.MAC);
            cmd.setPublicNetmask(pifr.netmask);
        }

        if (_host.getStoragePif1() != null) {
            pif = PIF.getByUuid(conn, _host.getStoragePif1());
            pifr = pif.getRecord(conn);
            if (pifr.IP != null && pifr.IP.length() > 0) {
                cmd.setStorageIpAddress(pifr.IP);
                cmd.setStorageMacAddress(pifr.MAC);
                cmd.setStorageNetmask(pifr.netmask);
            }
        }

        if (_host.getStoragePif2() != null) {
            pif = PIF.getByUuid(conn, _host.getStoragePif2());
            pifr = pif.getRecord(conn);
            if (pifr.IP != null && pifr.IP.length() > 0) {
                cmd.setStorageIpAddressDeux(pifr.IP);
                cmd.setStorageMacAddressDeux(pifr.MAC);
                cmd.setStorageNetmaskDeux(pifr.netmask);
            }
        }

        final Map<String, String> configs = hr.otherConfig;
        cmd.setIqn(configs.get("iscsi_iqn"));

        cmd.setPod(_pod);
        cmd.setVersion(CitrixResourceBase.class.getPackage().getImplementationVersion());

        try {
            final String cmdLine = "xe sm-list | grep \"resigning of duplicates\"";

            final XenServerUtilitiesHelper xenServerUtilitiesHelper = getXenServerUtilitiesHelper();

            Pair<Boolean, String> result = xenServerUtilitiesHelper.executeSshWrapper(_host.getIp(), 22,
                    _username, null, getPwdFromQueue(), cmdLine);

            boolean supportsClonedVolumes = result != null && result.first() != null && result.first()
                    && result.second() != null && result.second().length() > 0;

            cmd.setSupportsClonedVolumes(supportsClonedVolumes);
        } catch (NumberFormatException ex) {
            s_logger.warn("Issue sending 'xe sm-list' via SSH to XenServer host: " + ex.getMessage());
        }
    } catch (final XmlRpcException e) {
        throw new CloudRuntimeException("XML RPC Exception: " + e.getMessage(), e);
    } catch (final XenAPIException e) {
        throw new CloudRuntimeException("XenAPIException: " + e.toString(), e);
    } catch (final Exception e) {
        throw new CloudRuntimeException("Exception: " + e.toString(), e);
    }
}

From source file:com.irccloud.android.ColorFormatter.java

public static String irc_to_html(String msg) {
    if (msg == null)
        return "";

    int pos = 0;//from   w ww.j a  v  a 2 s.c o m
    boolean bold = false, underline = false, italics = false;
    String fg = "", bg = "";
    StringBuilder builder = new StringBuilder(msg);
    builder.insert(0, "<irc>");

    while (pos < builder.length()) {
        if (builder.charAt(pos) == 2) { //Bold
            String html = "";
            if (bold) {
                html += "</b>";
                if (fg.length() > 0) {
                    html += "</font>";
                }
                if (bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (italics)
                    html += "</i>";
                if (underline)
                    html += "</u>";
                if (fg.length() > 0) {
                    html += "<font color=\"#" + fg + "\">";
                }
                if (bg.length() > 0) {
                    html += "<_bg" + bg + ">";
                }
                if (italics)
                    html += "<i>";
                if (underline)
                    html += "<u>";
            } else {
                html += "<b>";
            }
            bold = !bold;
            builder.deleteCharAt(pos);
            builder.insert(pos, html);
        } else if (builder.charAt(pos) == 22 || builder.charAt(pos) == 29) { //Italics
            String html = "";
            if (italics) {
                html += "</i>";
                if (fg.length() > 0) {
                    html += "</font>";
                }
                if (bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (bold)
                    html += "</b>";
                if (underline)
                    html += "</u>";
                if (fg.length() > 0) {
                    html += "<font color=\"#" + fg + "\">";
                }
                if (bg.length() > 0) {
                    html += "<_bg" + bg + ">";
                }
                if (bold)
                    html += "<b>";
                if (underline)
                    html += "<u>";
            } else {
                html += "<i>";
            }
            italics = !italics;
            builder.deleteCharAt(pos);
            builder.insert(pos, html);
        } else if (builder.charAt(pos) == 31) { //Underline
            String html = "";
            if (underline) {
                html += "</u>";
                if (fg.length() > 0) {
                    html += "</font>";
                }
                if (bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (bold)
                    html += "</b>";
                if (italics)
                    html += "</i>";
                if (fg.length() > 0) {
                    html += "<font color=\"#" + fg + "\">";
                }
                if (bg.length() > 0) {
                    html += "<_bg" + bg + ">";
                }
                if (bold)
                    html += "<b>";
                if (italics)
                    html += "<i>";
            } else {
                html += "<u>";
            }
            underline = !underline;
            builder.deleteCharAt(pos);
            builder.insert(pos, html);
        } else if (builder.charAt(pos) == 15) { //Formatting clear
            String html = "";
            if (fg.length() > 0) {
                html += "</font>";
                fg = "";
            }
            if (bg.length() > 0) {
                html += "</_bg" + bg + ">";
                bg = "";
            }
            if (bold) {
                html += "</b>";
                bold = false;
            }
            if (underline) {
                html += "</u>";
                underline = false;
            }
            if (italics) {
                html += "</i>";
                italics = false;
            }
            builder.deleteCharAt(pos);
            if (html.length() > 0)
                builder.insert(pos, html);
        } else if (builder.charAt(pos) == 3 || builder.charAt(pos) == 4) { //Color
            boolean rgb = (builder.charAt(pos) == 4);
            int count = 0;
            String new_fg = "", new_bg = "";
            builder.deleteCharAt(pos);
            if (pos < builder.length()) {
                while (pos + count < builder.length()
                        && ((builder.charAt(pos + count) >= '0' && builder.charAt(pos + count) <= '9') || rgb
                                && ((builder.charAt(pos + count) >= 'a' && builder.charAt(pos + count) <= 'f')
                                        || (builder.charAt(pos + count) >= 'A'
                                                && builder.charAt(pos + count) <= 'F')))) {
                    if ((++count == 2 && !rgb) || count == 6)
                        break;
                }
                if (count > 0) {
                    if (count < 3 && !rgb) {
                        try {
                            int col = Integer.parseInt(builder.substring(pos, pos + count));
                            if (col > 15) {
                                count--;
                                col /= 10;
                            }
                            new_fg = COLOR_MAP[col];
                        } catch (NumberFormatException e) {
                            new_fg = builder.substring(pos, pos + count);
                        }
                    } else
                        new_fg = builder.substring(pos, pos + count);
                    builder.delete(pos, pos + count);
                }
                if (pos < builder.length() && builder.charAt(pos) == ',') {
                    builder.deleteCharAt(pos);
                    if (new_fg.length() == 0)
                        new_fg = "clear";
                    new_bg = "clear";
                    count = 0;
                    while (pos + count < builder.length()
                            && ((builder.charAt(pos + count) >= '0' && builder.charAt(pos + count) <= '9')
                                    || rgb && ((builder.charAt(pos + count) >= 'a'
                                            && builder.charAt(pos + count) <= 'f')
                                            || (builder.charAt(pos + count) >= 'A'
                                                    && builder.charAt(pos + count) <= 'F')))) {
                        if ((++count == 2 && !rgb) || count == 6)
                            break;
                    }
                    if (count > 0) {
                        if (count < 3 && !rgb) {
                            try {
                                int col = Integer.parseInt(builder.substring(pos, pos + count));
                                if (col > 15) {
                                    count--;
                                    col /= 10;
                                }
                                new_bg = COLOR_MAP[col];
                            } catch (NumberFormatException e) {
                                new_bg = builder.substring(pos, pos + count);
                            }
                        } else
                            new_bg = builder.substring(pos, pos + count);
                        builder.delete(pos, pos + count);
                    } else {
                        builder.insert(pos, ",");
                    }
                }
                String html = "";
                if (new_fg.length() == 0 && new_bg.length() == 0) {
                    new_fg = "clear";
                    new_bg = "clear";
                }
                if (new_fg.length() > 0 && fg.length() > 0) {
                    html += "</font>";
                }
                if (new_bg.length() > 0 && bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (new_bg.length() > 0) {
                    if (new_bg.equals("clear")) {
                        bg = "";
                    } else {
                        bg = "";
                        if (new_bg.length() == 6) {
                            bg = new_bg;
                        } else if (new_bg.length() == 3) {
                            bg += new_bg.charAt(0);
                            bg += new_bg.charAt(0);
                            bg += new_bg.charAt(1);
                            bg += new_bg.charAt(1);
                            bg += new_bg.charAt(2);
                            bg += new_bg.charAt(2);
                        } else {
                            bg = "ffffff";
                        }
                        if (bg.length() > 0)
                            html += "<_bg" + bg + ">";
                    }
                }
                if (new_fg.length() > 0) {
                    if (new_fg.equals("clear")) {
                        fg = "";
                    } else {
                        fg = "";
                        if (new_fg.length() == 6) {
                            fg = new_fg;
                        } else if (new_fg.length() == 3) {
                            fg += new_fg.charAt(0);
                            fg += new_fg.charAt(0);
                            fg += new_fg.charAt(1);
                            fg += new_fg.charAt(1);
                            fg += new_fg.charAt(2);
                            fg += new_fg.charAt(2);
                        } else {
                            fg = "000000";
                        }
                    }
                    if (ColorScheme.getInstance().theme != null && bg.length() == 0) {
                        if (ColorScheme.getInstance().isDarkTheme && DARK_FG_SUBSTITUTIONS.containsKey(fg))
                            fg = DARK_FG_SUBSTITUTIONS.get(fg);
                        if (Integer.toHexString(ColorScheme.getInstance().contentBackgroundColor)
                                .equalsIgnoreCase("ff" + fg)) {
                            int red = Integer.parseInt(fg.substring(0, 1), 16);
                            int blue = Integer.parseInt(fg.substring(2, 3), 16);
                            int green = Integer.parseInt(fg.substring(4, 5), 16);

                            red += 0x22;
                            if (red > 0xFF)
                                red = 0xFF;
                            green += 0x22;
                            if (green > 0xFF)
                                green = 0xFF;
                            blue += 0x22;
                            if (blue > 0xFF)
                                blue = 0xFF;

                            fg = String.format("%02x%02x%02x", red, green, blue);
                        }
                    }
                    if (fg.length() > 0)
                        html += "<font color=\"#" + fg + "\">";
                }
                builder.insert(pos, html);
            }
        } else {
            pos++;
        }
    }
    if (fg.length() > 0) {
        builder.append("</font>");
    }
    if (bg.length() > 0) {
        builder.append("</_bg").append(bg).append(">");
    }
    if (bold)
        builder.append("</b>");
    if (underline)
        builder.append("</u>");
    if (italics)
        builder.append("</i>");

    builder.append("</irc>");
    return builder.toString();
}

From source file:forge.game.card.Card.java

public String getAbilityText(final CardState state) {
    final CardTypeView type = state.getType();

    final StringBuilder sb = new StringBuilder();
    if (!mayPlay.isEmpty()) {
        sb.append("May be played by: ");
        sb.append(/*from w  ww.  j  a  va2s.c  o  m*/
                Lang.joinHomogenous(mayPlay.entrySet(), new Function<Entry<Player, CardPlayOption>, String>() {
                    @Override
                    public String apply(final Entry<Player, CardPlayOption> entry) {
                        return entry.getKey().toString() + entry.getValue().toString();
                    }
                }));
        sb.append("\r\n");
    }

    if (type.isInstant() || type.isSorcery()) {
        sb.append(abilityTextInstantSorcery(state));

        if (haunting != null) {
            sb.append("Haunting: ").append(haunting);
            sb.append("\r\n");
        }

        while (sb.toString().endsWith("\r\n")) {
            sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3);
        }

        return sb.toString().replaceAll("CARDNAME", state.getName());
    }

    if (monstrous) {
        sb.append("Monstrous\r\n");
    }
    if (renowned) {
        sb.append("Renowned\r\n");
    }
    if (manifested) {
        sb.append("Manifested\r\n");
    }
    sb.append(keywordsToText(getUnhiddenKeywords(state)));

    // Give spellText line breaks for easier reading
    sb.append("\r\n");
    sb.append(text.replaceAll("\\\\r\\\\n", "\r\n"));
    sb.append("\r\n");

    // Triggered abilities
    for (final Trigger trig : state.getTriggers()) {
        if (!trig.isSecondary()) {
            sb.append(trig.toString().replaceAll("\\\\r\\\\n", "\r\n")).append("\r\n");
        }
    }

    // Replacement effects
    for (final ReplacementEffect replacementEffect : state.getReplacementEffects()) {
        if (!replacementEffect.isSecondary()) {
            sb.append(replacementEffect.toString()).append("\r\n");
        }
    }

    // static abilities
    for (final StaticAbility stAb : state.getStaticAbilities()) {
        sb.append(stAb.toString()).append("\r\n");
    }

    final List<String> addedManaStrings = new ArrayList<>();
    boolean primaryCost = true;
    boolean isNonAura = !type.hasSubtype("Aura");

    for (final SpellAbility sa : state.getSpellAbilities()) {
        // only add abilities not Spell portions of cards
        if (sa == null || !state.getType().isPermanent()) {
            continue;
        }

        boolean isNonAuraPermanent = (sa instanceof SpellPermanent) && isNonAura;
        if (isNonAuraPermanent && primaryCost) {
            // For Alt costs, make sure to display the cost!
            primaryCost = false;
            continue;
        }

        final String sAbility = formatSpellAbility(sa);

        if (sa.getManaPart() != null) {
            if (addedManaStrings.contains(sAbility)) {
                continue;
            }
            addedManaStrings.add(sAbility);
        }

        if (isNonAuraPermanent) {
            sb.insert(0, "\r\n");
            sb.insert(0, sAbility);
        } else if (!sAbility.endsWith(state.getName() + "\r\n")) {
            sb.append(sAbility);
            sb.append("\r\n");
        }
    }

    // NOTE:
    if (sb.toString().contains(" (NOTE: ")) {
        sb.insert(sb.indexOf("(NOTE: "), "\r\n");
    }
    if (sb.toString().contains("(NOTE: ") && sb.toString().contains(".) ")) {
        sb.insert(sb.indexOf(".) ") + 3, "\r\n");
    }

    // replace triple line feeds with double line feeds
    int start;
    final String s = "\r\n\r\n\r\n";
    while (sb.toString().contains(s)) {
        start = sb.lastIndexOf(s);
        if ((start < 0) || (start >= sb.length())) {
            break;
        }
        sb.replace(start, start + 4, "\r\n");
    }

    return sb.toString().replaceAll("CARDNAME", state.getName()).trim();
}

From source file:org.apache.accumulo.examples.wikisearch.logic.AbstractQueryLogic.java

public Results runQuery(Connector connector, List<String> authorizations, String query, Date beginDate,
        Date endDate, Set<String> types) {

    if (StringUtils.isEmpty(query)) {
        throw new IllegalArgumentException(
                "NULL QueryNode reference passed to " + this.getClass().getSimpleName());
    }/*  www.  ja  v  a 2s  .  c om*/

    Set<Range> ranges = new HashSet<Range>();
    Set<String> typeFilter = types;
    String array[] = authorizations.toArray(new String[0]);
    Authorizations auths = new Authorizations(array);
    Results results = new Results();

    // Get the query string
    String queryString = query;

    StopWatch abstractQueryLogic = new StopWatch();
    StopWatch optimizedQuery = new StopWatch();
    StopWatch queryGlobalIndex = new StopWatch();
    StopWatch optimizedEventQuery = new StopWatch();
    StopWatch fullScanQuery = new StopWatch();
    StopWatch processResults = new StopWatch();

    abstractQueryLogic.start();

    StopWatch parseQuery = new StopWatch();
    parseQuery.start();

    QueryParser parser;
    try {
        if (log.isDebugEnabled()) {
            log.debug("ShardQueryLogic calling QueryParser.execute");
        }
        parser = new QueryParser();
        parser.execute(queryString);
    } catch (org.apache.commons.jexl2.parser.ParseException e1) {
        throw new IllegalArgumentException("Error parsing query", e1);
    }
    int hash = parser.getHashValue();
    parseQuery.stop();
    if (log.isDebugEnabled()) {
        log.debug(hash + " Query: " + queryString);
    }

    Set<String> fields = new HashSet<String>();
    for (String f : parser.getQueryIdentifiers()) {
        fields.add(f);
    }
    if (log.isDebugEnabled()) {
        log.debug("getQueryIdentifiers: " + parser.getQueryIdentifiers().toString());
    }
    // Remove any negated fields from the fields list, we don't want to lookup negated fields
    // in the index.
    fields.removeAll(parser.getNegatedTermsForOptimizer());

    if (log.isDebugEnabled()) {
        log.debug("getQueryIdentifiers: " + parser.getQueryIdentifiers().toString());
    }
    // Get the mapping of field name to QueryTerm object from the query. The query term object
    // contains the operator, whether its negated or not, and the literal to test against.
    Multimap<String, QueryTerm> terms = parser.getQueryTerms();

    // Find out which terms are indexed
    // TODO: Should we cache indexed terms or does that not make sense since we are always
    // loading data.
    StopWatch queryMetadata = new StopWatch();
    queryMetadata.start();
    Map<String, Multimap<String, Class<? extends Normalizer>>> metadataResults;
    try {
        metadataResults = findIndexedTerms(connector, auths, fields, typeFilter);
    } catch (Exception e1) {
        throw new RuntimeException("Error in metadata lookup", e1);
    }

    // Create a map of indexed term to set of normalizers for it
    Multimap<String, Normalizer> indexedTerms = HashMultimap.create();
    for (Entry<String, Multimap<String, Class<? extends Normalizer>>> entry : metadataResults.entrySet()) {
        // Get the normalizer from the normalizer cache
        for (Class<? extends Normalizer> clazz : entry.getValue().values()) {
            indexedTerms.put(entry.getKey(), normalizerCacheMap.get(clazz));
        }
    }
    queryMetadata.stop();
    if (log.isDebugEnabled()) {
        log.debug(hash + " Indexed Terms: " + indexedTerms.toString());
    }

    Set<String> orTerms = parser.getOrTermsForOptimizer();

    // Iterate over the query terms to get the operators specified in the query.
    ArrayList<String> unevaluatedExpressions = new ArrayList<String>();
    boolean unsupportedOperatorSpecified = false;
    for (Entry<String, QueryTerm> entry : terms.entries()) {
        if (null == entry.getValue()) {
            continue;
        }

        if (null != this.unevaluatedFields && this.unevaluatedFields.contains(entry.getKey().trim())) {
            unevaluatedExpressions.add(entry.getKey().trim() + " " + entry.getValue().getOperator() + " "
                    + entry.getValue().getValue());
        }

        int operator = JexlOperatorConstants.getJJTNodeType(entry.getValue().getOperator());
        if (!(operator == ParserTreeConstants.JJTEQNODE || operator == ParserTreeConstants.JJTNENODE
                || operator == ParserTreeConstants.JJTLENODE || operator == ParserTreeConstants.JJTLTNODE
                || operator == ParserTreeConstants.JJTGENODE || operator == ParserTreeConstants.JJTGTNODE
                || operator == ParserTreeConstants.JJTERNODE)) {
            unsupportedOperatorSpecified = true;
            break;
        }
    }
    if (null != unevaluatedExpressions)
        unevaluatedExpressions.trimToSize();
    if (log.isDebugEnabled()) {
        log.debug(hash + " unsupportedOperators: " + unsupportedOperatorSpecified + " indexedTerms: "
                + indexedTerms.toString() + " orTerms: " + orTerms.toString() + " unevaluatedExpressions: "
                + unevaluatedExpressions.toString());
    }

    // We can use the intersecting iterator over the field index as an optimization under the
    // following conditions
    //
    // 1. No unsupported operators in the query.
    // 2. No 'or' operators and at least one term indexed
    // or
    // 1. No unsupported operators in the query.
    // 2. and all terms indexed
    // or
    // 1. All or'd terms are indexed. NOTE, this will potentially skip some queries and push to a full table scan
    // // WE should look into finding a better way to handle whether we do an optimized query or not.
    boolean optimizationSucceeded = false;
    boolean orsAllIndexed = false;
    if (orTerms.isEmpty()) {
        orsAllIndexed = false;
    } else {
        orsAllIndexed = indexedTerms.keySet().containsAll(orTerms);
    }

    if (log.isDebugEnabled()) {
        log.debug("All or terms are indexed");
    }

    if (!unsupportedOperatorSpecified && (((null == orTerms || orTerms.isEmpty()) && indexedTerms.size() > 0)
            || (fields.size() > 0 && indexedTerms.size() == fields.size()) || orsAllIndexed)) {
        optimizedQuery.start();
        // Set up intersecting iterator over field index.

        // Get information from the global index for the indexed terms. The results object will contain the term
        // mapped to an object that contains the total count, and partitions where this term is located.

        // TODO: Should we cache indexed term information or does that not make sense since we are always loading data
        queryGlobalIndex.start();
        IndexRanges termIndexInfo;
        try {
            // If fields is null or zero, then it's probably the case that the user entered a value
            // to search for with no fields. Check for the value in index.
            if (fields.isEmpty()) {
                termIndexInfo = this.getTermIndexInformation(connector, auths, queryString, typeFilter);
                if (null != termIndexInfo && termIndexInfo.getRanges().isEmpty()) {
                    // Then we didn't find anything in the index for this query. This may happen for an indexed term that has wildcards
                    // in unhandled locations.
                    // Break out of here by throwing a named exception and do full scan
                    throw new DoNotPerformOptimizedQueryException();
                }
                // We need to rewrite the query string here so that it's valid.
                if (termIndexInfo instanceof UnionIndexRanges) {
                    UnionIndexRanges union = (UnionIndexRanges) termIndexInfo;
                    StringBuilder buf = new StringBuilder();
                    String sep = "";
                    for (String fieldName : union.getFieldNamesAndValues().keySet()) {
                        buf.append(sep).append(fieldName).append(" == ");
                        if (!(queryString.startsWith("'") && queryString.endsWith("'"))) {
                            buf.append("'").append(queryString).append("'");
                        } else {
                            buf.append(queryString);
                        }
                        sep = " or ";
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Rewrote query for non-fielded single term query: " + queryString + " to "
                                + buf.toString());
                    }
                    queryString = buf.toString();
                } else {
                    throw new RuntimeException("Unexpected IndexRanges implementation");
                }
            } else {
                RangeCalculator calc = this.getTermIndexInformation(connector, auths, indexedTerms, terms,
                        this.getIndexTableName(), this.getReverseIndexTableName(), queryString,
                        this.queryThreads, typeFilter);
                if (null == calc.getResult() || calc.getResult().isEmpty()) {
                    // Then we didn't find anything in the index for this query. This may happen for an indexed term that has wildcards
                    // in unhandled locations.
                    // Break out of here by throwing a named exception and do full scan
                    throw new DoNotPerformOptimizedQueryException();
                }
                termIndexInfo = new UnionIndexRanges();
                termIndexInfo.setIndexValuesToOriginalValues(calc.getIndexValues());
                termIndexInfo.setFieldNamesAndValues(calc.getIndexEntries());
                termIndexInfo.getTermCardinality().putAll(calc.getTermCardinalities());
                for (Range r : calc.getResult()) {
                    // foo is a placeholder and is ignored.
                    termIndexInfo.add("foo", r);
                }
            }
        } catch (TableNotFoundException e) {
            log.error(this.getIndexTableName() + "not found", e);
            throw new RuntimeException(this.getIndexTableName() + "not found", e);
        } catch (org.apache.commons.jexl2.parser.ParseException e) {
            throw new RuntimeException("Error determining ranges for query: " + queryString, e);
        } catch (DoNotPerformOptimizedQueryException e) {
            log.info("Indexed fields not found in index, performing full scan");
            termIndexInfo = null;
        }
        queryGlobalIndex.stop();

        // Determine if we should proceed with optimized query based on results from the global index
        boolean proceed = false;
        if (null == termIndexInfo || termIndexInfo.getFieldNamesAndValues().values().size() == 0) {
            proceed = false;
        } else if (null != orTerms && orTerms.size() > 0
                && (termIndexInfo.getFieldNamesAndValues().values().size() == indexedTerms.size())) {
            proceed = true;
        } else if (termIndexInfo.getFieldNamesAndValues().values().size() > 0) {
            proceed = true;
        } else if (orsAllIndexed) {
            proceed = true;
        } else {
            proceed = false;
        }
        if (log.isDebugEnabled()) {
            log.debug("Proceed with optimized query: " + proceed);
            if (null != termIndexInfo)
                log.debug("termIndexInfo.getTermsFound().size(): "
                        + termIndexInfo.getFieldNamesAndValues().values().size() + " indexedTerms.size: "
                        + indexedTerms.size() + " fields.size: " + fields.size());
        }
        if (proceed) {

            if (log.isDebugEnabled()) {
                log.debug(hash + " Performing optimized query");
            }
            // Use the scan ranges from the GlobalIndexRanges object as the ranges for the batch scanner
            ranges = termIndexInfo.getRanges();
            if (log.isDebugEnabled()) {
                log.info(hash + " Ranges: count: " + ranges.size() + ", " + ranges.toString());
            }

            // Create BatchScanner, set the ranges, and setup the iterators.
            optimizedEventQuery.start();
            BatchScanner bs = null;
            try {
                bs = connector.createBatchScanner(this.getTableName(), auths, queryThreads);
                bs.setRanges(ranges);
                IteratorSetting si = new IteratorSetting(21, "eval", OptimizedQueryIterator.class);

                if (log.isDebugEnabled()) {
                    log.debug("Setting scan option: " + EvaluatingIterator.QUERY_OPTION + " to " + queryString);
                }
                // Set the query option
                si.addOption(EvaluatingIterator.QUERY_OPTION, queryString);
                // Set the Indexed Terms List option. This is the field name and normalized field value pair separated
                // by a comma.
                StringBuilder buf = new StringBuilder();
                String sep = "";
                for (Entry<String, String> entry : termIndexInfo.getFieldNamesAndValues().entries()) {
                    buf.append(sep);
                    buf.append(entry.getKey());
                    buf.append(":");
                    buf.append(termIndexInfo.getIndexValuesToOriginalValues().get(entry.getValue()));
                    buf.append(":");
                    buf.append(entry.getValue());
                    if (sep.equals("")) {
                        sep = ";";
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Setting scan option: " + FieldIndexQueryReWriter.INDEXED_TERMS_LIST + " to "
                            + buf.toString());
                }
                FieldIndexQueryReWriter rewriter = new FieldIndexQueryReWriter();
                String q = "";
                try {
                    q = queryString;
                    q = rewriter.applyCaseSensitivity(q, true, false);// Set upper/lower case for fieldname/fieldvalue
                    Map<String, String> opts = new HashMap<String, String>();
                    opts.put(FieldIndexQueryReWriter.INDEXED_TERMS_LIST, buf.toString());
                    q = rewriter.removeNonIndexedTermsAndInvalidRanges(q, opts);
                    q = rewriter.applyNormalizedTerms(q, opts);
                    if (log.isDebugEnabled()) {
                        log.debug("runServerQuery, FieldIndex Query: " + q);
                    }
                } catch (org.apache.commons.jexl2.parser.ParseException ex) {
                    log.error("Could not parse query, Jexl ParseException: " + ex);
                } catch (Exception ex) {
                    log.error("Problem rewriting query, Exception: " + ex.getMessage());
                }
                si.addOption(BooleanLogicIterator.FIELD_INDEX_QUERY, q);

                // Set the term cardinality option
                sep = "";
                buf.delete(0, buf.length());
                for (Entry<String, Long> entry : termIndexInfo.getTermCardinality().entrySet()) {
                    buf.append(sep);
                    buf.append(entry.getKey());
                    buf.append(":");
                    buf.append(entry.getValue());
                    sep = ",";
                }
                if (log.isDebugEnabled())
                    log.debug("Setting scan option: " + BooleanLogicIterator.TERM_CARDINALITIES + " to "
                            + buf.toString());
                si.addOption(BooleanLogicIterator.TERM_CARDINALITIES, buf.toString());
                if (this.useReadAheadIterator) {
                    if (log.isDebugEnabled()) {
                        log.debug("Enabling read ahead iterator with queue size: " + this.readAheadQueueSize
                                + " and timeout: " + this.readAheadTimeOut);
                    }
                    si.addOption(ReadAheadIterator.QUEUE_SIZE, this.readAheadQueueSize);
                    si.addOption(ReadAheadIterator.TIMEOUT, this.readAheadTimeOut);

                }

                if (null != unevaluatedExpressions) {
                    StringBuilder unevaluatedExpressionList = new StringBuilder();
                    String sep2 = "";
                    for (String exp : unevaluatedExpressions) {
                        unevaluatedExpressionList.append(sep2).append(exp);
                        sep2 = ",";
                    }
                    if (log.isDebugEnabled())
                        log.debug("Setting scan option: " + EvaluatingIterator.UNEVALUTED_EXPRESSIONS + " to "
                                + unevaluatedExpressionList.toString());
                    si.addOption(EvaluatingIterator.UNEVALUTED_EXPRESSIONS,
                            unevaluatedExpressionList.toString());
                }

                bs.addScanIterator(si);

                processResults.start();
                processResults.suspend();
                long count = 0;
                for (Entry<Key, Value> entry : bs) {
                    count++;
                    // The key that is returned by the EvaluatingIterator is not the same key that is in
                    // the table. The value that is returned by the EvaluatingIterator is a kryo
                    // serialized EventFields object.
                    processResults.resume();
                    Document d = this.createDocument(entry.getKey(), entry.getValue());
                    results.getResults().add(d);
                    processResults.suspend();
                }
                log.info(count + " matching entries found in optimized query.");
                optimizationSucceeded = true;
                processResults.stop();
            } catch (TableNotFoundException e) {
                log.error(this.getTableName() + "not found", e);
                throw new RuntimeException(this.getIndexTableName() + "not found", e);
            } finally {
                if (bs != null) {
                    bs.close();
                }
            }
            optimizedEventQuery.stop();
        }
        optimizedQuery.stop();
    }

    // WE should look into finding a better way to handle whether we do an optimized query or not.
    // We are not setting up an else condition here because we may have aborted the logic early in the if statement.
    if (!optimizationSucceeded || ((null != orTerms && orTerms.size() > 0)
            && (indexedTerms.size() != fields.size()) && !orsAllIndexed)) {
        // if (!optimizationSucceeded || ((null != orTerms && orTerms.size() > 0) && (indexedTerms.size() != fields.size()))) {
        fullScanQuery.start();
        if (log.isDebugEnabled()) {
            log.debug(hash + " Performing full scan query");
        }

        // Set up a full scan using the date ranges from the query
        // Create BatchScanner, set the ranges, and setup the iterators.
        BatchScanner bs = null;
        try {
            // The ranges are the start and end dates
            Collection<Range> r = getFullScanRange(beginDate, endDate, terms);
            ranges.addAll(r);

            if (log.isDebugEnabled()) {
                log.debug(hash + " Ranges: count: " + ranges.size() + ", " + ranges.toString());
            }

            bs = connector.createBatchScanner(this.getTableName(), auths, queryThreads);
            bs.setRanges(ranges);
            IteratorSetting si = new IteratorSetting(22, "eval", EvaluatingIterator.class);
            // Create datatype regex if needed
            if (null != typeFilter) {
                StringBuilder buf = new StringBuilder();
                String s = "";
                for (String type : typeFilter) {
                    buf.append(s).append(type).append(".*");
                    s = "|";
                }
                if (log.isDebugEnabled())
                    log.debug("Setting colf regex iterator to: " + buf.toString());
                IteratorSetting ri = new IteratorSetting(21, "typeFilter", RegExFilter.class);
                RegExFilter.setRegexs(ri, null, buf.toString(), null, null, false);
                bs.addScanIterator(ri);
            }
            if (log.isDebugEnabled()) {
                log.debug("Setting scan option: " + EvaluatingIterator.QUERY_OPTION + " to " + queryString);
            }
            si.addOption(EvaluatingIterator.QUERY_OPTION, queryString);
            if (null != unevaluatedExpressions) {
                StringBuilder unevaluatedExpressionList = new StringBuilder();
                String sep2 = "";
                for (String exp : unevaluatedExpressions) {
                    unevaluatedExpressionList.append(sep2).append(exp);
                    sep2 = ",";
                }
                if (log.isDebugEnabled())
                    log.debug("Setting scan option: " + EvaluatingIterator.UNEVALUTED_EXPRESSIONS + " to "
                            + unevaluatedExpressionList.toString());
                si.addOption(EvaluatingIterator.UNEVALUTED_EXPRESSIONS, unevaluatedExpressionList.toString());
            }
            bs.addScanIterator(si);
            long count = 0;
            processResults.start();
            processResults.suspend();
            for (Entry<Key, Value> entry : bs) {
                count++;
                // The key that is returned by the EvaluatingIterator is not the same key that is in
                // the partition table. The value that is returned by the EvaluatingIterator is a kryo
                // serialized EventFields object.
                processResults.resume();
                Document d = this.createDocument(entry.getKey(), entry.getValue());
                results.getResults().add(d);
                processResults.suspend();
            }
            processResults.stop();
            log.info(count + " matching entries found in full scan query.");
        } catch (TableNotFoundException e) {
            log.error(this.getTableName() + "not found", e);
        } finally {
            if (bs != null) {
                bs.close();
            }
        }
        fullScanQuery.stop();
    }

    log.info("AbstractQueryLogic: " + queryString + " " + timeString(abstractQueryLogic.getTime()));
    log.info("  1) parse query " + timeString(parseQuery.getTime()));
    log.info("  2) query metadata " + timeString(queryMetadata.getTime()));
    log.info("  3) full scan query " + timeString(fullScanQuery.getTime()));
    log.info("  3) optimized query " + timeString(optimizedQuery.getTime()));
    log.info("  1) process results " + timeString(processResults.getTime()));
    log.info("      1) query global index " + timeString(queryGlobalIndex.getTime()));
    log.info(hash + " Query completed.");

    return results;
}

From source file:org.ohmage.query.impl.SurveyResponseQueries.java

/**
 * Builds the SQL for the survey response SELECT and generates a parameter
 * list that corresponds to that SQL. The parameter list is returned and
 * the SQL is set as the final parameter.
 * /*  ww  w . jav a2s.c om*/
 * @param campaign The campaign to which the survey responses must belong.
 * 
 * @param username The username of the user that is making this request.
 *                This is used by the ACLs to limit who sees what.
 * 
 * @param usernames Limits the results to only those submitted by any one 
 *                of the users in the list.
 * 
 * @param startDate Limits the results to only those survey responses that
 *                occurred on or after this date.
 * 
 * @param endDate Limits the results to only those survey responses that
 *               occurred on or before this date.
 * 
 * @param privacyState Limits the results to only those survey responses
 *                   with this privacy state.
 * 
 * @param surveyIds Limits the results to only those survey responses that 
 *                were derived from a survey in this collection.
 * 
 * @param promptIds Limits the results to only those survey responses that 
 *                were derived from a prompt in this collection.
 * 
 * @param promptType Limits the results to only those survey responses that
 *                 are of the given prompt type.
 * 
 * @param columns Aggregates the data based on the column keys. If this is
 *               null, no aggregation is performed. If the list is empty,
 *               an empty list is returned.
 * 
 * @param parameters This is a list created by the caller to be populated
 *                 with the parameters aggregated while generating this
 *                 SQL.
 * 
 * @return The list of parameters that corresponds with the generated SQL.
 */
private String buildSqlAndParameters(final Campaign campaign, final String username,
        final Set<UUID> surveyResponseIds, final Collection<String> usernames, final DateTime startDate,
        final DateTime endDate, final SurveyResponse.PrivacyState privacyState,
        final Collection<String> surveyIds, final Collection<String> promptIds, final String promptType,
        final Set<String> promptResponseSearchTokens, final Collection<ColumnKey> columns,
        final List<SortParameter> sortOrder, final Collection<Object> parameters) throws DataAccessException {

    // Begin with the SQL string which gets all results or the one that
    // aggregates results.
    StringBuilder sqlBuilder = new StringBuilder(SQL_BASE_WHERE);
    parameters.add(campaign.getId());

    // Catch any query exceptions.
    try {
        // If the requesting user is an admin, don't bother applying the
        // ACLs.
        if (!getJdbcTemplate().queryForObject("SELECT admin FROM user WHERE username = ?",
                new Object[] { username }, Boolean.class)) {

            // Get the roles for the user in the campaign.
            List<Campaign.Role> roles = getJdbcTemplate().query(
                    "SELECT ur.role " + "FROM user u, campaign c, user_role ur, user_role_campaign urc "
                            + "WHERE u.username = ? " + "AND u.id = urc.user_id " + "AND c.urn = ? "
                            + "AND c.id = urc.campaign_id " + "AND urc.user_role_id = ur.id",
                    new Object[] { username, campaign.getId() }, new RowMapper<Campaign.Role>() {
                        @Override
                        public Campaign.Role mapRow(final ResultSet rs, final int rowNum) throws SQLException {

                            return Campaign.Role.getValue(rs.getString("role"));
                        }
                    });

            // If the user is not a supervisor in the campaign, then we
            // will add additional ACLs based on their role.
            if (!roles.contains(Campaign.Role.SUPERVISOR)) {
                // Users are always allowed to query about themselves.
                sqlBuilder.append(" AND ((u.username = ?)");
                parameters.add(username);

                // If the user is an author or analyst, they may see shared
                // responses as well.
                if (roles.contains(Campaign.Role.AUTHOR) || roles.contains(Campaign.Role.ANALYST)) {

                    // Add the shared survey responses.
                    sqlBuilder.append(" OR ((srps.privacy_state = 'shared')");

                    // However, if the user is only an analyst, the
                    // campaign must also be shared.
                    if (!roles.contains(Campaign.Role.AUTHOR)) {
                        sqlBuilder.append(" AND (cps.privacy_state = 'shared')");
                    }

                    // Finally, close the OR.
                    sqlBuilder.append(')');
                }

                // Finally, close the AND.
                sqlBuilder.append(')');
            }
        }
    } catch (org.springframework.dao.DataAccessException e) {
        throw new DataAccessException("Error querying about the user.", e);
    }

    // Check all of the criteria and if any are non-null add their SQL and
    // append the parameters.
    if (surveyResponseIds != null) {
        sqlBuilder.append(SQL_WHERE_SURVEY_RESPONSE_IDS);
        sqlBuilder.append(StringUtils.generateStatementPList(surveyResponseIds.size()));

        for (UUID surveyResponseId : surveyResponseIds) {
            parameters.add(surveyResponseId.toString());
        }
    }
    if ((usernames != null) && (usernames.size() > 0)) {
        sqlBuilder.append(SQL_WHERE_USERNAMES);
        sqlBuilder.append(StringUtils.generateStatementPList(usernames.size()));
        parameters.addAll(usernames);
    }
    if (startDate != null) {
        sqlBuilder.append(SQL_WHERE_ON_OR_AFTER);
        parameters.add(startDate.getMillis());
    }
    if (endDate != null) {
        sqlBuilder.append(SQL_WHERE_ON_OR_BEFORE);
        parameters.add(endDate.getMillis());
    }
    if (privacyState != null) {
        sqlBuilder.append(SQL_WHERE_PRIVACY_STATE);
        parameters.add(privacyState.toString());
    }
    if (surveyIds != null) {
        sqlBuilder.append(SQL_WHERE_SURVEY_IDS);
        sqlBuilder.append(StringUtils.generateStatementPList(surveyIds.size()));
        parameters.addAll(surveyIds);
    }
    if (promptIds != null) {
        sqlBuilder.append(SQL_WHERE_PROMPT_IDS);
        sqlBuilder.append(StringUtils.generateStatementPList(promptIds.size()));
        parameters.addAll(promptIds);
    }
    if (promptType != null) {
        sqlBuilder.append(SQL_WHERE_PROMPT_TYPE);
        parameters.add(promptType);
    }
    if (promptResponseSearchTokens != null) {
        for (String promptResponseSearchToken : promptResponseSearchTokens) {
            sqlBuilder.append(SQL_WHERE_PROMPT_RESPONSE_SEARCH_TOKEN);
            parameters.add('%' + promptResponseSearchToken + '%');
        }
    }

    // Now, collapse the columns if columns is non-null.
    boolean onSurveyResponse = true;
    if (columns != null) {
        sqlBuilder.append(" GROUP BY ");

        boolean firstPass = true;
        for (ColumnKey columnKey : columns) {
            if (firstPass) {
                firstPass = false;
            } else {
                sqlBuilder.append(", ");
            }

            switch (columnKey) {
            case CONTEXT_CLIENT:
                sqlBuilder.append("sr.client");
                break;

            case CONTEXT_DATE:
                sqlBuilder
                        .append("DATE(CONVERT_TZ(FROM_UNIXTIME(epoch_millis / 1000), 'UTC', phone_timezone))");
                break;

            case CONTEXT_TIMESTAMP:
            case CONTEXT_UTC_TIMESTAMP:
                sqlBuilder.append("(sr.epoch_millis / 1000)");
                break;

            case CONTEXT_EPOCH_MILLIS:
                sqlBuilder.append("sr.epoch_millis");
                break;

            case CONTEXT_TIMEZONE:
                sqlBuilder.append("sr.phone_timezone");
                break;

            case CONTEXT_LAUNCH_CONTEXT_LONG:
            case CONTEXT_LAUNCH_CONTEXT_SHORT:
                sqlBuilder.append("sr.launch_context");
                break;

            case CONTEXT_LOCATION_STATUS:
                sqlBuilder.append("sr.location_status");
                break;

            case USER_ID:
                sqlBuilder.append("u.username");
                break;

            case SURVEY_ID:
                sqlBuilder.append("sr.survey_id");
                break;

            case SURVEY_RESPONSE_ID:
                sqlBuilder.append("sr.uuid");
                break;

            case SURVEY_PRIVACY_STATE:
                sqlBuilder.append("srps.privacy_state");
                break;

            case REPEATABLE_SET_ID:
                onSurveyResponse = false;
                sqlBuilder.append("pr.repeatable_set_id");
                break;

            case REPEATABLE_SET_ITERATION:
                onSurveyResponse = false;
                sqlBuilder.append("pr.repeatable_set_iteration");
                break;

            case PROMPT_RESPONSE:
                onSurveyResponse = false;
                sqlBuilder.append("pr.response");
                break;

            // This is inaccurate and will only work if the entire 
            // JSONObject is the same. We cannot do this without JSONObject
            // dissection in SQL.
            case CONTEXT_LOCATION_LATITUDE:
            case CONTEXT_LOCATION_LONGITUDE:
            case CONTEXT_LOCATION_TIMESTAMP:
            case CONTEXT_LOCATION_TIMEZONE:
            case CONTEXT_LOCATION_ACCURACY:
            case CONTEXT_LOCATION_PROVIDER:
                sqlBuilder.append("sr.location");
                break;

            // This cannot be done without XML manipulation in the SQL. 
            // Instead, we shouldn't dump the XML in the database and 
            // should explode it into its own series of columns and, if
            // necessary, additional tables.
            case SURVEY_TITLE:

            case SURVEY_DESCRIPTION:

            default:
                int length = sqlBuilder.length();
                sqlBuilder.delete(length - 2, length);
            }
        }
    }
    // Now, go back and insert the correct SELECT clause based on if we are
    // grouping or not and, if so, if we are doing it at the survey level
    // or the prompt level.
    if (columns == null) {
        sqlBuilder.insert(0, SQL_GET_SURVEY_RESPONSES_INDIVIDUAL);
    } else if (onSurveyResponse) {
        sqlBuilder.insert(0, SQL_GET_SURVEY_RESPONSES_AGGREGATED_SURVEY);
    } else {
        sqlBuilder.insert(0, SQL_GET_SURVEY_RESPONSES_AGGREGATED_PROMPT);
    }

    // Finally, add some ordering to facilitate consistent results in the
    // paging system.
    if (sortOrder == null) {
        sqlBuilder.append(" ORDER BY epoch_millis DESC, uuid");
    } else {
        sqlBuilder.append(" ORDER BY ");
        boolean firstPass = true;
        for (SortParameter sortParameter : sortOrder) {
            if (firstPass) {
                firstPass = false;
            } else {
                sqlBuilder.append(", ");
            }

            sqlBuilder.append(sortParameter.getSqlColumn());
        }
        // We must always include the UUID in the order to guarantee that 
        // all survey responses are grouped together.
        if (firstPass) {
            sqlBuilder.append("uuid");
        } else {
            sqlBuilder.append(", uuid");
        }
    }

    return sqlBuilder.toString();
}

From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java

protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) {
    final StringBuilder caps = new StringBuilder();
    try {/*from www  .  j  a v  a 2  s. c o m*/

        Host host = Host.getByUuid(conn, _host.uuid);
        Host.Record hr = host.getRecord(conn);

        Map<String, String> details = cmd.getHostDetails();
        if (details == null) {
            details = new HashMap<String, String>();
        }

        String productBrand = hr.softwareVersion.get("product_brand");
        if (productBrand == null) {
            productBrand = hr.softwareVersion.get("platform_name");
        }
        details.put("product_brand", productBrand);
        details.put("product_version", _host.product_version);

        if (hr.softwareVersion.get("product_version_text_short") != null) {
            details.put("product_version_text_short", hr.softwareVersion.get("product_version_text_short"));
            cmd.setHypervisorVersion(hr.softwareVersion.get("product_version_text_short"));

            cmd.setHypervisorVersion(_host.product_version);
        }
        if (_privateNetworkName != null) {
            details.put("private.network.device", _privateNetworkName);
        }

        details.put("can_bridge_firewall", Boolean.toString(_canBridgeFirewall));
        cmd.setHostDetails(details);
        cmd.setName(hr.nameLabel);
        cmd.setGuid(_host.uuid);
        cmd.setPool(_host.pool);
        cmd.setDataCenter(Long.toString(_dcId));
        for (final String cap : hr.capabilities) {
            if (cap.length() > 0) {
                caps.append(cap).append(" , ");
            }
        }
        if (caps.length() > 0) {
            caps.delete(caps.length() - 3, caps.length());
        }
        cmd.setCaps(caps.toString());

        cmd.setSpeed(_host.speed);
        cmd.setCpus(_host.cpus);

        HostMetrics hm = host.getMetrics(conn);

        long ram = 0;
        long dom0Ram = 0;
        ram = hm.getMemoryTotal(conn);
        Set<VM> vms = host.getResidentVMs(conn);
        for (VM vm : vms) {
            if (vm.getIsControlDomain(conn)) {
                dom0Ram = vm.getMemoryDynamicMax(conn);
                break;
            }
        }

        ram = (long) ((ram - dom0Ram - _xs_memory_used) * _xs_virtualization_factor);
        cmd.setMemory(ram);
        cmd.setDom0MinMemory(dom0Ram);

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Total Ram: " + ram + " dom0 Ram: " + dom0Ram);
        }

        PIF pif = PIF.getByUuid(conn, _host.privatePif);
        PIF.Record pifr = pif.getRecord(conn);
        if (pifr.IP != null && pifr.IP.length() > 0) {
            cmd.setPrivateIpAddress(pifr.IP);
            cmd.setPrivateMacAddress(pifr.MAC);
            cmd.setPrivateNetmask(pifr.netmask);
        } else {
            cmd.setPrivateIpAddress(_host.ip);
            cmd.setPrivateMacAddress(pifr.MAC);
            cmd.setPrivateNetmask("255.255.255.0");
        }

        pif = PIF.getByUuid(conn, _host.publicPif);
        pifr = pif.getRecord(conn);
        if (pifr.IP != null && pifr.IP.length() > 0) {
            cmd.setPublicIpAddress(pifr.IP);
            cmd.setPublicMacAddress(pifr.MAC);
            cmd.setPublicNetmask(pifr.netmask);
        }

        if (_host.storagePif1 != null) {
            pif = PIF.getByUuid(conn, _host.storagePif1);
            pifr = pif.getRecord(conn);
            if (pifr.IP != null && pifr.IP.length() > 0) {
                cmd.setStorageIpAddress(pifr.IP);
                cmd.setStorageMacAddress(pifr.MAC);
                cmd.setStorageNetmask(pifr.netmask);
            }
        }

        if (_host.storagePif2 != null) {
            pif = PIF.getByUuid(conn, _host.storagePif2);
            pifr = pif.getRecord(conn);
            if (pifr.IP != null && pifr.IP.length() > 0) {
                cmd.setStorageIpAddressDeux(pifr.IP);
                cmd.setStorageMacAddressDeux(pifr.MAC);
                cmd.setStorageNetmaskDeux(pifr.netmask);
            }
        }

        Map<String, String> configs = hr.otherConfig;
        cmd.setIqn(configs.get("iscsi_iqn"));

        cmd.setPod(_pod);
        cmd.setVersion(CitrixResourceBase.class.getPackage().getImplementationVersion());

    } catch (final XmlRpcException e) {
        throw new CloudRuntimeException("XML RPC Exception" + e.getMessage(), e);
    } catch (XenAPIException e) {
        throw new CloudRuntimeException("XenAPIException" + e.toString(), e);
    }
}

From source file:com.flexive.shared.scripting.groovy.GroovyScriptExporterTools.java

/**
 * Write the script code to create a property from a given FxPropertyAssignment
 *
 * @param pa                          the FxPropertyAssignment to be scripted
 * @param defaultsOnly                use only default settings provided by the GTB, no analysis of assignments will be performed
 * @param tabCount                    the number of tabs to be added to the code's left hand side
 * @param withoutDependencies         true = do not create assignment:xpath code
 * @param differingDerivedAssignments the List of assignment ids for derived assignments differing from their base assignments
 * @return returns the partial script as a StringBuilder instance
 *//*from ww w  . j  a  va2 s  .c o  m*/
public static String createProperty(FxPropertyAssignment pa, boolean defaultsOnly, int tabCount,
        boolean withoutDependencies, List<Long> differingDerivedAssignments) {
    final FxProperty prop = pa.getProperty();
    StringBuilder script = new StringBuilder(1000);

    // NAME
    script.append(Indent.tabs(tabCount));
    tabCount++;
    final String propName = keyWordNameCheck(prop.getName().toLowerCase(), true);
    script.append(propName).append("( "); // opening parenthesis + 1x \s

    if (!defaultsOnly) {
        script.append("\n");
        // label and hint
        script.append(getLabelAndHintStructure(prop, true, true, tabCount));

        final String dataType = prop.getDataType() + "";
        // sopts - a map for "simple" GroovyTypeBuilder options
        Map<String, String> sopts = new LinkedHashMap<String, String>();
        // ALIAS --> set if different from name
        if (!prop.getName().equals(pa.getAlias())) {
            sopts.put("alias", "\"" + pa.getAlias() + "\"");
        }
        // def multiplicity for the assignment
        sopts.put("defaultMultiplicity", pa.getDefaultMultiplicity() + "");
        sopts.put("multilang", prop.isMultiLang() + "");
        sopts.put("dataType", "FxDataType." + dataType + "");
        sopts.put("acl", "CacheAdmin.getEnvironment().getACL(ACLCategory." + prop.getACL().getCategory()
                + ".getDefaultId())");
        sopts.put("multiplicity", "new FxMultiplicity(" + prop.getMultiplicity().getMin() + ","
                + prop.getMultiplicity().getMax() + ")");
        sopts.put("overrideACL", prop.mayOverrideACL() + "");
        sopts.put("overrideMultiplicity", prop.mayOverrideBaseMultiplicity() + "");

        if (prop.hasOption(FxStructureOption.OPTION_SHOW_OVERVIEW))
            sopts.put("overrideInOverview", prop.mayOverrideInOverview() + "");

        if (prop.hasOption(FxStructureOption.OPTION_MAXLENGTH))
            sopts.put("overrideMaxLength", prop.mayOverrideMaxLength() + "");

        if (prop.hasOption(FxStructureOption.OPTION_MULTILINE))
            sopts.put("overrideMultiline", prop.mayOverrideMultiLine() + "");

        if (prop.hasOption(FxStructureOption.OPTION_SEARCHABLE))
            sopts.put("overrideSearchable", prop.mayOverrideSearchable() + "");

        if (prop.hasOption(FxStructureOption.OPTION_HTML_EDITOR))
            sopts.put("overrideUseHtmlEditor", prop.mayOverrideUseHTMLEditor() + "");

        if (prop.hasOption(FxStructureOption.OPTION_MULTILANG))
            sopts.put("overrideMultilang", prop.mayOverrideMultiLang() + "");

        if (prop.getMaxLength() != 0) {// means that maxLength is not set
            sopts.put("maxLength", prop.getMaxLength() + "");
        }
        sopts.put("searchable", prop.isSearchable() + "");
        sopts.put("fullTextIndexed", prop.isFulltextIndexed() + "");
        sopts.put("multiline", prop.isMultiLine() + "");
        sopts.put("inOverview", prop.isInOverview() + "");
        sopts.put("useHtmlEditor", prop.isUseHTMLEditor() + "");
        sopts.put("uniqueMode", "UniqueMode." + prop.getUniqueMode());
        sopts.put("enabled", pa.isEnabled() + "");
        // REFERENCE
        if ("Reference".equals(dataType)) {
            final String refType = "CacheAdmin.getEnvironment().getType(\"" + prop.getReferencedType().getName()
                    + "\")";
            sopts.put("referencedType", refType + "");
        }
        if (prop.getReferencedList() != null) {
            final String refList = "CacheAdmin.getEnvironment().getSelectList(\""
                    + prop.getReferencedList().getName() + "\")";
            sopts.put("referencedList", refList + "");
        }

        // FxStructureOptions via the GroovyOptionbuilder
        script.append(getStructureOptions(prop, tabCount));

        // DEFAULT VALUES
        if (prop.isDefaultValueSet()) {
            final FxValue val = prop.getDefaultValue();
            String defaultValue = val.toString();
            StringBuilder out = new StringBuilder(100);
            final String multiLang = prop.isMultiLang() + "";

            if (DATATYPES.contains(dataType)) {
                // SELECT LIST DATATYPES
                if ("SelectOne".equals(dataType) || "SelectMany".equals(dataType)) {
                    final String refListName = "CacheAdmin.getEnvironment().getSelectList(\""
                            + prop.getReferencedList().getName();
                    sopts.put("referencedList", refListName + "\"),\n");
                    final FxSelectList list = prop.getReferencedList();
                    if ("SelectOne".equals(dataType)) {
                        for (FxSelectListItem item : list.getItems()) {
                            if (defaultValue.equals(item.getLabel().toString())) {
                                defaultValue = item.getName(); // reassign
                            }
                        }
                        out.append("new FxSelectOne(").append(multiLang)
                                .append(", CacheAdmin.getEnvironment().getSelectListItem(").append(refListName)
                                .append("\"), \"").append(defaultValue).append("\"))");

                    } else if ("SelectMany".equals(dataType)) {
                        String[] defaults = FxSharedUtils.splitLiterals(defaultValue);
                        for (int i = 0; i < defaults.length; i++) {
                            for (FxSelectListItem item : list.getItems()) {
                                if (defaults[i].equals(item.getLabel().toString())) {
                                    defaults[i] = item.getName(); // reassign
                                }
                            }
                        }
                        out.append("new FxSelectMany(").append(multiLang).append(", new SelectMany(")
                                .append(refListName).append("\"))");
                        // traverse renamed defaults and append them to the script
                        for (String d : defaults) {
                            out.append(".selectItem(CacheAdmin.getEnvironment().getSelectListItem(")
                                    .append(refListName).append("\"), \"").append(d).append("\"))");
                        }
                        out.append(")");
                    }
                } else if ("Date".equals(dataType) || "DateTime".equals(dataType)
                        || "DateRange".equals(dataType) || "DateTimeRange".equals(dataType)) {
                    final String df = "\"MMM dd, yyyy\"";
                    final String dtf = "\"MMM dd, yyyy h:mm:ss a\"";
                    if ("Date".equals(dataType)) {
                        out.append("new FxDate(").append(multiLang).append(", new SimpleDateFormat(").append(df)
                                .append(").parse(\"").append(defaultValue).append("\"))");
                    } else if ("DateTime".equals(dataType)) {
                        out.append("new FxDateTime(").append(multiLang).append(", new SimpleDateFormat(")
                                .append(dtf).append(").parse(\"").append(defaultValue).append("\"))");
                    } else if ("DateRange".equals(dataType)) {
                        final String lower = stripToEmpty(defaultValue.substring(0, defaultValue.indexOf("-")));
                        final String upper = stripToEmpty(
                                defaultValue.substring(defaultValue.indexOf("-") + 1));
                        out.append("new FxDateRange(").append(multiLang)
                                .append(", new DateRange(new SimpleDateFormat(").append(df).append(").parse(\"")
                                .append(lower).append("\"), new SimpleDateFormat(").append(df)
                                .append(").parse(\"").append(upper).append("\")))");
                    } else if ("DateTimeRange".equals(dataType)) {
                        final String lower = stripToEmpty(defaultValue.substring(0, defaultValue.indexOf("-")));
                        final String upper = stripToEmpty(
                                defaultValue.substring(defaultValue.indexOf("-") + 1));
                        out.append("new FxDateTimeRange(").append(multiLang)
                                .append(", new DateRange(new SimpleDateFormat(").append(dtf)
                                .append(").parse(\"").append(lower).append("\"), new SimpleDateFormat(")
                                .append(dtf).append(").parse(\"").append(upper).append("\")))");
                    }
                } else if ("Reference".equals(dataType)) {
                    final FxPK pk = FxPK.fromString(defaultValue);
                    out.append("new FxReference(").append(multiLang).append(", new ReferencedContent(")
                            .append(pk.getId()).append(", ").append(pk.getVersion()).append("))");

                } else if ("InlineReference".equals(dataType)) {
                    // ignore for now, doesn't work properly as of yet
                } else if ("Binary".equals(dataType)) {
                    // uses a new BinaryDescriptor( .. )
                }
            }

            // "SIMPLE" dataTYPES
            if (DATATYPESSIMPLE.keySet().contains(dataType)) {
                for (String d : DATATYPESSIMPLE.keySet()) {
                    if (d.equals(dataType)) {
                        out.append(DATATYPESSIMPLE.get(d)).append("(").append(multiLang).append(", ");
                        if (d.equals("Float") || d.equals("Double") || d.equals("LargeNumber")
                                || d.equals("Boolean")) {
                            out.append(defaultValue);
                        } else {
                            out.append("\"").append(defaultValue).append("\"");
                        }
                        out.append(")");
                    }
                }
            }

            out.trimToSize();
            // add the computed value to the "simpleOtions"
            sopts.put("defaultValue", out.toString() + ",");
        }

        // append options to script
        for (String option : sopts.keySet()) {
            script.append(simpleOption(option, sopts.get(option), tabCount));
        }

        script.trimToSize();
        if (script.indexOf(",\n", script.length() - 2) != -1)
            script.delete(script.length() - 2, script.length());
        if (script.indexOf(",", script.length() - 1) != -1)
            script.delete(script.length() - 1, script.length());
    }

    script.append(")\n"); // closing parenthesis

    // if the difference analyser yields any data, change the assignment in the next line (only launch if defaultsOnly = false)
    if (!defaultsOnly) {
        final List<String> differences = AssignmentDifferenceAnalyser.analyse(pa, false);
        if (differences.size() > 0) {
            script.append(updatePropertyAssignment(pa, false, differences, defaultsOnly, --tabCount,
                    withoutDependencies, differingDerivedAssignments));
        }
    }
    script.trimToSize();
    return script.toString();
}