Přeskočit na hlavní obsah

Expanze proměnných – neobjevujte kolo

Možná jste už někdy řešili problém, jak nahradit proměnné jejich hodnotou třeba v konfiguračním souboru. Například ze vstupu

<app-config baseDir="${projectDirectory}">
 <timeout>${timeout}</timeout>
</app-config>
chceme ve výsledku dostat
<app-config baseDir="C:\Projects\MyApp">
 <timeout>30</timeout>
</app-config>

Asi vás napadne využít String.replaceAll(String, String) nebo v lepším případě přímo dvojice Pattern/Matcher a capturing groups. Proč ale znovu vymýšlet kolo, když knihovna Apache Commons Lang (která by mimochodem měla být standardní součástí každého netriviálního projektu) nabízí pro daný problém přesně ty třídy, které potřebujeme. Výchozím bodem je třída StrSubstitutor, která obsahuje i statické metody pro zjednodušení v nejpoužívanějších případech:

Map<String, Object> properties = new HashMap<String, Object>();
properties.put("animal", "dog");
properties.put("legs", new Integer(4));

System.out.println(
    StrSubstitutor.replace("The ${animal} has ${legs} legs.", properties));
//prints: The dog has 4 legs. 

StrSubstitutor zvládá nahrazovat i Java property (standardní i ty zadané jako argumenty JVM)

System.out.println(
    StrSubstitutor.replaceSystemProperties("Your OS is '${os.name}'"));
//prints: Your OS is 'Windows XP'

A nejsme vázáni ani zdrojem hodnot našich proměnných. Například, chceme-li expandovat na proměnné prostředí a property mají syntaxi proměnných ve Windows, není to vůbec složité. Stačí vlastní implementace abstraktní třídy StrLookup:

//Anonymous child of StrLookup class, which
//maps property names to environment variables in the system
public static final StrLookup ENV_VAR_LOOKUP = new StrLookup() {
    @Override public String lookup(final String key) {
        return System.getenv(key);
    }
};

//expands windows-like properties to system environment variables (e.g. %PATH%)
public static String expandBatch(final String textToExpand) {
    final StrSubstitutor batchSubstitutor = new StrSubstitutor(
        ENV_VAR_LOOKUP, "%", "%", StrSubstitutor.DEFAULT_ESCAPE);
    return batchSubstitutor.replace(textToExpand);
}

//used then
System.out.println(
    expandBatch("Windows is installed in '%WINDIR%'."));
//prints: Windows is installed in 'C:\WINNT'.

A připomenutí na závěr – neobjevujte znovu kolo – pro začátek si projděte API ke Commons Lang a nebojte se tuto knihovnu používat.

Komentáře

Tomáš píše…
Diky za pripomenuti kdyz jsem prochazeil to API tak jsem se pristihl kolik takovych podobnych metod jsem zbytecne napsali, kdyz uz jsou 3x a lepe napsany

Populární příspěvky z tohoto blogu

Three ways to redirect HTTP requests to HTTPs in WildFly and JBoss EAP

WildFly application server (and JBoss EAP) supports several simple ways how to redirect the communication from plain HTTP to TLS protected HTTPs. This article presents 3 ways. Two are on the application level and the last one is on the server level valid for requests to all deployments. 1. Request confidentiality in the deployment descriptor The first way is based on the Servlet specification. You need to specify which URLs should be protected in the web.xml deployment descriptor. It's the same approach as the one used for specifying which URLs require authentication/authorization. Just instead of requesting an assigned role, you request a transport-guarantee . Sample content of the WEB-INF/web.xml <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1...

Simple TLS certificates in WildFly 18

It's just 2 weeks when WildFly 18 was released. It includes nice improvements in TLS certificates handling through ACME protocol (Automatic Certificate Management Environment), it greatly simplifies obtaining valid HTTPS certificates. There was already a support for the Let's Encrypt CA in WildFly 14 as Farah Juma described in her blog post last year. New WildFly version allows using other CA-s with ACME protocol support. It also adds new switch --lets-encrypt to interactive mode of security enable-ssl-http-server JBoss CLI commands. Let's try it. Before we jump on WildFly configuration, let's just mention the HTTPs can be used even in the default configuration and a self-signed certificate is generated on the fly. Nevertheless, it's not secure and you should not use it for any other purpose than testing. Use Let's Encrypt signed certificate for HTTPs application interface Start WildFly on a machine with the public IP address. Run it on the defaul...

JSignPKCS11 - when your smartcard is too smart

TL;DR Yes, you can add digital signatures in Java even when you use newer hardware tokens such as Gemalto SafeNet eToken 5110 CC. JSignPKCS11 might help. Maybe you've seen the infamous PKCS11 error message CKR_USER_NOT_LOGGED_IN already. Thrown even when the SunPKCS11 security provider and the keystore settings were properly configured for your hardware token. java.security.ProviderException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN at jdk.crypto.cryptoki/sun.security.pkcs11.P11Signature.engineSign(P11Signature.java:685) at java.base/java.security.Signature$Delegate.engineSign(Signature.java:1404) at java.base/java.security.Signature.sign(Signature.java:713) ... Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN at jdk.crypto.cryptoki/sun.security.pkcs11.wrapper.PKCS11.C_Sign(Native Method) at jdk.crypto.cryptoki/sun.security.pkcs11.P11Signature.engineSign(P11Signature.java:664) ...