List of usage examples for org.apache.commons.lang3 StringUtils replaceOnce
public static String replaceOnce(final String text, final String searchString, final String replacement)
Replaces a String with another String inside a larger String, once.
A null reference passed to this method is a no-op.
StringUtils.replaceOnce(null, *, *) = null StringUtils.replaceOnce("", *, *) = "" StringUtils.replaceOnce("any", null, *) = "any" StringUtils.replaceOnce("any", *, null) = "any" StringUtils.replaceOnce("any", "", *) = "any" StringUtils.replaceOnce("aba", "a", null) = "aba" StringUtils.replaceOnce("aba", "a", "") = "ba" StringUtils.replaceOnce("aba", "a", "z") = "zba"
From source file:net.minecraftforge.common.config.ConfigManager.java
private static void sync(Configuration cfg, Class<?> cls, String modid, String category, boolean loading, Object instance) {/*from ww w . java2s . co m*/ for (Field f : cls.getDeclaredFields()) { if (!Modifier.isPublic(f.getModifiers())) continue; //Only the root class may have static fields. Otherwise category tree nodes of the same type would share the //contained value messing up the sync if (Modifier.isStatic(f.getModifiers()) != (instance == null)) continue; if (f.isAnnotationPresent(Config.Ignore.class)) continue; String comment = null; Comment ca = f.getAnnotation(Comment.class); if (ca != null) comment = NEW_LINE.join(ca.value()); String langKey = modid + "." + (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER) + f.getName().toLowerCase(Locale.ENGLISH); LangKey la = f.getAnnotation(LangKey.class); if (la != null) langKey = la.value(); boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class); boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class); if (FieldWrapper.hasWrapperFor(f)) //Wrappers exist for primitives, enums, maps and arrays { if (Strings.isNullOrEmpty(category)) throw new RuntimeException( "An empty category may not contain anything but objects representing categories!"); try { IFieldWrapper wrapper = FieldWrapper.get(instance, f, category); ITypeAdapter adapt = wrapper.getTypeAdapter(); Property.Type propType = adapt.getType(); for (String key : wrapper.getKeys()) //Iterate the fully qualified property names the field provides { String suffix = StringUtils.replaceOnce(key, wrapper.getCategory() + Configuration.CATEGORY_SPLITTER, ""); boolean existed = exists(cfg, wrapper.getCategory(), suffix); if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added { Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter()); adapt.setDefaultValue(property, wrapper.getValue(key)); if (!existed) adapt.setValue(property, wrapper.getValue(key)); else wrapper.setValue(key, adapt.getValue(property)); } else //If the key is not new, sync according to shouldReadFromVar() { Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter()); Object propVal = adapt.getValue(property); Object mapVal = wrapper.getValue(key); if (shouldReadFromVar(property, propVal, mapVal)) adapt.setValue(property, mapVal); else wrapper.setValue(key, propVal); } } ConfigCategory confCat = cfg.getCategory(wrapper.getCategory()); for (Property property : confCat.getOrderedValues()) //Iterate the properties to check for new data from the config side { String key = confCat.getQualifiedName() + Configuration.CATEGORY_SPLITTER + property.getName(); if (!wrapper.handlesKey(key)) continue; if (loading || !wrapper.hasKey(key)) { Object value = wrapper.getTypeAdapter().getValue(property); wrapper.setValue(key, value); } } if (loading) wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart); } catch (Exception e) { String format = "Error syncing field '%s' of class '%s'!"; String error = String.format(format, f.getName(), cls.getName()); throw new RuntimeException(error, e); } } else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class)) { //If the field extends Object directly, descend the object tree and access the objects members Object newInstance = null; try { newInstance = f.get(instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } //Setup the sub category with its respective name, comment, language key, etc. String sub = (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER) + getName(f).toLowerCase(Locale.ENGLISH); ConfigCategory confCat = cfg.getCategory(sub); confCat.setComment(comment); confCat.setLanguageKey(langKey); confCat.setRequiresMcRestart(requiresMcRestart); confCat.setRequiresWorldRestart(requiresWorldRestart); sync(cfg, f.getType(), modid, sub, loading, newInstance); } else { String format = "Can't handle field '%s' of class '%s': Unknown type."; String error = String.format(format, f.getName(), cls.getCanonicalName()); throw new RuntimeException(error); } } }
From source file:com.oltpbenchmark.benchmarks.rest.procedures.RESTOrderStatus.java
public Customer getCustomerByName(int c_w_id, int c_d_id, String c_last) throws SQLException, JSONException { ArrayList<Customer> customers = new ArrayList<Customer>(); String customerByNameSQL = customerByNameSQLWithVariables; customerByNameSQL = StringUtils.replaceOnce(customerByNameSQL, SQL_VARIABLE, Integer.toString(c_w_id)); customerByNameSQL = StringUtils.replaceOnce(customerByNameSQL, SQL_VARIABLE, Integer.toString(c_d_id)); customerByNameSQL = StringUtils.replaceOnce(customerByNameSQL, SQL_VARIABLE, c_last); ClientResponse response = getClient().post(ClientResponse.class, customerByNameSQL); if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) { throw new SQLException("Query " + customerByNameSQL + " encountered an error "); }//from w ww . j av a2 s . co m JSONArray jsonArray = response.getEntity(JSONArray.class); response.close(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Customer c = RESTUtil.newCustomerFromResults(jsonObject); c.c_id = jsonObject.optInt("C_ID"); c.c_last = c_last; customers.add(c); } if (customers.size() == 0) { throw new RuntimeException( "C_LAST=" + c_last + " C_D_ID=" + c_d_id + " C_W_ID=" + c_w_id + " not found!"); } // TPC-C 2.5.2.2: Position n / 2 rounded up to the next integer, but // that // counts starting from 1. int index = customers.size() / 2; if (customers.size() % 2 == 0) { index -= 1; } return customers.get(index); }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Removes directory index files. They are often not needed in URLs.</p> * <code>http://www.example.com/a/index.html → * http://www.example.com/a/</code> * <p>Index files must be the last URL path segment to be considered. * The following are considered index files:</p> * <ul>/*from w w w . j a va 2s . c o m*/ * <li>index.html</li> * <li>index.htm</li> * <li>index.shtml</li> * <li>index.php</li> * <li>default.html</li> * <li>default.htm</li> * <li>home.html</li> * <li>home.htm</li> * <li>index.php5</li> * <li>index.php4</li> * <li>index.php3</li> * <li>index.cgi</li> * <li>placeholder.html</li> * <li>default.asp</li> * </ul> * <p><b>Please Note:</b> There are no guarantees a URL without its * index files will be semantically equivalent, or even be valid.</p> * @return this instance */ public URLNormalizer removeDirectoryIndex() { String path = toURI(url).getPath(); if (PATTERN_PATH_LAST_SEGMENT.matcher(path).matches()) { url = StringUtils.replaceOnce(url, path, StringUtils.substringBeforeLast(path, "/") + "/"); } return this; }
From source file:com.oltpbenchmark.benchmarks.rest.procedures.RESTOrderStatus.java
private JSONArray queryRESTEndpoint(String sqlStringWithVariables, String... replacements) throws SQLException { String sqlQuery = sqlStringWithVariables; for (int i = 0; i < replacements.length; i++) { sqlQuery = StringUtils.replaceOnce(sqlQuery, SQL_VARIABLE, replacements[i]); }// w ww . ja va2s .com ClientResponse response = getClient().post(ClientResponse.class, sqlQuery); if (response.getClientResponseStatus() != com.sun.jersey.api.client.ClientResponse.Status.OK) { throw new SQLException("Query " + sqlQuery + " encountered an error "); } JSONArray jsonArray = response.getEntity(JSONArray.class); response.close(); return jsonArray; }
From source file:com.elementwin.bs.controller.RevisitExportController.java
private List<String> getExportData(List<RevisitTask> tasks, Map<Long, List<BaseModel>> allAnswerMap, Map<Long, List<BaseModel>> allRecordMap, Map<Long, List<BaseModel>> allWorkOrderMap, int questionItemCount) throws Exception { List<String> taskStrs = new ArrayList<String>(); for (RevisitTask task : tasks) { //?//from w ww.j av a2 s .c om List<BaseModel> answers = allAnswerMap != null ? allAnswerMap.get(task.getId()) : null; int beginIdx = 21; int fluidLength = beginIdx + (questionItemCount * 2); //excelHelper? String[] records = new String[fluidLength + 8]; //???8 records[0] = task.getId().toString(); records[1] = task.getServiceEndDate(); records[2] = task.getIsDealerStore(); records[3] = task.getCarFrameNo(); records[4] = task.getCarLicenseNo(); records[5] = task.getCarBrand(); records[6] = task.getCarModelType(); records[7] = task.getCustomerManager(); records[8] = task.getCarDriver(); records[9] = task.getCarDriverPhone(); records[10] = task.getCarOwner(); records[11] = task.getAddress(); records[12] = task.getServiceType(); records[13] = task.getMileage().toString(); records[14] = task.getIsMember(); records[15] = task.getIsOutInsure(); records[16] = DateUtils.getDateTime(task.getUpdateTime()); //? List<BaseModel> rcs = (List<BaseModel>) allRecordMap.get(task.getId()); String isCall = "?"; if (rcs != null && !rcs.isEmpty()) { for (BaseModel rc : rcs) { if (((RevisitRecord) rc).getCallDuration() > 0) { isCall = ""; break; } } } records[17] = isCall; records[18] = task.getOwnerName() != null ? task.getOwnerName() : "-"; // records[19] = task.getStatusName(); // String comment = ""; if (rcs != null && !rcs.isEmpty()) { for (BaseModel rc : rcs) { RevisitRecord record = (RevisitRecord) rc; comment += DateUtils.getDateTime(record.getCreateTime()) + " - " + record.getCcuserName() + " - " + record.getStatusName() + "; "; } } records[20] = comment; // if (answers != null && !answers.isEmpty()) { String[] answerArray = new String[questionItemCount]; String[] scoreArray = new String[questionItemCount]; if (answers.size() != questionItemCount) { logger.warn("????taskId=" + task.getId() + ", questionItemCount=" + questionItemCount + ", answerSize=" + answers.size()); } for (int i = 0; i < answers.size(); i++) { RevisitAnswer answer = (RevisitAnswer) answers.get(i); //checkbox? String rs = StringUtils.replaceOnce(answer.getAnswer(), "_", ","); if (i >= questionItemCount) { break; } answerArray[i] = rs; scoreArray[i] = answer.getScore() > 0 ? String.valueOf(answer.getScore()) : "0"; } for (int i = 0; i < questionItemCount; i++) { records[beginIdx++] = answerArray[i]; records[beginIdx++] = scoreArray[i]; } } String category = "-", content = "-"; //update2016_12_30 RevisitWorkOrder workOrder = null; //end_update if (allWorkOrderMap != null && !allWorkOrderMap.isEmpty()) { List<BaseModel> workOrders = allWorkOrderMap.get(task.getWorkOrderId()); if (workOrders != null && !workOrders.isEmpty()) { workOrder = (RevisitWorkOrder) workOrders.get(0); category = workOrder.getCategory(); content = workOrder.getContent(); } } // ???? records[fluidLength] = String.valueOf(task.getTotalScore()); records[fluidLength + 1] = category; records[fluidLength + 2] = content; //update2016_12_30 if (workOrder != null) { records[fluidLength + 3] = workOrder.getStatusTrace(); //? records[fluidLength + 4] = workOrder.getProgressTrace(); // // records[fluidLength + 5] = DateUtils.getDateTime(workOrder.getCreateTime()); records[fluidLength + 6] = workOrder.getCloseTime() != null ? DateUtils.getDateTime(workOrder.getCloseTime()) : "-"; // records[fluidLength + 7] = workOrder.getCloseTime() != null ? workOrder.getCloseByName() : "-"; // } //end_update taskStrs.add(StringUtils.join(records, Cons.SPLIT_FLAG)); } return taskStrs; }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Removes duplicate slashes. Two or more adjacent slash ("/") * characters will be converted into one.</p> * <code>http://www.example.com/foo//bar.html * → http://www.example.com/foo/bar.html </code> * @return this instance/*from www . j a v a 2 s. co m*/ */ public URLNormalizer removeDuplicateSlashes() { String path = toURI(url).getPath(); String newPath = path.replaceAll("/{2,}", "/"); url = StringUtils.replaceOnce(url, path, newPath); return this; }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Removes "www." domain name prefix.</p> * <code>http://www.example.com/ → http://example.com/</code> * @return this instance/*from ww w . jav a2s . com*/ */ public URLNormalizer removeWWW() { String host = toURI(url).getHost(); String newHost = StringUtils.removeStartIgnoreCase(host, "www."); url = StringUtils.replaceOnce(url, host, newHost); return this; }
From source file:io.bitsquare.gui.util.BSFormatter.java
public static String formatDurationAsWords(long durationMillis, boolean showSeconds) { String format;//w ww . j ava2 s.c o m if (showSeconds) format = "d\' days, \'H\' hours, \'m\' minutes, \'s\' seconds\'"; else format = "d\' days, \'H\' hours, \'m\' minutes\'"; String duration = DurationFormatUtils.formatDuration(durationMillis, format); String tmp; duration = " " + duration; tmp = StringUtils.replaceOnce(duration, " 0 days", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(tmp, " 0 hours", ""); if (tmp.length() != duration.length()) { tmp = StringUtils.replaceOnce(tmp, " 0 minutes", ""); duration = tmp; if (tmp.length() != tmp.length()) { duration = StringUtils.replaceOnce(tmp, " 0 seconds", ""); } } } if (duration.length() != 0) { duration = duration.substring(1); } tmp = StringUtils.replaceOnce(duration, " 0 seconds", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(tmp, " 0 minutes", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(tmp, " 0 hours", ""); if (tmp.length() != duration.length()) { duration = StringUtils.replaceOnce(tmp, " 0 days", ""); } } } duration = " " + duration; duration = StringUtils.replaceOnce(duration, " 1 seconds", " 1 second"); duration = StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute"); duration = StringUtils.replaceOnce(duration, " 1 hours", " 1 hour"); duration = StringUtils.replaceOnce(duration, " 1 days", " 1 day"); if (duration.startsWith(" ,")) duration = duration.replace(" ,", ""); else if (duration.startsWith(", ")) duration = duration.replace(", ", ""); if (duration.equals("")) duration = "Trade period is over"; return duration.trim(); }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Adds "www." domain name prefix.</p> * <code>http://example.com/ → http://www.example.com/</code> * @return this instance/*from ww w .jav a 2s. c o m*/ */ public URLNormalizer addWWW() { String host = toURI(url).getHost(); if (!host.toLowerCase().startsWith("www.")) { url = StringUtils.replaceOnce(url, host, "www." + host); } return this; }
From source file:com.gargoylesoftware.htmlunit.WebTestCase.java
/** * Generates an instrumented HTML file in the temporary dir to easily make a manual test in a real browser. * The file is generated only if the system property {@link #PROPERTY_GENERATE_TESTPAGES} is set. * @param content the content of the HTML page * @param expectedAlerts the expected alerts * @throws IOException if writing file fails *///w ww . j av a2 s . c o m protected void createTestPageForRealBrowserIfNeeded(final String content, final List<String> expectedAlerts) throws IOException { // save the information to create a test for WebDriver generateTest_content_ = content; generateTest_expectedAlerts_ = expectedAlerts; final Method testMethod = findRunningJUnitTestMethod(); generateTest_testName_ = testMethod.getDeclaringClass().getSimpleName() + "_" + testMethod.getName() + ".html"; if (System.getProperty(PROPERTY_GENERATE_TESTPAGES) != null) { // should be optimized.... // calls to alert() should be replaced by call to custom function String newContent = StringUtils.replace(content, "alert(", "htmlunitReserved_caughtAlert("); final String instrumentationJS = createInstrumentationScript(expectedAlerts); // first version, we assume that there is a <head> and a </body> or a </frameset> if (newContent.indexOf("<head>") > -1) { newContent = StringUtils.replaceOnce(newContent, "<head>", "<head>" + instrumentationJS); } else { newContent = StringUtils.replaceOnce(newContent, "<html>", "<html>\n<head>\n" + instrumentationJS + "\n</head>\n"); } final String endScript = "\n<script>htmlunitReserved_addSummaryAfterOnload();</script>\n"; if (newContent.contains("</body>")) { newContent = StringUtils.replaceOnce(newContent, "</body>", endScript + "</body>"); } else { LOG.info("No test generated: currently only content with a <head> and a </body> is supported"); } final File f = File.createTempFile("TEST" + '_', ".html"); FileUtils.writeStringToFile(f, newContent, "ISO-8859-1"); LOG.info("Test file written: " + f.getAbsolutePath()); } else { if (LOG.isDebugEnabled()) { LOG.debug("System property \"" + PROPERTY_GENERATE_TESTPAGES + "\" not set, don't generate test HTML page for real browser"); } } }