Example usage for org.apache.commons.lang3 StringUtils equalsIgnoreCase

List of usage examples for org.apache.commons.lang3 StringUtils equalsIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils equalsIgnoreCase.

Prototype

public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) 

Source Link

Document

Compares two CharSequences, returning true if they represent equal sequences of characters, ignoring case.

null s are handled without exceptions.

Usage

From source file:com.nridge.core.base.io.xml.DocumentReplyXML.java

/**
 * Parses an XML DOM element and loads it into a document list.
 *
 * @param anElement DOM element.//from  ww w. j a v a2s.  c  o m
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Attr nodeAttr;
    Node nodeItem;
    Document document;
    Element nodeElement;
    DocumentXML documentXML;
    String nodeName, nodeValue;

    nodeName = anElement.getNodeName();
    if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_REPLY_NODE_NAME)) {
        mField.clearFeatures();
        String attrValue = anElement.getAttribute(Doc.FEATURE_OP_STATUS_CODE);
        if (StringUtils.isNotEmpty(attrValue)) {
            mField.setName(Doc.FEATURE_OP_STATUS_CODE);
            mField.setValue(attrValue);
            NamedNodeMap namedNodeMap = anElement.getAttributes();
            int attrCount = namedNodeMap.getLength();
            for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
                nodeAttr = (Attr) namedNodeMap.item(attrOffset);
                nodeName = nodeAttr.getNodeName();
                nodeValue = nodeAttr.getNodeValue();

                if (StringUtils.isNotEmpty(nodeValue)) {
                    if ((!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_STATUS_CODE))
                            && (!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_COUNT)))
                        mField.addFeature(nodeName, nodeValue);
                }
            }
        }
        NodeList nodeList = anElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodeItem = nodeList.item(i);

            if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
                continue;

            // We really do not know how the node was named, so we will just accept it.

            nodeElement = (Element) nodeItem;
            documentXML = new DocumentXML();
            documentXML.load(nodeElement);
            document = documentXML.getDocument();
            if (document != null)
                mDocumentList.add(document);
        }
    }
}

From source file:com.nike.cerberus.module.CerberusModule.java

private Optional<String> findBucket(final String environmentName) {
    AmazonS3Client s3Client = new AmazonS3Client();
    List<Bucket> buckets = s3Client.listBuckets();

    String envBucket = null;//  w ww  .  java2s  . co  m
    for (final Bucket bucket : buckets) {
        if (StringUtils.contains(bucket.getName(), ConfigConstants.CONFIG_BUCKET_KEY)) {
            String[] parts = bucket.getName().split("-");
            if (StringUtils.equalsIgnoreCase(environmentName, parts[0])) {
                envBucket = bucket.getName();
                break;
            }
        }
    }

    return Optional.ofNullable(envBucket);
}

From source file:com.ottogroup.bi.spqr.operator.kafka.source.KafkaTopicSource.java

/**
 * @see com.ottogroup.bi.spqr.pipeline.component.MicroPipelineComponent#initialize(java.util.Properties)
 *//*from  ww w .  j  a v  a 2  s  .  c  o m*/
public void initialize(Properties settings)
        throws RequiredInputMissingException, ComponentInitializationFailedException {

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    // extract data required for setting up a consumer from configuration 

    // read out auto offset reset type and check if it contains a valid value, otherwise reset to 'LARGEST'
    this.autoOffsetResetType = settings.getProperty(CFG_OPT_KAFKA_AUTO_OFFSET_RESET);
    if (!StringUtils.equalsIgnoreCase(this.autoOffsetResetType, KAFKA_AUTO_OFFSET_RESET_TYPE_LARGEST)
            && !StringUtils.equalsIgnoreCase(this.autoOffsetResetType, KAFKA_AUTO_OFFSET_RESET_TYPE_SMALLEST))
        this.autoOffsetResetType = KAFKA_AUTO_OFFSET_RESET_TYPE_LARGEST;

    // read out value indicating whether auto commit is enabled or not and validate it for 'true' or 'false' --> otherwise set to default 'true'
    this.autoCommitEnabled = settings.getProperty(CFG_OPT_KAFKA_ZOOKEEPER_AUTO_COMMIT_ENABLED);
    if (!StringUtils.equalsIgnoreCase(this.autoCommitEnabled, "true")
            && !StringUtils.equalsIgnoreCase(this.autoCommitEnabled, "false"))
        this.autoCommitEnabled = "true";

    // check if the provided session timeout is a valid number --> otherwise reset to default '6000' 
    this.zookeeperSessionTimeout = settings.getProperty(CFG_OPT_KAFKA_ZOOKEEPER_SESSION_TIMEOUT);
    try {
        long longVal = Long.parseLong(this.zookeeperSessionTimeout);
        if (longVal < 1) {
            logger.info("Found invalid session timeout value '" + this.zookeeperSessionTimeout
                    + "'. Resetting to '6000'");
            this.zookeeperSessionTimeout = "6000";
        }
    } catch (Exception e) {
        logger.info("Found invalid session timeout value '" + this.zookeeperSessionTimeout
                + "'. Resetting to '6000'");
        this.zookeeperSessionTimeout = "6000";
    }

    // check if the provided sync interval is a valid number --> otherwise reset to default '2000'
    this.zookeeperSyncInterval = settings.getProperty(CFG_OPT_KAFKA_ZOOKEEPER_SYNC_INTERVAL);
    try {
        long longVal = Long.parseLong(this.zookeeperSyncInterval);
        if (longVal < 1) {
            logger.info("Found invalid session sync interval '" + this.zookeeperSyncInterval
                    + "'. Resetting to '2000'");
            this.zookeeperSyncInterval = "2000";
        }
    } catch (Exception e) {
        logger.info("Found invalid session sync interval '" + this.zookeeperSyncInterval
                + "'. Resetting to '2000'");
        this.zookeeperSyncInterval = "2000";
    }

    // check if the provided auto commit interval is a valid number --> otherwise reset to default '60 * 1000'
    this.autoCommitInterval = settings.getProperty(CFG_OPT_KAFKA_ZOOKEEPER_AUTO_COMMIT_INTERVAL);
    try {
        long longVal = Long.parseLong(this.autoCommitInterval);
        if (longVal < 1) {
            logger.info("Found invalid auto commit interval '" + this.autoCommitInterval
                    + "'. Resetting to '60000'");
            this.autoCommitInterval = "60000";
        }
    } catch (Exception e) {
        logger.info(
                "Found invalid auto commit interval '" + this.autoCommitInterval + "'. Resetting to '60000'");
        this.autoCommitInterval = "60000";
    }

    String numOfThreadsStr = settings.getProperty(CFG_OPT_KAFKA_NUM_THREADS);
    try {
        this.numOfThreads = Integer.parseInt(numOfThreadsStr);
    } catch (Exception e) {
        logger.info("Found invalid number of partitions '" + numOfThreadsStr + "'. Resetting to '60000'");
    }
    if (this.numOfThreads < 1)
        this.numOfThreads = 5;

    this.groupId = settings.getProperty(CFG_OPT_KAFKA_GROUP_ID);
    this.topic = settings.getProperty(CFG_OPT_KAFKA_TOPIC);
    this.zookeeperConnect = settings.getProperty(CFG_OPT_KAFKA_ZOOKEEPER_CONNECT);

    if (StringUtils.isBlank(groupId))
        throw new RequiredInputMissingException("Missing required input for '" + CFG_OPT_KAFKA_GROUP_ID + "'");
    if (StringUtils.isBlank(topic))
        throw new RequiredInputMissingException("Missing required input for '" + CFG_OPT_KAFKA_TOPIC + "'");
    if (StringUtils.isBlank(zookeeperConnect))
        throw new RequiredInputMissingException(
                "Missing required input for '" + CFG_OPT_KAFKA_ZOOKEEPER_CONNECT + "'");

    int internalQueueCapacity = 8192;
    try {
        internalQueueCapacity = Integer.parseInt(settings.getProperty(CFG_OPT_KAFKA_SOURCE_QUEUE_CAPACITY));
    } catch (Exception e) {
        logger.info("Found invalid internal queue capacity. Resetting to 8192");
        internalQueueCapacity = 8192;
    }
    if (internalQueueCapacity < 1)
        internalQueueCapacity = 8192;

    //
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    // establish connection with kafka

    Properties props = new Properties();
    props.put(KAFKA_CONN_PARAM_ZK_CONNECT, this.zookeeperConnect);
    props.put(KAFKA_CONN_PARAM_ZK_SESSION_TIMEOUT, this.zookeeperSessionTimeout);
    props.put(KAFKA_CONN_PARAM_ZK_SYNC_INTERVAL, this.zookeeperSyncInterval);
    props.put(KAFKA_CONN_PARAM_GROUP_ID, this.groupId);
    props.put(KAFKA_CONN_PARAM_AUTO_COMMIT_INTERVAL, this.autoCommitInterval);
    props.put(KAFKA_CONN_PARAM_AUTO_OFFSET_RESET, this.autoOffsetResetType);
    props.put(KAFKA_CONN_PARAM_AUTO_COMMIT_ENABLED, this.autoCommitEnabled);

    if (logger.isDebugEnabled())
        logger.debug("kafkaSource[group=" + this.groupId + ", topic=" + this.topic + ", zk="
                + this.zookeeperConnect + ", zkTimeout=" + this.zookeeperSessionTimeout + ", zkSync="
                + this.zookeeperSyncInterval + ", autoCommit=" + this.autoCommitEnabled + ", commitInterval="
                + this.autoCommitInterval + ", commitReset=" + this.autoOffsetResetType + "]");

    ConsumerConfig consumerConfig = new ConsumerConfig(props);
    this.kafkaConsumerConnector = Consumer.createJavaConsumerConnector(consumerConfig);

    // get access to topic streams
    Map<String, Integer> topicCountMap = new HashMap<>();
    topicCountMap.put(this.topic, this.numOfThreads);
    Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = this.kafkaConsumerConnector
            .createMessageStreams(topicCountMap);

    // receive topic streams, each entry holds a single partition
    List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(this.topic);
    if (streams == null || streams.isEmpty())
        throw new RuntimeException("Failed to establish connection with kafka topic [zkConnect="
                + this.zookeeperConnect + ", topic=" + this.topic + "]");

    // create a fixed thread pool which has capacity for number of available streams 
    this.executorService = Executors.newFixedThreadPool(streams.size());

    this.messages = new OneToOneConcurrentArrayQueue3<byte[]>(internalQueueCapacity);
    this.messageWaitStrategy = new BlockingWaitStrategy();

    // iterate through streams and assign each to a partition reader
    for (KafkaStream<byte[], byte[]> kafkaStream : streams) {

        if (kafkaStream == null)
            throw new RuntimeException("Found null entry in list of kafka streams [zkConnect="
                    + this.zookeeperConnect + ", topic=" + this.topic + "]");

        KafkaTopicStreamConsumer partitionConsumer = new KafkaTopicStreamConsumer(kafkaStream, this.messages,
                this.messageWaitStrategy);
        this.executorService.submit(partitionConsumer);
        this.partitionConsumers.put("kafka-topic-" + topic, partitionConsumer);
    }

    this.isRunning = true;
}

From source file:com.mnxfst.stream.pipeline.PipelineRoot.java

/**
 * Shuts down the pipeline if the reference provided in the message is the same as
 * the one carried by the pipeline root//from  w ww  . j  ava 2 s.  c om
 * @param msg
 */
protected void shutdown(final PipelineShutdownMessage msg) {
    if (StringUtils.equalsIgnoreCase(msg.getPipelineId(), this.pipelineConfiguration.getPipelineId())) {
        for (final ActorRef elementRef : this.pipelineElements.values()) {
            context().stop(elementRef);
        }
    }
}

From source file:com.nridge.core.ds.io.xml.DataSourceXML.java

/**
 * Parses an XML DOM element and loads it into the document.
 *
 * @param anElement DOM element./*from www .  j  av  a2 s . com*/
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    String nodeName;
    DataBag dataBag;
    Element nodeElement;
    DataField dataField;
    DataTable dataTable;
    DataBagXML dataBagXML;
    DSCriteria dsCriteria;
    Document relatedDocument;
    DSCriteriaXML dsCriteriaXML;
    Relationship docRelationship;
    Logger appLogger = mAppMgr.getLogger(this, "load");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    String typeName = anElement.getAttribute("type");
    if (StringUtils.isNotEmpty(typeName))
        mDocument.setType(typeName);
    String docName = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(typeName))
        mDocument.setName(docName);
    String docTitle = anElement.getAttribute("title");
    if (StringUtils.isNotEmpty(typeName))
        mDocument.setTitle(docTitle);

    DataFieldXML dataFieldXML = new DataFieldXML();
    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (StringUtils.equalsIgnoreCase(nodeName, "Field")) {
            nodeElement = (Element) nodeItem;
            dataField = dataFieldXML.load(nodeElement);
            if (dataField != null) {
                dataBag = mDocument.getBag();
                dataBag.add(dataField);
            }
        } else if (StringUtils.equalsIgnoreCase(nodeName, DS.RELATIONSHIP_CONFIGURATION)) {
            nodeElement = (Element) nodeItem;
            dataBagXML = new DataBagXML();
            dataBagXML.load(nodeElement);
            dataBag = dataBagXML.getBag();
            if (dataBag.count() > 0) {
                docRelationship = new Relationship(DS.RELATIONSHIP_CONFIGURATION, dataBag);
                mDocument.addRelationship(docRelationship);
            }
        } else if (StringUtils.equalsIgnoreCase(nodeName, DS.RELATIONSHIP_SCHEMA)) {
            nodeElement = (Element) nodeItem;
            dataBagXML = new DataBagXML();
            dataBagXML.load(nodeElement);
            dataBag = dataBagXML.getBag();
            if (dataBag.count() > 0) {
                if (StringUtils.isEmpty(dataBag.getName()))
                    dataBag.setName(mDocument.getName());
                {
                    docRelationship = new Relationship(DS.RELATIONSHIP_SCHEMA, dataBag);
                    mDocument.addRelationship(docRelationship);
                }
            }
        } else if (StringUtils.equalsIgnoreCase(nodeName, DS.RELATIONSHIP_VALUES)) {
            nodeElement = (Element) nodeItem;
            dataBagXML = new DataBagXML();
            dataBagXML.load(nodeElement);
            dataBag = dataBagXML.getBag();
            if (dataBag.count() > 0) {
                docRelationship = new Relationship(DS.RELATIONSHIP_VALUES, dataBag);
                mDocument.addRelationship(docRelationship);
            }
        } else if (StringUtils.equalsIgnoreCase(nodeName, DS.RELATIONSHIP_CRITERIA)) {
            nodeElement = (Element) nodeItem;
            dsCriteriaXML = new DSCriteriaXML();
            dsCriteriaXML.load(nodeElement);
            dsCriteria = dsCriteriaXML.getCriteria();
            if (dsCriteria.count() > 0) {
                dataTable = dsCriteria.toTable();
                relatedDocument = new Document(DS.RELATIONSHIP_CRITERIA, dataTable);
                mDocument.addRelationship(relatedDocument.getType(), relatedDocument);
            }
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.inkubator.hrm.web.approval.ApprovalDefinitionFormController.java

public void onAppoverChange() {
    String apporverType = approvalDefinitionModel.getApproverType();
    if (StringUtils.equalsIgnoreCase(apporverType, HRMConstant.APPROVAL_TYPE_INDIVIDUAL)) {
        approverTypeIndividual = Boolean.FALSE;
        approverTypePosition = Boolean.TRUE;
        approverTypeDepartment = Boolean.TRUE;

    }//from w w w .  j  a  v a 2 s . c om
    if (StringUtils.equalsIgnoreCase(apporverType, HRMConstant.APPROVAL_TYPE_DEPARTMENT)) {
        approverTypeIndividual = Boolean.TRUE;
        approverTypePosition = Boolean.TRUE;
        approverTypeDepartment = Boolean.FALSE;
    }

    if (StringUtils.equalsIgnoreCase(apporverType, HRMConstant.APPROVAL_TYPE_POSITION)) {
        approverTypeIndividual = Boolean.TRUE;
        approverTypePosition = Boolean.FALSE;
        approverTypeDepartment = Boolean.TRUE;
    }

    approvalDefinitionModel.setHrmUserByApproverIndividualId(null);
    approvalDefinitionModel.setHrmUserByApproverIndividualName("");
    approvalDefinitionModel.setJabatanByApproverPositionId(null);
    approvalDefinitionModel.setJabatanByApproverPositionName("");
}

From source file:com.nridge.core.base.io.xml.DocumentXML.java

private void loadRelated(Document aDocument, Element anElement) throws IOException {
    Node nodeItem;// w  w w  .j a  v a 2  s .co  m
    String nodeName;
    Element nodeElement;
    RelationshipXML relationshipXML;

    ArrayList<Relationship> docRelationships = aDocument.getRelationships();
    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
            nodeName = nodeItem.getNodeName();
            if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_RELATIONSHIP_NODE_NAME)) {
                nodeElement = (Element) nodeItem;
                relationshipXML = new RelationshipXML();
                relationshipXML.load(nodeElement);
                docRelationships.add(relationshipXML.getRelationship());
            }
        }
    }
}

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  ww .  ja va2  s . c  o m
    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:io.wcm.maven.plugins.i18n.TransformMojo.java

/**
 * Get i18n reader for source file.//from  w  w w  . j a v a 2s . co  m
 * @param sourceFile Source file
 * @return I18n reader
 * @throws MojoFailureException
 */
private I18nReader getI18nReader(File sourceFile) throws MojoFailureException {
    String extension = FileUtils.getExtension(sourceFile.getName());
    if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_PROPERTIES)) {
        return new PropertiesI18nReader();
    }
    if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_XML)) {
        return new XmlI18nReader();
    }
    if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_JSON)) {
        return new JsonI18nReader();
    }
    throw new MojoFailureException(
            "Unsupported file extension '" + extension + "': " + sourceFile.getAbsolutePath());
}

From source file:ec.edu.chyc.manejopersonal.managebean.GestorArticulo.java

/**
 * Agrega la firma de la persona vaca al listado de autores
 * @param personaVacia Entidad que contiene la persona sin datos pero con firmas de desconocidos
 * @param firma firma a agregarse//  w  w  w .j a  va2 s  . co  m
 */
private boolean agregarFirmaSinAutor(Persona personaVacia, String strNuevaFirma) {
    boolean encontrado = false;
    for (PersonaArticulo perart : listaPersonaArticulo) {
        //revisar si ya existe la persona y la firma en la lista de autores
        if (perart.getPersona().getId().equals(personaVacia.getId())
                && StringUtils.equalsIgnoreCase(perart.getFirma().getNombre(), strNuevaFirma)) {
            encontrado = true;
            break;
        }
    }
    if (!encontrado) {
        PersonaFirma personaFirmaUsar = null;
        for (PersonaFirma perFirma : personaVacia.getPersonaFirmasCollection()) {
            //revisar si ya existe la firma que se va a ingresar en la lista de firmas de la personavacia
            if (StringUtils.equalsIgnoreCase(perFirma.getFirma().getNombre(), strNuevaFirma)) {
                personaFirmaUsar = perFirma;
                break;
            }
        }

        if (personaFirmaUsar == null) {
            //si la firma no pertenece a la personavacia es porque es una nueva firma no existente en la base de datos, 
            // por lo tanto hay que crear una nueva firma para agregarla
            Firma nuevaFirma = new Firma();
            nuevaFirma.setNombre(strNuevaFirma);
            nuevaFirma.setId(idFirmaGen);

            idFirmaGen--;

            PersonaFirma nuevaPersonaFirma = new PersonaFirma();
            nuevaPersonaFirma.setFirma(nuevaFirma);
            nuevaPersonaFirma.setId(idPersonaFirmaGen);
            nuevaPersonaFirma.setPersona(personaVacia);

            idPersonaFirmaGen--;

            personaFirmaUsar = nuevaPersonaFirma;
        }

        PersonaArticulo perArt = new PersonaArticulo();
        perArt.setPersona(personaVacia);
        perArt.setFirma(personaFirmaUsar.getFirma());
        perArt.setPersonaFirma(personaFirmaUsar);
        perArt.setId(idPersonaArticuloGen);

        personaVacia.getPersonaFirmasCollection().add(personaFirmaUsar);
        listaPersonaArticulo.add(perArt);
        idPersonaArticuloGen--;
        return true;
    }
    return false;
}