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:ec.edu.chyc.manejopersonal.managebean.GestorArticulo.java

/**
 * Agrega la persona a la lista de autores solo si no existe
 * @param per Persona a agregar/*  www  . java  2 s .c o m*/
 */
private void agregarNuevoAutor(Persona per, String firmaSel) {
    boolean encontrado = false;
    //buscar si la persona ya se encuentra en la lista de autores
    for (PersonaArticulo perart : listaPersonaArticulo) {
        if (perart.getPersona().getId().equals(per.getId())) {
            encontrado = true;
            break;
        }
    }

    if (!encontrado) {
        //Agregar la nueva persona 
        PersonaArticulo perArt = new PersonaArticulo();
        perArt.setPersona(per);
        per.getListaFirmas().clear();
        int c = 0;

        //Obtener el objeto firma para indicar que el autor eligi la firma
        for (PersonaFirma perFirma : per.getPersonaFirmasCollection()) {
            if (firmaSel == null) { //Si no eligi una firma de la persona, usar la primera por defecto
                if (c == 0) {
                    perArt.setFirma(perFirma.getFirma());
                }
            } else if (StringUtils.equalsIgnoreCase(perFirma.getFirma().getNombre(), firmaSel)) { //Si la firma coincide con la seleccionada
                perArt.setFirma(perFirma.getFirma()); //usar esa firma
            }
            per.getListaFirmas().add(perFirma.getFirma());
            c++;
        }

        perArt.setId(idPersonaArticuloGen);

        //Si la persona no posee ninguna firma o la firma es nueva, crear nueva firma y asignarla a la persona
        if (firmaSel == null && perArt.getFirma() == null) {

            Firma firmaNueva = new Firma();
            firmaNueva.setId(idFirmaGen);
            firmaNueva.setNombre(per.getApellidos() + ", " + per.getNombres());

            PersonaFirma perFirmaNuevo = new PersonaFirma();
            perFirmaNuevo.setId(idPersonaFirmaGen);
            perFirmaNuevo.setPersona(per);
            perFirmaNuevo.setFirma(firmaNueva);

            perArt.setPersonaFirma(perFirmaNuevo);
            perArt.setPersona(per);
            perArt.setFirma(firmaNueva);

            per.getListaFirmas().add(perFirmaNuevo.getFirma());

            idPersonaFirmaGen--;
            idFirmaGen--;
        }

        listaPersonaArticulo.add(perArt);
        idPersonaArticuloGen--;
    }
}

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

/**
 * Parses an XML DOM element and loads it into a criteria.
 *
 * @param anElement DOM element./*from  w w  w .j  a  v  a  2  s  .  c  o m*/
 *
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    DataField dataField;
    String nodeName, nodeValue, logicalOperator;

    String className = mDSCriteria.getClass().getName();
    String attrValue = anElement.getAttribute("type");
    if ((StringUtils.isNotEmpty(attrValue)) && (!IO.isTypesEqual(attrValue, className)))
        throw new IOException("Unsupported type: " + attrValue);

    attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue))
        mDSCriteria.setName(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, "name"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "type")))
                continue;
            else
                mDSCriteria.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;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase(IO.XML_FIELD_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            dataField = mDataFieldXML.load(nodeElement);
            if (dataField != null) {
                logicalOperator = dataField.getFeature("operator");
                if (StringUtils.isEmpty(logicalOperator))
                    logicalOperator = Field.operatorToString(Field.Operator.EQUAL);
                mDSCriteria.add(dataField, Field.stringToOperator(logicalOperator));
            }
        }
    }
}

From source file:cgeo.geocaching.connector.oc.OCApiLiveConnector.java

@Override
public boolean isSearchForMyCaches(final String username) {
    return StringUtils.equalsIgnoreCase(username, getUserName());
}

From source file:ke.co.tawi.babblesms.server.sendsms.tawismsgw.PostSMS.java

/**
 * //  w ww  .  j a v  a2 s . c o m
 */
@Override
public void run() {
    HttpEntity responseEntity = null;
    Map<String, String> params;

    if (urlValidator.isValid(smsGateway.getUrl())) {

        // Prepare the parameters to send
        params = new HashMap<>();

        params.put("username", smsGateway.getUsername());
        params.put("password", smsGateway.getPasswd());
        params.put("source", smsSource.getSource());
        params.put("message", message);

        switch (smsSource.getNetworkuuid()) {
        case Network.SAFARICOM_KE:
            params.put("network", "safaricom_ke");
            break;

        case Network.AIRTEL_KE:
            params.put("network", "safaricom_ke"); // TODO: change to airtel_ke
            break;
        }

        // When setting the destination, numbers beginning with '07' are edited
        // to begin with '254'
        phoneMap = new HashMap<>();
        StringBuffer phoneBuff = new StringBuffer();
        String phoneNum;

        for (Phone phone : phoneList) {
            phoneNum = phone.getPhonenumber();

            if (StringUtils.startsWith(phoneNum, "07")) {
                phoneNum = "254" + StringUtils.substring(phoneNum, 1);
            }

            phoneMap.put(phoneNum, phone);
            phoneBuff.append(phoneNum).append(";");
        }

        params.put("destination", StringUtils.removeEnd(phoneBuff.toString(), ";"));

        // Push to the URL
        try {
            URL url = new URL(smsGateway.getUrl());

            if (StringUtils.equalsIgnoreCase(url.getProtocol(), "http")) {
                responseEntity = doPost(smsGateway.getUrl(), params, retry);

            }
            //            else if(StringUtils.equalsIgnoreCase(url.getProtocol(), "https")) {
            //               doPostSecure(smsGateway.getUrl(), params, retry);
            //            }

        } catch (MalformedURLException e) {
            logger.error("MalformedURLException for URL: '" + smsGateway.getUrl() + "'");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    } // end 'if(urlValidator.isValid(urlStr))'

    // Process the response from the SMS Gateway
    // Assuming all is ok, it would have the following pattern:
    // requestStatus=ACCEPTED&messageIds=254726176878:b265ce23;254728932844:367941a36d2e4ef195;254724300863:11fca3c5966d4d
    if (responseEntity != null) {

        OutgoingLog outgoingLog;

        try {
            String response = EntityUtils.toString(responseEntity);
            GatewayDAO.getInstance().logResponse(account, response, new Date());

            String[] strTokens = StringUtils.split(response, '&');
            String tmpStr = "", dateStr = "";
            for (String str : strTokens) {
                if (StringUtils.startsWith(str, "messageIds")) {
                    tmpStr = StringUtils.removeStart(str, "messageIds=");
                } else if (StringUtils.startsWith(str, "datetime")) {
                    dateStr = StringUtils.removeStart(str, "datetime=");
                }
            }

            strTokens = StringUtils.split(tmpStr, ';');
            String phoneStr, uuid;
            Phone phone;
            DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis();

            for (String str : strTokens) {
                phoneStr = StringUtils.split(str, ':')[0];
                uuid = StringUtils.split(str, ':')[1];
                phone = phoneMap.get(phoneStr);

                outgoingLog = new OutgoingLog();
                outgoingLog.setUuid(uuid);
                outgoingLog.setOrigin(smsSource.getSource());
                outgoingLog.setMessage(message);
                outgoingLog.setDestination(phone.getPhonenumber());
                outgoingLog.setNetworkUuid(phone.getNetworkuuid());
                outgoingLog.setMessagestatusuuid(MsgStatus.SENT);
                outgoingLog.setSender(account.getUuid());
                outgoingLog.setPhoneUuid(phone.getUuid());

                // Set the date of the OutgoingLog to match the SMS Gateway time

                LocalDateTime datetime = timeFormatter.parseLocalDateTime(dateStr);
                outgoingLog.setLogTime(datetime.toDate());

                outgoingLogDAO.put(outgoingLog);
            }

        } catch (ParseException e) {
            logger.error("ParseException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));

        } catch (IOException e) {
            logger.error("IOException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:com.glaf.base.modules.sys.springmvc.SendBaseDataController.java

@RequestMapping
public void sendMail(HttpServletRequest request) {
    SysUser login = RequestUtil.getLoginUser(request);
    if (login.isSystemAdmin()) {
        StringBuffer sb = new StringBuffer();
        JSONArray result = null;/* w  w w  .  ja  v  a2 s  .  c o  m*/
        SystemParam param = systemParamService.getSystemParam("sys_table");
        if (param != null && StringUtils.isNotEmpty(param.getTextVal())) {
            result = JSON.parseArray(param.getTextVal());
        }
        String dbType = request.getParameter("dbType");
        if (StringUtils.isNotEmpty(dbType) && result != null) {
            for (int index = 0, len = result.size(); index < len; index++) {
                JSONObject json = result.getJSONObject(index);
                String tablename = json.getString("tablename");
                if (StringUtils.isNotEmpty(tablename)) {
                    List<ColumnDefinition> columns = DBUtils.getColumnDefinitions(tablename);
                    TablePageQuery query = new TablePageQuery();
                    query.tableName(tablename);
                    query.firstResult(0);
                    query.maxResults(5000);
                    int count = tablePageService.getTableCount(query);
                    if (count <= 5000) {
                        List<Map<String, Object>> rows = tablePageService.getTableData(query);
                        if (rows != null && !rows.isEmpty()) {
                            for (Map<String, Object> dataMap : rows) {
                                Map<String, Object> lowerMap = QueryUtils.lowerKeyMap(dataMap);
                                sb.append(" insert into ").append(tablename).append(" (");
                                for (int i = 0, len2 = columns.size(); i < len2; i++) {
                                    ColumnDefinition column = columns.get(i);
                                    sb.append(column.getColumnName().toLowerCase());
                                    if (i < columns.size() - 1) {
                                        sb.append(", ");
                                    }
                                }
                                sb.append(" ) values (");
                                for (int i = 0, len2 = columns.size(); i < len2; i++) {
                                    ColumnDefinition column = columns.get(i);
                                    Object value = lowerMap.get(column.getColumnName().toLowerCase());
                                    if (value != null) {
                                        if (value instanceof Short) {
                                            sb.append(value);
                                        } else if (value instanceof Integer) {
                                            sb.append(value);
                                        } else if (value instanceof Long) {
                                            sb.append(value);
                                        } else if (value instanceof Double) {
                                            sb.append(value);
                                        } else if (value instanceof String) {
                                            String str = (String) value;
                                            str = StringTools.replace(str, "'", "''");
                                            sb.append("'").append(str).append("'");
                                        } else if (value instanceof Date) {
                                            Date date = (Date) value;
                                            if (StringUtils.equalsIgnoreCase(dbType, "oracle")) {
                                                sb.append(" to_date('").append(DateUtils.getDateTime(date))
                                                        .append("', 'yyyy-mm-dd hh24:mi:ss')");
                                            } else if (StringUtils.equalsIgnoreCase(dbType, "db2")) {
                                                sb.append(" TO_DATE('").append(DateUtils.getDateTime(date))
                                                        .append("', ''YYY-MM-DD HH24:MI:SS')");
                                            } else {
                                                sb.append("'").append(DateUtils.getDateTime(date)).append("'");
                                            }
                                        } else {
                                            String str = value.toString();
                                            str = StringTools.replace(str, "'", "''");
                                            sb.append("'").append(str).append("'");
                                        }
                                    } else {
                                        sb.append("null");
                                    }
                                    if (i < columns.size() - 1) {
                                        sb.append(", ");
                                    }
                                }
                                sb.append(");");
                                sb.append(FileUtils.newline);
                            }
                        }
                    }
                    sb.append(FileUtils.newline);
                    sb.append(FileUtils.newline);
                }
            }
        }
        if (sb.length() > 1000) {
            String mailTo = request.getParameter("mailTo");
            if (StringUtils.isNotEmpty(mailTo)) {
                MailMessage mailMessage = new MailMessage();
                mailMessage.setTo("mailTo");
                mailMessage.setSubject("sys_data");
                mailMessage.setContent(sb.toString());
                mailMessage.setSupportExpression(false);
                mailMessage.setSaveMessage(false);
                MailSender mailSender = ContextFactory.getBean("mailSender");
                try {
                    mailSender.send(mailMessage);
                } catch (Exception ex) {
                }
            }
        }
    }
}

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

/**
 * Parses an XML DOM element and loads it into a bag/table.
 *
 * @param anElement DOM element./*ww w .j  a v  a2  s  .c om*/
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    DataField dataField;
    String nodeName, nodeValue;

    String className = mBag.getClass().getName();
    String attrValue = anElement.getAttribute("type");
    if ((StringUtils.isNotEmpty(attrValue)) && (!IO.isTypesEqual(attrValue, className)))
        throw new IOException("Unsupported type: " + attrValue);

    attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue))
        mBag.setName(attrValue);
    attrValue = anElement.getAttribute("title");
    if (StringUtils.isNotEmpty(attrValue))
        mBag.setTitle(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, "name"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "type"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "count"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "title"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "version")))
                continue;
            else
                mBag.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;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase(IO.XML_FIELD_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            dataField = mDataFieldXML.load(nodeElement);
            if (dataField != null)
                mBag.add(dataField);
        }
    }
}

From source file:com.navercorp.lucy.security.xss.servletfilter.XssEscapeFilterConfig.java

/**
 * @param element Element/*from ww  w .j  a  v  a 2s . co  m*/
 * @return Map<String, XssEscapeFilterRule>
 */
private Map<String, XssEscapeFilterRule> createRequestParamRuleMap(Element element) {
    Map<String, XssEscapeFilterRule> urlRuleMap = new HashMap<String, XssEscapeFilterRule>();

    NodeList nodeList = element.getElementsByTagName("param");
    for (int i = 0; nodeList.getLength() > 0 && i < nodeList.getLength(); i++) {
        Element eachElement = (Element) nodeList.item(i);
        String name = eachElement.getAttribute("name");
        boolean useDefender = StringUtils.equalsIgnoreCase(eachElement.getAttribute("useDefender"), "false")
                ? false
                : true;
        boolean usePrefix = StringUtils.equalsIgnoreCase(eachElement.getAttribute("usePrefix"), "true") ? true
                : false;
        Defender defender = null;

        NodeList defenderNodeList = eachElement.getElementsByTagName("defender");
        if (defenderNodeList.getLength() > 0) {
            defender = defenderMap.get(defenderNodeList.item(0).getTextContent());

            if (defender == null) {
                LOG.error(
                        "Error config 'param defender': Not found '" + nodeList.item(0).getTextContent() + "'");
            }
        } else {
            defender = defaultDefender;
        }

        XssEscapeFilterRule urlRule = new XssEscapeFilterRule();
        urlRule.setName(name);
        urlRule.setUseDefender(useDefender);
        urlRule.setDefender(defender);
        urlRule.setUsePrefix(usePrefix);

        urlRuleMap.put(name, urlRule);
    }

    return urlRuleMap;
}

From source file:net.java.sip.communicator.plugin.propertieseditor.SearchField.java

/**
 * Runs in {@link #filterThread} to apply {@link #filter} to the displayed
 * <tt>ConfigurationService</tt> properties.
 *///from   w  w w  .j a  v  a2 s . c o  m
private void runInFilterThread() {
    String prevFilter = null;
    long prevFilterTime = 0;

    do {
        final String filter;

        synchronized (filterSyncRoot) {
            filter = this.filter;

            /*
             * If the currentThread is idle for too long (which also means
             * that the filter has not been changed), kill it because we do
             * not want to keep it alive forever.
             */
            if ((prevFilterTime != 0) && StringUtils.equalsIgnoreCase(filter, prevFilter)) {
                long timeout = FILTER_THREAD_TIMEOUT - (System.currentTimeMillis() - prevFilterTime);

                if (timeout > 0) {
                    // The currentThread has been idle but not long enough.
                    try {
                        filterSyncRoot.wait(timeout);
                        continue;
                    } catch (InterruptedException ie) {
                        // The currentThread will die bellow at the break.
                    }
                }
                // Commit suicide.
                if (Thread.currentThread().equals(filterThread))
                    filterThread = null;
                break;
            }
        }

        List<String> properties = confService.getAllPropertyNames();
        final List<Object[]> rows = new ArrayList<Object[]>(properties.size());

        for (String property : properties) {
            String value = (String) confService.getProperty(property);
            if ((filter == null) || StringUtils.containsIgnoreCase(property, filter)
                    || StringUtils.containsIgnoreCase(value, filter)) {
                rows.add(new Object[] { property, confService.getProperty(property) });
            }
        }

        // If in the meantime someone has changed the filter, we don't want
        // to update the GUI but filter the results again.
        if (StringUtils.equalsIgnoreCase(filter, this.filter)) {
            LowPriorityEventQueue.invokeLater(new Runnable() {
                public void run() {
                    DefaultTableModel model = (DefaultTableModel) table.getModel();

                    model.setRowCount(0);
                    for (Object[] row : rows) {
                        model.addRow(row);
                        if (filter != SearchField.this.filter)
                            return;
                    }
                }
            });
        }

        prevFilter = filter;
        prevFilterTime = System.currentTimeMillis();
    } while (true);
}

From source file:com.ottogroup.bi.spqr.websocket.kafka.KafkaTopicConsumer.java

public void initialize(final Map<String, String> settings) throws RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 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.get(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.get(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.get(CFG_OPT_KAFKA_ZOOKEEPER_SESSION_TIMEOUT);
    try {//  w  w  w  .j  a v a2 s  . c  o  m
        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.get(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.get(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.get(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.get(CFG_OPT_KAFKA_GROUP_ID);
    this.topic = settings.get(CFG_OPT_KAFKA_TOPIC);
    this.zookeeperConnect = settings.get(CFG_OPT_KAFKA_ZOOKEEPER_CONNECT);

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

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 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);

    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 + "]");

    // 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);
        executorService.submit(partitionConsumer);
        this.partitionConsumers.put("kafka-topic-" + topic, partitionConsumer);
    }
}

From source file:com.fbr.services.SecurityService.java

private boolean isUriTokenMatch(UserDbType userDbType, String uriToken, String givenUriToken,
        String beforeToken) {//from ww  w. ja v a  2s. co  m
    if (StringUtils.equalsIgnoreCase(uriToken, givenUriToken)) {
        return true;
    }

    if (uriToken.startsWith("{") && uriToken.endsWith("}")) {
        if (beforeToken != null && beforeToken.equalsIgnoreCase("company")) {
            return userService.validateCompanyId(userDbType, Integer.parseInt(givenUriToken));
        } else if (beforeToken != null && beforeToken.equalsIgnoreCase("branch")) {
            return userService.validateBranchId(userDbType, Integer.parseInt(givenUriToken));
        }
        logger.debug("Escaping the placeholder");
        return true;

    }
    return false;
}