Example usage for org.apache.commons.lang.text StrSubstitutor replace

List of usage examples for org.apache.commons.lang.text StrSubstitutor replace

Introduction

In this page you can find the example usage for org.apache.commons.lang.text StrSubstitutor replace.

Prototype

public static String replace(Object source, Map valueMap) 

Source Link

Document

Replaces all the occurrences of variables in the given source object with their matching values from the map.

Usage

From source file:com.wso2telco.gsma.authenticators.util.OutboundMessage.java

/**
 * Prepare the USSD/SMS message from database config table for service provider, operator specific message or
 * default message stored in mobile-connect.xml. Message template can have ${variable} and relevant data to apply
 * to the template should be passed with map parameter.
 *
 * @param clientId    sp client id/*from   ww  w  . j a  v  a2s .co  m*/
 * @param messageType ussd/sms message type
 * @param map         additional variable data map for the message template
 * @param operator    operator name
 * @return prepared ussd message
 */
public static String prepare(String clientId, MessageType messageType, HashMap<String, String> map,
        String operator) {

    MobileConnectConfig.OperatorSpecificMessage operatorSpecificMessage = null;
    String template = null;

    Map<String, String> data = new HashMap<String, String>();
    // add default map values here
    // data.put("key", "value");

    if (map != null && map.size() > 0) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            data.put(entry.getKey(), entry.getValue());
        }
    }

    // Load operator specific message from hash map
    if (operator != null) {
        if (messageType == MessageType.USSD_LOGIN || messageType == MessageType.USSD_REGISTRATION) {
            operatorSpecificMessage = operatorSpecificMessageMap.get(operator);
        } else if (messageType == MessageType.USSD_PIN_LOGIN
                || messageType == MessageType.USSD_PIN_REGISTRATION) {
            operatorSpecificMessage = operatorSpecificPinMessageMap.get(operator);
        } else if (messageType == MessageType.SMS_LOGIN || messageType == MessageType.SMS_REGISTRATION) {
            operatorSpecificMessage = operatorSpecificSmsMessageMap.get(operator);
        } else if (messageType == MessageType.SMS_OTP) {
            operatorSpecificMessage = operatorSpecificSmsotpMessageMap.get(operator);
        }

        data.put("operator", operator);
    }

    // RULE 1 : first try to get login/registration messages from sp config table
    if (messageType == MessageType.USSD_LOGIN) {
        template = spConfigService.getUSSDLoginMessage(clientId);
    } else if (messageType == MessageType.USSD_REGISTRATION) {
        template = spConfigService.getUSSDRegistrationMessage(clientId);
    } else if (messageType == MessageType.USSD_PIN_LOGIN) {
        template = spConfigService.getUSSDPinLoginMessage(clientId);
    } else if (messageType == MessageType.USSD_PIN_REGISTRATION) {
        template = spConfigService.getUSSDPinRegistrationMessage(clientId);
    } else if (messageType == MessageType.SMS_LOGIN) {
        template = spConfigService.getSMSLoginMessage(clientId);
    } else if (messageType == MessageType.SMS_REGISTRATION) {
        template = spConfigService.getSMSRegistrationMessage(clientId);
    } else if (messageType == MessageType.SMS_OTP) {
        template = spConfigService.getSMSOTPMessage(clientId);
    }

    if (template == null) {
        // RULE 2 : if message template is not found, try loading them from operator specific config from xml
        if (operatorSpecificMessage != null) {
            if (messageType == MessageType.USSD_LOGIN) {
                template = operatorSpecificMessage.getLoginMessage();
            } else if (messageType == MessageType.USSD_REGISTRATION) {
                template = operatorSpecificMessage.getRegistrationMessage();
            } else if (messageType == MessageType.USSD_PIN_LOGIN) {
                template = operatorSpecificMessage.getLoginMessage();
            } else if (messageType == MessageType.USSD_PIN_REGISTRATION) {
                template = operatorSpecificMessage.getRegistrationMessage();
            } else if (messageType == MessageType.SMS_LOGIN) {
                template = operatorSpecificMessage.getLoginMessage();
            } else if (messageType == MessageType.SMS_REGISTRATION) {
                template = operatorSpecificMessage.getRegistrationMessage();
            } else if (messageType == MessageType.SMS_OTP) {
                template = operatorSpecificMessage.getSmsotpMessage();
            }
        } else {
            // RULE 3 : if no operator specific message is found, try loading from common messages
            if (messageType == MessageType.USSD_LOGIN) {
                template = ussdConfig.getUssdLoginMessage();
            } else if (messageType == MessageType.USSD_REGISTRATION) {
                template = ussdConfig.getUssdRegistrationMessage();
            } else if (messageType == MessageType.USSD_PIN_LOGIN) {
                template = ussdConfig.getPinLoginMessage();
            } else if (messageType == MessageType.USSD_PIN_REGISTRATION) {
                template = ussdConfig.getPinRegistrationMessage();
            } else if (messageType == MessageType.SMS_LOGIN) {
                template = smsConfig.getLoginMessage();
            } else if (messageType == MessageType.SMS_REGISTRATION) {
                template = smsConfig.getRegistrationMessage();
            } else if (messageType == MessageType.SMS_OTP) {
                template = smsConfig.getSmsotpMessage();
            }
        }
    }

    return template == null ? null : StrSubstitutor.replace(template, data);
}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorBuilder.java

/**
 * Expand tokens with token macro and build variables
 *//*  w  w  w.j  a v a  2 s  .c  om*/
protected static String expandTokens(TaskListener listener, String str, Run<?, ?> run) throws Exception {
    if (str == null) {
        return null;
    }
    try {
        Class<?> clazz = Class.forName("org.jenkinsci.plugins.tokenmacro.TokenMacro");
        Method expandMethod = ReflectionUtils.findMethod(clazz, "expand", new Class[] { AbstractBuild.class, //
                TaskListener.class, //
                String.class });
        return (String) expandMethod.invoke(null, run, listener, str);
        //opts = TokenMacro.expand(this, listener, opts);
    } catch (Exception tokenException) {
        //Token plugin not present. Ignore, this is OK.
        LOGGER.trace("Ignore problem in expanding tokens", tokenException);
    } catch (LinkageError linkageError) {
        // Token plugin not present. Ignore, this is OK.
        LOGGER.trace("Ignore problem in expanding tokens", linkageError);
    }

    str = StrSubstitutor.replace(str, run.getEnvironment(listener));

    return str;
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile,
        File jobTransformDir) throws CompilationException, IOException {
    // Determine correct compiler, returning if none specified
    String compiler = languageConf.getString("compiler-" + transformTypeString, "");
    if (compiler.isEmpty())
        compiler = languageConf.getString("compiler", "");
    if (compiler.isEmpty())
        return srcTransformFile;

    // Determine destination filename
    File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString);

    // Create map to replace ${wmr:...} variables.
    // NOTE: Commons Configuration's built-in interpolator does not work here
    //  for some reason.
    File jobTempDir = getJobTempDir();
    Hashtable<String, String> variableMap = new Hashtable<String, String>();
    File libDir = getLibraryDirectory(languageConf);
    variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : "");
    variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString());
    variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString());
    variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString());
    variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString());

    // Replace variables in compiler string
    compiler = StrSubstitutor.replace(compiler, variableMap);

    // Run the compiler

    CommandLine compilerCommand = CommandLine.parse(compiler);
    DefaultExecutor exec = new DefaultExecutor();
    ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output);
    exec.setWorkingDirectory(jobTempDir);
    exec.setWatchdog(dog);//  w w w.j  a v  a2s.  c o m
    exec.setStreamHandler(pump);
    exec.setExitValues(null); // Can't get the exit code if it throws exception

    int exitStatus = -1;
    try {
        exitStatus = exec.execute(compilerCommand);
    } catch (IOException ex) {
        // NOTE: Exit status is still -1 in this case, since exception was thrown
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));
    }

    // Check for successful exit

    if (exitStatus != 0)
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));

    // Check that output exists and is readable, and make it executable

    if (!compiledTransformFile.isFile())
        throw new CompilationException(
                "Compiler did not output a " + transformTypeString
                        + " executable (or it was not a regular file).",
                exitStatus, new String(output.toByteArray()));

    if (!compiledTransformFile.canRead())
        throw new IOException(StringUtils.capitalize(transformTypeString)
                + " executable output from compiler was not readable: " + compiledTransformFile.toString());

    if (!compiledTransformFile.canExecute())
        compiledTransformFile.setExecutable(true, false);

    return compiledTransformFile;
}

From source file:com.siberhus.easyexecutor.EasyExecutor.java

private BeanExecutor createBeanExecutor(DomElementFinder def, DataElement beanElem, String args[])
        throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException {

    BeanExecutor be = new BeanExecutor();

    String beanId = beanElem.getAttribute("id");
    be.setId(beanId);//from   www. j  a  v  a  2s . com
    Class<?> beanClass = beanElem.getAttribute(Class.class, "class");
    be.setTargetClass(beanClass);
    be.setTargetObject(beanClass.newInstance());

    List<DataElement> methodElems = def.findElements(beanElem, "method");

    for (DataElement methodElem : methodElems) {
        if (methodElem != null) {
            String methodName = methodElem.getAttribute("name");
            Map<String, String> argMap = new HashMap<String, String>();
            for (int i = 0; i < args.length; i++) {
                argMap.put(String.valueOf(i), args[i]);
            }

            List<DataElement> argElemList = def.findElements(methodElem, "arg");
            if (argElemList != null) {
                int argSize = argElemList.size();
                Class<?> argTypes[] = new Class[argSize];
                Object argValues[] = new Object[argSize];
                for (int i = 0; i < argSize; i++) {
                    DataElement paramElem = argElemList.get(i);
                    Class<?> argType = paramElem.getAttribute(Class.class, "type");
                    argTypes[i] = argType;
                    String argValueStr = paramElem.getValue();
                    argValueStr = StrSubstitutor.replace(argValueStr, argMap);
                    argValues[i] = TypeConvertUtils.convert(argValueStr, getLocale(), argType);
                }
                be.addMethodInvoker(methodName, argTypes, argValues);
            } else {
                be.addMethodInvoker(methodName, null, null);
            }
        } else {
            Object passedArgs[] = { args };// Create the actual argument array
            be.addMethodInvoker("main", new Class[] { String[].class }, passedArgs);
        }
    }

    return be;
}

From source file:databaseadapter.GenerateMojo.java

private String tableToClassName(Table table, Template template) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("tableName", table.getName());
    map.put("tableNameAsCamelCase", databaseadapter.StringUtils.toCamelCase(table.getName()));
    String className = StrSubstitutor.replace(template.getClassName(), map);
    return className;
}

From source file:org.aludratest.impl.log4testing.configuration.ReflectionUtil.java

private static String substituteEnvVariables(String param) {
    final Map<String, String> envVariables = System.getenv();
    return StrSubstitutor.replace(param, envVariables);
}

From source file:org.apache.hadoop.minikdc.MiniKdc.java

private void initKDCServer() throws Exception {
    String orgName = conf.getProperty(ORG_NAME);
    String orgDomain = conf.getProperty(ORG_DOMAIN);
    String bindAddress = conf.getProperty(KDC_BIND_ADDRESS);
    final Map<String, String> map = new HashMap<String, String>();
    map.put("0", orgName.toLowerCase(Locale.ENGLISH));
    map.put("1", orgDomain.toLowerCase(Locale.ENGLISH));
    map.put("2", orgName.toUpperCase(Locale.ENGLISH));
    map.put("3", orgDomain.toUpperCase(Locale.ENGLISH));
    map.put("4", bindAddress);

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is1 = cl.getResourceAsStream("minikdc.ldiff");

    SchemaManager schemaManager = ds.getSchemaManager();
    LdifReader reader = null;/*from   www . jav a2 s  .com*/

    try {
        final String content = StrSubstitutor.replace(IOUtils.toString(is1), map);
        reader = new LdifReader(new StringReader(content));

        for (LdifEntry ldifEntry : reader) {
            ds.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
        }
    } finally {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(is1);
    }

    KerberosConfig kerberosConfig = new KerberosConfig();
    kerberosConfig.setMaximumRenewableLifetime(Long.parseLong(conf.getProperty(MAX_RENEWABLE_LIFETIME)));
    kerberosConfig.setMaximumTicketLifetime(Long.parseLong(conf.getProperty(MAX_TICKET_LIFETIME)));
    kerberosConfig.setSearchBaseDn(String.format("dc=%s,dc=%s", orgName, orgDomain));
    kerberosConfig.setPaEncTimestampRequired(false);
    kdc = new KdcServer(kerberosConfig);
    kdc.setDirectoryService(ds);

    // transport
    String transport = conf.getProperty(TRANSPORT);
    AbstractTransport absTransport;
    if (transport.trim().equals("TCP")) {
        absTransport = new TcpTransport(bindAddress, port, 3, 50);
    } else if (transport.trim().equals("UDP")) {
        absTransport = new UdpTransport(port);
    } else {
        throw new IllegalArgumentException("Invalid transport: " + transport);
    }
    kdc.addTransports(absTransport);
    kdc.setServiceName(conf.getProperty(INSTANCE));
    kdc.start();
    // if using ephemeral port, update port number for binding
    if (port == 0) {
        InetSocketAddress addr = (InetSocketAddress) absTransport.getAcceptor().getLocalAddress();
        port = addr.getPort();
    }

    StringBuilder sb = new StringBuilder();
    InputStream is2 = cl.getResourceAsStream("minikdc-krb5.conf");

    BufferedReader r = null;

    try {
        r = new BufferedReader(new InputStreamReader(is2, StandardCharsets.UTF_8));
        String line = r.readLine();

        while (line != null) {
            sb.append(line).append("{3}");
            line = r.readLine();
        }
    } finally {
        IOUtils.closeQuietly(r);
        IOUtils.closeQuietly(is2);
    }

    krb5conf = new File(workDir, "krb5.conf").getAbsoluteFile();
    FileUtils.writeStringToFile(krb5conf, MessageFormat.format(sb.toString(), getRealm(), getHost(),
            Integer.toString(getPort()), System.getProperty("line.separator")));
    System.setProperty(JAVA_SECURITY_KRB5_CONF, krb5conf.getAbsolutePath());

    System.setProperty(SUN_SECURITY_KRB5_DEBUG, conf.getProperty(DEBUG, "false"));

    // refresh the config
    Class<?> classRef;
    if (System.getProperty("java.vendor").contains("IBM")) {
        classRef = Class.forName("com.ibm.security.krb5.internal.Config");
    } else {
        classRef = Class.forName("sun.security.krb5.Config");
    }
    Method refreshMethod = classRef.getMethod("refresh", new Class[0]);
    refreshMethod.invoke(classRef, new Object[0]);

    LOG.info("MiniKdc listening at port: {}", getPort());
    LOG.info("MiniKdc setting JVM krb5.conf to: {}", krb5conf.getAbsolutePath());
}

From source file:org.apache.ranger.policyengine.RangerPolicyEnginePerformanceTest.java

@AfterClass
public static void chartResults() throws IOException {
    // row: policies
    // column: concurrency
    // value: average
    LineChart chart = buildChart(parsePerformanceTable());
    String chartMarkup = StrSubstitutor.replace(
            RangerPolicyFactory.readResourceFile("/testdata/performance-chart.template"),
            ImmutableMap.of("data", chart.toJson()));
    Files.write(chartMarkup, new File("target", "performance-chart.html"), Charsets.UTF_8);
}

From source file:org.commonjava.maven.firth.model.index.ArtifactMap.java

private void mapManifestArtifacts(final SourceManifest manifest) {
    for (final BuildManifest bmanifest : manifest.getBuilds().values()) {
        for (final String file : bmanifest.getFiles()) {
            final String existingPath = basePaths.get(file);
            if (existingPath != null) {
                logger.warn("Skipping: {} in {}. It's already mapped to: {}", file, manifest.getSource(),
                        existingPath);//from   w w  w  . j  av a 2  s.  co  m
                continue;
            }

            // Sample package-path: "/brewroot/packages/org.commonjava.maven.ext-pom-manipulation-ext-0.5.2/1/maven"
            // Or, the format: "/brewroot/packages/%(groupId)-%(artifactId)-%(versionNoDashes)/%(build)/maven"
            basePaths.put(file, StrSubstitutor.replace(packagePathFormat, bmanifest.getPathVariables()));
        }
    }
}

From source file:org.eclipse.fx.ide.rrobot.impl.RRobotImpl.java

@Override
public IStatus executeTask(IProgressMonitor monitor, RobotTask task, Map<String, Object> additionalData) {

    // We'll operate on a copy because we modify the model and replace variable
    if (!task.getVariables().isEmpty()) {
        task = EcoreUtil.copy(task);/*ww w  .j  a  v  a  2 s.  c o m*/
    }

    System.err.println("ADDITIONAL: " + additionalData);

    for (Variable v : task.getVariables()) {
        if (!additionalData.containsKey(v.getKey())) {
            additionalData.put(v.getKey(), getVariableData(v));
        }
    }

    for (Entry<String, Object> e : additionalData.entrySet()) {
        if (e.getValue() instanceof String) {
            e.setValue(StrSubstitutor.replace((String) e.getValue(), additionalData));
        }
    }

    List<ProjectHandler<Project>> handlers;

    synchronized (this.handlers) {
        handlers = new ArrayList<ProjectHandler<Project>>(this.handlers);
    }

    TreeIterator<EObject> it = task.eAllContents();
    while (it.hasNext()) {
        EObject eo = it.next();
        for (EStructuralFeature f : eo.eClass().getEAllStructuralFeatures()) {
            Object val = eo.eGet(f);
            if (val instanceof String) {
                //               System.err.println("REPLACING: " + f + " val: " + val);
                eo.eSet(f, StrSubstitutor.replace(val, additionalData));
            }
        }
    }

    System.err.println("ADDITIONAL: " + additionalData);

    List<IStatus> states = new ArrayList<IStatus>();
    for (Project p : task.getProjects()) {
        for (ProjectHandler<Project> handler : handlers) {
            if (handler.isHandled(p.eClass())) {
                states.add(handler.createProject(monitor, p, additionalData));
            }
        }
    }

    return new MultiStatus("org.eclipse.fx.ide.rrobot", 0, states.toArray(new IStatus[0]), "Task executed",
            null);
}