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:org.jboss.as.test.integration.security.common.AbstractKrb5ConfServerSetupTask.java

/**
 *
 * @param managementClient//w  w  w.  j  a  v  a 2 s  . c o m
 * @param containerId
 * @throws Exception
 * @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
 *      java.lang.String)
 */
public void setup(ManagementClient managementClient, String containerId) throws Exception {
    LOGGER.trace("(Re)Creating workdir: " + WORK_DIR.getAbsolutePath());
    FileUtils.deleteDirectory(WORK_DIR);
    WORK_DIR.mkdirs();
    final String cannonicalHost = NetworkUtils
            .formatPossibleIpv6Address(Utils.getCannonicalHost(managementClient));
    final Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", cannonicalHost);
    final String supportedEncTypes = Utils.IBM_JDK ? getSupportedEncTypes() : "des-cbc-md5,des3-cbc-sha1-kd";
    map.put("enctypes", supportedEncTypes);
    LOGGER.trace("Supported enctypes in krb5.conf: " + supportedEncTypes);
    FileUtils.write(KRB5_CONF_FILE,
            StrSubstitutor.replace(IOUtils.toString(
                    AbstractKrb5ConfServerSetupTask.class.getResourceAsStream(KRB5_CONF), "UTF-8"), map),
            "UTF-8");
    createServerKeytab(cannonicalHost);
    final List<UserForKeyTab> kerberosUsers = kerberosUsers();
    if (kerberosUsers != null) {
        for (UserForKeyTab userForKeyTab : kerberosUsers) {
            createKeytab(userForKeyTab.getUser(), userForKeyTab.getPassword(),
                    userForKeyTab.getKeyTabFileName());
        }
    }
    LOGGER.trace("Setting Kerberos configuration: " + KRB5_CONF_FILE);
    origKrb5Conf = Utils.setSystemProperty("java.security.krb5.conf", KRB5_CONF_FILE.getAbsolutePath());
    origKrbDebug = Utils.setSystemProperty("sun.security.krb5.debug", "true");
    origIbmJGSSDebug = Utils.setSystemProperty("com.ibm.security.jgss.debug", "all");
    origIbmKrbDebug = Utils.setSystemProperty("com.ibm.security.krb5.Krb5Debug", "all");
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Replace keystore paths and passwords variables in original configuration file with given values and set ${hostname}
 * variable from system property: node0//from  w w  w. ja v a  2 s. co m
 *
 * @param originalFile String
 * @param keystoreFile File
 * @param trustStoreFile File
 * @param keystorePassword String
 * @param vaultConfig - path to vault settings
 * @return String content
 */
public static String propertiesReplacer(String originalFile, String keystoreFile, String trustStoreFile,
        String keystorePassword, String vaultConfig) {
    String hostname = getDefaultHost(false);

    // expand possible IPv6 address
    try {
        hostname = NetworkUtils.formatPossibleIpv6Address(InetAddress.getByName(hostname).getHostAddress());
    } catch (UnknownHostException ex) {
        String message = "Cannot resolve host address: " + hostname + " , error : " + ex.getMessage();
        LOGGER.error(message);
        throw new RuntimeException(ex);
    }

    final Map<String, String> map = new HashMap<String, String>();
    String content = "";
    if (vaultConfig == null) {
        map.put("vaultConfig", "");
    } else {
        map.put("vaultConfig", vaultConfig);
    }
    map.put("hostname", hostname);
    map.put("keystore", keystoreFile);
    map.put("truststore", trustStoreFile);
    map.put("password", keystorePassword);

    try {
        content = StrSubstitutor
                .replace(IOUtils.toString(CoreUtils.class.getResourceAsStream(originalFile), "UTF-8"), map);
    } catch (IOException ex) {
        String message = "Cannot find or modify configuration file " + originalFile + " , error : "
                + ex.getMessage();
        LOGGER.error(message);
        throw new RuntimeException(ex);
    }

    return content;
}

From source file:org.jboss.as.test.integration.security.loginmodules.LdapExtLDAPServerSetupTask.java

@CreateDS(name = "JBossDS-LdapExtLDAPServerSetupTask", factory = org.jboss.as.test.integration.ldap.InMemoryDirectoryServiceFactory.class, partitions = {
        @CreatePartition(name = "jboss", suffix = "dc=jboss,dc=org", contextEntry = @ContextEntry(entryLdif = "dn: dc=jboss,dc=org\n"
                + "dc: jboss\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes = {
                        @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"),
                        @CreateIndex(attribute = "ou") }) }, additionalInterceptors = {
                                KeyDerivationInterceptor.class })
@CreateLdapServer(transports = { @CreateTransport(protocol = "LDAP", port = LDAP_PORT),
        @CreateTransport(protocol = "LDAPS", port = LDAPS_PORT) }, certificatePassword = "secret")
//@formatter:on/*  w  w w. jav a2 s.  co m*/
public void createLdap1(final String hostname) throws Exception {
    final Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", NetworkUtils.formatPossibleIpv6Address(hostname));
    map.put("ldapPort2", Integer.toString(LDAP_PORT2));
    directoryService1 = DSAnnotationProcessor.getDirectoryService();
    final String ldifContent = StrSubstitutor.replace(
            IOUtils.toString(LdapExtLoginModuleTestCase.class
                    .getResourceAsStream(LdapExtLoginModuleTestCase.class.getSimpleName() + ".ldif"), "UTF-8"),
            map);
    LOGGER.debug(ldifContent);

    final SchemaManager schemaManager = directoryService1.getSchemaManager();
    try {
        for (LdifEntry ldifEntry : new LdifReader(IOUtils.toInputStream(ldifContent))) {
            directoryService1.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    final ManagedCreateLdapServer createLdapServer = new ManagedCreateLdapServer(
            (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
    FileOutputStream fos = new FileOutputStream(KEYSTORE_FILE);
    IOUtils.copy(getClass().getResourceAsStream(KEYSTORE_FILENAME), fos);
    fos.close();
    createLdapServer.setKeyStore(KEYSTORE_FILE.getAbsolutePath());
    fixTransportAddress(createLdapServer, hostname);
    ldapServer1 = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService1);
    ldapServer1.start();
    LOGGER.trace("ldapServer1 = " + ldapServer1);
}

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.Krb5ConfServerSetupTask.java

/**
 * /*from  www  .  ja  v a  2 s .c  o m*/
 * @param managementClient
 * @param containerId
 * @throws Exception
 * @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
 *      java.lang.String)
 */
public void setup(ManagementClient managementClient, String containerId) throws Exception {
    LOGGER.info("(Re)Creating workdir: " + WORK_DIR.getAbsolutePath());
    FileUtils.deleteDirectory(WORK_DIR);
    WORK_DIR.mkdirs();
    final String canonicalHost = NetworkUtils
            .formatPossibleIpv6Address(Utils.getCannonicalHost(managementClient));
    final Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", canonicalHost);
    FileUtils.write(KRB5_CONF_FILE,
            StrSubstitutor.replace(IOUtils.toString(getClass().getResourceAsStream(KRB5_CONF), "UTF-8"), map),
            "UTF-8");

    createKeytab("HTTP/" + canonicalHost + "@JBOSS.ORG", "httppwd", HTTP_KEYTAB_FILE);
    createKeytab("hnelson@JBOSS.ORG", "secret", HNELSON_KEYTAB_FILE);
    createKeytab("jduke@JBOSS.ORG", "theduke", JDUKE_KEYTAB_FILE);

    LOGGER.info("Setting Kerberos configuration: " + KRB5_CONF_FILE);
    origKrb5Conf = Utils.setSystemProperty("java.security.krb5.conf", KRB5_CONF_FILE.getAbsolutePath());
    origKrbDebug = Utils.setSystemProperty("sun.security.krb5.debug", "true");

}

From source file:org.jboss.as.test.integration.security.picketlink.KerberosServerSetupTask.java

@CreateDS(name = "JBossDS", partitions = {
        @CreatePartition(name = "jboss", suffix = "dc=jboss,dc=org", contextEntry = @ContextEntry(entryLdif = "dn: dc=jboss,dc=org\n"
                + "dc: jboss\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes = {
                        @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"),
                        @CreateIndex(attribute = "ou") }) }, additionalInterceptors = {
                                KeyDerivationInterceptor.class })
@CreateLdapServer(transports = {/*from  ww w  . ja v  a  2 s  .  co  m*/
        @CreateTransport(protocol = "LDAP", port = LDAP_PORT), }, certificatePassword = "secret")
@CreateKdcServer(primaryRealm = KERBEROS_PRIMARY_REALM, kdcPrincipal = "krbtgt/" + KERBEROS_PRIMARY_REALM + "@"
        + KERBEROS_PRIMARY_REALM, searchBaseDn = "dc=jboss,dc=org", transports = {
                @CreateTransport(protocol = "UDP", port = KERBEROS_PORT),
                @CreateTransport(protocol = "TCP", port = KERBEROS_PORT) })
//@formatter:on
public void createLdap1(ManagementClient managementClient, final String hostname)
        throws Exception, IOException, ClassNotFoundException, FileNotFoundException {
    final Map<String, String> map = new HashMap<String, String>();
    final String cannonicalHost = getCannonicalHost(managementClient);
    final String cannonicalIp = getFullCannonicalIp(managementClient);
    map.put("hostname", cannonicalHost);
    map.put("hostaddr", cannonicalIp);
    map.put("realm", KERBEROS_PRIMARY_REALM);
    directoryService1 = DSAnnotationProcessor.getDirectoryService();
    final String ldifContent = StrSubstitutor.replace(
            IOUtils.toString(KerberosServerSetupTask.class
                    .getResourceAsStream(KerberosServerSetupTask.class.getSimpleName() + ".ldif"), "UTF-8"),
            map);
    LOGGER.debug(ldifContent);

    final SchemaManager schemaManager = directoryService1.getSchemaManager();
    try {
        for (LdifEntry ldifEntry : new LdifReader(IOUtils.toInputStream(ldifContent))) {
            directoryService1.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    final ManagedCreateLdapServer createLdapServer = new ManagedCreateLdapServer(
            (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
    fixTransportAddress(createLdapServer, cannonicalHost);

    ldapServer1 = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService1);
    krbServer1 = KDCServerAnnotationProcessor.getKdcServer(directoryService1, KERBEROS_PORT, cannonicalHost);
    ldapServer1.start();

    createKrb5Conf(cannonicalHost, KRB5_CONF_FILE, KERBEROS_PORT);
}

From source file:org.jboss.as.test.integration.security.picketlink.KerberosServerSetupTask.java

/**
 * Creates a krb5.conf file for use with Kerberos server setup with this
 * server setup task.//from   ww  w .  j  a  v a 2 s  .co m
 * @param hostname Hostname to use
 * @param outputFile File to output
 * @param port Kerberos server port
 * @throws IOException
 * @throws FileNotFoundException
 */
private static void createKrb5Conf(final String hostname, final File outputFile, int port)
        throws IOException, FileNotFoundException {
    FileOutputStream krb5Conf = new FileOutputStream(outputFile);

    Map<String, String> properties = new HashMap<String, String>();
    properties.put("krbHostAndPort", hostname + ":" + port);
    properties.put("krbHost", hostname);

    String content = StrSubstitutor.replace(IOUtils.toString(
            SAML2BasicAuthenticationTestCase.class.getResourceAsStream(KRB5_CONF_RESOURCE_FILENAME), "UTF-8"),
            properties);

    IOUtils.write(content, krb5Conf);
    krb5Conf.close();

    LOGGER.debug(outputFile.getAbsolutePath() + ": \n" + content);
}

From source file:org.jboss.as.test.integration.security.xacml.JBossPDPInteroperabilityTestCase.java

/**
 * Tests loading XACML policies from a filesystem folder.
 *
 * @throws Exception// w w w .j a v a2 s . c  om
 */
@Test
public void testPoliciesLoadedFromDir() throws Exception {
    //create temporary folder for policies
    final File policyDir = new File("test-JBossPDP-Med-" + System.currentTimeMillis());
    final InputStream requestIS = getClass()
            .getResourceAsStream(XACMLTestUtils.TESTOBJECTS_REQUESTS + "/med-example-request.xml");
    try {
        policyDir.mkdirs();
        final JBossPDP pdp = createPDPForMed(policyDir);
        final String requestTemplate = IOUtils.toString(requestIS, "UTF-8");
        LOGGER.trace("REQUEST template: " + requestTemplate);
        final Map<String, Object> substitutionMap = new HashMap<String, Object>();

        substitutionMap.put(XACMLTestUtils.SUBST_SUBJECT_ID, "josef@med.example.com");
        assertEquals("Decision for josef@med.example.com should be DECISION_PERMIT",
                XACMLConstants.DECISION_PERMIT,
                getDecisionForStr(pdp, StrSubstitutor.replace(requestTemplate, substitutionMap)));

        substitutionMap.put(XACMLTestUtils.SUBST_SUBJECT_ID, "guest@med.example.com");
        assertEquals("Decision for guest@med.example.com should be DECISION_DENY", XACMLConstants.DECISION_DENY,
                getDecisionForStr(pdp, StrSubstitutor.replace(requestTemplate, substitutionMap)));

        substitutionMap.put(XACMLTestUtils.SUBST_SUBJECT_ID, "hs@simpsons.com");
        assertEquals("Decision for hs@simpsons.com should be DECISION_DENY", XACMLConstants.DECISION_DENY,
                getDecisionForStr(pdp, StrSubstitutor.replace(requestTemplate, substitutionMap)));

        substitutionMap.put(XACMLTestUtils.SUBST_SUBJECT_ID, "bs@simpsons.com");
        assertEquals("Decision for bs@simpsons.com should be DECISION_NOT_APPLICABLE",
                XACMLConstants.DECISION_NOT_APPLICABLE,
                getDecisionForStr(pdp, StrSubstitutor.replace(requestTemplate, substitutionMap)));

        substitutionMap.put(XACMLTestUtils.SUBST_SUBJECT_ID, "admin@acme.com");
        assertEquals("Decision for admin@acme.com should be DECISION_NOT_APPLICABLE",
                XACMLConstants.DECISION_NOT_APPLICABLE,
                getDecisionForStr(pdp, StrSubstitutor.replace(requestTemplate, substitutionMap)));

    } finally {
        FileUtils.deleteDirectory(policyDir);
        requestIS.close();
    }
}

From source file:org.jboss.test.kerberos.KerberosSetup.java

protected void startKDC(final String[] args) throws Exception {
    directoryService = DSAnnotationProcessor.getDirectoryService();
    LOGGER.info("Initializing KDC server with binding to '{}'", canonicalHost);
    final Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", canonicalHost);
    if (args != null && args.length > 0) {
        for (String ldifFile : args) {

            final String ldifContent = StrSubstitutor
                    .replace(FileUtils.readFileToString(new File(ldifFile), "UTF-8"), map);
            LOGGER.debug(ldifContent);/*from  w ww . j ava  2 s .co m*/
            final SchemaManager schemaManager = directoryService.getSchemaManager();
            try {
                for (LdifEntry ldifEntry : new LdifReader(IOUtils.toInputStream(ldifContent))) {
                    directoryService.getAdminSession()
                            .add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }
    }
    LOGGER.info("Generating kerberos configuration file '{}'", krb5ConfPath);
    FileUtils.write(new File(krb5ConfPath), StrSubstitutor
            .replace(IOUtils.toString(getClass().getResourceAsStream("/krb5.conf"), "UTF-8"), map));
    System.out.println("Starting KDC");
    kdcServer = KDCServerAnnotationProcessor.getKdcServer(directoryService, 1024, canonicalHost);
    System.out.println("Starting LDAP server");
    final ManagedCreateLdapServer createLdapServer = new ManagedCreateLdapServer(
            (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
    createLdapServer.setSaslHost(canonicalHost);
    createLdapServer.setSaslPrincipal("ldap/" + canonicalHost + "@JBOSS.ORG");
    fixTransportAddress(createLdapServer, canonicalHost);
    ldapServer = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService);
    ldapServer.setSearchBaseDn("dc=jboss,dc=org");
    ldapServer.start();
}

From source file:org.jtester.module.utils.ConfigurationLoader.java

/**
 * Expands all property place holders to actual values. For example suppose
 * you have a property defined as follows: root.dir=/usr/home Expanding
 * following ${root.dir}/somesubdir will then give following result:
 * /usr/home/somesubdir//from   w  w  w  .ja v  a2 s.  c o  m
 * 
 * @param properties
 *            The properties, not null
 */
protected void expandPropertyValues(Properties properties) {
    for (Object key : properties.keySet()) {
        Object value = properties.get(key);
        try {
            String expandedValue = StrSubstitutor.replace(value, properties);
            properties.put(key, expandedValue);
        } catch (Exception e) {
            throw new JTesterException(
                    "Unable to load unitils configuration. Could not expand property value for key: " + key
                            + ", value " + value,
                    e);
        }
    }

}

From source file:org.keycloak.util.ldap.LDAPEmbeddedServer.java

private void importLdif() throws Exception {
    Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", this.bindHost);
    if (this.ldapSaslPrincipal != null) {
        map.put("ldapSaslPrincipal", this.ldapSaslPrincipal);
    }/* ww w  . j  a  v a2s  . c om*/

    // Find LDIF file on filesystem or classpath ( if it's like classpath:ldap/users.ldif )
    InputStream is = FindFile.findFile(ldifFile);
    if (is == null) {
        throw new IllegalStateException(
                "LDIF file not found on classpath or on file system. Location was: " + ldifFile);
    }

    final String ldifContent = StrSubstitutor.replace(StreamUtil.readString(is), map);
    log.info("Content of LDIF: " + ldifContent);
    final SchemaManager schemaManager = directoryService.getSchemaManager();

    importLdifContent(directoryService, ldifContent);
}