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:in.mycp.remote.WorkflowService.java
@RemoteMethod public List<Workflow> findAll() { try {/*w ww . j a v a2 s . com*/ User user = Commons.getCurrentUser(); List<Workflow> wfs = null; if (user.getRole().getName().equals(Commons.ROLE.ROLE_MANAGER + "") || user.getRole().getName().equals(Commons.ROLE.ROLE_ADMIN + "")) { wfs = Workflow .findWorkflowsByCompany(Company.findCompany(Commons.getCurrentSession().getCompanyId())) .getResultList(); } else if (user.getRole().getName().equals(Commons.ROLE.ROLE_SUPERADMIN + "")) { wfs = Workflow.findAllWorkflows(); } else { wfs = Workflow.findWorkflowsByUser(user).getResultList(); } List<Workflow> wfs2return = new ArrayList<Workflow>(); for (Iterator iterator = wfs.iterator(); iterator.hasNext();) { Workflow workflow = (Workflow) iterator.next(); ProcessInstance pi = workflowImpl4Jbpm.findProcessInstance(workflow.getProcessId()); if (pi == null || pi.getId() == null) { continue; } else { workflow.setProcessName(pi.getId()); String activityName = ""; Set<String> activityNames = pi.findActiveActivityNames(); for (Iterator iterator1 = activityNames.iterator(); iterator1.hasNext();) { String string = (String) iterator1.next(); activityName = string; // System.out.println("before move activityNames = " + // string); break; } activityName = StringUtils.replace(activityName, "null", " "); log.debug("activityName = " + activityName + " pi.getId() = " + pi.getId()); // if currently looged in user is manager , do not show any // workflows in Admin status //TODO - uncomment this when needed /*if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_MANAGER + "")) { if (activityName != null && activityName.contains("Admin")) { continue; } } else if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_ADMIN + "")) { if (activityName != null && activityName.contains("Manager")) { continue; } }*/ workflow.setProcessStatus(activityName); workflow.setStartTime(workflowImpl4Jbpm.findStartTime(pi.getId())); try { workflow.setProcessName( workflow.getProcessName().substring(0, workflow.getProcessName().indexOf("."))); } catch (Exception e) { e.printStackTrace(); } wfs2return.add(workflow); } if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.ComputeImage)) { try { ImageDescriptionP image = ImageDescriptionP.findImageDescriptionP(workflow.getAssetId()); workflow.setAssetDetails( workflow.getAssetType() + " " + image.getName() + " " + image.getImageId()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.ComputeInstance)) { try { InstanceP instance = InstanceP.findInstanceP(workflow.getAssetId()); workflow.setAssetDetails(workflow.getAssetType() + " " + instance.getName() + " " + instance.getDnsName() + " " + instance.getInstanceId()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.IpAddress)) { try { AddressInfoP address = AddressInfoP.findAddressInfoP(workflow.getAssetId()); workflow.setAssetDetails( workflow.getAssetType() + " " + address.getName() + " " + address.getPublicIp()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.IpPermission)) { // nothig here } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.KeyPair)) { try { KeyPairInfoP k = KeyPairInfoP.findKeyPairInfoP(workflow.getAssetId()); workflow.setAssetDetails(workflow.getAssetType() + " " + k.getKeyName()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.SecurityGroup)) { try { GroupDescriptionP g = GroupDescriptionP.findGroupDescriptionP(workflow.getAssetId()); workflow.setAssetDetails(workflow.getAssetType() + " " + g.getName()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.Volume)) { try { VolumeInfoP volume = VolumeInfoP.findVolumeInfoP(workflow.getAssetId()); workflow.setAssetDetails(workflow.getAssetType() + " " + volume.getName() + " " + volume.getVolumeId() + " " + volume.getSize() + "(GB)"); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.VolumeSnapshot)) { try { SnapshotInfoP snapshot = SnapshotInfoP.findSnapshotInfoP(workflow.getAssetId()); workflow.setAssetDetails(workflow.getAssetType() + " " + snapshot.getSnapshotId() + " " + snapshot.getOwnerId()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else if (workflow.getAssetType().equals("" + Commons.ASSET_TYPE.addressInfo)) { try { AddressInfoP address = AddressInfoP.findAddressInfoP(workflow.getAssetId()); workflow.setAssetDetails( workflow.getAssetType() + " " + address.getName() + " " + address.getPublicIp()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } else { log.error("Which asset does this workflow belong?"); // throw new // Exception("Which asset does this workflow belong?"); } String assetDetails = workflow.getAssetDetails(); assetDetails = StringUtils.replace(assetDetails, "null", ""); workflow.setAssetDetails(assetDetails); } return wfs2return; } catch (Exception e) { //e.printStackTrace(); log.error(e);//e.printStackTrace(); } return null; }
From source file:com.monarchapis.client.rest.BaseClient.java
public String getPath() { String url = this.url; for (Entry<String, String> entry : this.paths.entrySet()) { url = StringUtils.replace(url, "{" + entry.getKey() + "}", entry.getValue()); }/*from w w w . ja v a 2s . c o m*/ return url; }
From source file:de.decoit.simu.cbor.ifmap.identifier.CBORMacAddress.java
/** * Parse the string representation of a MAC address into a byte array. * * @param value String representation of MAC address * @return Raw bytes of MAC address/*from ww w . j a v a 2s . co m*/ */ private byte[] processStringRepresentation(String value) { if (StringUtils.isBlank(value)) { throw new IllegalArgumentException("Value string may not be blank"); } // Remove seprators and leading and trailing whitespaces String strippedAddress; if (value.contains("-")) { strippedAddress = StringUtils.replace(value, "-", ""); } else if (value.contains(":")) { strippedAddress = StringUtils.replace(value, ":", ""); } else if (value.contains(".")) { strippedAddress = StringUtils.replace(value, ".", ""); } else { strippedAddress = value; } byte[] address = DatatypeConverter.parseHexBinary(strippedAddress); if (address.length != 6) { throw new IllegalArgumentException("Invalid number of bytes for MAC address: " + address.length); } return address; }
From source file:com.xpn.xwiki.content.parsers.DocumentParser.java
/** * Parse the links contained into the passed content represent the raw content from a document * (as typed by the user) and replace links that matches the passed linkToLookFor Link with the * specified newLink link. The comparison between found links and the link to look for is done * by the ReplaceLinkHandler passed as parameter. * * @param contentToParse the raw document content to parse. * @param linkToLookFor the link to look for that will be replaced by the new link * @param newLink the new link//from ww w . j a v a2 s . c o m * @param linkHandler the handler to use for comparing the links and for deciding what the * replaced link will look like. For example two links may be pointing to the same * document but one link may have a different alias or target. The handler decides * what to do in these cases. * @param currentSpace the space to use for normalizing links. This is used for links that have * no space defined. * @return a list of {@link Link} objects containing the parsed links, a list of invalid * link contents found and a list of replaced links, returned as a * {@link ReplacementResultCollection}. This allows users of this method to decide what * they want to do with invalid links (like report them to the user, fix them, generate * an error, etc). */ public ReplacementResultCollection parseLinksAndReplace(String contentToParse, Link linkToLookFor, Link newLink, ReplaceLinkHandler linkHandler, String currentSpace) { ReplacementResultCollection results = new ReplacementResultCollection(); LinkParser linkParser = new LinkParser(); Matcher matcher = LINK_PATTERN.matcher(contentToParse); StringBuffer modifiedContent = new StringBuffer(); Link normalizedLinkToLookFor = linkToLookFor.getNormalizedLink(currentSpace); Link nomalizedNewLink = newLink.getNormalizedLink(currentSpace); while (matcher.find()) { Link foundLink = parseLink(linkParser, matcher.group(1), results); // Verify if the link found matches the link to look for if (foundLink != null) { Link normalizedFoundLink = foundLink.getNormalizedLink(currentSpace); if (linkHandler.compare(normalizedLinkToLookFor, normalizedFoundLink)) { // Compute the replacement string to use. This string must have "$" and // "\" symbols escaped as otherwise "$" will be considered as a regex group // replacement and "\" as a regex escape. // Note: We need to replace the "\" before the "$" as the "$" replacement // introduces other backslashes which would themselves be espaced... String replacementText = "[" + linkHandler.getReplacementLink(nomalizedNewLink, normalizedFoundLink).toString() + "]"; replacementText = StringUtils.replace(replacementText, "\\", "\\\\"); replacementText = StringUtils.replace(replacementText, "$", "\\$"); matcher.appendReplacement(modifiedContent, replacementText); results.addReplacedElement(normalizedFoundLink); } } } matcher.appendTail(modifiedContent); results.setModifiedContent(modifiedContent.toString()); return results; }
From source file:de.blizzy.documentr.markdown.MarkdownProcessorTest.java
@Test public void processNonCacheableMacros() { when(descriptor.isCacheable()).thenReturn(false); when(macro.getDescriptor()).thenReturn(descriptor); when(macro.createRunnable()).thenReturn(runnable); String macroHtml = "<div>macroHtml</div>"; //$NON-NLS-1$ when(runnable.getHtml(any(IMacroContext.class))).thenReturn(macroHtml); String cleanedMacroHtml = "<div>cleanedMacroHtml</div>"; //$NON-NLS-1$ when(runnable.cleanupHtml(anyString())).thenAnswer(new Answer<String>() { @Override//from w ww . j a va 2 s . c o m public String answer(InvocationOnMock invocation) { String html = (String) invocation.getArguments()[0]; return StringUtils.replace(html, "macroHtml", "cleanedMacroHtml"); //$NON-NLS-1$ //$NON-NLS-2$ } }); when(macroFactory.get(MACRO)).thenReturn(macro); String html = "<p>__" + MarkdownProcessor.NON_CACHEABLE_MACRO_MARKER + "_1__" + MACRO + " " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ PARAMS + "__/" + MarkdownProcessor.NON_CACHEABLE_MACRO_MARKER + "_1__</p>"; //$NON-NLS-1$ //$NON-NLS-2$ String result = markdownProcessor.processNonCacheableMacros(html, "project", "branch", //$NON-NLS-1$ //$NON-NLS-2$ DocumentrConstants.HOME_PAGE_NAME + "/bar", authentication, CONTEXT); //$NON-NLS-1$ String expectedHtml = cleanedMacroHtml; assertEquals(expectedHtml, result); }
From source file:me.ryanhamshire.griefprevention.permission.GPPermissionHandler.java
public static Tristate getClaimPermission(Event event, Location<World> location, GPClaim claim, String flagPermission, Object source, Object target, User user, TrustType type, boolean checkOverride) { if (claim == null) { return Tristate.TRUE; }/*from www .j a v a 2s . c o m*/ GPPlayerData playerData = null; eventSubject = null; if (user != null) { eventSubject = user; if (user instanceof Player) { playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(claim.world, user.getUniqueId()); } } currentEvent = event; eventLocation = location; String sourceId = getPermissionIdentifier(source, true); String targetPermission = flagPermission; String targetId = getPermissionIdentifier(target); String targetModPermission = null; String targetMetaPermission = null; if (!targetId.isEmpty()) { String[] parts = targetId.split(":"); String targetMod = parts[0]; // move target meta to end of permission Matcher m = PATTERN_META.matcher(targetId); String targetMeta = ""; if (!flagPermission.contains("command-execute")) { if (m.find()) { targetMeta = m.group(0); targetId = StringUtils.replace(targetId, targetMeta, ""); } if (!targetMeta.isEmpty()) { targetMetaPermission = flagPermission + "." + StringUtils.replace(targetId, ":", ".") + targetMeta; } } if (!sourceId.isEmpty()) { targetModPermission = flagPermission + "." + targetMod + ".source." + sourceId + targetMeta; targetModPermission = StringUtils.replace(targetModPermission, ":", "."); targetPermission += "." + targetId + ".source." + sourceId + targetMeta; } else { targetModPermission = flagPermission + "." + targetMod + targetMeta; targetModPermission = StringUtils.replace(targetModPermission, ":", "."); targetPermission += "." + targetId + targetMeta; } } else if (!sourceId.isEmpty()) { String targetMod = ""; if (sourceId.contains(":")) { String[] parts = sourceId.split(":"); targetMod = parts[0]; targetModPermission = flagPermission + "." + targetMod + ".source." + sourceId; targetModPermission = StringUtils.replace(targetModPermission, ":", "."); } targetPermission += ".source." + sourceId; } targetPermission = StringUtils.replace(targetPermission, ":", "."); if (checkOverride) { Tristate override = Tristate.UNDEFINED; if (user != null) { // check global bans in wilderness override = getFlagOverride((GPClaim) claim.getWilderness(), user, user, playerData, targetPermission, targetModPermission, targetMetaPermission); if (override != Tristate.UNDEFINED) { return override; } } // First check for claim flag overrides override = getFlagOverride(claim, user == null ? GriefPreventionPlugin.GLOBAL_SUBJECT : user, user, playerData, targetPermission, targetModPermission, targetMetaPermission); if (override != Tristate.UNDEFINED) { return override; } } if (playerData != null) { if (playerData.debugClaimPermissions) { if (user != null && type != null && claim.isUserTrusted(user, type)) { return processResult(claim, "trust." + type.toString().toLowerCase(), Tristate.TRUE, user); } return getClaimFlagPermission(claim, targetPermission, targetModPermission, targetMetaPermission); } // Check for ignoreclaims after override and debug checks if (playerData.canIgnoreClaim(claim)) { return processResult(claim, "trust.ignore", Tristate.TRUE, user); } } if (user != null) { if (type != null) { if (claim.isUserTrusted(user, type)) { return processResult(claim, "trust." + type.toString().toLowerCase(), Tristate.TRUE, user); } } return getUserPermission(user, claim, targetPermission, targetModPermission, targetMetaPermission, playerData); } return getClaimFlagPermission(claim, targetPermission, targetModPermission, targetMetaPermission); }
From source file:ca.simplegames.micro.utils.UrlResource.java
/** * Normalize the path by suppressing sequences like "path/.." and * inner simple dots./*w w w .j a v a 2 s . c o m*/ * <p>The result is convenient for path comparison. For other uses, * notice that Windows separators ("\") are replaced by simple slashes. * * @param path the original path * @return the normalized path */ public static String cleanPath(String path) { String pathToUse = StringUtils.replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); // Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // "file:core/../core/io/Resource.class", where the ".." should just // strip the first "core" directory while keeping the "file:" prefix. int prefixIndex = pathToUse.indexOf(":"); String prefix = ""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); pathToUse = pathToUse.substring(prefixIndex + 1); } String[] pathArray = StringUtils.split(pathToUse, FOLDER_SEPARATOR); List pathElements = new LinkedList(); int tops = 0; for (int i = pathArray.length - 1; i >= 0; i--) { if (CURRENT_PATH.equals(pathArray[i])) { // Points to current directory - drop it. } else if (TOP_PATH.equals(pathArray[i])) { // Registering top path found. tops++; } else { if (tops > 0) { // Merging path element with corresponding to top path. tops--; } else { // Normal path element found. pathElements.add(0, pathArray[i]); } } } // Remaining top paths need to be retained. for (int i = 0; i < tops; i++) { pathElements.add(0, TOP_PATH); } return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); }
From source file:io.gs2.AbstractGs2Client.java
/** * GET?/*from w w w . ja v a2 s.c o m*/ * * @param url URL * @param credential ? * @param service * @param module * @param function * @return */ protected HttpGet createHttpGet(String url, IGs2Credential credential, String service, String module, String function) { Long timestamp = System.currentTimeMillis() / 1000; url = StringUtils.replace(url, "{service}", service); url = StringUtils.replace(url, "{region}", region.getName()); HttpGet get = new HttpGet(url); get.setHeader("Content-Type", "application/json"); credential.authorized(get, service, module, function, timestamp); return get; }
From source file:com.xpn.xwiki.render.XWikiRadeoxRenderer.java
public String convertMultiLine(String macroname, String params, String data, String allcontent, XWikiVirtualMacro macro, XWikiContext context) { String result;//from ww w . j av a 2s .c om // This is huge hack to ensure that the {code} macro content is not parsed by the Velocity // or Groovy Renderers. It relies on the fact that the MacroMapping executes before these // Renderers and the code macro must be defined in the macros.txt file, as otherwise this // will not work. if (macroname.equals("code")) { // Escape the Velocity special characters: '$' and '#' so that they are not interpreted. result = StringUtils.replace(allcontent, "#", "#"); result = StringUtils.replace(result, "$", "$"); // Escape the Groovy special characters '<%' and '%>' so that the Groovy Renderer // doesn't execute. result = StringUtils.replace(result, "<%", "<%"); result = StringUtils.replace(result, "%>", "%>"); } else { result = allcontent; } return result; }
From source file:com.sonicle.webtop.mail.bol.model.ImapQuery.java
private static Date parseDate(String value, DateTimeZone timezone) { String date = StringUtils.replace(value, "/", "-"); Instant instant = DateTimeUtils.toInstant(DateTimeUtils.parseLocalDate(date), DateTimeUtils.toZoneId(timezone)); return new Date(instant.toEpochMilli()); }