Example usage for java.lang String compareToIgnoreCase

List of usage examples for java.lang String compareToIgnoreCase

Introduction

In this page you can find the example usage for java.lang String compareToIgnoreCase.

Prototype

public int compareToIgnoreCase(String str) 

Source Link

Document

Compares two strings lexicographically, ignoring case differences.

Usage

From source file:org.books.integration.AmazonCatalogBean.java

private boolean isMatching(String value, String matchingString) {
    if (value == null) {
        return false;
    }//from  w  w w.  j  a  va2s  . co m
    if (matchingString == null) {
        return true;
    }
    return value.compareToIgnoreCase(matchingString) == 0;
}

From source file:org.sipfoundry.openfire.vcard.provider.SipXVCardProvider.java

/**
 * Updates the vCard both in SipX and in the database.
 *//*from w ww  .  j  a  v a 2s.  c  o  m*/
@Override
public Element updateVCard(String username, Element vCardElement) {
    if (username.compareToIgnoreCase(PA_USER) == 0) {
        try {
            return defaultProvider.updateVCard(username, vCardElement);
        } catch (NotFoundException e) {
            e.printStackTrace();
            logger.error("update " + PA_USER + "'s vcard failed!");
            return null;
        }
    }

    try {
        defaultProvider.updateVCard(username, vCardElement);
    } catch (NotFoundException e) {
        try {
            defaultProvider.createVCard(username, vCardElement);
        } catch (AlreadyExistsException e1) {
            logger.error("Failed to create vcard due to existing vcard found");
            e1.printStackTrace();
        }
        e.printStackTrace();
    }

    try {
        String sipUserName = getAORFromJABBERID(username);
        if (sipUserName != null) {

            int attempts = 0;
            boolean tryAgain;
            do {
                tryAgain = false;
                try {
                    RestInterface.sendRequest(MODIFY_METHOD, vCardElement);
                } catch (ConnectException e) {
                    try {
                        Thread.sleep(ATTEMPT_INTERVAL);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    attempts++;
                    tryAgain = true;
                }
            } while (attempts < MAX_ATTEMPTS && tryAgain);

            if (attempts >= MAX_ATTEMPTS) {
                logger.error(
                        "Failed to update contact info for user " + username + ", sipXconfig might be down");
            }

            Element vcardAfterUpdate = cacheVCard(username);

            //If client doesn't set local avatar, use the avatar from sipx/gravatar.
            if (getAvatar(vCardElement) == null) {
                VCardManager.getInstance().reset();
                Util.updateAvatar(username, vcardAfterUpdate);
            }

            return vcardAfterUpdate;

        }
        logger.error("Failed to find a valid SIP account for user " + username);

        return vCardElement;
    }

    catch (Exception ex) {
        logger.error("updateVCard failed! " + ex.getMessage());
        return vCardElement;
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static Element createElement(Document doc, Element root, String name, String text, String sortAttribute,
        String sortValue) {/*from   w  ww .  ja va 2s  . co m*/

    if (name == null) {
        throw new XMLToolException("Element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Element name has to contain at least one character!");
    }

    Element elem = doc.createElement(name);
    if (text != null) {
        Text textNode = doc.createTextNode(StringUtil.getXMLSafeString(text));
        elem.appendChild(textNode);
    }

    if (sortAttribute == null || sortValue == null) {
        root.appendChild(elem);
    } else {
        Element[] childElems = getElements(root);
        if (childElems.length == 0) {
            root.appendChild(elem);
        } else {
            int i = 0;
            for (; i < childElems.length; i++) {
                String childValue = childElems[i].getAttribute(sortAttribute);
                if (childValue != null && childValue.compareToIgnoreCase(sortValue) >= 0) {
                    break;
                }
            }

            if (i < childElems.length) {
                root.insertBefore(elem, childElems[i]);
            } else {
                root.appendChild(elem);
            }
        }
    }

    return elem;
}

From source file:com.edgenius.wiki.render.handler.PageIndexHandler.java

public void renderStart(AbstractPage page) {
    if (page != null && page.getSpace() != null) {
        String spaceUname = page.getSpace().getUnixName();
        List<Page> pages = pageService.getPageTree(spaceUname);
        indexMap = new TreeMap<String, LinkModel>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                Character c1 = Character.toUpperCase(o1.charAt(0));
                Character c2 = Character.toUpperCase(o2.charAt(0));
                if (c1.equals(c2)) {
                    return o1.compareToIgnoreCase(o2);
                } else {
                    return c1.compareTo(c2);
                }//w  ww. j ava  2 s  .c  om

            }
        });
        indexer = new TreeMap<Character, Integer>(new Comparator<Character>() {
            public int compare(Character o1, Character o2) {
                return o1.compareTo(o2);
            }
        });
        Character indexKey = null;
        int indexAnchor = 1;
        for (Page pg : pages) {
            String title = pg.getTitle();
            if (StringUtils.isBlank(title)) {
                log.error("Blank title page found in {}", spaceUname);
                continue;
            }
            LinkModel link = new LinkModel();
            link.setLink(title);
            link.setType(LinkModel.LINK_TO_VIEW_FLAG);
            link.setSpaceUname(spaceUname);
            link.setView(title);
            indexMap.put(title, link);

            Character first = Character.toUpperCase(title.charAt(0));
            if (!first.equals(indexKey)) {
                indexKey = first;
                indexer.put(indexKey, indexAnchor++);
            }
        }

    }
}

From source file:org.obsidian.test.TestAbstract.java

public <T> void appendDynamicImports(Class<T> classToImport) {
    boolean shouldBeIgnored = false;

    //Make sure: not already in dynamic imports
    for (String s : getDynamicImports()) {
        if (s.compareToIgnoreCase(classToImport.getName().replaceAll("\\$", ".")) == 0) {
            shouldBeIgnored = true;//from   w  w  w .  j ava 2  s  . c  o  m
        }
    }

    if (!classToImport.isPrimitive() && !classToImport.isArray()) {
        //make sure: not in imports from constants
        for (String s : Content.IMPORTS) {
            if (s.compareToIgnoreCase(classToImport.getName()) == 0) {
                shouldBeIgnored = true;
            }

        }

        //make sure: not in same package
        if (classToImport.getPackage().toString()
                .compareToIgnoreCase(classTested.getPackage().toString()) == 0) {

            //#### Patch Submitted by Michael Cole (micole.3@gmail.com) 2/13/13
            if (!(classToImport.isMemberClass() || classToImport.isEnum() || classToImport.isLocalClass())) {
                shouldBeIgnored = true;
            }

        }

        //make sure not private
        if (Modifier.isPrivate(classToImport.getModifiers())) {
            shouldBeIgnored = true;
        }

        //make sure: not importing from java.lang unless at least 3 deep 
        //ex)java.lang.reflect
        String[] packageStructure = classToImport.getPackage().getName().split("\\.");
        int packageDepth = packageStructure.length;

        //if dataInputStream java.lang
        if (packageStructure[0].compareToIgnoreCase("java") == 0
                && packageStructure[1].compareToIgnoreCase("lang") == 0) {

            //and less than three deep
            if (packageDepth < 3) {
                shouldBeIgnored = true;
                classToImport.getName();
            }
        }
    } else {
        shouldBeIgnored = true;
        if (classToImport.isArray() && !classToImport.getComponentType().isPrimitive()) {
            appendDynamicImports(classToImport.getComponentType());
        }
    }

    //if: not already in imports and not in same package
    if (!shouldBeIgnored) {
        //add to dynamic imports
        String importName = classToImport.getName();
        importName = importName.replaceAll("\\$", ".");
        getDynamicImports().add(importName);
    }
}

From source file:org.etudes.mneme.impl.PoolStorageSample.java

/**
 * {@inheritDoc}/*from   w w w  . ja v a 2  s .  co m*/
 */
public List<PoolImpl> findPools(String context, final PoolService.FindPoolsSort sort) {
    fakeIt();

    List<PoolImpl> rv = new ArrayList<PoolImpl>();

    for (PoolImpl pool : this.pools.values()) {
        if ((!pool.historical) && (!pool.getMint()) && pool.getContext().equals(context)) {
            rv.add(clone(pool));
        }
    }

    // sort
    Collections.sort(rv, new Comparator() {
        public int compare(Object arg0, Object arg1) {
            int rv = 0;
            switch (sort) {
            case title_a:
            case title_d: {
                String s0 = StringUtil.trimToZero(((Pool) arg0).getTitle());
                String s1 = StringUtil.trimToZero(((Pool) arg1).getTitle());
                rv = s0.compareToIgnoreCase(s1);
                break;
            }
            case points_a:
            case points_d: {
                Float f0 = ((Pool) arg0).getPoints();
                if (f0 == null)
                    f0 = Float.valueOf(0f);
                Float f1 = ((Pool) arg1).getPoints();
                if (f1 == null)
                    f1 = Float.valueOf(0f);
                rv = f0.compareTo(f1);
                break;
            }
            }

            return rv;
        }
    });

    if ((sort == PoolService.FindPoolsSort.title_d) || (sort == PoolService.FindPoolsSort.points_d)) {
        Collections.reverse(rv);
    }

    return rv;
}

From source file:org.apache.synapse.transport.nhttp.ClientWorker.java

/**
 * Create the thread that would process the response message received for the outgoing message
 * context sent// w  ww. j a  v a2s . co  m
 * @param cfgCtx the Axis2 configuration context
 * @param in the InputStream to read the body of the response message received
 * @param response HTTP response received from the server
 * @param outMsgCtx the original outgoing message context (i.e. corresponding request)
 * @param endpointURLPrefix The endpoint URL prefix
 */
public ClientWorker(ConfigurationContext cfgCtx, InputStream in, HttpResponse response,
        MessageContext outMsgCtx, String endpointURLPrefix) {

    this.cfgCtx = cfgCtx;
    this.in = in;
    this.response = response;
    this.endpointURLPrefix = endpointURLPrefix;
    this.outMsgCtx = outMsgCtx;

    try {
        responseMsgCtx = outMsgCtx.getOperationContext().getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
        // fix for RM to work because of a soapAction and wsaAction conflict
        if (responseMsgCtx != null) {
            responseMsgCtx.setSoapAction("");
        }
    } catch (AxisFault af) {
        log.error("Error getting IN message context from the operation context", af);
        return;
    }

    // this conditional block is to support Sandesha, as it uses an out-in mep, but without
    // creating the message context to write the response and adding it into the operation
    // context, as it may get a 202 accepted or 200. So if the operation is complete ignore
    // this message, else, create a new message context and handle this
    if (responseMsgCtx == null && outMsgCtx.getOperationContext().isComplete()) {

        if (log.isDebugEnabled()) {
            log.debug("Error getting IN message context from the operation context. "
                    + "Possibly an RM terminate sequence message");
        }

    } else {
        if (responseMsgCtx == null) {
            responseMsgCtx = new MessageContext();
            responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
        }

        responseMsgCtx.setProperty(MessageContext.IN_MESSAGE_CONTEXT, outMsgCtx);
        responseMsgCtx.setServerSide(true);
        responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST());
        responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN,
                outMsgCtx.getProperty(MessageContext.TRANSPORT_IN));
        responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn());
        responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut());

        // set any transport headers received
        Header[] headers = response.getAllHeaders();
        if (headers != null && headers.length > 0) {

            Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() {
                public int compare(String o1, String o2) {
                    return o1.compareToIgnoreCase(o2);
                }
            });

            String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];

                // if this header is already added
                if (headerMap.containsKey(header.getName())) {
                    /* this is a multi-value header */
                    // generate the key
                    String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
                    // get the old value
                    String oldValue = headerMap.get(header.getName());
                    // adds additional values to a list in a property of
                    // message context
                    Map map;
                    if (responseMsgCtx.getProperty(key) != null) {
                        map = (Map) responseMsgCtx.getProperty(key);
                        map.put(header.getName(), oldValue);
                    } else {
                        map = new MultiValueMap();
                        map.put(header.getName(), oldValue);
                        // set as a property in message context
                        responseMsgCtx.setProperty(key, map);
                    }

                }

                if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) {
                    //Here, we are changing only the host name and the port of the new URI - value of the Location
                    //header.
                    //If the new URI is again referring to a resource in the server to which the original request
                    //is sent, then replace the hostname and port of the URI with the hostname and port of synapse
                    //We are not changing the request url here, only the host name and the port.
                    try {
                        URI serviceURI = new URI(servicePrefix);
                        URI endpointURI = new URI(endpointURLPrefix);
                        URI locationURI = new URI(header.getValue());

                        if ((locationURI.getHost().equalsIgnoreCase(endpointURI.getHost()))
                                && (locationURI.getPort() == endpointURI.getPort())) {
                            URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(),
                                    serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(),
                                    locationURI.getQuery(), locationURI.getFragment());
                            headerMap.put(header.getName(), newURI.toString());
                            responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX,
                                    outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX));
                        } else {
                            headerMap.put(header.getName(), header.getValue());
                        }
                    } catch (URISyntaxException e) {
                        log.error(e.getMessage(), e);
                    }
                } else {
                    headerMap.put(header.getName(), header.getValue());
                }
            }
            responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
        }

        responseMsgCtx.setAxisMessage(outMsgCtx.getOperationContext().getAxisOperation()
                .getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
        responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
        responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext());
        responseMsgCtx.setTo(null);

        // Ensure MessageContext has a ClientConnectionDebug attached before we start streaming
        ClientConnectionDebug cd = (ClientConnectionDebug) outMsgCtx
                .getProperty(ClientHandler.CLIENT_CONNECTION_DEBUG);
        if (cd != null) {
            responseMsgCtx.setProperty(ClientHandler.CLIENT_CONNECTION_DEBUG, cd);
        }
    }
    setServerContextAttribute(NhttpConstants.CLIENT_WORKER_INIT_TIME, System.currentTimeMillis(), outMsgCtx);
}

From source file:sim.app.sugarscape.util.ResultsGrapher.java

public void loadConfigFile(String config) {
    try {/*www . j  a  v a  2 s .co  m*/
        File f = new File(config);
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        String line;// = br.readLine();
        String var = null;
        while ((line = br.readLine()) != null) {
            if ((line.startsWith("#")) || (line.startsWith("//"))) {
                continue;
            } //ignore comment lines
            StringTokenizer st0 = new StringTokenizer(line, "=");
            String axis = st0.nextToken();
            String field_name = st0.nextToken();
            if (axis.compareToIgnoreCase("x_axis") == 0) {
                x_axis_fieldname = field_name;
            } else if (axis.compareToIgnoreCase("y_axis") == 0) {
                y_axis_fieldname = field_name;
            } else if (axis.compareToIgnoreCase("x_param") == 0) {
                x_param_fieldname = field_name;
            }
            //StringTokenizer st = new StringTokenizer(line,",");
        }

        //System.out.println(line);

        if ((x_axis_fieldname == null) || (y_axis_fieldname == null) || (x_param_fieldname == null)) {
            System.out.println("Missing field in configuration file!");
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.out.println("Finished loading config file.");
}

From source file:com.quinsoft.zeidon.domains.StringDomain.java

/**
 * StringDomain needs to override compare() because it potentially needs to convert empty strings ("") to
 * null before doing the comparison./*from  w ww  .  j  a  va2 s  .co m*/
 */
@Override
public int compare(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef,
        Object internalValue, Object externalValue) {
    Object value = convertExternalValue(task, attributeInstance, attributeDef, null, externalValue);
    String s1 = checkNullString(internalValue);
    String s2 = checkNullString(value);

    Integer rc = compareNull(task, attributeDef, s1, s2);
    if (rc != null)
        return rc;

    int c = 0;

    if (attributeDef.isCaseSensitive())
        c = s1.compareTo(s2);
    else
        c = s1.compareToIgnoreCase(s2);

    if (c < 0)
        return -1;
    if (c > 0)
        return 1;
    return 0;
}

From source file:de.hybris.platform.webservices.paging.impl.QueryPagingStrategy.java

/**
 * Returns page context if query parameters and collection property name suit each other. If not, the null is
 * returned./*from   w  ww.ja v  a 2 s .  c o m*/
 * <p/>
 * 
 * @param collectionPropertyName
 *           The Name of the collection property.
 * @param queryParams
 *           Query parameters which comes from requested URL.
 * 
 * @return page context if query parameters and collection property name suit each other. If not, the null is
 *         returned.
 */
@Override
public PageInfoCtx findPageContext(final String collectionPropertyName,
        final Map<String, List<String>> queryParams) {
    PageInfoCtx result = null;
    if (queryParams != null) {
        //Nice trick: using TreeMap with case-insensitive comparator gives a case-insensitive Map!
        final Map<String, Collection<String>> caseInsensitiveMap = new TreeMap<String, Collection<String>>(
                new Comparator<String>() {
                    @Override
                    public int compare(final String object1, final String object2) {
                        return object1.compareToIgnoreCase(object2);
                    }
                });
        caseInsensitiveMap.putAll(queryParams);

        final String _page = findParameter(caseInsensitiveMap, collectionPropertyName, "page");
        final String _size = findParameter(caseInsensitiveMap, collectionPropertyName, "size");
        final String _sort = findParameter(caseInsensitiveMap, collectionPropertyName, "sort");

        final String _query = findParameter(caseInsensitiveMap, collectionPropertyName, "query");
        final String _subtypes = findParameter(caseInsensitiveMap, collectionPropertyName, "subtypes");

        if (_page != null || _size != null || _sort != null || _query != null || _subtypes != null) {
            Integer page = null;
            Integer size = null;

            try {
                page = _page != null ? Integer.valueOf(_page) : Integer.valueOf(0);
                size = _size != null ? Integer.valueOf(_size)
                        : Integer.valueOf(Config.getInt("webservices.paging.default_page_size",
                                PageInfoCtx.DEFAULT_PAGE_SIZE.intValue()));
            } catch (final NumberFormatException nfe) {
                throw new BadRequestException("Query parameter [" + collectionPropertyName + "_page or "
                        + collectionPropertyName + "_size] has inappropriate value!", nfe);
            }

            final boolean subtypes = _subtypes != null ? Boolean.parseBoolean(_subtypes)
                    : PageInfoCtx.DEFAULT_SUBTYPES;
            result = new PageInfoCtx(page, size, _sort, _query, subtypes);
            result.setCollectionPropertyName(collectionPropertyName);
        }
    }

    return result;
}