List of usage examples for org.apache.commons.lang3 StringUtils replace
public static String replace(final String text, final String searchString, final String replacement)
Replaces all occurrences of a String within another String.
A null reference passed to this method is a no-op.
StringUtils.replace(null, *, *) = null StringUtils.replace("", *, *) = "" StringUtils.replace("any", null, *) = "any" StringUtils.replace("any", *, null) = "any" StringUtils.replace("any", "", *) = "any" StringUtils.replace("aba", "a", null) = "aba" StringUtils.replace("aba", "a", "") = "b" StringUtils.replace("aba", "a", "z") = "zbz"
From source file:com.squid.kraken.v4.auth.OAuth2LoginServlet.java
/** * Perform the login action via API calls. * * @param request/* w ww.j av a 2 s . com*/ * @param response * @throws ServletException * @throws IOException */ private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, URISyntaxException { String responseType = request.getParameter(RESPONSE_TYPE); if (responseType == null) { responseType = RESPONSE_TYPE_TOKEN; } String customerId = request.getParameter(CUSTOMER_ID); // create a POST method to execute the login request HttpPost post; List<NameValuePair> values = new ArrayList<NameValuePair>(); if (responseType.equals(RESPONSE_TYPE_TOKEN)) { post = new HttpPost(privateServerURL + V4_RS_AUTH_TOKEN); } else { post = new HttpPost(privateServerURL + V4_RS_AUTH_CODE); } if (StringUtils.isNotBlank(customerId)) { values.add(new BasicNameValuePair(CUSTOMER_ID, customerId)); } if (request.getParameter(CLIENT_ID) != null) { values.add(new BasicNameValuePair(CLIENT_ID, request.getParameter(CLIENT_ID))); } // get login and pwd either from the request or from the session HttpSession session = request.getSession(false); String login = request.getParameter(LOGIN); if ((session != null) && (login == null)) { login = (String) session.getAttribute(LOGIN); session.setAttribute(LOGIN, null); } String password = request.getParameter(PASSWORD); if ((session != null) && (password == null)) { password = (String) session.getAttribute(PASSWORD); session.setAttribute(PASSWORD, null); } boolean isSso = false; String redirectUri = null; if (request.getParameter(REDIRECT_URI) != null) { redirectUri = request.getParameter(REDIRECT_URI).trim(); values.add(new BasicNameValuePair(REDIRECT_URI, redirectUri)); isSso = isSso(request, redirectUri); } if (isSso == false && ((login == null) || (password == null))) { showLogin(request, response); } else { if (isSso == false) { values.add(new BasicNameValuePair(LOGIN, login)); values.add(new BasicNameValuePair(PASSWORD, password)); } else { String uri = request.getScheme() + "://" + request.getServerName() + ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort()); post = new HttpPost(uri + V4_RS_SSO_TOKEN); if (values != null) { URL url = new URL(redirectUri); values = getQueryPairs(getRedirectParameters(url.getQuery())); } } post.setEntity(new UrlEncodedFormEntity(values)); try { String redirectUrl = redirectUri; // T489 remove any trailing # if (redirectUrl.endsWith("#")) { redirectUrl = redirectUrl.substring(0, redirectUrl.length() - 1); } if (responseType.equals(RESPONSE_TYPE_TOKEN)) { // token type // execute the login request AccessToken token = RequestHelper.processRequest(AccessToken.class, request, post); String tokenId = token.getId().getTokenId(); // redirect URL if (redirectUrl.contains(ACCESS_TOKEN_PARAM_PATTERN)) { // replace access_token parameter pattern redirectUrl = StringUtils.replace(redirectUrl, ACCESS_TOKEN_PARAM_PATTERN, tokenId); } else { // append access_token anchor redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&"; redirectUrl += ACCESS_TOKEN + "=" + tokenId; } } else { // auth code type // execute the login request AuthCode codeObj = RequestHelper.processRequest(AuthCode.class, request, post); String code = codeObj.getCode(); if (redirectUrl.contains(AUTH_CODE_PARAM_PATTERN)) { // replace code parameter pattern redirectUrl = StringUtils.replace(redirectUrl, AUTH_CODE_PARAM_PATTERN, code); } else { // append code param redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&"; redirectUrl += AUTH_CODE + "=" + code; } } response.sendRedirect(redirectUrl); } catch (ServerUnavailableException e1) { // Authentication server unavailable logger.error(e1.getLocalizedMessage()); request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE); showLogin(request, response); return; } catch (ServiceException e2) { WebServicesException exception = e2.getWsException(); if (exception != null) { if (exception.getCustomers() != null) { // multiple customers found request.setAttribute(DUPLICATE_USER_ERROR, Boolean.TRUE); request.setAttribute(CUSTOMERS_LIST, exception.getCustomers()); // save the credentials for later use request.getSession().setAttribute(LOGIN, login); request.getSession().setAttribute(PASSWORD, password); } else { String errorMessage = exception.getError(); if (!errorMessage.contains("Password")) { request.setAttribute(ERROR, exception.getError()); } else { request.setAttribute(ERROR, Boolean.TRUE); } } } else { request.setAttribute(ERROR, Boolean.TRUE); } // forward to login page showLogin(request, response); return; } catch (SSORedirectException error) { response.sendRedirect(error.getRedirectURL()); } } }
From source file:de.crowdcode.kissmda.maven.plugin.KissMdaMojo.java
private Class<? extends AbstractModule> getGuiceModule(final Set<Class<? extends AbstractModule>> guiceModules, final Class<? extends Transformer> transformerClazz) throws MojoExecutionException { Class<? extends AbstractModule> currentGuiceModuleClazz = null; for (Class<? extends AbstractModule> guiceModuleClazz : guiceModules) { // Check the package String transformerPackageName = transformerClazz.getPackage().getName(); String guiceModulePackageName = guiceModuleClazz.getPackage().getName(); if (guiceModulePackageName.equalsIgnoreCase(transformerPackageName)) { String guiceModuleNameWithoutModule = StringUtils.replace(guiceModuleClazz.getName(), MODULE_SUFFIX, ""); String transformerNameWithoutTransformer = StringUtils.replace(transformerClazz.getName(), TRANSFORMER_SUFFIX, ""); if (guiceModuleNameWithoutModule.equals(transformerNameWithoutTransformer)) { currentGuiceModuleClazz = guiceModuleClazz; logger.info("Start the transformation with following Guice Module: " + currentGuiceModuleClazz.getName()); break; }/* w ww. ja v a 2s.com*/ } } if (currentGuiceModuleClazz == null) { // No module found at all, error throw new MojoExecutionException(ERROR_GUICE_SAME_PACKAGE_NOT_FOUND); } return currentGuiceModuleClazz; }
From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java
private Checksums getChecksums(String version) throws IOException { String url = config.getNodeJsBinariesRootUrl() + StringUtils.replace(config.getNodeJsChecksumUrl(), "${version}", version); log.info("Get file: {}", url); HttpGet get = new HttpGet(url); HttpResponse response = httpClient.execute(get); try {// ww w . j av a 2s . com if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { return new Checksums(EntityUtils.toString(response.getEntity())); } else { return null; } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:com.erudika.para.utils.Utils.java
/** * Formats a messages containing {0}, {1}... etc. Used for translation. * @param msg a message with placeholders * @param params objects used to populate the placeholders * @return a formatted message/*from ww w .j a v a 2 s.c o m*/ */ public static String formatMessage(String msg, Object... params) { try { // required by MessageFormat, single quotes break string interpolation! msg = StringUtils.replace(msg, "'", "''"); return StringUtils.isBlank(msg) ? "" : MessageFormat.format(msg, params); } catch (IllegalArgumentException e) { return msg; } }
From source file:de.blizzy.documentr.markdown.MarkdownProcessor.java
public String processNonCacheableMacros(String html, String projectName, String branchName, String path, Authentication authentication, String contextPath) { HtmlSerializerContext context = new HtmlSerializerContext(projectName, branchName, path, this, authentication, pageStore, systemSettingsStore, contextPath); String startMarkerPrefix = "__" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$ String endMarkerPrefix = "__/" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$ String bodyMarker = "__" + NON_CACHEABLE_MACRO_BODY_MARKER + "__"; //$NON-NLS-1$ //$NON-NLS-2$ for (;;) {// w ww . ja v a 2s . c o m int start = html.indexOf(startMarkerPrefix); if (start < 0) { break; } start += startMarkerPrefix.length(); int end = html.indexOf('_', start); if (end < 0) { break; } String idx = html.substring(start, end); start = html.indexOf("__", start); //$NON-NLS-1$ if (start < 0) { break; } start += 2; end = html.indexOf(endMarkerPrefix + idx + "__", start); //$NON-NLS-1$ if (end < 0) { break; } String macroCallWithBody = html.substring(start, end); String macroCall = StringUtils.substringBefore(macroCallWithBody, bodyMarker); String body = StringUtils.substringAfter(macroCallWithBody, bodyMarker); String macroName = StringUtils.substringBefore(macroCall, " "); //$NON-NLS-1$ String params = StringUtils.substringAfter(macroCall, " "); //$NON-NLS-1$ IMacro macro = macroFactory.get(macroName); MacroContext macroContext = MacroContext.create(macroName, params, body, context, beanFactory); IMacroRunnable macroRunnable = macro.createRunnable(); html = StringUtils.replace(html, startMarkerPrefix + idx + "__" + macroCallWithBody + endMarkerPrefix + idx + "__", //$NON-NLS-1$ //$NON-NLS-2$ StringUtils.defaultString(macroRunnable.getHtml(macroContext))); MacroInvocation invocation = new MacroInvocation(macroName, params); html = cleanupHtml(html, Collections.singletonList(invocation), false); } return html; }
From source file:com.kylinolap.cube.CubeManager.java
public static String getHbaseStorageLocationPrefix(String hbaseMetadataUrl) { String defaultPrefix = "KYLIN_CUBE_"; if (StringUtils.containsIgnoreCase(hbaseMetadataUrl, "hbase:")) { int cut = hbaseMetadataUrl.indexOf('@'); String tmp = cut < 0 ? defaultPrefix : hbaseMetadataUrl.substring(0, cut); String prefix = StringUtils.replace(tmp, "_metadata", ""); return (prefix + "_CUBE_").toUpperCase(); } else {/*from w w w.j a va2 s . c o m*/ return defaultPrefix; } }
From source file:hu.bme.mit.sette.tools.spf.SpfParser.java
@Override protected void parseSnippet(Snippet snippet, SnippetInputsXml inputsXml) throws Exception { File outputFile = RunnerProjectUtils.getSnippetOutputFile(getRunnerProjectSettings(), snippet); File errorFile = RunnerProjectUtils.getSnippetErrorFile(getRunnerProjectSettings(), snippet); if (errorFile.exists()) { // TODO make this section simple and clear List<String> lines = FileUtils.readLines(errorFile); String firstLine = lines.get(0); if (firstLine.startsWith("java.lang.RuntimeException: ## Error: Operation not supported!")) { inputsXml.setResultType(ResultType.NA); } else if (firstLine.startsWith("java.lang.NullPointerException")) { inputsXml.setResultType(ResultType.EX); } else if (firstLine .startsWith("java.lang.RuntimeException: ## Error: symbolic log10 not implemented")) { inputsXml.setResultType(ResultType.NA); } else if (firstLine.startsWith("***********Warning: everything false")) { // TODO enhance // now skip } else if (snippet.getMethod().toString().contains("_Constants") || snippet.getMethod().toString().contains(".always()")) { // TODO JPF/SPF compilation differences between javac and ecj: // https://groups.google.com/forum/#!topic/java-pathfinder/jhOkvLx-SKE // now just accept } else {/*from ww w. ja va 2s . co m*/ // TODO error handling // this is debug (only if unhandled error) System.err.println("============================="); System.err.println(snippet.getMethod()); System.err.println("============================="); for (String line : lines) { System.err.println(line); } System.err.println("============================="); // TODO error handling throw new RuntimeException("PARSER PROBLEM, UNHANDLED ERROR"); } } if (inputsXml.getResultType() == null) { // TODO enhance inputsXml.setResultType(ResultType.S); if (snippet.getMethod().toString().contains("_Constants") || snippet.getMethod().toString().contains(".always()")) { // TODO JPF/SPF compilation differences between javac and ecj: // https://groups.google.com/forum/#!topic/java-pathfinder/jhOkvLx-SKE // now just accept // no inputs for constant tests, just call them once inputsXml.getGeneratedInputs().add(new InputElement()); } else { LineIterator lines = FileUtils.lineIterator(outputFile); // find input lines List<String> inputLines = new ArrayList<>(); boolean shouldCollect = false; while (lines.hasNext()) { String line = lines.next(); if (line.trim() .equals("====================================================== Method Summaries")) { shouldCollect = true; } else if (shouldCollect) { if (line.startsWith("======================================================")) { // start of next section shouldCollect = false; break; } else { if (!StringUtils.isBlank(line)) { inputLines.add(line.trim()); } } } } // close iterator lines.close(); // remove duplicates inputLines = new ArrayList<>(new LinkedHashSet<>(inputLines)); System.out.println(snippet.getMethod()); String firstLine = inputLines.get(0); assert (firstLine.startsWith("Inputs: ")); firstLine = firstLine.substring(7).trim(); String[] parameterStrings = StringUtils.split(firstLine, ','); ParameterType[] parameterTypes = new ParameterType[parameterStrings.length]; if (inputLines.size() == 2 && inputLines.get(1).startsWith("No path conditions for")) { InputElement input = new InputElement(); for (int i = 0; i < parameterStrings.length; i++) { // no path conditions, only considering the "default" // inputs Class<?> type = snippet.getMethod().getParameterTypes()[i]; parameterTypes[i] = getParameterType(type); input.getParameters() .add(new ParameterElement(parameterTypes[i], getDefaultParameterString(type))); } inputsXml.getGeneratedInputs().add(input); } else { // parse parameter types Class<?>[] paramsJavaClass = snippet.getMethod().getParameterTypes(); for (int i = 0; i < parameterStrings.length; i++) { String parameterString = parameterStrings[i]; Class<?> pjc = ClassUtils.primitiveToWrapper(paramsJavaClass[i]); if (parameterString.endsWith("SYMINT")) { if (pjc == Boolean.class) { parameterTypes[i] = ParameterType.BOOLEAN; } else if (pjc == Byte.class) { parameterTypes[i] = ParameterType.BYTE; } else if (pjc == Short.class) { parameterTypes[i] = ParameterType.SHORT; } else if (pjc == Integer.class) { parameterTypes[i] = ParameterType.INT; } else if (pjc == Long.class) { parameterTypes[i] = ParameterType.LONG; } else { // int for something else parameterTypes[i] = ParameterType.INT; } } else if (parameterString.endsWith("SYMREAL")) { if (pjc == Float.class) { parameterTypes[i] = ParameterType.FLOAT; } else if (pjc == Float.class) { parameterTypes[i] = ParameterType.DOUBLE; } else { // int for something else parameterTypes[i] = ParameterType.DOUBLE; } } else if (parameterString.endsWith("SYMSTRING")) { parameterTypes[i] = ParameterType.EXPRESSION; } else { // TODO error handling // int for something else System.err.println(parameterString); throw new RuntimeException("PARSER PROBLEM"); } } // example // inheritsAPIGuessTwoPrimitives(11,-2147483648(don't care)) // --> // "java.lang.IllegalArgumentException..." // inheritsAPIGuessTwoPrimitives(9,11) --> // "java.lang.IllegalArgumentException..." // inheritsAPIGuessTwoPrimitives(7,9) --> // "java.lang.RuntimeException: Out of range..." // inheritsAPIGuessTwoPrimitives(4,1) --> Return Value: 1 // inheritsAPIGuessTwoPrimitives(0,0) --> Return Value: 0 // inheritsAPIGuessTwoPrimitives(9,-88) --> // "java.lang.IllegalArgumentException..." // inheritsAPIGuessTwoPrimitives(-88,-2147483648(don't // care)) // --> "java.lang.IllegalArgumentException..." String ps = String.format("^%s\\((.*)\\)\\s+-->\\s+(.*)$", snippet.getMethod().getName()); // ps = String.format("^%s(.*)\\s+-->\\s+(.*)$", // snippet.getMethod() // .getName()); ps = String.format("^(%s\\.)?%s(.*)\\s+-->\\s+(.*)$", snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName()); Pattern p = Pattern.compile(ps); // parse inputs int i = -1; for (String line : inputLines) { i++; if (i == 0) { // first line continue; } else if (StringUtils.isEmpty(line)) { continue; } Matcher m = p.matcher(line); if (m.matches()) { String paramsString = StringUtils.substring(m.group(2).trim(), 1, -1); String resultString = m.group(3).trim(); paramsString = StringUtils.replace(paramsString, "(don't care)", ""); String[] paramsStrings = StringUtils.split(paramsString, ','); InputElement input = new InputElement(); // if index error -> lesser inputs than parameters for (int j = 0; j < parameterTypes.length; j++) { if (parameterTypes[j] == ParameterType.BOOLEAN && paramsStrings[j].contains("-2147483648")) { // don't care -> 0 paramsStrings[j] = "false"; } ParameterElement pe = new ParameterElement(parameterTypes[j], paramsStrings[j].trim()); try { // just check the type format pe.validate(); } catch (Exception e) { // TODO error handling System.out.println(parameterTypes[j]); System.out.println(paramsStrings[j]); System.out.println(pe.getType()); System.out.println(pe.getValue()); e.printStackTrace(); System.err.println("============================="); System.err.println(snippet.getMethod()); System.err.println("============================="); for (String lll : inputLines) { System.err.println(lll); } System.err.println("============================="); System.exit(-1); } input.getParameters().add(pe); } if (resultString.startsWith("Return Value:")) { // has retval, nothing to do } else { // exception; example (" is present inside the // string!!!): // "java.lang.ArithmeticException: div by 0..." // "java.lang.IndexOutOfBoundsException: Index: 1, Size: 5..." int pos = resultString.indexOf(':'); if (pos < 0) { // not found :, search for ... pos = resultString.indexOf("..."); } String ex = resultString.substring(1, pos); input.setExpected(ex); // System.err.println(resultString); // System.err.println(ex); // // input.setExpected(expected); } inputsXml.getGeneratedInputs().add(input); } else { System.err.println("NO MATCH"); System.err.println(ps); System.err.println(line); throw new Exception("NO MATCH: " + line); } } } } inputsXml.validate(); } }
From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java
private String getPomValidateUrl(ArtifactType artifactType, String version) { switch (artifactType) { case NODEJS:/*from ww w . j a va 2 s. c o m*/ return config.getNodeJsBinariesRootUrl() + StringUtils.replace(config.getNodeJsChecksumUrl(), "${version}", version); case NPM: return config.getNodeJsBinariesRootUrl() + StringUtils.replace( StringUtils.replace(config.getNpmBinariesUrl(), "${version}", version), "${type}", "tgz"); default: throw new IllegalArgumentException("Illegal artifact type: " + artifactType); } }
From source file:de.micromata.genome.gwiki.controls.GWikiTreeChildrenActionBean.java
protected JsonObject createDirNode(String path) { JsonObject node = new JsonObject(); String title = StringUtils.substringAfterLast(path, "/"); if (StringUtils.isEmpty(title) == true) { if (StringUtils.isEmpty(path) == true) { title = "Root"; } else {//from www . j av a2s . c o m title = path; } } String id = StringUtils.replace(path, "/", "_"); node.add("id", id); node.add("url", path); node.add("text", title); node.add("children", new JsonArray()); JsonObject data = new JsonObject(); node.add("data", data); data.add("url", path); return node; }
From source file:de.micromata.tpsb.doc.parser.JavaDocUtil.java
public static String getScenarioInfo(String projectRoot, TestStepInfo stepInfo, AnnotationInfo annotation) { MethodInfo testMethod = stepInfo.getTestMethod(); AnnotationInfo scenarioFilesAnotation = TpsbEnvUtils.getAnnotation(testMethod, "TpsbScenarioSuiteFiles"); if (scenarioFilesAnotation != null) { return getScenarioSuiteFileContent(projectRoot, stepInfo, scenarioFilesAnotation); }/* w w w .j av a 2s.com*/ Map<String, String> replMap = new HashMap<String, String>(); for (int i = 0; i < stepInfo.getParameters().size(); ++i) { ParameterInfo param = stepInfo.getParameters().get(i); replMap.put("${" + i + "}", TypeUtils.unqoteString(param.getParamValue())); } String fileName = (String) annotation.getParams().get("filePattern"); if (fileName == null) { return null; } fileName = TypeUtils.unqoteString(fileName); for (Map.Entry<String, String> me : replMap.entrySet()) { fileName = StringUtils.replace(fileName, me.getKey(), me.getValue()); } File file = lookupFileOrDir(projectRoot, fileName); if (file == null) { return null; } try { AnnotationInfo scent = TpsbEnvUtils.getAnnotation(stepInfo.getTestBuilderMethod(), "TpsbScenarioFile"); String content = FileUtils.readFileToString(file, CharEncoding.UTF_8); return renderScenarioFile(file, scent, content); } catch (IOException ex) { log.warn("Scanrio file can't be read: " + file.getAbsolutePath() + "; " + ex.getMessage(), ex); return null; } }