Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *
   *  JBoss, Home of Professional Open Source.
   *  Copyright 2014, Red Hat, Inc., and individual contributors
   *  as indicated by the @author tags. See the copyright.txt file in the
   *  distribution for a full listing of individual contributors.
   *
   *  This is free software; you can redistribute it and/or modify it
   *  under the terms of the GNU Lesser General Public License as
  *  published by the Free Software Foundation; either version 2.1 of
  *  the License, or (at your option) any later version.
  *
  *  This software is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  *  Lesser General Public License for more details.
  *
  *  You should have received a copy of the GNU Lesser General Public
  *  License along with this software; if not, write to the Free
  *  Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  *  02110-1301 USA, or see the FSF site: http://www.fsf.org.
  * /
  */
 package org.jboss.as.test.integration.security.common;
 
 import static org.junit.Assert.assertEquals;
 
 import java.io.File;
 import java.net.URI;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
Common utilities for JBoss AS security tests.

Author(s):
Jan Lanik
Josef Cacek
 
 public class CoreUtils {
 
     private static final Logger LOGGER = Logger.getLogger(CoreUtils.class);
 
     public static final String UTF_8 = "UTF-8";

    
Return MD5 hash of the given string value, encoded with given Coding. If the value or coding is null then original value is returned.

Returns:
encoded MD5 hash of the string or original value if some of parameters is null
 
     public static String hashMD5(String valueCoding coding) {
         return (coding == null || value == null) ? value : hash(value"MD5"coding);
     }
 
     public static String hash(String targetString algorithmCoding coding) {
         MessageDigest md = null;
         try {
             md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] bytes = target.getBytes();
        byte[] byteHash = md.digest(bytes);
        String encodedHash = null;
        switch (coding) {
            case :
                encodedHash = Base64.encodeBytes(byteHash);
                break;
            case :
                encodedHash = toHex(byteHash);
                break;
            default:
                throw new IllegalArgumentException("Unsuported coding:" + coding.name());
        }
        return encodedHash;
    }
    public static String toHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.lengthi++) {
            byte b = bytes[i];
            // top 4 bits
            char c = (char) ((b >> 4) & 0xf);
            if (c > 9) { c = (char) ((c - 10) + 'a'); } else { c = (char) (c + '0'); }
            sb.append(c);
            // bottom 4 bits
            c = (char) (b & 0xf);
            if (c > 9) { c = (char) ((c - 10) + 'a'); } else { c = (char) (c + '0'); }
            sb.append(c);
        }
        return sb.toString();
    }
    public static URL getResource(String name) {
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        return tccl.getResource(name);
    }
    private static final long STOP_DELAY_DEFAULT = 0;

    
stops execution of the program indefinitely useful in testsuite debugging
    public static void stop() {
        stop();
    }

    
stop test execution for a given time interval useful for debugging

Parameters:
delay interval (milliseconds), if delay<=0, interval is considered to be infinite (Long.MAX_VALUE)
    public static void stop(long delay) {
        long currentTime = System.currentTimeMillis();
        long remainingTime = 0 < delay ? currentTime + delay - System.currentTimeMillis() : .;
        while (remainingTime > 0) {
            try {
                Thread.sleep(remainingTime);
            } catch (InterruptedException ex) {
                remainingTime = currentTime + delay - System.currentTimeMillis();
                continue;
            }
        }
    }
    public static void applyUpdates(final List<ModelNodeupdatesfinal ModelControllerClient clientthrows Exception {
        for (ModelNode update : updates) {
            applyUpdate(updateclient);
        }
    }
    public static void applyUpdate(ModelNode updatefinal ModelControllerClient clientthrows Exception {
        ModelNode result = client.execute(new OperationBuilder(update).build());
        if (.isInfoEnabled()) {
            .info("Client update: " + update);
            .info("Client update result: " + result);
        }
        if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
            .debug("Operation succeeded.");
        } else if (result.hasDefined("failure-description")) {
            throw new RuntimeException(result.get("failure-description").toString());
        } else {
            throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
        }
    }

    
Read the contents of an HttpResponse's entity and return it as a String. The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.

Parameters:
response
Returns:
Throws:
java.io.IOException
    public static String getContent(HttpResponse responsethrows IOException {
        return EntityUtils.toString(response.getEntity());
    }

    
Makes HTTP call with FORM authentication.

Parameters:
URL
user
pass
expectedStatusCode
Throws:
java.lang.Exception
    public static void makeCall(String URLString userString passint expectedStatusCodethrows Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet(URL);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) { EntityUtils.consume(entity); }
            // We should get the Login Page
            StatusLine statusLine = response.getStatusLine();
            ..println("Login form get: " + statusLine);
            assertEquals(200, statusLine.getStatusCode());
            ..println("Initial set of cookies:");
            List<Cookiecookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                ..println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    ..println("- " + cookies.get(i).toString());
                }
            }
            // We should now login with the user name and password
            HttpPost httpost = new HttpPost(URL + "/j_security_check");
            List<NameValuePairnvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("j_username"user));
            nvps.add(new BasicNameValuePair("j_password"pass));
            httpost.setEntity(new UrlEncodedFormEntity(nvps"UTF-8"));
            response = httpclient.execute(httpost);
            entity = response.getEntity();
            if (entity != null) { EntityUtils.consume(entity); }
            statusLine = response.getStatusLine();
            // Post authentication - we have a 302
            assertEquals(302, statusLine.getStatusCode());
            Header locationHeader = response.getFirstHeader("Location");
            String location = locationHeader.getValue();
            HttpGet httpGet = new HttpGet(location);
            response = httpclient.execute(httpGet);
            entity = response.getEntity();
            if (entity != null) { EntityUtils.consume(entity); }
            ..println("Post logon cookies:");
            cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                ..println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    ..println("- " + cookies.get(i).toString());
                }
            }
            // Either the authentication passed or failed based on the expected status code
            statusLine = response.getStatusLine();
            assertEquals(expectedStatusCodestatusLine.getStatusCode());
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }

    
Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the expected one. If the server returns HttpServletResponse and username is provided, then a new request is created with the provided credentials (basic authentication).

Parameters:
url URL to which the request should be made
user Username (may be null)
pass Password (may be null)
expectedStatusCode expected status code returned from the requested server
Returns:
HTTP response body
Throws:
java.io.IOException
java.net.URISyntaxException
    public static String makeCallWithBasicAuthn(URL urlString userString passint expectedStatusCodethrows IOExceptionURISyntaxException {
        .info("Requesting URL " + url);
        final DefaultHttpClient httpClient = new DefaultHttpClient();
        try {
            final HttpGet httpGet = new HttpGet(url.toURI());
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (401 != statusCode || StringUtils.isEmpty(user)) {
                assertEquals("Unexpected HTTP response status code."expectedStatusCodestatusCode);
                return EntityUtils.toString(response.getEntity());
            }
            if (.isDebugEnabled()) {
                .debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null)
                EntityUtils.consume(entity);
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userpass);
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials);
            response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code returned after the authentication."expectedStatusCodestatusCode);
            return EntityUtils.toString(response.getEntity());
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }
    }

    
Exports given archive to the given file path.

Parameters:
archive
filePath
    public static void saveArchive(Archive<?> archiveString filePath) {
        archive.as(ZipExporter.class).exportTo(new File(filePath), true);
    }

    
Exports given archive to the given folder.

Parameters:
archive archive to export (not-null)
folderPath
    public static void saveArchiveToFolder(Archive<?> archiveString folderPath) {
        final File exportFile = new File(folderPatharchive.getName());
        .info("Exporting archive: " + exportFile.getAbsolutePath());
        archive.as(ZipExporter.class).exportTo(exportFiletrue);
    }



    
Requests given URL and checks if the returned HTTP status code is the expected one. Returns HTTP response body

Parameters:
url url to which the request should be made
httpClient httpClient to test multiple access
expectedStatusCode expected status code returned from the requested server
Returns:
HTTP response body
Throws:
java.io.IOException
java.net.URISyntaxException
    public static String makeCallWithHttpClient(URL urlHttpClient httpClientint expectedStatusCode)
            throws IOExceptionURISyntaxException {
        String httpResponseBody = null;
        HttpGet httpGet = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        .info("Request to: " + url + " responds: " + statusCode);
        assertEquals("Unexpected status code"expectedStatusCodestatusCode);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            httpResponseBody = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(entity);
        }
        return httpResponseBody;
    }


    
Sets or removes (in case value==null) a system property. It's only a helper method, which avoids java.lang.NullPointerException thrown from java.lang.System.setProperty(java.lang.String,java.lang.String) method, when the value is null.

Parameters:
key property name
value property value
Returns:
the previous string value of the system property
    public static String setSystemProperty(final String keyfinal String value) {
        return value == null ? System.clearProperty(key) : System.setProperty(keyvalue);
    }

    
Returns canonical hostname form of the given address.

Parameters:
address hosname or IP address
Returns:
    public static final String getCannonicalHost(final String address) {
        String host = stripSquareBrackets(address);
        try {
            host = InetAddress.getByName(host).getCanonicalHostName();
        } catch (UnknownHostException e) {
            .warn("Unable to get canonical host name"e);
        }
        return host.toLowerCase(.);
    }

    
Returns given URI with the replaced hostname. If the URI or host is null, then the original URI is returned.

Parameters:
uri
host
Returns:
Throws:
java.net.URISyntaxException
    public static final URI replaceHost(final URI urifinal String hostthrows URISyntaxException {
        final String origHost = uri == null ? null : uri.getHost();
        final String newHost = NetworkUtils.formatPossibleIpv6Address(host);
        if (origHost == null || newHost == null || newHost.equals(origHost)) {
            return uri;
        }
        return new URI(uri.toString().replace(origHostnewHost));
    }

    
Generates content of jboss-ejb3.xml file as a ShrinkWrap asset with the given security domain name.

Parameters:
securityDomain security domain name
Returns:
Asset instance
    public static Asset getJBossEjb3XmlAsset(final String securityDomain) {
        final StringBuilder sb = new StringBuilder();
        sb.append("<jboss:ejb-jar xmlns:jboss='http://www.jboss.com/xml/ns/javaee'");
        sb.append("\n\txmlns='http://java.sun.com/xml/ns/javaee'");
        sb.append("\n\txmlns:s='urn:security'");
        sb.append("\n\tversion='3.1'");
        sb.append("\n\timpl-version='2.0'>");
        sb.append("\n\t<assembly-descriptor><s:security>");
        sb.append("\n\t\t<ejb-name>*</ejb-name>");
        sb.append("\n\t\t<s:security-domain>").append(securityDomain).append("</s:security-domain>");
        sb.append("\n\t</s:security></assembly-descriptor>");
        sb.append("\n</jboss:ejb-jar>");
        return new StringAsset(sb.toString());
    }

    
Generates content of jboss-web.xml file as a ShrinkWrap asset with the given security domain name and given valve class.

Parameters:
securityDomain security domain name (not-null)
valveClassNames valve class (e.g. an Authenticator) which should be added to jboss-web file (may be null)
Returns:
Asset instance
    public static Asset getJBossWebXmlAsset(final String securityDomainfinal String... valveClassNames) {
        final StringBuilder sb = new StringBuilder();
        sb.append("<jboss-web>");
        sb.append("\n\t<security-domain>").append(securityDomain).append("</security-domain>");
        if (valveClassNames != null) {
            for (String valveClassName : valveClassNames) {
                if (StringUtils.isNotEmpty(valveClassName)) {
                    sb.append("\n\t<valve><class-name>").append(valveClassName).append("</class-name></valve>");
                }
            }
        }
        sb.append("\n</jboss-web>");
        return new StringAsset(sb.toString());
    }

    
Generates content of the jboss-deployment-structure.xml deployment descriptor as a ShrinkWrap asset. It fills the given dependencies (module names) into it.

Parameters:
dependencies AS module names
Returns:
    public static Asset getJBossDeploymentStructure(String... dependencies) {
        final StringBuilder sb = new StringBuilder();
        sb.append("<jboss-deployment-structure><deployment><dependencies>");
        if (dependencies != null) {
            for (String moduleName : dependencies) {
                sb.append("\n\t<module name='").append(moduleName).append("'/>");
            }
        }
        sb.append("\n</dependencies></deployment></jboss-deployment-structure>");
        return new StringAsset(sb.toString());
    }

    
Creates content of users.properties and/or roles.properties files for given array of role names.

For instance if you provide 2 roles - "role1", "role2" then the result will be:

 role1=role1
 role2=role2
 

If you use it as users.properties and roles.properties, then roleName == userName == password

Parameters:
roles role names (used also as user names and passwords)
Returns:
not-null content of users.properties and/or roles.properties
    public static String createUsersFromRoles(String... roles) {
        final StringBuilder sb = new StringBuilder();
        if (roles != null) {
            for (String role : roles) {
                sb.append(role).append("=").append(role).append("\n");
            }
        }
        return sb.toString();
    }

    
Strips square brackets - '[' and ']' from the given string. It can be used for instance to remove the square brackets around IPv6 address in a URL.

Parameters:
str string to strip
Returns:
str without square brackets in it
    public static String stripSquareBrackets(final String str) {
        return StringUtils.strip(str"[]");
    }


    
Copies server and clients keystores and truststores from this package to the given folder. Server truststore has accepted certificate from client keystore and vice-versa

Parameters:
workingFolder folder to which key material should be copied
Throws:
java.io.IOException copying of keystores fails
java.lang.IllegalArgumentException workingFolder is null or it's not a directory
    public static void createKeyMaterial(final File workingFolderthrows IOExceptionIllegalArgumentException {
        if (workingFolder == null || !workingFolder.isDirectory()) {
            throw new IllegalArgumentException("Provide an existing folder as the method parameter.");
        }
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        createTestResource(new File(workingFolder.));
        .info("Key material created in " + workingFolder.getAbsolutePath());
    }

    
Copies a resource file from current package to location denoted by given java.io.File instance.

Parameters:
file
Throws:
java.io.IOException
    private static void createTestResource(File filethrows IOException {
        FileOutputStream fos = null;
        .info("Creating test file " + file.getAbsolutePath());
        try {
            fos = new FileOutputStream(file);
            IOUtils.copy(CoreUtils.class.getResourceAsStream(file.getName()), fos);
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }
    public static String propertiesReplacer(String originalFileFile keystoreFileFile trustStoreFileString keystorePassword) {
        return propertiesReplacer(originalFilekeystoreFile.getAbsolutePath(), trustStoreFile.getAbsolutePath(), keystorePasswordnull);
    }
    public static String propertiesReplacer(String originalFileFile keystoreFileFile trustStoreFileString keystorePassword,
                                            String vaultConfig) {
        return propertiesReplacer(originalFilekeystoreFile.getAbsolutePath(), trustStoreFile.getAbsolutePath(), keystorePassword,
                vaultConfig);
    }

    
Replace keystore paths and passwords variables in original configuration file with given values and set ${hostname} variable from system property: node0

Returns:
String content
    public static String propertiesReplacer(String originalFileString keystoreFileString trustStoreFileString keystorePassword,
                                            String vaultConfig) {
        String hostname = System.getProperty("node0");
        // 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();
            .error(message);
            throw new RuntimeException(ex);
        }
        final Map<StringStringmap = new HashMap<StringString>();
        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();
            .error(message);
            throw new RuntimeException(ex);
        }
        return content;
    }

    
Makes HTTP call without authentication. Returns response body as a String.

Parameters:
uri requested URL
expectedStatusCode expected status code - it's checked after the request is executed
Throws:
java.lang.Exception
    public static String makeCall(URI uriint expectedStatusCodethrows Exception {
        final DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            final HttpGet httpget = new HttpGet(uri);
            final HttpResponse response = httpclient.execute(httpget);
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code returned after the authentication."expectedStatusCodestatusCode);
            return EntityUtils.toString(response.getEntity());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

    
Returns param/value pair in form "urlEncodedName=urlEncodedValue". It can be used for instance in HTTP get queries.

Parameters:
paramName parameter name
paramValue parameter value
Returns:
"[urlEncodedName]=[urlEncodedValue]" string
    public static String encodeQueryParam(final String paramNamefinal String paramValue) {
        String response = null;
        try {
            response = StringUtils.isEmpty(paramValue) ? null : (URLEncoder.encode(paramName) + "=" + URLEncoder.encode(
                    StringUtils.defaultString(paramValue.), ));
        } catch (UnsupportedEncodingException e) {
            // should never happen - everybody likes the "UTF-8" :)
        }
        return response;
    }
New to GrepCode? Check out our FAQ X