下面列出了org.apache.commons.lang3.StringUtils#replaceOnce ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* sqlStatementPartForData may not include the "select * from "-part (stripped sql select statement)
*/
@Override
public int getNumberOfRecipients(@VelocityCheck int companyID, String statement, Object[] parameters) {
String selectTotalRows;
if (StringUtils.startsWithIgnoreCase(statement, "SELECT * FROM")) {
selectTotalRows = StringUtils.replaceOnce(statement, "SELECT * FROM", "SELECT COUNT(*) FROM");
} else {
selectTotalRows = "SELECT COUNT(*) FROM " + statement;
}
try {
return selectRecipients(companyID, Integer.class, selectTotalRows, parameters);
} catch (Exception e) {
logger.error("Error occurred: " + e.getMessage(), e);
}
return 0;
}
private String createMemberView(MemberInfo memberInfo) {
@Language("HTML")
String panel =
"<div class='panel panel-{{color}}'>\n" +
" <div class='panel-heading'>\n" +
" <h3 class='panel-title'>{{name}} <span class='text-muted'>{{type}}</span></h3>\n" +
" </div>\n" +
" <div class='panel-body'><code>{{declaration}}</code></div>\n" +
"</div>";
panel = StringUtils.replaceOnce(panel, "{{name}}", memberInfo.getName());
panel = StringUtils.replaceOnce(panel, "{{declaration}}", memberInfo.getDeclaration());
panel = StringUtils.replaceOnce(panel, "{{type}}", memberInfo.getType().toString());
panel = StringUtils.replaceOnce(panel, "{{color}}", memberInfo.getType().getColor());
return panel;
}
private static Location fixLocation(IJavaElement element, Location location, IJavaProject javaProject) {
if (location == null) {
return null;
}
if (!javaProject.equals(element.getJavaProject()) && element.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
// see issue at: https://github.com/eclipse/eclipse.jdt.ls/issues/842 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=541573
// for jdk classes, jdt will reuse the java model by altering project to share the model between projects
// so that sometimes the project for `element` is default project and the project is different from the project for `unit`
// this fix is to replace the project name with non-default ones since default project should be transparent to users.
if (location.getUri().contains(ProjectsManager.DEFAULT_PROJECT_NAME)) {
String patched = StringUtils.replaceOnce(location.getUri(), ProjectsManager.DEFAULT_PROJECT_NAME, javaProject.getProject().getName());
try {
IClassFile cf = (IClassFile) JavaCore.create(JDTUtils.toURI(patched).getQuery());
if (cf != null && cf.exists()) {
location.setUri(patched);
}
} catch (Exception ex) {
}
}
}
return location;
}
protected void checkAndReplaceOutput(List<IntrospectedColumn> columns, TextElement te) {
String sql = te.getContent();
for(IntrospectedColumn column : columns){
if(column.getFullyQualifiedJavaType().getShortName().equals("Geometry")){
String columnStr = null;
if(column.isColumnNameDelimited()){
columnStr = "\""+column.getActualColumnName()+"\"";
}else{
columnStr = column.getActualColumnName();
}
sql = StringUtils.replaceOnce(sql, columnStr, "ST_AsText("+columnStr+") as " + columnStr);
//sql = sql.replace(column.getActualColumnName(), "ST_AsText("+column.getActualColumnName()+")");
// System.out.println();
// System.out.println(sql);
}
}
try {
FieldUtils.writeDeclaredField(te, "content", sql, true);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public void process(ProductList productList) {
HttpRequest currRequest = productList.getRequest();
//下一页继续抓取
int currPage = productList.getCurrPage();
int nextPage = currPage + 1;
int totalPage = productList.getTotalPage();
if(nextPage <= totalPage) {
String nextUrl = "";
String currUrl = currRequest.getUrl();
if(currUrl.indexOf("page=") != -1) {
nextUrl = StringUtils.replaceOnce(currUrl, "page=" + currPage, "page=" + nextPage);
} else {
nextUrl = currUrl + "&" + "page=" + nextPage;
}
SchedulerContext.into(currRequest.subRequest(nextUrl));
}
}
public String formatAccountAge(long durationMillis) {
durationMillis = Math.max(0, durationMillis);
String day = Res.get("time.day").toLowerCase();
String days = Res.get("time.days");
String format = "d\' " + days + "\'";
return StringUtils.replaceOnce(DurationFormatUtils.formatDuration(durationMillis, format), "1 " + days, "1 " + day);
}
private String createDetailView(TypeInfo typeInfo) {
String content = createClassView(typeInfo);
for (MemberInfo memberInfo : typeInfo.getMembers()) {
String panel = createMemberView(memberInfo);
content += panel;
}
@Language("HTML")
String html = "<div id='{{id}}' class='detail-view' data-name='{{name}}'>{{content}}</div>";
html = StringUtils.replaceOnce(html, "{{id}}", typeInfo.getId());
html = StringUtils.replaceOnce(html, "{{name}}", typeInfo.getName());
html = StringUtils.replaceOnce(html, "{{content}}", content);
return html;
}
private String getShortCwd() {
String currentDir = contextCommands.getCurrentDir();
if (currentDir.startsWith("/user/")) {
final String userHome = "/user/" + this.getWhoami();//call getWhoami later
if (currentDir.startsWith(userHome)) {
currentDir = StringUtils.replaceOnce(currentDir, userHome, "~");
}
}
return currentDir;
}
@SuppressWarnings({"PMD.UseStringBufferForStringAppends"})
String buildSchema(Path file) throws IOException {
String specification;
try (InputStream fileIn = Files.newInputStream(file)) {
specification = IOUtils.toString(fileIn, StandardCharsets.UTF_8);
}
final Path parent = file.getParent();
if (parent == null) {
throw new IllegalArgumentException(file + " needs to be within a directory");
}
String fhirBaseTemplate;
try (InputStream baseIn = Files.newInputStream(parent.resolve("fhir-base-template.xml"))) {
fhirBaseTemplate = IOUtils.toString(baseIn, StandardCharsets.UTF_8);
}
String fhirCommonTemplate;
try (InputStream commonIn = Files.newInputStream(parent.resolve("fhir-common-template.xml"))) {
fhirCommonTemplate = IOUtils.toString(commonIn, StandardCharsets.UTF_8);
}
Pattern pattern = Pattern.compile("<xs:element name=\"(\\w+)\" type=\"(\\w+)\">");
Matcher matcher = pattern.matcher(specification);
matcher.find();
String type = matcher.group(1);
String resourceContainer = "<xs:complexType name=\"ResourceContainer\"><xs:choice><xs:element ref=\"" + type + "\"/></xs:choice></xs:complexType>";
fhirBaseTemplate = StringUtils.replaceOnce(fhirBaseTemplate, "<!-- RESOURCE CONTAINER PLACEHOLDER -->", resourceContainer);
fhirBaseTemplate += fhirCommonTemplate;
specification = StringUtils.replaceOnce(specification, "<xs:include schemaLocation=\"fhir-base.xsd\"/>", fhirBaseTemplate);
return specification;
}
private static String[] replaceWithSysPropUserHome(final String[] pathArray) {
if (ArrayUtils.isEmpty(pathArray)) {
return pathArray;
}
final String SYS_PROP_USER_HOME = System.getProperty("user.home");
for (int index = 0; index < pathArray.length; index++) {
if (StringUtils.startsWith(pathArray[index], "~")) {
pathArray[index] = StringUtils.replaceOnce(pathArray[index], "~", SYS_PROP_USER_HOME);
}
}
return pathArray;
}
public static String getScriptFunctionNameForXhrMain(String functionName) {
if (StringUtils.isBlank(functionName)) {
return "";
}
functionName = functionName.trim();
if (functionName.indexOf(";")>-1) {
functionName = StringUtils.replaceOnce(functionName, ";", "");
}
if (functionName.indexOf(")")==-1) {
functionName = functionName + "()";
}
return functionName;
}
private Grid handler() {
this.width = this.width.toLowerCase();
if (this.width.endsWith("px")) {
this.width = StringUtils.replaceOnce(this.width, "px", "");
}
Grid grid = new Grid();
grid.setId(this.id);
grid.setGridFieldStructure(this.gridFieldStructure);
grid.setClearQueryFn(this.clearQueryFn);
grid.setWidth(Integer.parseInt(this.width));
grid.setProgramId(this.programId);
grid.setDisableOnHeaderCellClick(this.disableOnHeaderCellClick);
return grid;
}
/**
* 根据用户名称删除用户下的所有问题文件
* @param userName 用户名称
* @param isStaff 是否为员工
*/
public void deleteQuestionFile(String userName, boolean isStaff){
int firstIndex = 0;//起始页
int maxResult = 100;// 每页显示记录数
String fileNumber = questionManage.generateFileNumber(userName, isStaff);
while(true){
List<Question> questionContentList = questionService.findQuestionContentByPage(firstIndex, maxResult,userName,isStaff);
if(questionContentList == null || questionContentList.size() == 0){
break;
}
firstIndex = firstIndex+maxResult;
for (Question question :questionContentList) {
Long questionId = question.getId();
String questionContent = question.getContent();
//删除最后一个逗号
String _appendContent = StringUtils.substringBeforeLast(question.getAppendContent(), ",");//从右往左截取到相等的字符,保留左边的
List<AppendQuestionItem> appendQuestionItemList = JsonUtils.toGenericObject(_appendContent+"]", new TypeReference< List<AppendQuestionItem> >(){});
if(appendQuestionItemList != null && appendQuestionItemList.size() >0){
for(AppendQuestionItem appendQuestionItem : appendQuestionItemList){
questionContent += appendQuestionItem.getContent();
}
}
if(questionContent != null && !"".equals(questionContent.trim())){
Object[] obj = textFilterManage.readPathName(questionContent,"question");
if(obj != null && obj.length >0){
List<String> filePathList = new ArrayList<String>();
//删除图片
List<String> imageNameList = (List<String>)obj[0];
for(String imageName :imageNameList){
filePathList.add(imageName);
}
//删除Flash
List<String> flashNameList = (List<String>)obj[1];
for(String flashName :flashNameList){
filePathList.add(flashName);
}
//删除影音
List<String> mediaNameList = (List<String>)obj[2];
for(String mediaName :mediaNameList){
filePathList.add(mediaName);
}
//删除文件
List<String> fileNameList = (List<String>)obj[3];
for(String fileName :fileNameList){
filePathList.add(fileName);
}
for(String filePath :filePathList){
//如果验证不是当前用户上传的文件,则不删除
if(!questionManage.getFileNumber(FileUtil.getBaseName(filePath.trim())).equals(fileNumber)){
continue;
}
//替换路径中的..号
filePath = FileUtil.toRelativePath(filePath);
filePath = FileUtil.toSystemPath(filePath);
//删除旧路径文件
Boolean state = fileManage.deleteFile(filePath);
if(state != null && state == false){
//替换指定的字符,只替换第一次出现的
filePath = StringUtils.replaceOnce(filePath, "file"+File.separator+"question"+File.separator, "");
//创建删除失败文件
fileManage.failedStateFile("file"+File.separator+"question"+File.separator+"lock"+File.separator+FileUtil.toUnderline(filePath));
}
}
}
}
//清空目录
Boolean state_ = fileManage.removeDirectory("file"+File.separator+"answer"+File.separator+questionId+File.separator);
if(state_ != null && state_ == false){
//创建删除失败目录文件
fileManage.failedStateFile("file"+File.separator+"answer"+File.separator+"lock"+File.separator+"#"+questionId);
}
}
}
}
/**
*
* @param obj
* object to be serialized and built into xml
* @param localPartQName
* local part of the QName
* @param requestVersion
* the version of EC2 API used by client (aws-sdk, cmd-line tools or other third-party client tools)
* @return xml representation bound to the given object
*/
public static String marshall(final Object obj, final String localPartQName,
final String requestVersion) {
StringWriter writer = new StringWriter();
try {
/*-
* call jaxbMarshaller.marshal() synchronized (fixes the issue of
* java.lang.ArrayIndexOutOfBoundsException: -1
* at com.sun.xml.internal.bind.v2.util.CollisionCheckStack.pushNocheck(CollisionCheckStack.java:117))
* in case of jaxbMarshaller.marshal() is called concurrently
*/
synchronized (jaxbMarshaller) {
jaxbMarshaller.marshal(new JAXBElement<Object>(new QName(
PropertiesUtils.getProperty(Constants.PROP_NAME_XMLNS_CURRENT),
localPartQName), Object.class, obj), writer);
}
} catch (JAXBException e) {
String errMsg = "failed to marshall object to xml, localPartQName="
+ localPartQName + ", requestVersion="
+ requestVersion;
log.error("{}, exception message: {}", errMsg, e.getMessage());
throw new AwsMockException(errMsg, e);
}
String ret = writer.toString();
/*- If elasticfox.compatible set to true, we replace the version number in the xml
* to match the version of elasticfox so that it could successfully accept the xml as reponse.
*/
if ("true".equalsIgnoreCase(PropertiesUtils
.getProperty(Constants.PROP_NAME_ELASTICFOX_COMPATIBLE))
&& null != requestVersion
&& requestVersion.equals(PropertiesUtils
.getProperty(Constants.PROP_NAME_EC2_API_VERSION_ELASTICFOX))) {
ret = StringUtils
.replaceOnce(ret, PropertiesUtils
.getProperty(Constants.PROP_NAME_EC2_API_VERSION_CURRENT_IMPL),
PropertiesUtils
.getProperty(Constants.PROP_NAME_EC2_API_VERSION_ELASTICFOX));
}
return ret;
}
/**
* Experimental method for trying out the loading of complex_annotation doc type.
* Works with --read-ca-list <file>.
*
* @param opts
* @throws Exception
*/
@CLIMethod("--solr-load-complex-exp")
public void loadComplexAnnotationSolr(Opts opts) throws Exception {
// Check to see if the global url has been set.
String url = sortOutSolrURL(globalSolrURL);
// Only proceed if our environment was well-defined.
if( caFiles == null || caFiles.isEmpty() ){
LOG.warn("LEGO environment not well defined--will skip loading LEGO/CA.");
}else{
// NOTE: These two lines are remainders from old code, and I'm not sure of their place in this world of ours.
// I wish there was an arcitecture diagram somehwere...
OWLOntologyManager manager = pw.getManager();
OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
// Actual loading--iterate over our list and load individually.
for( String fname : caFiles ){
OWLReasoner currentReasoner = null;
OWLOntology ontology = null;
// TODO: Temp cover for missing group labels and IDs.
//String agID = legoFile.getCanonicalPath();
String pretmp = StringUtils.removeEnd(fname, ".owl");
String[] bits = StringUtils.split(pretmp, "/");
String agID = bits[bits.length -1];
String agLabel = new String(StringUtils.replaceOnce(agID, ":", "_"));
try {
ontology = pw.parseOWL(IRI.create(fname));
currentReasoner = reasonerFactory.createReasoner(ontology);
// Some sanity checks--some of the genereated ones are problematic.
boolean consistent = currentReasoner.isConsistent();
if( consistent == false ){
LOG.info("Skip since inconsistent: " + fname);
continue;
}
Set<OWLClass> unsatisfiable = currentReasoner.getUnsatisfiableClasses().getEntitiesMinusBottom();
if (unsatisfiable.isEmpty() == false) {
LOG.info("Skip since unsatisfiable: " + fname);
continue;
}
Set<OWLNamedIndividual> individuals = ontology.getIndividualsInSignature();
Set<OWLAnnotation> modelAnnotations = ontology.getAnnotations();
OWLGraphWrapper currentGraph = new OWLGraphWrapper(ontology);
try {
LOG.info("Trying complex annotation load of: " + fname);
ComplexAnnotationSolrDocumentLoader loader =
new ComplexAnnotationSolrDocumentLoader(url, currentGraph, currentReasoner, individuals, modelAnnotations, agID, agLabel, fname);
loader.load();
} catch (SolrServerException e) {
LOG.info("Complex annotation load of " + fname + " at " + url + " failed!");
e.printStackTrace();
System.exit(1);
}
} finally {
// Cleanup reasoner and ontology.
if (currentReasoner != null) {
currentReasoner.dispose();
}
if (ontology != null) {
manager.removeOntology(ontology);
}
}
}
}
}
/**
* 根据用户名称删除用户下的所有评论文件
* @param userName 用户名称
* @param isStaff 是否为员工
*/
public void deleteCommentFile(String userName, boolean isStaff){
int firstIndex = 0;//起始页
int maxResult = 100;// 每页显示记录数
String fileNumber = topicManage.generateFileNumber(userName, isStaff);
while(true){
List<String> topicContentList = commentService.findCommentContentByPage(firstIndex, maxResult,userName,isStaff);
if(topicContentList == null || topicContentList.size() == 0){
break;
}
firstIndex = firstIndex+maxResult;
for (String topicContent: topicContentList) {
if(topicContent != null && !"".equals(topicContent.trim())){
//删除图片
List<String> imageNameList = textFilterManage.readImageName(topicContent,"comment");
if(imageNameList != null && imageNameList.size() >0){
for(String imagePath : imageNameList){
//如果验证不是当前用户上传的文件,则不删除锁
if(!topicManage.getFileNumber(FileUtil.getBaseName(imagePath.trim())).equals(fileNumber)){
continue;
}
//替换路径中的..号
imagePath = FileUtil.toRelativePath(imagePath);
imagePath = FileUtil.toSystemPath(imagePath);
Boolean state = fileManage.deleteFile(imagePath);
if(state != null && state == false){
//替换指定的字符,只替换第一次出现的
imagePath = StringUtils.replaceOnce(imagePath, "file"+File.separator+"comment"+File.separator, "");
//创建删除失败文件
fileManage.failedStateFile("file"+File.separator+"comment"+File.separator+"lock"+File.separator+FileUtil.toUnderline(imagePath));
}
}
}
}
}
}
}
/**
* 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
*/
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");
}
}
}
@NotNull
private String trimResponse(@NotNull String response) {
return StringUtils.replaceOnce(response, JSON_RESPONSE_PREFIX, "");
}
/**
*
* @param obj
* DescribeAlarmsResponse to be serialized and built into xml
* @param localPartQName
* local part of the QName
* @param requestVersion
* the version of CloudWatch API used by client (aws-sdk, cmd-line tools or other
* third-party client tools)
* @return xml representation bound to the given object
*/
public static String marshall(final DescribeAlarmsResponse obj,
final String localPartQName, final String requestVersion) {
StringWriter writer = new StringWriter();
try {
/*-
* call jaxbMarshaller.marshal() synchronized (fixes the issue of
* java.lang.ArrayIndexOutOfBoundsException: -1
* at com.sun.xml.internal.bind.v2.util.CollisionCheckStack.pushNocheck(CollisionCheckStack.java:117))
* in case of jaxbMarshaller.marshal() is called concurrently
*/
synchronized (jaxbMarshaller) {
JAXBElement<DescribeAlarmsResponse> jAXBElement = new JAXBElement<DescribeAlarmsResponse>(
new QName(PropertiesUtils
.getProperty(Constants.PROP_NAME_CLOUDWATCH_XMLNS_CURRENT),
"local"),
DescribeAlarmsResponse.class, obj);
jaxbMarshaller.marshal(jAXBElement, writer);
}
} catch (JAXBException e) {
String errMsg = "failed to marshall object to xml, localPartQName="
+ localPartQName + ", requestVersion="
+ requestVersion;
log.error("{}, exception message: {}", errMsg, e.getLinkedException());
throw new AwsMockException(errMsg, e);
}
String ret = writer.toString();
/*- If elasticfox.compatible set to true, we replace the version number in the xml
* to match the version of elasticfox so that it could successfully accept the xml as reponse.
*/
if ("true".equalsIgnoreCase(PropertiesUtils
.getProperty(Constants.PROP_NAME_ELASTICFOX_COMPATIBLE))
&& null != requestVersion
&& requestVersion.equals(PropertiesUtils
.getProperty(Constants.PROP_NAME_EC2_API_VERSION_ELASTICFOX))) {
ret = StringUtils
.replaceOnce(ret, PropertiesUtils
.getProperty(Constants.PROP_NAME_CLOUDWATCH_API_VERSION_CURRENT_IMPL),
PropertiesUtils
.getProperty(Constants.PROP_NAME_EC2_API_VERSION_ELASTICFOX));
}
return ret;
}
@Override
protected String handle(String input, String second, String third) {
return StringUtils.replaceOnce(input, second, third);
}