Example usage for org.apache.commons.collections4.map CaseInsensitiveMap CaseInsensitiveMap

List of usage examples for org.apache.commons.collections4.map CaseInsensitiveMap CaseInsensitiveMap

Introduction

In this page you can find the example usage for org.apache.commons.collections4.map CaseInsensitiveMap CaseInsensitiveMap.

Prototype

public CaseInsensitiveMap() 

Source Link

Document

Constructs a new empty map with default size and load factor.

Usage

From source file:io.vitess.client.cursor.FieldMap.java

public FieldMap(Iterable<Field> fields) {
    this.fields = ImmutableList.copyOf(checkNotNull(fields));

    labelMap = new CaseInsensitiveMap<String, Integer>();
    nameMap = new CaseInsensitiveMap<String, Integer>();
    fullNameMap = new CaseInsensitiveMap<String, Integer>();
    // columnIndex is 1-based.
    int columnIndex = 1;
    for (Field field : this.fields) {
        // If multiple columns have the same name,
        // prefer the earlier one as JDBC ResultSet does.
        String columnLabel = field.getName();
        if (!labelMap.containsKey(columnLabel)) {
            labelMap.put(columnLabel, columnIndex);
        }//from  w w w .j a  v  a  2 s .com
        String origName = field.getOrgName();
        if (origName != null && !"".equals(origName) && !nameMap.containsKey(origName)) {
            nameMap.put(origName, columnIndex);
        }
        String tableName = field.getTable();
        if (tableName != null && !"".equals(tableName)) {
            StringBuilder fullNameBuf = new StringBuilder();
            fullNameBuf.append(tableName);
            fullNameBuf.append('.');
            fullNameBuf.append(field.getName());
            String fullName = fullNameBuf.toString();
            if (!fullNameMap.containsKey(fullName)) {
                fullNameMap.put(fullName, columnIndex);
            }
        }
        ++columnIndex;
    }
}

From source file:com.joyent.manta.client.crypto.EncryptedMetadataUtils.java

/**
 * Parses a plaintext metadata string and converts it into a {@link Map} of
 * keys and values./*from   ww  w.j  av a  2  s .c o  m*/
 *
 * @param plaintext Plaintext binary data in US-ASCII encoding
 * @return headers as map
 */
public static Map<String, String> plaintextMetadataAsMap(final byte[] plaintext) {
    Map<String, String> map = new CaseInsensitiveMap<>();

    boolean parsingKey = true;
    boolean parsingVal = false;

    final int initialSize = 24;
    StringBuilder key = new StringBuilder(initialSize);
    StringBuilder val = new StringBuilder(initialSize);

    for (int i = 0; i <= plaintext.length; i++) {
        // Done parsing a line, now we add it to the map
        if (i == plaintext.length || (char) plaintext[i] == CharUtils.LF) {
            if (key.length() > 0) {
                map.put(key.toString(), val.toString());
            }

            key.setLength(0);
            val.setLength(0);
            parsingKey = true;
            parsingVal = false;
            continue;
        }

        char c = (char) plaintext[i];

        if (!CharUtils.isAsciiPrintable(c)) {
            String msg = "Encrypted metadata contained a " + "non-ascii or unprintable character";
            throw new MantaClientEncryptionException(msg);
        }

        if (c == ':' && parsingKey) {
            parsingKey = false;
            continue;
        }

        if (c == ' ' && !parsingKey && !parsingVal) {
            continue;
        } else if (!parsingKey && !parsingVal) {
            parsingVal = true;
        }

        if (parsingKey) {
            key.append(c);
        }

        if (parsingVal) {
            val.append(c);
        }
    }

    return map;
}

From source file:com.joyent.manta.client.MantaMetadata.java

/**
 * Create a new instance backed with a new empty map.
 *//*ww w  .j ava 2s . c om*/
public MantaMetadata() {
    final Map<String, String> map = new CaseInsensitiveMap<>();
    final Predicate<String> keyPredicate = new HttpHeaderNameKeyPredicate();
    this.innerMap = PredicatedMap.predicatedMap(map, keyPredicate, null);
}

From source file:com.mirth.connect.plugins.httpauth.RequestInfo.java

public Map<String, List<String>> getHeaders() {
    Map<String, List<String>> headers = new CaseInsensitiveMap<String, List<String>>();
    for (Entry<String, List<String>> entry : this.headers.entrySet()) {
        headers.put(entry.getKey(), Collections.unmodifiableList(entry.getValue()));
    }//from  w  w  w  .  j  a  v  a 2  s  . c o m
    return Collections.unmodifiableMap(headers);
}

From source file:net.dv8tion.jda.core.requests.restaction.AuditableRestAction.java

@Override
protected CaseInsensitiveMap<String, String> finalizeHeaders() {
    CaseInsensitiveMap<String, String> headers = super.finalizeHeaders();

    if (reason == null || reason.isEmpty())
        return headers;

    if (headers == null)
        headers = new CaseInsensitiveMap<>();

    headers.put("X-Audit-Log-Reason", uriEncode(reason));

    return headers;
}

From source file:com.mirth.connect.plugins.httpauth.RequestInfo.java

public Map<String, List<String>> getQueryParameters() {
    Map<String, List<String>> queryParameters = new CaseInsensitiveMap<String, List<String>>();
    for (Entry<String, List<String>> entry : this.queryParameters.entrySet()) {
        queryParameters.put(entry.getKey(), Collections.unmodifiableList(entry.getValue()));
    }// w w  w.j  a  v  a2  s.c o  m
    return Collections.unmodifiableMap(queryParameters);
}

From source file:com.mirth.connect.plugins.httpauth.digest.DigestAuthenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) {
    DigestHttpAuthProperties properties = getReplacedProperties(request);
    List<String> authHeaderList = request.getHeaders().get(HttpHeader.AUTHORIZATION.asString());
    Map<String, String> directives = new CaseInsensitiveMap<String, String>();
    String nonceString = null;//from  w w  w. j a v  a2  s. com
    String nonceCountString = null;
    String nonceOpaque = "";

    /*
     * This status is used to determine whether or not to send back a challenge. It's also used
     * to determine whether the nonce used by the client is stale (expired past the max nonce
     * age, or the max nonce count).
     */
    Status status = Status.INVALID;

    if (CollectionUtils.isNotEmpty(authHeaderList)) {
        String authHeader = authHeaderList.iterator().next();

        /*
         * This splits up the Authorization header into name-value pairs and puts them into the
         * directives map.
         */
        QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(authHeader, "=, ", true, false);
        String directive = null;
        String lastToken = null;
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            char c;
            if (token.length() == 1 && ((c = token.charAt(0)) == '=' || c == ',' || c == ' ')) {
                if (c == '=') {
                    directive = lastToken;
                } else if (c == ',') {
                    directive = null;
                }
            } else {
                if (directive != null) {
                    directives.put(directive, token);
                    directive = null;
                }
                lastToken = token;
            }
        }

        nonceString = directives.get(NONCE);
        nonceCountString = directives.get(NONCE_COUNT);

        // The authentication attempt isn't valid without a nonce
        if (StringUtils.isNotBlank(nonceString)) {
            Nonce nonce = nonceMap.get(nonceString);

            if (nonce != null) {
                // Nonce was found
                nonceOpaque = nonce.getOpaque();

                if (nonce.isExpired()) {
                    status = Status.STALE;
                } else if (StringUtils.isNotBlank(nonceCountString)) {
                    /*
                     * Nonce count is supplied, so update the nonce with it. If the count is
                     * less than or equal to the current counter, it's an invalid request. If
                     * the count is greater than the max nonce count, the nonce is stale.
                     */
                    try {
                        status = nonce.updateCount(Long.parseLong(nonceCountString, 16));
                    } catch (NumberFormatException e) {
                        // If an exception occurs parsing the nonce count, leave the status as invalid
                    }
                } else {
                    /*
                     * If no nonce count was supplied, just increment the internal counter by 1.
                     * If the count is greater than the max nonce count, the nonce is stale.
                     */
                    status = nonce.incrementCount();
                }
            } else {
                // Nonce has expired or never existed
                status = Status.STALE;
            }
        }
    }

    // Remove expired nonces from the cache
    cleanupNonces();

    /*
     * If the status is valid or stale, attempt to calculate the digest and compare it to the
     * response hash. If the response hash is incorrect, the status should always be set to
     * invalid. If the response hash is correct but the nonce is stale, the stale directive
     * should be set to true in the response challenge.
     */
    if (status != Status.INVALID) {
        try {
            // Retrieve directives from the map
            String username = directives.get(USERNAME);
            String realm = directives.get(REALM);
            String uri = directives.get(URI);
            String response = directives.get(RESPONSE);
            String clientNonceString = directives.get(CLIENT_NONCE);
            String qop = directives.get(QOP);
            String algorithm = directives.get(ALGORITHM);
            String opaque = StringUtils.trimToEmpty(directives.get(OPAQUE));

            // Do some initial validation on required directives 
            if (StringUtils.isBlank(username)) {
                throw new Exception("Username missing.");
            } else if (StringUtils.isBlank(realm)) {
                throw new Exception("Realm missing.");
            } else if (uri == null) {
                throw new Exception("URI missing.");
            } else if (StringUtils.isBlank(response)) {
                throw new Exception("Response digest missing.");
            }

            String requestURI = request.getRequestURI();
            // Allow empty URI to match "/"
            if (StringUtils.isEmpty(uri) && StringUtils.equals(requestURI, "/")) {
                requestURI = "";
            }

            if (!StringUtils.equalsIgnoreCase(properties.getRealm(), realm)) {
                throw new Exception("Realm \"" + realm + "\" does not match expected realm \""
                        + properties.getRealm() + "\".");
            } else if (!StringUtils.equalsIgnoreCase(requestURI, uri)) {
                throw new Exception(
                        "URI \"" + uri + "\" does not match the request URI \"" + requestURI + "\".");
            } else if (!StringUtils.equals(opaque, nonceOpaque)) {
                throw new Exception("Opaque value \"" + opaque + "\" does not match the expected value \""
                        + properties.getOpaque() + "\".");
            }

            String password = properties.getCredentials().get(username);
            if (password == null) {
                throw new Exception("Credentials for username " + username + " not found.");
            }

            /*
             * Calculate H(A1).
             * 
             * Algorithm MD5: A1 = username:realm:password
             * 
             * Algorithm MD5-sess: A1 = H(username:realm:password):nonce:cnonce
             */
            String ha1;

            if (algorithm == null || (StringUtils.equalsIgnoreCase(algorithm, Algorithm.MD5.toString())
                    && properties.getAlgorithms().contains(Algorithm.MD5))) {
                ha1 = digest(username, realm, password);
            } else if (StringUtils.equalsIgnoreCase(algorithm, Algorithm.MD5_SESS.toString())
                    && properties.getAlgorithms().contains(Algorithm.MD5_SESS)) {
                if (StringUtils.isBlank(clientNonceString)) {
                    throw new Exception("Client nonce missing.");
                }
                String credentialsDigest = digest(username, realm, password);
                ha1 = digest(credentialsDigest, nonceString, clientNonceString);
            } else {
                throw new Exception("Algorithm \"" + algorithm + "\" not supported.");
            }

            /*
             * Calculate H(A2).
             * 
             * QOP undefined/auth: A2 = method:uri
             * 
             * QOP auth-int: A2 = method:uri:H(entityBody)
             */
            String ha2;

            if (qop == null || (StringUtils.equalsIgnoreCase(qop, QOPMode.AUTH.toString())
                    && properties.getQopModes().contains(QOPMode.AUTH))) {
                ha2 = digest(request.getMethod(), uri);
            } else if (StringUtils.equalsIgnoreCase(qop, QOPMode.AUTH_INT.toString())
                    && properties.getQopModes().contains(QOPMode.AUTH_INT)) {
                String entityDigest = digest(request.getEntityProvider().getEntity());
                ha2 = digest(request.getMethod(), uri, entityDigest);
            } else {
                throw new Exception("Quality of protection mode \"" + qop + "\" not supported.");
            }

            /*
             * Calculate response.
             * 
             * QOP undefined: response = H(H(A1):nonce:H(A2))
             * 
             * QOP auth/auth-int: response = H(H(A1):nonce:nc:cnonce:qop:H(A2))
             */
            String rsp;

            if (qop == null) {
                rsp = digest(ha1, nonceString, ha2);
            } else {
                if (StringUtils.isBlank(nonceCountString)) {
                    throw new Exception("Nonce count missing.");
                } else if (StringUtils.isBlank(clientNonceString)) {
                    throw new Exception("Client nonce missing.");
                }
                rsp = digest(ha1, nonceString, nonceCountString, clientNonceString, qop, ha2);
            }

            if (logger.isTraceEnabled()) {
                logger.trace("H(A1): " + ha1);
                logger.trace("H(A2): " + ha2);
                logger.trace("response: " + rsp);
            }

            if (StringUtils.equalsIgnoreCase(rsp, response)) {
                /*
                 * If the status is valid, return a successful result. Otherwise, the status
                 * will remain stale and a challenge will be reissued.
                 */
                if (status == Status.VALID) {
                    return AuthenticationResult.Success(username, realm);
                }
            } else {
                throw new Exception(
                        "Response digest \"" + response + "\" does not match expected digest \"" + rsp + "\".");
            }
        } catch (Exception e) {
            logger.debug("Error validating digest response.", e);
            status = Status.INVALID;
        }
    }

    /*
     * If we got to this point, an authentication challenge will be sent back, with a new nonce.
     * If the status is stale, the stale directive will also be set to true.
     */
    Nonce nonce = new Nonce(properties.getOpaque());
    nonceMap.put(nonce.getValue(), nonce);

    String contextPath = "/";
    try {
        contextPath = new URI(request.getRequestURI()).getPath();
    } catch (URISyntaxException e) {
    }

    Map<String, String> responseDirectives = new HashMap<String, String>();
    responseDirectives.put(REALM, properties.getRealm());
    responseDirectives.put(DOMAIN, contextPath);
    responseDirectives.put(NONCE, nonce.getValue());
    responseDirectives.put(ALGORITHM, StringUtils.join(properties.getAlgorithms(), ','));
    if (CollectionUtils.isNotEmpty(properties.getQopModes())) {
        responseDirectives.put(QOP, StringUtils.join(properties.getQopModes(), ','));
    }
    if (StringUtils.isNotBlank(nonce.getOpaque())) {
        responseDirectives.put(OPAQUE, nonce.getOpaque());
    }
    if (status == Status.STALE) {
        responseDirectives.put(STALE, "true");
    }

    /*
     * Build up the WWW-Authenticate header to be sent back in the response.
     */
    StringBuilder digestBuilder = new StringBuilder("Digest ");
    for (Iterator<Entry<String, String>> it = responseDirectives.entrySet().iterator(); it.hasNext();) {
        Entry<String, String> entry = it.next();
        digestBuilder.append(entry.getKey());
        digestBuilder.append("=\"");
        digestBuilder.append(entry.getValue());
        digestBuilder.append('"');
        if (it.hasNext()) {
            digestBuilder.append(", ");
        }
    }
    return AuthenticationResult.Challenged(digestBuilder.toString());
}

From source file:de.unentscheidbar.csv2.CaseInsensitiveBenchmark.java

static Collection<String> getLotsOfColumnNames() {

    Random rnd = new Random(0);
    Set<String> names = Collections.newSetFromMap(new CaseInsensitiveMap<String, Boolean>());
    while (names.size() < 100) {
        names.add(randomString(rnd, 1 + rnd.nextInt(30)));
    }//from  www  .  ja v a  2  s.c o  m
    List<String> uniqueNames = new ArrayList<>(names);
    /* For predictable iteration order: */
    Collections.sort(uniqueNames);
    Collections.shuffle(uniqueNames, rnd);
    return Collections.unmodifiableList(uniqueNames);
}

From source file:com.t3.model.Token.java

private CaseInsensitiveMap<String, Object> getPropertyMap() {
    if (propertyMap == null) {
        propertyMap = new CaseInsensitiveMap<String, Object>();
    }//from w  ww. ja  v  a 2s  .  c om
    return propertyMap;
}