Example usage for org.apache.commons.lang StringUtils replaceOnce

List of usage examples for org.apache.commons.lang StringUtils replaceOnce

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils replaceOnce.

Prototype

public static String replaceOnce(String text, String searchString, String replacement) 

Source Link

Document

Replaces a String with another String inside a larger String, once.

Usage

From source file:de.torstenwalter.maven.plugins.AbstractDBMojo.java

protected String obfuscateCredentials(String string, Credentials credentials) {
    return StringUtils.replaceOnce(StringUtils.replaceOnce(string, credentials.getUsername(), "<username>"),
            credentials.getPassword(), "<password>");
}

From source file:com.clican.pluto.dataprocess.dpl.impl.DplStatementImpl.java

/**
 * @see DplStatement#execute(String, ProcessorContext)
 *///  ww w .j a  v  a  2s  . co  m

public List<Map<String, Object>> execute(String dpl, ProcessorContext context) throws DplException {
    dpl = trimDpl(dpl);
    if (dpl.trim().length() == 0) {
        log.warn("dpl statement empty, simple return null");
        return null;
    }
    ProcessorContext clone = context.getCloneContext();
    PrefixAndSuffix.setLocalContext(clone);
    try {
        // ?dpl??
        SubDpl subDpl = subDplParser.parseSubDpl(dpl, clone);
        if (subDpl != null) {
            for (String subDplStr : subDpl.getSubDplStrAliasMap().keySet()) {
                String alias = subDpl.getSubDplStrAliasMap().get(subDplStr);
                Object result = subDpl.getAliasResultMap().get(alias);
                dpl = StringUtils.replaceOnce(dpl, subDplStr, alias);
                if (alias.startsWith("dual")) {
                    clone.setAttribute(alias.substring(5), result);
                } else {
                    clone.setAttribute(alias, result);
                }
            }
        }
        From from = fromParser.parseFrom(dpl, clone);
        if (from.getVariableNames().size() == 0) {
            throw new DplParseException("From?");
        }
        Filter filter = filterParser.parseFilter(dpl, clone);
        GroupBy groupBy = groupByParser.parseGroupBy(dpl, clone);
        OrderBy orderBy = orderByParser.parseOrderBy(dpl, clone);
        Select select = selectParser.parseSelect(dpl, clone);
        Pagination pagination = pagingParser.parsePagination(dpl, clone);

        // ????
        DplResultSet dplResultSet = null;
        if (filter != null) {
            filter.filter(clone);
            dplResultSet = clone.getAttribute(CompareFilter.DPL_RESULT_SET);
        }
        if (dplResultSet == null) {
            dplResultSet = new DplResultSet();
            for (String name : from.getVariableNames()) {
                dplResultSet.getResultNames().add(name);
                List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
                List<Object> list = clone.getAttribute(name);
                if (list.size() == 0) {
                    dplResultSet = new DplResultSet();
                    break;
                }
                if (dplResultSet.getResultSet().size() == 0) {
                    for (Object obj : list) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put(name, obj);
                        result.add(map);
                    }
                    dplResultSet.setResultSet(result);
                } else {
                    for (Object obj : list) {
                        for (Map<String, Object> row : new ArrayList<Map<String, Object>>(
                                dplResultSet.getResultSet())) {
                            Map<String, Object> map = new HashMap<String, Object>(row);
                            map.put(name, obj);
                            result.add(map);
                        }
                    }
                    dplResultSet.setResultSet(result);
                }
            }
        }
        // Join???

        // ??
        Map<String, Set<Object>> data = new HashMap<String, Set<Object>>();
        for (String name : from.getVariableNames()) {
            if (!name.equals(CompareFilter.DPL_RESULT_SET)) {
                List<Object> list = clone.getAttribute(name);
                data.put(name, new HashSet<Object>(list));
            }
        }
        // ??
        List<Map<String, Object>> rs = new ArrayList<Map<String, Object>>();

        // ???Join???
        for (Map<String, Object> result : dplResultSet.getResultSet()) {
            boolean valid = true;
            for (String key : result.keySet()) {
                if (result.get(key) != null && !data.get(key).contains(result.get(key))) {
                    valid = false;
                }
            }
            if (valid) {
                rs.add(result);
            }
        }
        // ????
        Map<List<GroupCondition>, List<Map<String, Object>>> groupByRs = new HashMap<List<GroupCondition>, List<Map<String, Object>>>();

        // ???????
        if (groupBy != null) {
            try {
                for (Map<String, Object> result : rs) {
                    List<GroupCondition> gcSet = new ArrayList<GroupCondition>();
                    for (int i = 0; i < groupBy.getGroups().size(); i++) {
                        Group group = groupBy.getGroups().get(i);
                        Object groupValue = group.getValue(result);
                        GroupCondition gc = new GroupCondition();
                        gc.setPosition(i);
                        gc.setGroupName(group.getExpr());
                        gc.setGroupValue(groupValue);
                        gcSet.add(gc);
                    }
                    if (!groupByRs.containsKey(gcSet)) {
                        groupByRs.put(gcSet, new ArrayList<Map<String, Object>>());
                    }
                    groupByRs.get(gcSet).add(result);
                }
            } catch (Exception e) {
                throw new DplParseException(e);
            }
        }
        // SelectFunction???
        List<Map<String, Object>> newRs = new ArrayList<Map<String, Object>>();

        try {
            if (groupBy != null) {
                List<List<GroupCondition>> temp = new ArrayList<List<GroupCondition>>(groupByRs.keySet());
                // ????
                Collections.sort(temp, new GroupConditionComparator());
                // ??????Select???
                for (List<GroupCondition> gcSet : temp) {
                    Map<String, Object> groupMap = new HashMap<String, Object>();
                    for (GroupCondition gc : gcSet) {
                        groupMap.put(gc.getGroupName(), gc.getGroupValue());
                    }
                    Map<String, Object> row = new HashMap<String, Object>();

                    for (Column column : select.getColumns()) {
                        String key = column.getColumnName();
                        PrefixAndSuffix pas = column.getPrefixAndSuffix();
                        if (pas.getFunction() instanceof SingleRowFunction) {
                            SingleRowFunction fun = (SingleRowFunction) pas.getFunction();
                            if (groupMap.containsKey(fun.getExpr())) {
                                Object value = groupMap.get(fun.getExpr());
                                row.put(key, value);
                                groupMap.put(key, value);
                            } else {
                                Object value = fun.recurseCalculate(groupByRs.get(gcSet), groupMap);
                                row.put(key, value);
                                groupMap.put(key, value);
                            }
                        } else if (pas.getFunction() instanceof MultiRowFunction) {
                            MultiRowFunction fun = (MultiRowFunction) pas.getFunction();
                            Object value = fun.recurseCalculate(groupByRs.get(gcSet));
                            row.put(key, value);
                            groupMap.put(key, value);
                        } else {
                            Object value = pas.getValue(groupMap);
                            row.put(key, value);
                            groupMap.put(key, value);
                        }
                    }
                    newRs.add(row);
                }
            } else {
                // ???Join????Select???
                if (select.containMultiRowCalculation()) {
                    // ?
                    Map<String, Object> map = new HashMap<String, Object>();
                    Map<String, Object> row = new HashMap<String, Object>();
                    map.putAll(context.getMap());
                    for (Column column : select.getColumns()) {
                        String key = column.getColumnName();
                        PrefixAndSuffix pas = column.getPrefixAndSuffix();
                        if (pas.getFunction() instanceof SingleRowFunction) {
                            SingleRowFunction fun = (SingleRowFunction) pas.getFunction();
                            Object value = fun.recurseCalculate(rs, map);
                            map.put(key, value);
                            row.put(key, value);
                        } else if (pas.getFunction() instanceof MultiRowFunction) {
                            MultiRowFunction cal = (MultiRowFunction) pas.getFunction();
                            Object value = cal.recurseCalculate(rs);
                            map.put(key, value);
                            row.put(key, value);
                        } else {
                            Object value = pas.getValue(map);
                            if (value == null) {
                                pas.isSupportInMultiFunctionWithoutGroupBy();
                            }
                            map.put(key, value);
                            row.put(key, value);
                        }
                    }
                    newRs.add(row);
                } else {
                    for (Map<String, Object> map : rs) {
                        Map<String, Object> row = new HashMap<String, Object>();
                        for (Column column : select.getColumns()) {
                            String key = column.getColumnName();
                            PrefixAndSuffix pas = column.getPrefixAndSuffix();
                            if (pas.getFunction() instanceof SingleRowFunction) {
                                SingleRowFunction fun = (SingleRowFunction) pas.getFunction();
                                Object value = fun.recurseCalculate(rs, map);
                                map.put(key, value);
                                row.put(key, value);
                            } else if (pas.getFunction() instanceof MultiRowFunction) {
                                throw new DplException("????");
                            } else {
                                Object value = pas.getValue(map);
                                map.put(key, value);
                                row.put(key, value);
                            }
                        }
                        newRs.add(row);
                    }
                }
            }

        } catch (Exception e) {
            throw new DplException(e);
        }
        // ????
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(newRs);
        if (orderBy != null) {
            Collections.sort(list, new OrderByComparator(orderBy));
        }
        // ??
        if (pagination != null) {
            if (pagination.isReverse()) {
                if (pagination.getLimit() == null) {
                    if (list.size() - pagination.getOffset() > 0) {
                        return list.subList(0, list.size() - pagination.getOffset());
                    } else {
                        return new ArrayList<Map<String, Object>>();
                    }
                } else {
                    if (list.size() - pagination.getOffset() > 0) {
                        if (list.size() - pagination.getOffset() - pagination.getLimit() >= 0) {
                            return list.subList(list.size() - pagination.getOffset() - pagination.getLimit(),
                                    list.size() - pagination.getOffset());
                        } else {
                            return list.subList(0, list.size() - pagination.getOffset());
                        }
                    } else {
                        return new ArrayList<Map<String, Object>>();
                    }
                }
            } else {
                if (pagination.getLimit() == null) {
                    if (list.size() - pagination.getOffset() > 0) {
                        return list.subList(pagination.getOffset(), list.size());
                    } else {
                        return new ArrayList<Map<String, Object>>();
                    }
                } else {
                    if (list.size() - pagination.getOffset() > 0) {
                        if (list.size() - pagination.getOffset() - pagination.getLimit() >= 0) {
                            return list.subList(pagination.getOffset(),
                                    pagination.getOffset() + pagination.getLimit());
                        } else {
                            return list.subList(pagination.getOffset(), list.size());
                        }
                    } else {
                        return new ArrayList<Map<String, Object>>();
                    }
                }

            }
        } else {
            return list;
        }
    } finally {
        PrefixAndSuffix.releaseLocalContext();
    }
}

From source file:com.lakeside.data.sqldb.PageBaseDao.java

protected <X> String setPageParameter(final String sql, final Map<String, Object> values, final Page<X> page) {
    Dialect dialect = ((SessionFactoryImpl) sessionFactory).getDialect();
    String pageSql = dialect.getLimitString(sql, page.getFirst() - 1, page.getPageSize());
    boolean hasOffset = page.getFirst() - 1 > 0 || dialect.forceLimitUsage();
    if (!hasOffset) {
        pageSql = pageSql.replace("?", ":pageLimit");
        values.put("pageLimit", page.getPageSize());
        return pageSql;
    }/*ww w.  j ava 2s .  co m*/
    if (dialect.bindLimitParametersInReverseOrder()) {
        pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageLimit");
        pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageOffset");
    } else {
        pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageOffset");
        pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageLimit");
    }
    values.put("pageOffset", page.getFirst() - 1);
    values.put("pageLimit", page.getPageSize());
    if (dialect.useMaxForLimit()) {
        values.put("pageLimit", page.getFirst() - 1 + page.getPageSize());
    }
    return pageSql;
}

From source file:edu.stanford.base.batch.RawCollectionsExample.java

/**
 * @param subcat/*from  w  w w .  j  av  a  2  s .c  om*/
 * @throws IOException
 * @throws HttpException
 * @throws JsonParseException
 * @throws URISyntaxException 
 */
public static void pullSearsProducts(String subcat)
        throws IOException, HttpException, JsonParseException, URISyntaxException {
    StringBuffer reponse = new StringBuffer();
    //http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&searchType=category&productsOnly=1&contentType=json
    //String request = "http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&subCategoryName=Side-by-Side+Refrigerators&searchType=subcategory&productsOnly=1&endIndex=1000&startIndex=1&contentType=json";
    String request = "http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&subCategoryName="
            + subcat + "&searchType=subcategory&productsOnly=1&contentType=json&endIndex=1000&startIndex=1";

    URI uri = new URI(request);
    URL url = uri.toURL();
    //Compact+Refrigerators
    System.out.println(url);
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(request);

    // Send GET request
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
    }
    InputStream rstream = null;

    // Get the response body
    rstream = method.getResponseBodyAsStream();

    // Process the response from Yahoo! Web Services
    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    String line;
    while ((line = br.readLine()) != null) {
        reponse.append(line);
        System.out.println(line);
    }
    br.close();
    Gson gson = new Gson();
    /*   // gson.registerTypeAdapter(Event.class, new MyInstanceCreator());
        Collection collection = new ArrayList();
        collection.add("hello");
        collection.add(5);
        collection.add(new Event("GREETINGS", "guest"));
        String json2 = gson.toJson(collection);
        System.out.println("Using Gson.toJson() on a raw collection: " + json2);*/
    JsonParser parser = new JsonParser();
    //JsonArray array = parser.parse(json1).getAsJsonArray();

    String products = StringUtils.remove(reponse.toString(),
            "{\"mercadoresult\":{\"products\":{\"product\":[true,");
    //System.out.println(products);
    String productsList = StringUtils.substring(products, 0, StringUtils.indexOf(products, "productcount") - 3);
    // System.out.println(productsList);
    productsList = "[" + StringUtils.replaceOnce(productsList, "}}]]", "}]]");
    //System.out.println(productsList);
    List<SearsProduct> prodList = new ArrayList<SearsProduct>();

    // Reader reader = new InputStreamReader(productsList);
    Gson gson1 = new GsonBuilder().create();
    JsonArray array1 = parser.parse(productsList).getAsJsonArray();

    JsonArray prodArray = (JsonArray) array1.get(0);

    // prodList= gson1.fromJson(array1.get(2), ArrayList.class);

    for (JsonElement jsonElement : prodArray) {

        prodList.add(gson.fromJson(jsonElement, SearsProduct.class));
        //System.out.println(gson.fromJson(jsonElement, SearsProduct.class));

    }

    PullSearsProductsDAO pullSearsProductsDAO = new PullSearsProductsDAO();

    try {
        pullSearsProductsDAO.pullAllProducts(prodList);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:msi.gama.util.GamaDate.java

private static Temporal parse(final IScope scope, final String original, final DateTimeFormatter df) {
    if (original == null || original.isEmpty() || original.equals("now")) {
        return LocalDateTime.now(GamaDateType.DEFAULT_ZONE);
    }/*from ww  w .ja  v a 2 s. co m*/
    Temporal result = null;

    if (df != null) {
        try {
            final TemporalAccessor ta = df.parse(original);
            if (ta instanceof Temporal) {
                return (Temporal) ta;
            }
            if (!ta.isSupported(ChronoField.YEAR) && !ta.isSupported(ChronoField.MONTH_OF_YEAR)
                    && !ta.isSupported(ChronoField.DAY_OF_MONTH)) {
                if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
                    return LocalTime.from(ta);
                }
            }
            if (!ta.isSupported(ChronoField.HOUR_OF_DAY) && !ta.isSupported(ChronoField.MINUTE_OF_HOUR)
                    && !ta.isSupported(ChronoField.SECOND_OF_MINUTE)) {
                return LocalDate.from(ta);
            }
            return LocalDateTime.from(ta);
        } catch (final DateTimeParseException e) {
            e.printStackTrace();
        }
        GAMA.reportAndThrowIfNeeded(scope,
                GamaRuntimeException.warning(
                        "The date " + original + " can not correctly be parsed by the pattern provided", scope),
                false);
        return parse(scope, original, null);
    }

    String dateStr;
    try {
        // We first make sure all date fields have the correct length and
        // the string is correctly formatted
        String string = original;
        if (!original.contains("T") && original.contains(" ")) {
            string = StringUtils.replaceOnce(original, " ", "T");
        }
        final String[] base = string.split("T");
        final String[] date = base[0].split("-");
        String other;
        if (base.length == 1) {
            other = "00:00:00";
        } else {
            other = base[1];
        }
        String year, month, day;
        if (date.length == 1) {
            // ISO basic date format
            year = date[0].substring(0, 4);
            month = date[0].substring(4, 6);
            day = date[0].substring(6, 8);
        } else {
            year = date[0];
            month = date[1];
            day = date[2];
        }
        if (year.length() == 2) {
            year = "20" + year;
        }
        if (month.length() == 1) {
            month = '0' + month;
        }
        if (day.length() == 1) {
            day = '0' + day;
        }
        dateStr = year + "-" + month + "-" + day + "T" + other;
    } catch (final Exception e1) {
        throw GamaRuntimeException.error("The date " + original
                + " is not correctly formatted. Please refer to the ISO date/time format", scope);
    }

    try {
        result = LocalDateTime.parse(dateStr);
    } catch (final DateTimeParseException e) {
        try {
            result = OffsetDateTime.parse(dateStr);
        } catch (final DateTimeParseException e2) {
            try {
                result = ZonedDateTime.parse(dateStr);
            } catch (final DateTimeParseException e3) {
                throw GamaRuntimeException.error(
                        "The date " + original
                                + " is not correctly formatted. Please refer to the ISO date/time format",
                        scope);
            }
        }
    }

    return result;
}

From source file:com.comcast.cats.provider.VideoRecorderRESTProviderImpl.java

private String substituteFilePath(String filePath) {
    String retVal = filePath;/*from www  . ja  v  a  2  s. co m*/
    try {
        URL filePathURL = new URL(filePath);
        String host = filePathURL.getHost();
        retVal = StringUtils.replaceOnce(filePath, host, serverHost);
    } catch (MalformedURLException e) {
        logger.debug("Provider doesnt know how to parse this syntax");
    }
    return retVal;
}

From source file:com.liferay.sync.engine.service.persistence.SyncFilePersistence.java

public void renameByParentFilePathName(final String sourceParentFilePathName,
        final String targetParentFilePathName) throws SQLException {

    Callable<Object> callable = new Callable<Object>() {

        @Override/*  w w  w.  jav  a  2s .  c  o  m*/
        public Object call() throws Exception {
            FileSystem fileSystem = FileSystems.getDefault();

            List<SyncFile> syncFiles = findByParentFilePathName(sourceParentFilePathName);

            for (SyncFile syncFile : syncFiles) {
                String filePathName = syncFile.getFilePathName();

                filePathName = StringUtils.replaceOnce(filePathName,
                        sourceParentFilePathName + fileSystem.getSeparator(),
                        targetParentFilePathName + fileSystem.getSeparator());

                syncFile.setFilePathName(filePathName);

                update(syncFile);
            }

            return null;
        }

    };

    callBatchTasks(callable);
}

From source file:gda.device.detector.addetector.filewriter.SingleImagePerFileWriter.java

private void addPathTemplateToMetadata() {
    IJythonNamespace jythonNamespace = InterfaceProvider.getJythonNamespace();
    String existingMetadataString = (String) jythonNamespace.getFromJythonNamespace("SRSWriteAtFileCreation");
    String newMetadataString;/*from   ww w  .  j a v  a2s .  c  o  m*/
    if (existingMetadataString == null) {
        newMetadataString = "";
    } else {
        newMetadataString = existingMetadataString;
    }

    String fileDirRelativeToDataDirIfPossible = getFileDirRelativeToDataDirIfPossible();
    String template = (getFileTemplateForReadout() == null) ? getFileTemplate() : getFileTemplateForReadout();
    String newValue = StringUtils.replaceOnce(template, "%s", fileDirRelativeToDataDirIfPossible + "/");
    newValue = StringUtils.replaceOnce(newValue, "%s", getFileName());
    String newKey = getkeyNameForMetadataPathTemplate();
    jythonNamespace.placeInJythonNamespace("SRSWriteAtFileCreation",
            newMetadataString + newKey + "='" + newValue + "'\n");
    InterfaceProvider.getTerminalPrinter().print("Image location: " + newKey + "='" + newValue);
}

From source file:com.edgenius.wiki.render.filter.BasePatternFilter.java

public void setRegex(String regex) {
    if (regex.trim().equals(FilterRegxConstants.PATTERN_NORMAL_KEY)) {
        needSpecialSurrounding = true;/*from  w w w.  j a va 2  s.  c  o m*/
        regex = FilterRegxConstants.PATTERN_NORMAL_SURROUNDING.replaceAll(FilterRegxConstants.PATTERN_REP_TOKEN,
                getMarkupPrint());
    } else if (regex.trim().equals(FilterRegxConstants.PATTERN_ANYTEXT_KEY)) {
        if (FilterRegxConstants.PRINT_VARIABLE.equals(getMarkupPrint())) {
            //variable token is {$xxx}
            //don't use String.replaceFirst(), which is not working properly for {\\$ as replacement
            regex = StringUtils.replaceOnce(FilterRegxConstants.PATTERN_ANYTEXT_SURROUNDING,
                    FilterRegxConstants.PATTERN_REP_TOKEN, "{\\$");
            regex = StringUtils.replaceOnce(regex, FilterRegxConstants.PATTERN_REP_TOKEN, "}");
        } else {
            regex = FilterRegxConstants.PATTERN_ANYTEXT_SURROUNDING
                    .replaceAll(FilterRegxConstants.PATTERN_REP_TOKEN, getMarkupPrint());
        }
    } else if (regex.trim().equals(FilterRegxConstants.PATTERN_SINGLE_KEY)) {
        regex = FilterRegxConstants.PATTERN_SINGLE_TOKEN.replaceAll(FilterRegxConstants.PATTERN_REP_TOKEN,
                getMarkupPrint());
    } else if (regex.trim().equals(FilterRegxConstants.PATTERN_ANCHOR_KEY)) {
        needSpecialSurrounding = true;
        regex = FilterRegxConstants.PATTERN_ANCHOR.replaceAll(FilterRegxConstants.PATTERN_REP_TOKEN,
                getMarkupPrint());
    }

    this.regex = regex;
}

From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java

/**
 * toPrintString/*w w w.j a  v a 2s  .c o m*/
 * 
 * @param sql
 *            sql
 * @param objects
 *            objects
 * @return sql String
 */
public String toPrintString(String sql, List<Object> objects) {
    if (CollectionUtils.isEmpty(objects)) {
        return sql;
    }
    String printSql = new String(sql);
    int valuesCount = 0;
    if (!StringUtils.isEmpty(printSql)) {
        for (Object value : objects) {
            valuesCount++;
            if (value instanceof String) {
                printSql = StringUtils.replaceOnce(printSql, "?", "'" + value.toString() + "'");
            } else {
                printSql = StringUtils.replaceOnce(printSql, "?", value.toString());
            }
            if (valuesCount > 2000) {
                return printSql;
            }
        }
        return printSql;
    } else {
        return "";
    }
}