Java Code Examples for org.apache.commons.lang3.StringUtils#replace()

The following examples show how to use org.apache.commons.lang3.StringUtils#replace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BatchStartedEventMessageActionTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
private Event getEvent(String filename, long actionId, Map<String, String> placeholders) throws Exception {
    Path path = new File(TestUtils.findTestData(
            "/com/suse/manager/reactor/messaging/test/" + filename).getPath()).toPath();
    String eventString = Files.lines(path)
            .collect(joining("\n"))
            .replaceAll("\"suma-action-id\": \\d+", "\"suma-action-id\": " + actionId);

    if (placeholders != null) {
        for (Map.Entry<String, String> entries : placeholders.entrySet()) {
            String placeholder = entries.getKey();
            String value = entries.getValue();
            eventString = StringUtils.replace(eventString, placeholder, value);
        }
    }
    return eventParser.parse(eventString);
}
 
Example 2
Source File: IOFunctions.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
public static String getMessage(String messageShortcut, final IAST listOfArgs, EvalEngine engine) {
	IExpr temp = F.General.evalMessage(messageShortcut);
	String message = null;
	if (temp.isPresent()) {
		message = temp.toString();
	}
	if (message == null) {
		message = "Undefined message shortcut: " + messageShortcut;
		engine.setMessageShortcut(messageShortcut);
		return message;
	}
	for (int i = 1; i < listOfArgs.size(); i++) {
		message = StringUtils.replace(message, "`" + (i) + "`", listOfArgs.get(i).toString());
	}
	engine.setMessageShortcut(messageShortcut);
	return message;
}
 
Example 3
Source File: LegacyListDelimiterHandler.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Escapes the given property value. This method is called on saving the
 * configuration for each property value. It ensures a correct handling of
 * backslash characters and also takes care that list delimiter characters
 * in the value are escaped.
 *
 * @param value the property value
 * @param inList a flag whether the value is part of a list
 * @param transformer the {@code ValueTransformer}
 * @return the escaped property value
 */
protected String escapeValue(final Object value, final boolean inList,
        final ValueTransformer transformer)
{
    String escapedValue =
            String.valueOf(transformer.transformValue(escapeBackslashs(
                    value, inList)));
    if (getDelimiter() != 0)
    {
        escapedValue =
                StringUtils.replace(escapedValue,
                        String.valueOf(getDelimiter()), ESCAPE
                                + getDelimiter());
    }
    return escapedValue;
}
 
Example 4
Source File: IpAddress.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * IP归属地格式化
 * @param ipAddress
 * @return
 */
private static String format(String ipAddress){
	if(ipAddress != null && !"".equals(ipAddress.trim())){
		ipAddress = StringUtils.replace(ipAddress, "|0", " ");//0替换成空串
		ipAddress = StringUtils.replace(ipAddress, "|", " ");//竖线替换成空格
	}
	return ipAddress;
}
 
Example 5
Source File: CryptoTool.java    From carina with Apache License 2.0 5 votes vote down vote up
public String encryptByPattern(String content, Pattern pattern) {
    if (isEncrypted(content, pattern)) {
        String wildcard = pattern.pattern().substring(pattern.pattern().indexOf("{") + 1,
                pattern.pattern().indexOf(":"));
        if (content != null && content.contains(wildcard)) {
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                String group = matcher.group();
                String crypt = StringUtils.removeStart(group, "{" + wildcard + ":").replace("}", "");
                content = StringUtils.replace(content, group, encrypt(crypt));
            }
        }
    }
    return content;
}
 
Example 6
Source File: MetadataTools.java    From archiva with Apache License 2.0 5 votes vote down vote up
public ItemSelector toProjectSelector( String path )
    throws RepositoryMetadataException
{
    if ( !path.endsWith( "/" + MAVEN_METADATA ) )
    {
        throw new RepositoryMetadataException( "Cannot convert to versioned reference, not a metadata file. " );
    }

    ArchivaItemSelector.Builder builder = ArchivaItemSelector.builder( );

    String normalizedPath = StringUtils.replace( path, "\\", "/" );
    String pathParts[] = StringUtils.split( normalizedPath, '/' );

    // Assume last part of the path is the version.

    int artifactIdOffset = pathParts.length - 2;
    int groupIdEnd = artifactIdOffset - 1;

    builder.withArtifactId( pathParts[artifactIdOffset] );
    builder.withProjectId( pathParts[artifactIdOffset] );

    StringBuilder gid = new StringBuilder();
    for ( int i = 0; i <= groupIdEnd; i++ )
    {
        if ( i > 0 )
        {
            gid.append( "." );
        }
        gid.append( pathParts[i] );
    }

    builder.withNamespace( gid.toString( ) );
    return builder.build();
}
 
Example 7
Source File: PuppetLintParser.java    From analysis-model with MIT License 5 votes vote down vote up
private String splitFileName(final String fileName) {
    Matcher matcher = PACKAGE_PATTERN.matcher(fileName);
    if (matcher.find()) {
        String main = matcher.group(2);
        String subclassed = matcher.group(3);
        String module = SEPARATOR + main;
        if (StringUtils.isNotBlank(subclassed)) {
            module += StringUtils.replace(subclassed, "/", SEPARATOR);
        }
        return module;
    }
    return StringUtils.EMPTY;
}
 
Example 8
Source File: HtmlSerializer.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Reduce the whitespace and do some more cleanup.
 * @param text the text to clean up
 * @return the new text
 */
protected String cleanUp(String text) {
    // ignore <br/> at the end of a block
    text = reduceWhitespace(text);
    text = StringUtils.replace(text, AS_TEXT_BLANK, " ");
    final String ls = System.lineSeparator();
    text = StringUtils.replace(text, AS_TEXT_NEW_LINE, ls);
    text = StringUtils.replace(text, AS_TEXT_BLOCK_SEPARATOR, ls);
    text = StringUtils.replace(text, AS_TEXT_TAB, "\t");

    return text;
}
 
Example 9
Source File: DefaultUniversalLinkGenerator.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Override
public String generate(ContextTag contextTag, TopicMapReferenceIF tmRefObj,
                       String template) {
  String link = template;
  
  // replace topicmap id placeholder with real value
  String topicmapId = tmRefObj.getId();
  link = StringUtils.replace(link, LINK_TOPICMAP_KEY, topicmapId);

  return link;
}
 
Example 10
Source File: ManipulateFunction.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create JSXGraph sliders.
 * 
 * @param ast
 *            from position 2 to size()-1 there maybe some <code>Manipulate</code> sliders defined
 * @param js
 *            the JSXGraph JavaScript template
 * @param boundingbox
 *            an array of double values (length 4) which describes the bounding box
 *            <code>[xMin, yMAx, xMax, yMin]</code>
 * @param toJS
 *            the Symja to JavaScript converter factory
 * @return
 */
private static String jsxgraphSlidersFromList(final IAST ast, String js, double[] boundingbox,
		JavaScriptFormFactory toJS) {
	if (ast.size() >= 3) {
		if (ast.arg2().isList()) {
			double xDelta = (boundingbox[2] - boundingbox[0]) / 10;
			double yDelta = (boundingbox[1] - boundingbox[3]) / 10;
			double xPos1Slider = boundingbox[0] + xDelta;
			double xPos2Slider = boundingbox[2] - xDelta;
			double yPosSlider = boundingbox[1] - yDelta;
			StringBuilder slider = new StringBuilder();
			for (int i = 2; i < ast.size(); i++) {
				if (ast.get(i).isList()) {
					if (!jsxgraphSingleSlider((IAST) ast.getAST(i), slider, xPos1Slider, xPos2Slider, yPosSlider,
							toJS)) {
						return null;
					}
					yPosSlider -= yDelta;
				} else {
					break;
				}
			}
			js = StringUtils.replace(js, "`1`", slider.toString());
		}
	} else {
		js = StringUtils.replace(js, "`1`", "");
	}
	return js;
}
 
Example 11
Source File: PlayerChat.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
private boolean sendMessageToAllGuilds(AsyncPlayerChatEvent event, String message, PluginConfiguration c, Player player, Guild guild) {
    String allGuildsPrefix = c.chatGlobal;
    int prefixLength = allGuildsPrefix.length();
    
    if (message.length() > prefixLength && message.substring(0, prefixLength).equals(allGuildsPrefix)) {
        String resultMessage = c.chatGlobalDesign;
        
        resultMessage = StringUtils.replace(resultMessage, "{PLAYER}", player.getName());
        resultMessage = StringUtils.replace(resultMessage, "{TAG}", guild.getTag());
        resultMessage = StringUtils.replace(resultMessage, "{POS}",
                StringUtils.replace(c.chatPosition, "{POS}", getPositionString(User.get(player), c)));

        String subMessage = event.getMessage().substring(prefixLength).trim();
        resultMessage = StringUtils.replace(resultMessage, "{MESSAGE}", subMessage);

        this.spy(player, subMessage);

        for (Guild g : GuildUtils.getGuilds()) {
            this.sendMessageToGuild(g, player, resultMessage);
        }
        
        event.setCancelled(true);
        return true;
    }
    
    return false;
}
 
Example 12
Source File: CustomCondition.java    From cuba with Apache License 2.0 5 votes vote down vote up
public CustomCondition(AbstractConditionDescriptor descriptor, String where, String join, String entityAlias, boolean inExpr) {
    super(descriptor);
    this.entityAlias = entityAlias;
    this.join = join;
    this.text = where;
    this.inExpr = inExpr;
    //re-create param because at this moment we have a correct value of inExpr
    param = AppBeans.get(ConditionParamBuilder.class).createParam(this);
    if (param != null)
        text = StringUtils.replace(text, "?", ":" + param.getName());
}
 
Example 13
Source File: NumericEditText.java    From fingen with Apache License 2.0 5 votes vote down vote up
/**
 * Return numeric value represented by the text field
 *
 * @return numeric value
 */
public double getNumericValue() {
    String original = getText().toString().replaceAll(mNumberFilterRegex, "");
    if (hasCustomDecimalSeparator) {
        // swap custom decimal separator with locale one to allow parsing
        original = StringUtils.replace(original,
                String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR));
    }

    try {
        return NumberFormat.getInstance().parse(original).doubleValue();
    } catch (ParseException e) {
        return Double.NaN;
    }
}
 
Example 14
Source File: HtmlSortHeaderRenderer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void encodeBegin(FacesContext facesContext, UIComponent component)
		throws IOException {
	// If this is a currently sorted sort header, always give it the "currentSort" CSS style class
       if (component instanceof HtmlCommandSortHeader) {
           HtmlCommandSortHeader sortHeader = (HtmlCommandSortHeader)component;
           String styleClass = StringUtils.trimToNull(getStyleClass(facesContext, component));
           String newStyleClass;
           String unStyleClass;
           if (sortHeader.findParentDataTable().getSortColumn().equals(sortHeader.getColumnName())) {
           	newStyleClass = CURRENT_SORT_STYLE;
           	unStyleClass = NOT_CURRENT_SORT_STYLE;
           } else {
           	newStyleClass = NOT_CURRENT_SORT_STYLE;
           	unStyleClass = CURRENT_SORT_STYLE;
           }
           if (StringUtils.indexOf(styleClass, newStyleClass) == -1) {
           	if (StringUtils.indexOf(styleClass, unStyleClass) != -1) {
           		styleClass = StringUtils.replace(styleClass, unStyleClass, newStyleClass);
           	} else if (styleClass != null) {
           		styleClass = (new StringBuilder(styleClass)).append(' ').append(newStyleClass).toString();
           	} else {
           		styleClass = newStyleClass;
           	}
           	sortHeader.setStyleClass(styleClass);
           }
       }
		super.encodeBegin(facesContext, component); //check for NP
}
 
Example 15
Source File: BasicPathExample.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public void updateQueryParameterValue(Parameter parameter, Object example) {
    if (example == null)
        return;

    if (query.contains(parameter.getName()))
        query = StringUtils.replace(
                query,
                '{' + parameter.getName() + '}',
                encodeExampleForUrl(example)
        );
}
 
Example 16
Source File: ResResSpec.java    From ratel with Apache License 2.0 4 votes vote down vote up
public String getName() {
    return StringUtils.replace(mName, "\"", "q");
}
 
Example 17
Source File: CassandraAuthorizer.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
private static String escape(String name)
{
    return StringUtils.replace(name, "'", "''");
}
 
Example 18
Source File: DOTRenderingUtils.java    From textuml with Eclipse Public License 1.0 4 votes vote down vote up
public static String escapeForDot(String labelText) {
	return StringUtils.replace(labelText, "\"", "\\\"");
}
 
Example 19
Source File: J2MEDataValueSMSListener.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Transactional
@Override
public void receive( IncomingSms sms )
{
    String message = sms.getText();

    SMSCommand smsCommand = smsCommandService.getSMSCommand( SmsUtils.getCommandString( sms ),
        ParserType.J2ME_PARSER );

    String token[] = message.split( "!" );
    Map<String, String> parsedMessage = this.parse( token[1], smsCommand );

    String senderPhoneNumber = StringUtils.replace( sms.getOriginator(), "+", "" );
    Collection<OrganisationUnit> orgUnits = getOrganisationUnits( sms );

    if ( orgUnits == null || orgUnits.size() == 0 )
    {
        if ( StringUtils.isEmpty( smsCommand.getNoUserMessage() ) )
        {
            throw new SMSParserException( SMSCommand.NO_USER_MESSAGE );
        }
        else
        {
            throw new SMSParserException( smsCommand.getNoUserMessage() );
        }
    }

    OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit( orgUnits, parsedMessage, smsCommand );
    Period period = this.getPeriod( token[0].trim(), smsCommand.getDataset().getPeriodType() );
    boolean valueStored = false;

    for ( SMSCode code : smsCommand.getCodes() )
    {
        if ( parsedMessage.containsKey( code.getCode() ) )
        {
            storeDataValue( sms, orgUnit, parsedMessage, code, smsCommand, period );
            valueStored = true;
        }
    }

    if ( parsedMessage.isEmpty() || !valueStored )
    {
        if ( StringUtils.isEmpty( smsCommand.getDefaultMessage() ) )
        {
            throw new SMSParserException( "No values reported for command '" + smsCommand.getName() + "'" );
        }
        else
        {
            throw new SMSParserException( smsCommand.getDefaultMessage() );
        }
    }

    this.registerCompleteDataSet( smsCommand.getDataset(), period, orgUnit, "mobile" );

    this.sendSuccessFeedback( senderPhoneNumber, smsCommand, parsedMessage, period, orgUnit );
}
 
Example 20
Source File: ExcItems.java    From FunnyGuilds with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(CommandSender sender, String[] args) {
    Player player = (Player) sender;
    PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();

    List<ItemStack> guiItems = config.guiItems;
    String title = config.guiItemsTitle;

    if (!config.useCommonGUI && player.hasPermission("funnyguilds.vip.items")) {
        guiItems = config.guiItemsVip;
        title = config.guiItemsVipTitle;
    }

    GuiWindow gui = new GuiWindow(title, guiItems.size() / 9 + (guiItems.size() % 9 != 0 ? 1 : 0));
    gui.setCloseEvent(close -> gui.unregister());

    for (ItemStack item : guiItems) {
        item = item.clone();

        if (config.addLoreLines && (config.createItems.contains(item) || config.createItemsVip.contains(item))) {
            ItemMeta meta = item.getItemMeta();
            List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();

            int reqAmount = item.getAmount();
            int pinvAmount = ItemUtils.getItemAmount(item, player.getInventory());
            int ecAmount = ItemUtils.getItemAmount(item, player.getEnderChest());

            for (String line : config.guiItemsLore) {
                line = StringUtils.replace(line, "{REQ-AMOUNT}", Integer.toString(reqAmount));
                line = StringUtils.replace(line, "{PINV-AMOUNT}", Integer.toString(pinvAmount));
                line = StringUtils.replace(line, "{PINV-PERCENT}", ChatUtils.getPercent(pinvAmount, reqAmount));
                line = StringUtils.replace(line, "{EC-AMOUNT}", Integer.toString(ecAmount));
                line = StringUtils.replace(line, "{EC-PERCENT}", ChatUtils.getPercent(ecAmount, reqAmount));
                line = StringUtils.replace(line, "{ALL-AMOUNT}", Integer.toString(pinvAmount + ecAmount));
                line = StringUtils.replace(line, "{ALL-PERCENT}", ChatUtils.getPercent(pinvAmount + ecAmount, reqAmount));

                lore.add(line);
            }

            meta.setLore(lore);
            item.setItemMeta(meta);
        }

        gui.setToNextFree(new GuiItem(item));
    }

    gui.open(player);
}