Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

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

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java

public String getUrlPathPrefix(HttpServletRequest request) {
    StringBuilder urlStr = null;
    if (StringUtils.hasText(m_urlPathPrefix)) {
        // A specific prefix has been configured in, so use it.
        urlStr = new StringBuilder(m_urlPathPrefix);
    } else {/*from w ww .  j  a  va  2  s.c o m*/
        // Extract the path prefix from the request, using the servlet path as a guide.
        // e.g. "/preamble/servlet-mapping/folder/file.txt"
        // with a servlet path of "/servlet-mapping"
        // would result in a path prefix of "/preamble/servlet-mapping" being discovered.
        urlStr = new StringBuilder(request.getRequestURI());
        String servletPath = request.getServletPath();

        int rootPos = urlStr.indexOf(servletPath);
        if (rootPos != -1) {
            urlStr.setLength(rootPos + servletPath.length());
        }
    }

    // Ensure the prefix ends in the path separator.
    if (urlStr.length() == 0 || urlStr.charAt(urlStr.length() - 1) != PathSeperatorChar) {
        urlStr.append(PathSeperator);
    }

    return urlStr.toString();
}

From source file:org.xz.qstruts.dispatcher.mapper.DefaultActionMapper.java

public String getUriFromActionMapping(ActionMapping mapping) {
    StringBuilder uri = new StringBuilder();

    if (mapping.getNamespace() != null) {
        uri.append(mapping.getNamespace());
        if (!"/".equals(mapping.getNamespace())) {
            uri.append("/");
        }/*from   ww  w  .  ja v  a 2s .com*/
    }
    String name = mapping.getName();
    String params = "";
    if (name.indexOf('?') != -1) {
        params = name.substring(name.indexOf('?'));
        name = name.substring(0, name.indexOf('?'));
    }
    uri.append(name);

    if (null != mapping.getMethod() && !"".equals(mapping.getMethod())) {
        uri.append("/").append(mapping.getMethod());
    }

    String extension = mapping.getExtension();
    if (extension == null) {
        // Look for the current extension, if available
        ActionContext context = ActionContext.getContext();
        if (context != null) {
            ActionMapping orig = (ActionMapping) context.get(ServletActionContext.ACTION_MAPPING);
            if (orig != null) {
                extension = orig.getExtension();
            }
        }
        if (extension == null) {
            extension = getDefaultExtension();
        }
    }

    if (extension != null) {
        if (extension.length() == 0 || (extension.length() > 0 && uri.indexOf('.' + extension) == -1)) {
            if (extension.length() > 0) {
                uri.append(".").append(extension);
            }
        }
    }
    if (params.length() > 0) {
        uri.append(params);
    }

    return uri.toString();
}

From source file:edu.usu.sdl.openstorefront.service.PersistenceService.java

public <T> int deleteByExample(QueryByExample queryByExample) {
    int deleteCount = 0;
    StringBuilder queryString = new StringBuilder();

    queryString.append("delete from ").append(queryByExample.getExample().getClass().getSimpleName());

    Map<String, Object> mappedParams = new HashMap<>();
    String whereClause = generateWhereClause(queryByExample.getExample());
    if (StringUtils.isNotBlank(whereClause)) {
        queryString.append(" where ").append(whereClause);
        mappedParams.putAll(mapParameters(queryByExample.getExample()));
    }/*  w ww  .  ja  v  a  2  s .c om*/

    queryByExample.getExtraWhereCauses().forEach(item -> {
        SpecialOperatorModel special = (SpecialOperatorModel) item;
        String extraWhere = generateWhereClause(special.getExample(), new ComplexFieldStack(),
                special.getGenerateStatementOption());
        if (StringUtils.isNotBlank(extraWhere)) {
            if (queryString.indexOf(" where ") != -1) {
                queryString.append(" AND ");
            } else {
                queryString.append(" where ");
            }
            queryString.append(extraWhere);
            mappedParams.putAll(mapParameters(special.getExample(), new ComplexFieldStack(),
                    special.getGenerateStatementOption()));
        }
    });

    OObjectDatabaseTx db = getConnection();
    try {
        deleteCount = db.command(new OCommandSQL(queryString.toString())).execute(mappedParams);
    } finally {
        closeConnection(db);
    }

    return deleteCount;
}

From source file:org.apache.stratos.cloud.controller.services.impl.CloudControllerServiceImpl.java

private void replaceInPayload(String payloadParamName, StringBuilder payload, String name, String value) {

    payload.replace(payload.indexOf(payloadParamName), payload.indexOf(",", payload.indexOf(payloadParamName)),
            "," + name + "=" + value);
}

From source file:org.sakaiproject.nakamura.http.i18n.I18nFilter.java

/**
 * Filter <code>output</code> of any message keys by replacing them with the matching
 * message from the language bundle associated to the user.
 *
 * @param srequest// w w  w  .  j av a2  s  .  co  m
 * @param response
 * @param output
 * @throws IOException
 */
private void writeFilteredResponse(SlingHttpServletRequest srequest, ServletResponse response, String output)
        throws IOException {
    StringBuilder sb = new StringBuilder(output);
    try {
        Session session = srequest.getResourceResolver().adaptTo(Session.class);
        Node bundlesNode = session.getNode(bundlesPath);

        // load the language bundle
        Locale locale = getLocale(srequest);
        Properties bndLang = getLangBundle(bundlesNode, locale.toString());

        // load the default bundle
        Properties bndLangDefault = getLangBundle(bundlesNode, "default");

        // check for message keys and replace them with the appropriate message
        Matcher m = messageKeyPattern.matcher(output);
        ArrayList<String> matchedKeys = new ArrayList<String>();
        while (m.find()) {
            String msgKey = m.group(0);
            String key = m.group(1);
            if (!matchedKeys.contains(key)) {
                String message = "";

                if (bndLang.containsKey(key)) {
                    message = bndLang.getProperty(key);
                } else if (bndLangDefault.containsKey(key)) {
                    message = bndLangDefault.getProperty(key);
                } else {
                    String msg = "[MESSAGE KEY NOT FOUND '" + key + "']";
                    logger.warn(msg);
                    if (showMissingKeys) {
                        message = msg;
                    }
                }

                // replace all instances of msgKey with the actual message
                int keyStart = sb.indexOf(msgKey);
                while (keyStart >= 0) {
                    sb.replace(keyStart, keyStart + msgKey.length(), message);
                    keyStart = sb.indexOf(msgKey, keyStart);
                }

                // track the group so we don't try to replace it again
                matchedKeys.add(key);
            }
        }
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }

    response.setContentLength(sb.length());

    // send the output to the actual response
    try {
        response.getWriter().write(sb.toString());
    } catch (IllegalStateException e) {
        response.getOutputStream().write(sb.toString().getBytes("UTF-8"));
    }
}

From source file:org.jahia.services.importexport.LegacyImportHandler.java

private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node,
        String propertyName, String value, Map<String, String> creationMetadata) throws RepositoryException {
    JCRNodeWrapper parent = node;/*ww w .ja v a 2  s  .  co m*/
    String mixinType = null;
    if (propertyName.contains("|")) {
        mixinType = StringUtils.substringBefore(propertyName, "|");
        propertyName = StringUtils.substringAfter(propertyName, "|");
    }
    if (StringUtils.contains(propertyName, "/")) {
        String parentPath = StringUtils.substringBeforeLast(propertyName, "/");
        if (parent.hasNode(parentPath)) {
            parent = parent.getNode(parentPath);
        }
        propertyName = StringUtils.substringAfterLast(propertyName, "/");
    }
    parent = checkoutNode(parent);
    if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) {
        parent.addMixin(mixinType);
    }

    ExtendedPropertyDefinition propertyDefinition;
    propertyDefinition = parent.getApplicablePropertyDefinition(propertyName);
    if (propertyDefinition == null) {
        return false;
    }
    if (propertyDefinition.isProtected()) {
        return false;
    }

    if (StringUtils.isNotBlank(value) && !value.equals("<empty>")) {
        Node n = parent;
        if (propertyDefinition.isInternationalized()) {
            n = getOrCreateI18N(parent, locale, creationMetadata);
        }
        if (!n.isCheckedOut()) {
            session.checkout(n);
        }
        switch (propertyDefinition.getRequiredType()) {
        case PropertyType.DATE:
            GregorianCalendar cal = new GregorianCalendar();
            try {
                DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT);
                Date d = df.parse(value);
                cal.setTime(d);
                n.setProperty(propertyName, cal);
            } catch (java.text.ParseException e) {
                logger.error(e.getMessage(), e);
            }
            break;

        case PropertyType.REFERENCE:
        case PropertyType.WEAKREFERENCE:
            if (propertyDefinition.isMultiple()) {
                String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                for (String s : strings) {
                    createReferenceValue(s, propertyDefinition.getSelector(), n, propertyName);
                }
            } else {
                createReferenceValue(value, propertyDefinition.getSelector(), n, propertyName);
            }
            break;

        default:
            switch (propertyDefinition.getSelector()) {
            case SelectorType.RICHTEXT: {
                if (value.contains("=\"###")) {
                    int count = 1;
                    StringBuilder buf = new StringBuilder(value);
                    while (buf.indexOf("=\"###") > -1) {
                        int from = buf.indexOf("=\"###") + 2;
                        int to = buf.indexOf("\"", from);

                        String ref = buf.substring(from, to);
                        if (ref.startsWith("###/webdav")) {
                            ref = StringUtils.substringAfter(ref, "###/webdav");
                            buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##");
                        } else if (ref.startsWith("###file:")) {
                            ref = StringUtils.substringAfter(ref, "###file:");
                            final int qmPos = ref.indexOf('?');
                            boolean isUuid = false;
                            if (qmPos != -1) {
                                if (StringUtils.substring(ref, qmPos + 1).startsWith("uuid=default:")) {
                                    ref = StringUtils.substring(ref, qmPos + 14);
                                    isUuid = true;
                                } else
                                    ref = StringUtils.substringBefore(ref, "?");
                            }
                            if (!isUuid)
                                ref = correctFilename(ref);
                            buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##");
                        } else {
                            ref = StringUtils.substringAfterLast(ref, "/");
                            // we keep the URL parameters if any
                            String params = "";
                            int pos = ref.indexOf('?');
                            if (pos == -1) {
                                pos = ref.indexOf('#');
                            }
                            if (pos != -1) {
                                params = ref.substring(pos);
                                ref = ref.substring(0, pos);
                            }
                            buf.replace(from, to,
                                    "##cms-context##/{mode}/{lang}/##ref:link" + count + "##.html" + params);
                        }
                        try {
                            ref = URLDecoder.decode(ref, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                        }

                        if (!references.containsKey(ref)) {
                            references.put(ref, new ArrayList<String>());
                        }
                        references.get(ref)
                                .add(n.getIdentifier() + "/[" + count + "]" + propertyDefinition.getName());
                        count++;
                    }
                    value = buf.toString();
                }
                n.setProperty(propertyName, value);
                if (logger.isDebugEnabled())
                    logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value="
                            + value);
                break;
            }
            default: {
                String[] vcs = propertyDefinition.getValueConstraints();
                List<String> constraints = Arrays.asList(vcs);
                if (!propertyDefinition.isMultiple()) {
                    if (value.startsWith("<jahia-resource")) {
                        value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey();
                        if (value.startsWith(propertyDefinition.getResourceBundleKey())) {
                            value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1);
                        }
                    } else if ("jcr:description".equals(propertyName)) {
                        value = removeHtmlTags(value);
                    }

                    value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                            : value;
                    if (valueMatchesContraints(value, constraints)) {
                        try {
                            n.setProperty(propertyName, value);
                            if (logger.isDebugEnabled())
                                logger.debug("Setting on node " + n.getPath() + " property " + propertyName
                                        + " with value=" + value);
                        } catch (Exception e) {
                            logger.error("Impossible to set property " + propertyName + " due to exception", e);
                        }
                    } else {
                        logger.error(
                                "Impossible to set property " + propertyName + " due to some constraint error");
                        logger.error(" - value       = " + value);
                        logger.error(" - constraints = " + constraints.toString());
                    }
                } else {
                    String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                    List<Value> values = new ArrayList<Value>();
                    for (String string : strings) {

                        if (string.startsWith("<jahia-resource")) {
                            string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey();
                            if (string.startsWith(propertyDefinition.getResourceBundleKey())) {
                                string = string
                                        .substring(propertyDefinition.getResourceBundleKey().length() + 1);
                            }
                        }
                        value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                                : value;
                        if (constraints.isEmpty() || constraints.contains(value)) {
                            values.add(new ValueImpl(string, propertyDefinition.getRequiredType()));
                        }
                    }
                    n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                    if (logger.isDebugEnabled())
                        logger.debug("Setting on node " + n.getPath() + " property " + propertyName
                                + " with value=" + values);
                }
                break;
            }
            }
        }
    } else {
        return false;
    }

    return true;
}

From source file:org.codelibs.fess.web.IndexAction.java

protected String doSearchInternal() {
    final StringBuilder queryBuf = new StringBuilder(255);
    if (StringUtil.isNotBlank(indexForm.query)) {
        queryBuf.append(indexForm.query);
    }// w  ww  .  j av a  2  s .  c  o  m
    if (StringUtil.isNotBlank(indexForm.op)) {
        request.setAttribute(Constants.DEFAULT_OPERATOR, indexForm.op);
    }
    if (queryBuf.indexOf(" OR ") >= 0) {
        queryBuf.insert(0, '(').append(')');
    }
    if (indexForm.additional != null) {
        final Set<String> fieldSet = new HashSet<String>();
        for (final String additional : indexForm.additional) {
            if (StringUtil.isNotBlank(additional) && additional.length() < 1000
                    && !hasFieldInQuery(fieldSet, additional)) {
                queryBuf.append(' ').append(additional);
            }
        }
    }
    if (!indexForm.fields.isEmpty()) {
        for (final Map.Entry<String, String[]> entry : indexForm.fields.entrySet()) {
            final List<String> valueList = new ArrayList<String>();
            final String[] values = entry.getValue();
            if (values != null) {
                for (final String v : values) {
                    valueList.add(v);
                }
            }
            if (valueList.size() == 1) {
                queryBuf.append(' ').append(entry.getKey()).append(":\"").append(valueList.get(0)).append('\"');
            } else if (valueList.size() > 1) {
                queryBuf.append(" (");
                for (int i = 0; i < valueList.size(); i++) {
                    if (i != 0) {
                        queryBuf.append(" OR");
                    }
                    queryBuf.append(' ').append(entry.getKey()).append(":\"").append(valueList.get(i))
                            .append('\"');
                }
                queryBuf.append(')');
            }

        }
    }
    if (StringUtil.isNotBlank(indexForm.sort)) {
        queryBuf.append(" sort:").append(indexForm.sort);
    }
    if (indexForm.lang != null) {
        final Set<String> langSet = new HashSet<>();
        for (final String lang : indexForm.lang) {
            if (StringUtil.isNotBlank(lang) && lang.length() < 1000) {
                if (Constants.ALL_LANGUAGES.equalsIgnoreCase(lang)) {
                    langSet.add(Constants.ALL_LANGUAGES);
                } else {
                    final String normalizeLang = systemHelper.normalizeLang(lang);
                    if (normalizeLang != null) {
                        langSet.add(normalizeLang);
                    }
                }
            }
        }
        if (langSet.size() > 1 && langSet.contains(Constants.ALL_LANGUAGES)) {
            langSet.clear();
            indexForm.lang = new String[] { Constants.ALL_LANGUAGES };
        } else {
            langSet.remove(Constants.ALL_LANGUAGES);
        }
        appendLangQuery(queryBuf, langSet);
    } else if (Constants.TRUE.equals(
            crawlerProperties.getProperty(Constants.USE_BROWSER_LOCALE_FOR_SEARCH_PROPERTY, Constants.FALSE))) {
        final Set<String> langSet = new HashSet<>();
        final Enumeration<Locale> locales = request.getLocales();
        if (locales != null) {
            while (locales.hasMoreElements()) {
                final Locale locale = locales.nextElement();
                final String normalizeLang = systemHelper.normalizeLang(locale.toString());
                if (normalizeLang != null) {
                    langSet.add(normalizeLang);
                }
            }
            if (!langSet.isEmpty()) {
                appendLangQuery(queryBuf, langSet);
            }
        }
    }

    final String query = queryBuf.toString().trim();

    // init pager
    if (StringUtil.isBlank(indexForm.start)) {
        indexForm.start = String.valueOf(DEFAULT_START_COUNT);
    } else {
        try {
            Long.parseLong(indexForm.start);
        } catch (final NumberFormatException e) {
            indexForm.start = String.valueOf(DEFAULT_START_COUNT);
        }
    }
    if (StringUtil.isBlank(indexForm.num)) {
        indexForm.num = String.valueOf(getDefaultPageSize());
    }
    normalizePageNum();

    final int pageStart = Integer.parseInt(indexForm.start);
    final int pageNum = Integer.parseInt(indexForm.num);
    try {
        documentItems = searchService.getDocumentList(query, pageStart, pageNum, indexForm.facet, indexForm.geo,
                indexForm.mlt, queryHelper.getResponseFields(), queryHelper.getResponseDocValuesFields());
    } catch (final SolrLibQueryException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, "errors.invalid_query_unknown");
    } catch (final InvalidQueryException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, e.getMessageCode());
    } catch (final ResultOffsetExceededException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, "errors.result_size_exceeded");
    }
    // search
    final QueryResponseList queryResponseList = (QueryResponseList) documentItems;
    facetResponse = queryResponseList.getFacetResponse();
    moreLikeThisResponse = queryResponseList.getMoreLikeThisResponse();
    final NumberFormat nf = NumberFormat.getInstance(RequestUtil.getRequest().getLocale());
    nf.setMaximumIntegerDigits(2);
    nf.setMaximumFractionDigits(2);
    try {
        execTime = nf.format((double) queryResponseList.getExecTime() / 1000);
    } catch (final Exception e) {
        // ignore
    }

    final Clock clock = Clock.systemDefaultZone();
    indexForm.rt = Long.toString(clock.millis());

    // favorite
    if (favoriteSupport || screenShotManager != null) {
        indexForm.queryId = userInfoHelper.generateQueryId(query, documentItems);
        if (screenShotManager != null) {
            screenShotManager.storeRequest(indexForm.queryId, documentItems);
            screenShotSupport = true;
        }
    }

    // search log
    if (searchLogSupport) {
        final LocalDateTime now = systemHelper.getCurrentTime();

        final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
        final SearchLog searchLog = new SearchLog();

        String userCode = null;
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.USER_INFO_PROPERTY, Constants.TRUE))) {
            userCode = userInfoHelper.getUserCode();
            if (StringUtil.isNotBlank(userCode)) {
                final UserInfo userInfo = new UserInfo();
                userInfo.setCode(userCode);
                userInfo.setCreatedTime(now);
                userInfo.setUpdatedTime(now);
                searchLog.setUserInfo(OptionalEntity.of(userInfo));
            }
        }

        searchLog.setHitCount(queryResponseList.getAllRecordCount());
        searchLog.setResponseTime(Integer.valueOf((int) queryResponseList.getExecTime()));
        searchLog.setSearchWord(StringUtils.abbreviate(query, 1000));
        searchLog.setSearchQuery(StringUtils.abbreviate(queryResponseList.getSearchQuery(), 1000));
        searchLog.setSolrQuery(StringUtils.abbreviate(queryResponseList.getSolrQuery(), 1000));
        searchLog.setRequestedTime(now);
        searchLog.setQueryOffset(pageStart);
        searchLog.setQueryPageSize(pageNum);

        searchLog.setClientIp(StringUtils.abbreviate(request.getRemoteAddr(), 50));
        searchLog.setReferer(StringUtils.abbreviate(request.getHeader("referer"), 1000));
        searchLog.setUserAgent(StringUtils.abbreviate(request.getHeader("user-agent"), 255));
        if (userCode != null) {
            searchLog.setUserSessionId(userCode);
        }
        final Object accessType = request.getAttribute(Constants.SEARCH_LOG_ACCESS_TYPE);
        if (accessType instanceof CDef.AccessType) {
            switch ((CDef.AccessType) accessType) {
            case Json:
                searchLog.setAccessType_Json();
                searchLog.setAccessType_Others();
                searchLog.setAccessType_Xml();
                break;
            case Xml:
                searchLog.setAccessType_Xml();
                break;
            case Others:
                searchLog.setAccessType_Others();
                break;
            default:
                searchLog.setAccessType_Web();
                break;
            }
        } else {
            searchLog.setAccessType_Web();
        }

        @SuppressWarnings("unchecked")
        final Map<String, List<String>> fieldLogMap = (Map<String, List<String>>) request
                .getAttribute(Constants.FIELD_LOGS);
        if (fieldLogMap != null) {
            for (final Map.Entry<String, List<String>> logEntry : fieldLogMap.entrySet()) {
                for (final String value : logEntry.getValue()) {
                    searchLog.addSearchFieldLogValue(logEntry.getKey(), StringUtils.abbreviate(value, 1000));
                }
            }
        }

        searchLogHelper.addSearchLog(searchLog);
    }

    final String[] highlightQueries = (String[]) request.getAttribute(Constants.HIGHLIGHT_QUERIES);
    if (highlightQueries != null) {
        final StringBuilder buf = new StringBuilder(100);
        for (final String q : highlightQueries) {
            buf.append("&hq=").append(q);
        }
        appendHighlightQueries = buf.toString();
    }

    Beans.copy(documentItems, this)
            .includes("pageSize", "currentPageNumber", "allRecordCount", "allPageCount", "existNextPage",
                    "existPrevPage", "currentStartRecordNumber", "currentEndRecordNumber", "pageNumberList",
                    "partialResults", "queryTime", "searchTime")
            .execute();

    return query;
}

From source file:edu.usu.sdl.openstorefront.service.OrientPersistenceService.java

@Override
public <T> int deleteByExample(QueryByExample queryByExample) {
    int deleteCount = 0;
    StringBuilder queryString = new StringBuilder();

    queryString.append("delete from ").append(queryByExample.getExample().getClass().getSimpleName());

    Map<String, Object> mappedParams = new HashMap<>();
    String whereClause = generateWhereClause(queryByExample.getExample(), new ComplexFieldStack(),
            queryByExample.getExampleOption());
    if (StringUtils.isNotBlank(whereClause)) {
        queryString.append(" where ").append(whereClause);
        mappedParams.putAll(mapParameters(queryByExample.getExample()));
    }// www.j a v  a  2s  .  c om

    queryByExample.getExtraWhereCauses().forEach(item -> {
        SpecialOperatorModel special = (SpecialOperatorModel) item;
        String extraWhere = generateWhereClause(special.getExample(), new ComplexFieldStack(),
                special.getGenerateStatementOption());
        if (StringUtils.isNotBlank(extraWhere)) {
            if (queryString.indexOf(" where ") != -1) {
                queryString.append(" AND ");
            } else {
                queryString.append(" where ");
            }
            queryString.append(extraWhere);
            mappedParams.putAll(mapParameters(special.getExample(), new ComplexFieldStack(),
                    special.getGenerateStatementOption()));
        }
    });

    OObjectDatabaseTx db = getConnection();
    try {
        deleteCount = db.command(new OCommandSQL(queryString.toString())).execute(mappedParams);
    } finally {
        closeConnection(db);
    }

    return deleteCount;
}

From source file:org.jahia.services.search.jcr.JahiaJCRSearchProvider.java

private StringBuilder appendConstraints(SearchCriteria params, StringBuilder query, boolean xpath) {
    StringBuilder constraints = new StringBuilder(64);

    addTermConstraints(params, constraints, xpath);

    addDateAndAuthorConstraints(params, constraints, xpath);

    addFileTypeConstraints(params, constraints, xpath);

    addLanguageConstraints(params, constraints, xpath);

    List<NodeProperty> props = params.getPropertiesAll();
    if (!props.isEmpty()) {
        addPropertyConstraints(constraints, props, xpath);
    }//from   w  w  w  .  ja  v  a 2 s  . c om

    if (constraints.length() > 0) {
        if (xpath) {
            query.append("[").append(constraints).append("]");
        } else {
            if (query.indexOf("where") > -1) {
                query.append(" and ");
            } else {
                query.append(" where ");
            }
            query.append("(").append(constraints).append(")");
        }
    }

    return query;
}

From source file:com.axway.ats.testexplorer.pages.testcase.statistics.charts.ChartsPanel.java

private AjaxLink<?> getRefreshChartLink(final String diagramName) {

    AjaxLink refreshChartLink = new AjaxLink("refreshChart") {

        private static final long serialVersionUID = 1L;

        @Override/*from   w  ww  .j a  va 2  s.  c  om*/
        public void onClick(AjaxRequestTarget target) {

            List<DbStatisticDescription> dataToBeUpdated = diagramContent.get(diagramName);
            Set<Integer> sysStatisticTypeIds = new HashSet<Integer>();
            Set<Integer> sysMachineIds = new HashSet<Integer>();
            Set<Integer> usrStatisticTypeIds = new HashSet<Integer>();
            Set<Integer> usrMachineIds = new HashSet<Integer>();
            Set<Integer> testcaseIds = new HashSet<Integer>();
            StringBuilder actions = new StringBuilder();
            StringBuilder actionParents = new StringBuilder();
            Set<String> expectedActions = new HashSet<String>();

            // collect all the data from this diagram, so all statistics could be updated successfully
            for (DbStatisticDescription dbStatDescription : dataToBeUpdated) {
                testcaseIds.add(dbStatDescription.testcaseId);
                if (SQLServerDbReadAccess.MACHINE_NAME_FOR_ATS_AGENTS.equals(dbStatDescription.machineName)) {
                    usrStatisticTypeIds.add(dbStatDescription.statisticId);
                    usrMachineIds.add(dbStatDescription.machineId);
                } else if (dbStatDescription.machineId != 0) {
                    sysStatisticTypeIds.add(dbStatDescription.statisticId);
                    sysMachineIds.add(dbStatDescription.machineId);
                } else {
                    actions.append("'").append(dbStatDescription.name).append("'").append(",");
                    if (actionParents.indexOf(dbStatDescription.parentName) == -1) {
                        actionParents.append("'").append(dbStatDescription.parentName).append("',");
                    }
                    expectedActions.add(dbStatDescription.testcaseId + "->" + dbStatDescription.machineId + "->"
                            + dbStatDescription.parentName + "->" + dbStatDescription.name);
                }
            }

            loadActionStatisticsFromDatabase(testcaseIds, actions, actionParents, expectedActions);
            loadSystemStatisticsFromDatabase(sysStatisticTypeIds, sysMachineIds);
            loadUserStatisticsFromDatabase(usrStatisticTypeIds, usrMachineIds);

            refreshDiagramContent();

            target.add(chartsPanelContent);
        }
    };
    return refreshChartLink;
}