public static String unescapeXML(String str) { str = StringUtils.replace(str, "&", "&"); str = StringUtils.replace(str, "<", "<"); str = StringUtils.replace(str, ">", ">"); str = StringUtils.replace(str, """, "\""); str = StringUtils.replace(str, "'", "'"); return str; }
public static String escapeHTML(String str) { str = StringUtils.replace(str, "&", "&"); str = StringUtils.replace(str, "<", "<"); str = StringUtils.replace(str, ">", ">"); str = StringUtils.replace(str, "\"", """); str = StringUtils.replace(str, "'", "'"); return str; }
public static String escapeShell(String arg, OS os) { if (os.isPosix) { return "'" + StringUtils.replace(arg, "'", "'\\''") + "'"; } else if (os == OS.WINDOWS) { return '"' + StringUtils.replace(arg, "\"", "\\\"") + '"'; } throw new IllegalArgumentException("unsupported OS"); }
private void whenThePracticeStatusQueueServiceIsCalled() throws IOException { String url = StringUtils.replace(STATUS_URL, "{practiceId}", "1"); url = StringUtils.replace(url, "{username}", username); yatspec.log("STATUS_URL", url); Response response = Request.Get(url).connectTimeout(1000).socketTimeout(1000).execute(); httpResponse = response.returnResponse(); responseContent = EntityUtils.toString(httpResponse.getEntity()); }
public static String removeGarbage(String sentence) { StringUtils.replace(sentence, "[^\\p{ASCII}]", ""); // non-ASCII StringUtils.replace(sentence, "\\s+", " "); // recurring whitespace StringUtils.replace(sentence, "\\p{Cntrl}", ""); // Control StringUtils.replace(sentence, "[^\\p{Print}]", ""); // Non-printable StringUtils.replace(sentence, "\\p{C}", ""); // non-printable for // unicode return sentence; } // end method
/** * @param act * @param locale * @param exception */ private void sendKrashAuditEmail(Act act, Locale locale, Exception exception) { ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale); String emailFrom = bundle.getString(RECIPIENT_KEY); String projectName = getProjectNameFromAct(act); if (isAllowedToSendKrashReport && CollectionUtils.isNotEmpty(krashReportMailList)) { Set<String> emailToSet = new HashSet<>(); emailToSet.addAll(krashReportMailList); String host = ""; try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { } String msgSubject = bundle.getString(KRASH_ADMIN_SUBJECT_KEY); msgSubject = StringUtils.replace(msgSubject, PROJECT_NAME_TO_REPLACE, projectName); msgSubject = StringUtils.replace(msgSubject, HOST_TO_REPLACE, host); String msgContent = bundle.getString(KRASH_ADMIN_MSG_CONTENT_KEY); msgContent = StringUtils.replace(msgContent, PROJECT_NAME_TO_REPLACE, projectName); msgContent = StringUtils.replace( msgContent, USER_EMAIL_TO_REPLACE, act.getContract().getUser().getEmail1()); msgContent = StringUtils.replace(msgContent, HOST_TO_REPLACE, host); msgContent = StringUtils.replace( msgContent, EXCEPTION_TO_REPLACE, ExceptionUtils.getStackTrace(exception)); if (act.getAudit().getSubject() != null) { msgContent = StringUtils.replace( msgContent, AUDIT_URL_TO_REPLACE, act.getAudit().getSubject().getURL()); } LOGGER.info( "krash email sent to " + krashReportMailList + " on audit n° " + act.getAudit().getId()); sendEmail(emailFrom, emailToSet, msgSubject, msgContent); } String emailTo = act.getContract().getUser().getEmail1(); if (this.emailSentToUserExclusionList.contains(emailTo)) { LOGGER.info("Email not set cause user " + emailTo + " belongs to " + "exlusion list"); return; } Set<String> emailToSet = new HashSet<>(); emailToSet.add(emailTo); String msgSubject = bundle.getString(KRASH_SUBJECT_KEY); msgSubject = StringUtils.replace(msgSubject, PROJECT_NAME_TO_REPLACE, projectName); String msgContent = bundle.getString(KRASH_MSG_CONTENT_KEY); msgContent = StringUtils.replace(msgContent, PROJECT_NAME_TO_REPLACE, projectName); msgContent = StringUtils.replace( msgContent, PROJECT_URL_TO_REPLACE, buildContractUrl(act.getContract())); LOGGER.info("krash email sent to [" + emailTo + "]" + " on audit n° " + act.getAudit().getId()); sendEmail(emailFrom, emailToSet, msgSubject, msgContent); }
private String clearString(String text) { String dummyString = StringUtils.replace(text, "\n", ","); dummyString = dummyString.replaceAll("\\s+", ""); // if (StringUtils.contains(text, "//") && StringUtils.indexOf(text, "//") == 0) { // char delimiter = text.charAt(2); // dummyString = StringUtils.replace(dummyString, Character.toString(delimiter), ","); // } String delimiter = getDelimiter(dummyString); if (delimiter != null) { dummyString = StringUtils.replace(dummyString, delimiter, ","); } return dummyString; }
@Transient public String getUrlStatic(Integer page, boolean isFull, boolean forRealPath) { if (isLinked()) { return getLinkUrl(); } // 超过静态化页数,则为动态页。 if (page != null && page > getStaticPageOrDef()) { return getUrlDynamic(page); } String path = getNodePathOrDef(); path = StringUtils.replace(path, PATH_NODE_ID, getId().toString()); String number = getNumber(); if (StringUtils.isBlank(number)) { number = getId().toString(); } path = StringUtils.replace(path, PATH_NODE_NUMBER, number); String extension = getNodeExtensionOrDef(); if (page != null && page > 1) { if (StringUtils.isNotBlank(extension)) { path += "_" + page + extension; } else { path += "_" + page; } } else if (!forRealPath && getDefPageOrDef()) { path = path.substring(0, path.lastIndexOf("/") + 1); } else { if (StringUtils.isNotBlank(extension)) { path += extension; } } StringBuilder sb = new StringBuilder(); Site site = getSite(); if (isFull && !forRealPath) { sb.append("//"); String domain = site.getDomain(); sb.append(domain); if (site.getPort() != null) { sb.append(":").append(site.getPort()); } } if (!forRealPath) { PublishPoint point = getSite().getHtmlPublishPoint(); String urlPrefix = point.getUrlPrefix(); if (StringUtils.isNotBlank(urlPrefix)) { sb.append(urlPrefix); } } sb.append(path); return sb.toString(); }
private static String getFormatedKeyName(String formatStr, String fieldName, Integer index) { if (formatStr != null) { formatStr = formatStr.toUpperCase(); if (StringUtils.isNotEmpty(fieldName)) { formatStr = StringUtils.replace(formatStr, "{NAME}", fieldName); } if (index != null) { formatStr = StringUtils.replace(formatStr, "{INDEX}", String.valueOf(index)); } return formatStr.toUpperCase(); } return fieldName.toUpperCase(); }
/** * Encodes illegal characters in the specified URL's path, query string and anchor according to * the URL encoding rules observed in real browsers. * * <p>For example, this method changes <tt>"http://first/?a=b c"</tt> to * <tt>"http://first/?a=b%20c"</tt>. * * @param url the URL to encode * @param minimalQueryEncoding whether or not to perform minimal query encoding, like IE does * @param charset the charset * @return the encoded URL */ public static URL encodeUrl( final URL url, final boolean minimalQueryEncoding, final String charset) { final String p = url.getProtocol(); if ("javascript".equalsIgnoreCase(p) || "about".equalsIgnoreCase(p) || "data".equalsIgnoreCase(p)) { // Special exception. return url; } try { String path = url.getPath(); if (path != null) { path = encode(path, PATH_ALLOWED_CHARS, "UTF-8"); } String query = url.getQuery(); if (query != null) { if (minimalQueryEncoding) { query = org.apache.commons.lang3.StringUtils.replace(query, " ", "%20"); } else { query = encode(query, QUERY_ALLOWED_CHARS, charset); } } String anchor = url.getRef(); if (anchor != null) { anchor = encode(anchor, ANCHOR_ALLOWED_CHARS, "UTF-8"); } return createNewUrl(url.getProtocol(), url.getHost(), url.getPort(), path, anchor, query); } catch (final MalformedURLException e) { // Impossible... I think. throw new RuntimeException(e); } }
@Override public String importQuestionnareOds(String filename, String questionnaireName) throws Exception { SpreadsheetDocument document = SpreadsheetDocument.loadDocument(new File(filename)); Table sheet = document.getSheetByIndex(0); List<String> questions = new ArrayList<>(); for (int i = 1; i < sheet.getRowList().size(); i++) { Row row = sheet.getRowList().get(i); String question = getCellStringValue(row, 0); if (StringUtils.isBlank(question)) { break; } String levelString = getCellStringValue(row, 1); long level = Long.valueOf(StringUtils.replace(levelString, "D", "")); String tagsString = getCellStringValue(row, 2); List<String> tags = Collections.emptyList(); if (StringUtils.isNotBlank(tagsString)) { tags = Lists.newArrayList(StringUtils.split(tagsString, ", ")); } String tip = StringUtils.defaultIfBlank(getCellStringValue(row, 3), null); XContentBuilder builder = jsonBuilder() .startObject() .field("title", question) .field("level", level) .field("tags", tags) .field("tip", tip) .endObject(); IndexResponse indexResponse = client .prepareIndex(domainResolver.resolveQuestionIndex(), Types.question) .setSource(builder) .execute() .actionGet(); questions.add(indexResponse.getId()); } XContentBuilder questionnaireBuilder = jsonBuilder() .startObject() .field("name", questionnaireName) .field("questions", questions) .endObject(); IndexResponse indexResponse = client .prepareIndex(domainResolver.resolveQuestionIndex(), Types.questionnaire) .setSource(questionnaireBuilder) .execute() .actionGet(); return indexResponse.getId(); }
/** * 新增多个点播MdnVodItem * * @param mdnItem mdn对象 * @param vodDomains 点播域名数组 * @param vodBandwidths 点播加速服务带宽(含单位)数组 * @param vodProtocols 播放协议数组 * @param sourceOutBandwidths 源站出口带宽(含单位)数组 * @param sourceStreamerUrls 源站Streamer公网地址 数组 */ @Transactional(readOnly = false) public void saveMdnVodItem( MdnItem mdnItem, String[] vodDomains, String[] vodBandwidths, String[] vodProtocols, String[] sourceOutBandwidths, String[] sourceStreamerUrls) { if (vodDomains != null) { for (int i = 0; i < vodDomains.length; i++) { MdnVodItem mdnVodItem = new MdnVodItem(); mdnVodItem.setMdnItem(mdnItem); mdnVodItem.setSourceOutBandwidth(sourceOutBandwidths[i]); mdnVodItem.setSourceStreamerUrl(sourceStreamerUrls[i]); mdnVodItem.setVodBandwidth(vodBandwidths[i]); mdnVodItem.setVodDomain(vodDomains[i]); mdnVodItem.setVodProtocol(StringUtils.replace(vodProtocols[i], "-", ",")); this.saveOrUpdate(mdnVodItem); } } }
/** * Extract the text from a HTML based string. This is similar to what HTML.fromHtml(...) does, but * this method also removes the embedded images instead of replacing them by a small rectangular * representation character. * * @param html * @return */ public static String extractText(CharSequence html) { String result = html.toString(); // recognize images in textview HTML contents if (html instanceof Spanned) { Spanned text = (Spanned) html; Object[] styles = text.getSpans(0, text.length(), Object.class); ArrayList<Pair<Integer, Integer>> removals = new ArrayList<Pair<Integer, Integer>>(); for (Object style : styles) { if (style instanceof ImageSpan) { int start = text.getSpanStart(style); int end = text.getSpanEnd(style); removals.add(Pair.of(start, end)); } } // sort reversed and delete image spans Collections.sort( removals, new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> lhs, Pair<Integer, Integer> rhs) { return rhs.getRight().compareTo(lhs.getRight()); } }); result = text.toString(); for (Pair<Integer, Integer> removal : removals) { result = result.substring(0, removal.getLeft()) + result.substring(removal.getRight()); } } // some line breaks are still in the text, source is unknown return StringUtils.replace(result, "<br />", "\n").trim(); }
private BitmapFontFile getBitmapFontFileInternal(EnumBitmapFont font, int size) { if (!mapBffByFontName.containsKey(font)) { String path = StringUtils.replace(font.getFilepath(), "$size", String.valueOf(size)); BitmapFontFile file = new BitmapFontFile(path); mapBffByFontName.put(font, file); } return mapBffByFontName.get(font); }
@Override public void createOrderedAndUnorderedRelationsForNode(String id) { String finalId = StringUtils.replace(id, "/", "%2F"); WebTarget target = client.target("/relations/generate/order/" + finalId); target.request().post(null); WebTarget unordered = client.target("/order/fakeorder/nodeId/" + finalId); unordered.request().get(); }
/** * Take the error key and expand as would happen when displaying error to the client. * * @param errorKey * @param params * @return */ protected String expandErrorString(String errorKey, String[] params) { ConfigurationService kualiConfiguration = getKualiConfigurationService(); String questionText = kualiConfiguration.getPropertyValueAsString(errorKey); for (int i = 0; i < params.length; i++) { questionText = StringUtils.replace(questionText, "{" + i + "}", params[i]); } return questionText; }
public static String handleDaysToken(String originalText, int daysLeft) { String ret = originalText; if (originalText != null) { ret = StringUtils.replace(originalText, Constants.EMAIL_DAYS_TOKEN, String.valueOf(daysLeft)); } return ret; }
public static String handleHostToken(String originalText, String host) { String ret = originalText; if (originalText != null) { ret = StringUtils.replace(originalText, Constants.EMAIL_WEB_HOST_TOKEN, host); } return ret; }
/** @return the matching resource folder of the package of the current class! */ protected String getTestSuiteFolder() { Path suiteFolder = resolveResource(this.getClass(), "."); if (Files.exists(suiteFolder)) { return suiteFolder.normalize().toAbsolutePath().toString(); } throw new SakuliRuntimeException( String.format( "Cannot load test suite folder from classpath! Should be at normal test 'src/test/resources/%s'", StringUtils.replace(this.getClass().getCanonicalName(), ".", "/"))); }
/** * Converts the received data of a complex member variable to a JSON string * * * @param data * @return */ private String parseValue(String data) { StringBuilder jsonData = new StringBuilder(); jsonData.append("{"); data = StringUtils.removeStart(data, "{"); data = StringUtils.removeEnd(data, "}"); data = StringUtils.replace(data, "=", ":"); jsonData.append(applyRegEx(data)); jsonData.append("}"); return jsonData.toString(); }
private String annotatedStepNameWithParameters(String annotatedStepTemplate) { String annotatedStepName = annotatedStepTemplate; Iterable<String> parameters = getParamatersFrom(description.getName()); int counter = 0; for (String parameter : parameters) { String token = "{" + counter++ + "}"; annotatedStepName = StringUtils.replace(annotatedStepName, token, parameter); } return annotatedStepName; }
@RequestMapping( value = "/showDetailPer/{date}", method = {RequestMethod.GET, RequestMethod.POST}) public String showDailyPer(Page page, @PathVariable String date, Map<String, Object> map) { List<BizFinanceTransDetail> list = financeTransDetailService.findByGmtCreate(page, date); List<Map<String, String>> tempList = new ArrayList<Map<String, String>>(); Map<Long, BizMember> cacheMap = new HashMap<Long, BizMember>(); if (!CollectionUtils.isEmpty(list)) { for (BizFinanceTransDetail detail : list) { Map<String, String> tempMap = new HashMap<String, String>(); tempMap.put("id", detail.getId() + ""); tempMap.put("date", DateUtil.date2String(detail.getGmtCreate(), BizConstant.DATE_FORMAT)); tempMap.put("time", DateUtil.date2String(detail.getGmtCreate(), BizConstant.TIME_FORMAT)); TransUserEnum enums = TransUserEnum.getEnum(detail.getTransUse()); if (enums == (TransUserEnum.MEMBER_ATTENT) || enums == TransUserEnum.MEMBER_ATTENT_PROLONG) { String name = "大师"; BizMember tempMem = cacheMap.get(detail.getTransUseId()) == null ? memberService.get(detail.getTransUseId()) : cacheMap.get(detail.getTransUseId()); if (null != tempMem) { name = "大师(" + tempMem.getName() + ")"; } tempMap.put( "summary", StringUtils.replace( TransUserEnum.getEnum(detail.getTransUse()).getName(), "大师", name)); } else { tempMap.put("summary", TransUserEnum.getEnum(detail.getTransUse()).getName()); } long out = 0; long in = 0; tempMap.put("left", detail.getSysLeft() + ""); tempMap.put("type", TransTypeEnum.getEnum(detail.getTransType()).getName()); switch (TransTypeEnum.getEnum(detail.getTransType())) { case IN: in = detail.getValue(); break; case OUT: out = detail.getValue(); break; default: break; } tempMap.put("out", out + ""); tempMap.put("in", in + ""); tempList.add(tempMap); } map.put("page", page); map.put("data", tempList); } return SHOW_DETAIL_PER; }
public static String handleExpiryDateToken(String originalText, Date expiryDate) { String ret = originalText; DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); String fDate = formatter.format(expiryDate); if (originalText != null) { ret = StringUtils.replace(originalText, Constants.EMAIL_EXPIRY_DATE_TOKEN, fDate); } return ret; }
public static String handleUserIDToken(String originalText, User user) throws Exception { String ret = originalText; if (user == null || user.getUsername() == null) { throw new Exception("User or user id is null or empty."); } if (originalText != null) { ret = StringUtils.replace(originalText, Constants.EMAIL_USER_ID_TOKEN, user.getUsername()); } return ret; }
public static List<String> getPaths(Class<?> clazz) { List<String> paths = new ArrayList<String>(); Path classPathAnnotation = clazz.getAnnotation(Path.class); // 类上必须有Path注解,否则整个类不会被认为是rest资源,即使方法上有Path注解 if (classPathAnnotation == null) { return paths; } String classPath = classPathAnnotation.value(); for (Method m : clazz.getDeclaredMethods()) { String methodType = StringUtils.EMPTY; GET get = m.getAnnotation(GET.class); POST post = m.getAnnotation(POST.class); PUT put = m.getAnnotation(PUT.class); DELETE delete = m.getAnnotation(DELETE.class); if (get != null) { methodType = "GET "; } if (post != null) { methodType = "POST "; } if (put != null) { methodType = "PUT "; } if (delete != null) { methodType = "DELETE "; } // 方法类型为空,说明此方法不是资源的操作方法 if (StringUtils.isEmpty(methodType)) { continue; } String methodPath = StringUtils.EMPTY; Path methodPathAnnotation = m.getAnnotation(Path.class); if (methodPathAnnotation != null) { methodPath = methodPathAnnotation.value(); } String fullPath = String.format("%-8s/%s/%s", methodType, classPath, methodPath); fullPath = StringUtils.replace(fullPath, "//", "/"); fullPath = StringUtils.removeEnd(fullPath, "/"); paths.add(fullPath); } return paths; }
public static String getQuartzFormulaByParameters( String sRegionTime, String saRegionWeekDay, Integer nLen) { // sRegionTime is in format HH:MM-HH:MM // saRegionWeekDay is in format "mo,tu,we,th,fr,sa". Need to convert to MON, TUE, WED, THU, FRI, // SAT, SUN String startTime = StringUtils.substringBefore(sRegionTime, "-"); String endTime = StringUtils.substringAfter(sRegionTime, "-"); String startHour = StringUtils.substringBefore(startTime, ":"); String startMinute = StringUtils.substringAfter(startTime, ":"); String endHour = StringUtils.substringBefore(endTime, ":"); for (DAY_OF_WEEK b : DAY_OF_WEEK.values()) { saRegionWeekDay = saRegionWeekDay.replace(b.getInternalStr(), b.getQuartzStr()); } String res = StringUtils.replace(QUARTZ_FORMAT, "[INTERVAL]", nLen.toString()); res = StringUtils.replace(res, "[START_MINUTE]", startMinute); res = StringUtils.replace(res, "[HOURS_PERIOD]", startHour + "-" + endHour); res = StringUtils.replace(res, "[DAYS]", saRegionWeekDay); return res; }
/** * Preprocess input file and append double quotes for all paths in the file. * * @param file File. * @return Preprocessed file. */ static String preprocess(final File file) { try { final String text = FileUtils.readFileToString(file); final String pattern = "- *"; return new Replace(text) .replace( line -> line.contains(pattern), line -> StringUtils.join(StringUtils.replace(line, pattern, "- \"*"), "\"")) .output(); } catch (final IOException exc) { throw new IllegalStateException("Unable to read config file", exc); } }
/** * Replaces a JavaType fullyQualifiedName for a shorter name using '~' for TopLevelPackage * * @param cid ClassOrInterfaceTypeDetails of a JavaType * @param currentText String current text for option value * @return the String representing a JavaType with its name shortened */ private String replaceTopLevelPackageString(ClassOrInterfaceTypeDetails cid, String currentText) { String javaTypeFullyQualilfiedName = cid.getType().getFullyQualifiedTypeName(); String javaTypeString = ""; String topLevelPackageString = ""; // Add module value to topLevelPackage when necessary if (StringUtils.isNotBlank(cid.getType().getModule()) && !cid.getType().getModule().equals(projectOperations.getFocusedModuleName())) { // Target module is not focused javaTypeString = cid.getType().getModule().concat(LogicalPath.MODULE_PATH_SEPARATOR); topLevelPackageString = projectOperations .getTopLevelPackage(cid.getType().getModule()) .getFullyQualifiedPackageName(); } else if (StringUtils.isNotBlank(cid.getType().getModule()) && cid.getType().getModule().equals(projectOperations.getFocusedModuleName()) && (currentText.startsWith(cid.getType().getModule()) || cid.getType().getModule().startsWith(currentText)) && StringUtils.isNotBlank(currentText)) { // Target module is focused but user wrote it javaTypeString = cid.getType().getModule().concat(LogicalPath.MODULE_PATH_SEPARATOR); topLevelPackageString = projectOperations .getTopLevelPackage(cid.getType().getModule()) .getFullyQualifiedPackageName(); } else { // Not multimodule project topLevelPackageString = projectOperations.getFocusedTopLevelPackage().getFullyQualifiedPackageName(); } // Autocomplete with abbreviate or full qualified mode String auxString = javaTypeString.concat( StringUtils.replace(javaTypeFullyQualilfiedName, topLevelPackageString, "~")); if ((StringUtils.isBlank(currentText) || auxString.startsWith(currentText)) && StringUtils.contains(javaTypeFullyQualilfiedName, topLevelPackageString)) { // Value is for autocomplete only or user wrote abbreviate value javaTypeString = auxString; } else { // Value could be for autocomplete or for validation javaTypeString = String.format("%s%s", javaTypeString, javaTypeFullyQualilfiedName); } return javaTypeString; }
protected Optional<Path> exportApiDocument(Table table, List<String> lines) { Path baseFolder = projectHome.resolve("api"); String pkgName = getPackageName(table); String folder = StringUtils.replace(pkgName, ".", "/"); Path path = Paths.get(folder).getParent().getFileName(); String className = getClassName(table); Path file = baseFolder .resolve(path) .resolve(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, className) + ".md"); return createFile(file, lines); }
/** * Using the provided list of name/value pairs, search and replace all matching substitution * variables, in the given {@code source} string, with their associated values. */ @Override public String replaceAll(final String source) { String result = source; for (KeyValuePair keyValuePair : substitutionSpecs) { result = StringUtils.replace( result, namePrefix + keyValuePair.getKey() + nameSuffix, keyValuePair.getValueAsString()); } return result; }