Example usage for java.text Collator getInstance

List of usage examples for java.text Collator getInstance

Introduction

In this page you can find the example usage for java.text Collator getInstance.

Prototype

public static synchronized Collator getInstance() 

Source Link

Document

Gets the Collator for the current default locale.

Usage

From source file:com.xerox.amazonws.common.AWSQueryConnection.java

/**
 * Make a http request and process the response. This method also performs automatic retries.
*
 * @param method The HTTP method to use (GET, POST, DELETE, etc)
 * @param action the name of the action for this query request
 * @param params map of request params//from  w w  w . j ava  2 s .c  o  m
 * @param respType the class that represents the desired/expected return type
 */
protected <T> T makeRequest(HttpMethodBase method, String action, Map<String, String> params, Class<T> respType)
        throws HttpException, IOException, JAXBException {

    // add auth params, and protocol specific headers
    Map<String, String> qParams = new HashMap<String, String>(params);
    qParams.put("Action", action);
    qParams.put("AWSAccessKeyId", getAwsAccessKeyId());
    qParams.put("SignatureVersion", "" + sigVersion);
    qParams.put("Timestamp", httpDate());
    if (headers != null) {
        for (Iterator<String> i = headers.keySet().iterator(); i.hasNext();) {
            String key = i.next();
            for (Iterator<String> j = headers.get(key).iterator(); j.hasNext();) {
                qParams.put(key, j.next());
            }
        }
    }
    // sort params by key
    ArrayList<String> keys = new ArrayList<String>(qParams.keySet());
    Collator stringCollator = Collator.getInstance();
    stringCollator.setStrength(Collator.PRIMARY);
    Collections.sort(keys, stringCollator);

    // build param string
    StringBuilder resource = new StringBuilder();
    if (sigVersion == 0) { // ensure Action, Timestamp come first!
        resource.append(qParams.get("Action"));
        resource.append(qParams.get("Timestamp"));
    } else {
        for (String key : keys) {
            resource.append(key);
            resource.append(qParams.get(key));
        }
    }

    // calculate signature
    String encoded = urlencode(encode(getSecretAccessKey(), resource.toString(), false));

    // build param string, encoding values and adding request signature
    resource = new StringBuilder();
    for (String key : keys) {
        resource.append("&");
        resource.append(key);
        resource.append("=");
        resource.append(urlencode(qParams.get(key)));
    }
    resource.setCharAt(0, '?'); // set first param delimeter
    resource.append("&Signature=");
    resource.append(encoded);

    // finally, build request object
    URL url = makeURL(resource.toString());
    method.setURI(new URI(url.toString(), true));
    method.setRequestHeader(new Header("User-Agent", userAgent));
    if (sigVersion == 0) {
        method.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
    }
    Object response = null;
    boolean done = false;
    int retries = 0;
    boolean doRetry = false;
    String errorMsg = "";
    do {
        int responseCode = 600; // default to high value, so we don't think it is valid
        try {
            responseCode = getHttpClient().executeMethod(method);
        } catch (SocketException ex) {
            // these can generally be retried. Treat it like a 500 error
            doRetry = true;
            errorMsg = ex.getMessage();
        }
        // 100's are these are handled by httpclient
        if (responseCode < 300) {
            // 200's : parse normal response into requested object
            if (respType != null) {
                InputStream iStr = method.getResponseBodyAsStream();
                response = JAXBuddy.deserializeXMLStream(respType, iStr);
            }
            done = true;
        } else if (responseCode < 400) {
            // 300's : what to do?
            throw new HttpException("redirect error : " + responseCode);
        } else if (responseCode < 500) {
            // 400's : parse client error message
            String body = getStringFromStream(method.getResponseBodyAsStream());
            throw new HttpException("Client error : " + getErrorDetails(body));
        } else if (responseCode < 600) {
            // 500's : retry...
            doRetry = true;
            String body = getStringFromStream(method.getResponseBodyAsStream());
            errorMsg = getErrorDetails(body);
        }
        if (doRetry) {
            retries++;
            if (retries > maxRetries) {
                throw new HttpException("Number of retries exceeded : " + action + ", " + errorMsg);
            }
            doRetry = false;
            try {
                Thread.sleep((int) Math.pow(2.0, retries) * 1000);
            } catch (InterruptedException ex) {
            }
        }
    } while (!done);
    return (T) response;
}

From source file:android.database.DatabaseUtils.java

private static byte[] getCollationKeyInBytes(String name) {
    if (mColl == null) {
        mColl = Collator.getInstance();
        mColl.setStrength(Collator.PRIMARY);
    }/*from   ww w. java2  s  .  co m*/
    return mColl.getCollationKey(name).toByteArray();
}

From source file:br.com.ingenieux.mojo.beanstalk.AbstractBeanstalkMojo.java

protected String lookupSolutionStack(final String solutionStack) {
    if (!hasWildcards(solutionStack)) {
        return solutionStack;
    }//from   w w w.j  a  v  a2s  .c  om

    getLog().info("Looking up for solution stacks matching '" + solutionStack + "'");

    final Function<SolutionStackDescription, String> stackTransformer = new Function<SolutionStackDescription, String>() {
        @Override
        public String apply(SolutionStackDescription input) {
            return input.getSolutionStackName();
        }
    };
    final List<SolutionStackDescription> stackDetails = getService().listAvailableSolutionStacks()
            .getSolutionStackDetails();

    Collection<String> solStackList = Collections2.transform(stackDetails, stackTransformer);

    final Pattern stackPattern = globify(solutionStack);

    List<String> matchingStacks = new ArrayList<String>(
            Collections2.filter(solStackList, new Predicate<String>() {
                @Override
                public boolean apply(String input) {
                    return stackPattern.matcher(input).matches();
                }
            }));

    Collections.sort(matchingStacks, ComparatorUtils.reversedComparator(Collator.getInstance()));

    if (matchingStacks.isEmpty()) {
        throw new IllegalStateException("unable to lookup a solution stack matching '" + solutionStack + "'");
    }

    return matchingStacks.iterator().next();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.teachersBody.ShowTeachersBodyDispatchAction.java

public ActionForward showTeachersBodyByDepartment(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws FenixActionException {

    DynaActionForm departmentForm = (DynaActionForm) actionForm;
    String departmentId = (String) departmentForm.get("departmentId");
    String executionYearId = (String) departmentForm.get("executionYearId");

    Integer semester = (Integer) departmentForm.get("semester");
    Integer teacherType = (Integer) departmentForm.get("teacherType");
    String searchDetails = (String) departmentForm.get("searchDetails");

    try {/* ww w.j  av  a 2 s.  co  m*/

        List detailedProfessorShipsListofLists = ReadProfessorshipsAndResponsibilitiesByDepartmentAndExecutionPeriod
                .run(departmentId, executionYearId, semester, teacherType);

        if ((detailedProfessorShipsListofLists != null) && (!detailedProfessorShipsListofLists.isEmpty())) {

            Collections.sort(detailedProfessorShipsListofLists, new Comparator() {

                @Override
                public int compare(Object o1, Object o2) {

                    List list1 = (List) o1;
                    List list2 = (List) o2;
                    DetailedProfessorship dt1 = (DetailedProfessorship) list1.iterator().next();
                    DetailedProfessorship dt2 = (DetailedProfessorship) list2.iterator().next();

                    return Collator.getInstance().compare(
                            dt1.getInfoProfessorship().getInfoExecutionCourse().getNome(),
                            dt2.getInfoProfessorship().getInfoExecutionCourse().getNome());
                }

            });
            request.setAttribute("detailedProfessorShipsListofLists", detailedProfessorShipsListofLists);
        }

        InfoDepartment department = ReadDepartmentByOID.run(departmentId);

        request.setAttribute("searchType", "Consulta Por Departmento");
        request.setAttribute("searchTarget", department.getName());
        request.setAttribute("searchDetails", searchDetails);
        request.setAttribute("semester", semester);
        request.setAttribute("teacherType", teacherType);
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }

    return mapping.findForward("showProfessorships");
}

From source file:VASL.build.module.map.ASLBoardPicker.java

/**
 * Reads the current board directory and constructs the list of available boards
 *///from  ww  w  .  j  av a  2  s.  com
public void refreshPossibleBoards() {
    String files[] = boardDir == null ? new String[0] : boardDir.list();
    List<String> sorted = new ArrayList<String>();
    for (int i = 0; i < files.length; ++i) {
        if (files[i].startsWith("bd") && !(new File(boardDir, files[i])).isDirectory()) {
            String name = files[i].substring(2);
            if (name.endsWith(".gif")) {
                name = name.substring(0, name.indexOf(".gif"));
            } else if (name.indexOf(".") >= 0) {
                name = null;
            }
            if (name != null && !sorted.contains(name)) {
                sorted.add(name);
            }
        }
    }

    //
    // * Strings with leading zeros sort ahead of those without.
    // * Strings with leading integer parts sort ahead of those without.
    // * Strings with lesser leading integer parts sort ahead of those with
    //   greater leading integer parts.
    // * Strings which are otherwise equal are sorted lexicographically by
    //   their trailing noninteger parts.
    //

    final Comparator<Object> alpha = Collator.getInstance();
    final Pattern pat = Pattern.compile("((0*)\\d*)(.*)");

    Comparator<String> comp = new Comparator<String>() {
        public int compare(String o1, String o2) {
            final Matcher m1 = pat.matcher(o1);
            final Matcher m2 = pat.matcher(o2);

            if (!m1.matches()) {
                // impossible
                throw new IllegalStateException();
            }

            if (!m2.matches()) {
                // impossible
                throw new IllegalStateException();
            }

            // count leading zeros
            final int z1 = m1.group(2).length();
            final int z2 = m2.group(2).length();

            // more leading zeros comes first
            if (z1 < z2) {
                return 1;
            } else if (z1 > z2) {
                return -1;
            }

            // same number of leading zeros
            final String o1IntStr = m1.group(1);
            final String o2IntStr = m2.group(1);
            if (o1IntStr.length() > 0) {
                if (o2IntStr.length() > 0) {
                    try {
                        // both strings have integer parts
                        final BigInteger o1Int = new BigInteger(o1IntStr);
                        final BigInteger o2Int = new BigInteger(o2IntStr);

                        if (!o1Int.equals(o2Int)) {
                            // one integer part is smaller than the other
                            return o1Int.compareTo(o2Int);

                        }
                    } catch (NumberFormatException e) {
                        // impossible
                        throw new IllegalStateException(e);
                    }
                } else {
                    // only o1 has an integer part
                    return -1;
                }
            } else if (o2IntStr.length() > 0) {
                // only o2 has an integer part
                return 1;
            }

            // the traling string part is decisive
            return alpha.compare(m1.group(3), m2.group(3));
        }
    };

    Collections.sort(sorted, comp);
    possibleBoards.clear();
    for (int i = 0; i < sorted.size(); ++i) {
        addBoard((String) sorted.get(i));
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty.java

/**
 * Sorts alphabetically by public name//from  ww  w  .  j ava 2  s . co  m
 */
public int compareTo(ObjectProperty op) {
    Collator collator = Collator.getInstance();
    return collator.compare(this.getDomainPublic(), (op).getDomainPublic());
}

From source file:org.apache.marmotta.platform.ldpath.webservices.LDPathWebService.java

/**
 * Return a list of all LDPath functions that have been registered in the LDPath installation.
 *
 * @HTTP 200 in case the functions exist; will return the function descriptions
 * @HTTP 500 in case there was an error accessing the triple store
 *
 * @return a list of JSON maps with the fields "name", "signature" and "description"
 *//*from  ww w.j a v a  2  s .  c  o m*/
@GET
@Path("/functions")
@Produces("application/json")
public Response listFunctions() {
    List<Map<String, String>> results = new ArrayList<Map<String, String>>();

    try {
        RepositoryConnection con = sesameService.getConnection();
        try {
            con.begin();
            SesameConnectionBackend backend = SesameConnectionBackend.withConnection(con);
            for (SelectorFunction<Value> function : ldPathService.getFunctions()) {
                Map<String, String> fmap = new HashMap<String, String>();
                fmap.put("name", function.getPathExpression(backend));
                fmap.put("signature", function.getSignature());
                fmap.put("description", function.getDescription());
                results.add(fmap);
            }
        } finally {
            con.commit();
            con.close();
        }
    } catch (RepositoryException e) {
        return Response.serverError().entity(e).build();
    }
    Collections.sort(results, new Comparator<Map<String, String>>() {
        @Override
        public int compare(Map<String, String> o1, Map<String, String> o2) {
            return Collator.getInstance().compare(o1.get("name"), o2.get("name"));
        }
    });

    return Response.ok().entity(results).build();
}

From source file:com.facebook.GraphObjectAdapter.java

private void rebuildSections() {
    sectionKeys = new ArrayList<String>();
    graphObjectsBySection = new HashMap<String, ArrayList<T>>();
    graphObjectsById = new HashMap<String, T>();
    displaySections = false;/*from w w  w .ja v a2s  .  co  m*/

    if (cursor == null || cursor.getCount() == 0) {
        return;
    }

    int objectsAdded = 0;
    cursor.moveToFirst();
    do {
        T graphObject = cursor.getGraphObject();

        if (!filterIncludesItem(graphObject)) {
            continue;
        }

        objectsAdded++;

        String sectionKeyOfItem = getSectionKeyOfGraphObject(graphObject);
        if (!graphObjectsBySection.containsKey(sectionKeyOfItem)) {
            sectionKeys.add(sectionKeyOfItem);
            graphObjectsBySection.put(sectionKeyOfItem, new ArrayList<T>());
        }
        List<T> section = graphObjectsBySection.get(sectionKeyOfItem);
        section.add(graphObject);

        graphObjectsById.put(getIdOfGraphObject(graphObject), graphObject);
    } while (cursor.moveToNext());

    if (sortFields != null) {
        final Collator collator = Collator.getInstance();
        for (List<T> section : graphObjectsBySection.values()) {
            Collections.sort(section, new Comparator<GraphObject>() {
                @Override
                public int compare(GraphObject a, GraphObject b) {
                    return Utility.compareGraphObjects(a, b, sortFields, collator);
                }
            });
        }
    }

    Collections.sort(sectionKeys, Collator.getInstance());

    displaySections = sectionKeys.size() > 1 && objectsAdded > DISPLAY_SECTIONS_THRESHOLD;
}

From source file:edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty.java

/**
 * Sorts the object property statements taking into account the sort order.
 *//*w w w .  j  av  a  2s .  c  o  m*/
public static List<ObjectPropertyStatement> sortObjectPropertyStatementsForDisplay(ObjectProperty prop,
        List objPropStmtsList) {

    if (objPropStmtsList == null) {
        log.error("incoming object property statement list is null; " + "returning null");
        return null;
    }
    if (objPropStmtsList.size() < 2) { // no need to sort
        return objPropStmtsList;
    }

    String tmpDirection = prop.getDomainEntitySortDirection();
    // Valid values are "desc" and "asc";
    // anything else will default to ascending.
    final boolean ascending = !"desc".equalsIgnoreCase(tmpDirection);

    String objIndivSortPropURI = prop.getObjectIndividualSortPropertyURI();
    if (prop.getObjectIndividualSortPropertyURI() == null
            || prop.getObjectIndividualSortPropertyURI().length() == 0) {
        log.debug("objectIndividualSortPropertyURI is null or blank " + "so sorting by name ");

        Comparator fieldComp = new Comparator() {

            public final int compare(Object o1, Object o2) {
                ObjectPropertyStatement e2e1 = (ObjectPropertyStatement) o1,
                        e2e2 = (ObjectPropertyStatement) o2;
                Individual e1, e2;
                e1 = e2e1 != null ? e2e1.getObject() : null;
                e2 = e2e2 != null ? e2e2.getObject() : null;

                Object val1 = null, val2 = null;
                if (e1 != null) {
                    val1 = e1.getName();
                } else {
                    log.debug("PropertyWebapp.sortObjectPropertiesForDisplay() "
                            + "passed object property statement with no range entity.");
                }
                if (e2 != null) {
                    val2 = e2.getName();
                } else {
                    log.debug("PropertyWebapp.sortObjectPropertyStatementsForDisplay "
                            + "passed object property statement with no range entity.");
                }
                int rv = 0;
                try {
                    if (val1 instanceof String) {
                        if (val2 == null) {
                            rv = -1;
                        } else {
                            Collator collator = Collator.getInstance();
                            rv = collator.compare(((String) val1), ((String) val2));
                        }
                    } else if (val1 instanceof Date) {
                        DateTime dt1 = new DateTime((Date) val1);
                        DateTime dt2 = new DateTime((Date) val2);
                        rv = dt1.compareTo(dt2);
                    } else {
                        rv = 0;
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }

                if (ascending) {
                    return rv;
                } else {
                    return rv * -1;
                }
            }
        };
        try {
            Collections.sort(objPropStmtsList, fieldComp);
        } catch (Exception e) {
            log.error("Exception sorting object property statements for object property " + prop.getURI());
        }
    } else { // sort by specified range entity data property value instead of a property having a get() method in Individual.java
        log.debug("using data property " + prop.getObjectIndividualSortPropertyURI()
                + " to sort related entities");
        final String objIndSortPropURI = prop.getObjectIndividualSortPropertyURI();
        Comparator dpComp = new Comparator() {
            final String cDatapropURI = objIndSortPropURI;

            public final int compare(Object o1, Object o2) {
                ObjectPropertyStatement e2e1 = (ObjectPropertyStatement) o1,
                        e2e2 = (ObjectPropertyStatement) o2;
                Individual e1, e2;
                e1 = e2e1 != null ? e2e1.getObject() : null;
                e2 = e2e2 != null ? e2e2.getObject() : null;

                Object val1 = null, val2 = null;
                if (e1 != null) {
                    try {
                        List<DataPropertyStatement> dataPropertyStatements = e1.getDataPropertyStatements();
                        for (DataPropertyStatement dps : dataPropertyStatements) {
                            if (cDatapropURI.equals(dps.getDatapropURI())) {
                                if (dps.getData() != null && dps.getData().trim().length() > 0) {
                                    if (XSDDatatype.XSDint.getURI().equals(dps.getDatatypeURI())
                                            || XSDDatatype.XSDinteger.getURI().equals(dps.getDatatypeURI())) {
                                        val1 = Integer.parseInt(dps.getData());
                                    } else {
                                        val1 = dps.getData();
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else
                    log.debug(
                            "PropertyWebapp.sortObjectPropertiesForDisplay passed object property statement with no range entity.");

                if (e2 != null) {
                    try {
                        List<DataPropertyStatement> dataPropertyStatements = e2.getDataPropertyStatements();
                        for (DataPropertyStatement dps : dataPropertyStatements) {
                            if (cDatapropURI.equals(dps.getDatapropURI())) {
                                if (dps.getData() != null && dps.getData().trim().length() > 0) {
                                    if (XSDDatatype.XSDint.getURI().equals(dps.getDatatypeURI())
                                            || XSDDatatype.XSDinteger.getURI().equals(dps.getDatatypeURI())) {
                                        val2 = Integer.parseInt(dps.getData());
                                    } else {
                                        val2 = dps.getData();
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    log.debug(
                            "PropertyWebapp.sortObjectPropertyStatementsForDisplay passed object property statement with no range entity.");
                }
                int rv = 0;
                try {
                    if (val1 == null && val2 == null) {
                        rv = 0;
                    } else if (val1 == null) {
                        rv = 1;
                    } else if (val2 == null) {
                        rv = -1;
                    } else {
                        if (val1 instanceof String) {
                            Collator collator = Collator.getInstance();
                            rv = collator.compare(((String) val1), ((String) val2)); //was rv = ((String)val1).compareTo((String)val2);
                        } else if (val1 instanceof Date) {
                            DateTime dt1 = new DateTime((Date) val1);
                            DateTime dt2 = new DateTime((Date) val2);
                            rv = dt1.compareTo(dt2);
                        } else if (val1 instanceof Integer) {
                            rv = ((Integer) val1) - ((Integer) val2);
                        } else {
                            rv = 0;
                        }
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }

                if (!ascending) {
                    rv = rv * -1;
                }

                // sort alphabetically by name if have same dataproperty value
                if (rv == 0) {
                    String nameValue1 = (e1.getName() != null) ? e1.getName() : "";
                    String nameValue2 = (e2.getName() != null) ? e2.getName() : "";
                    rv = Collator.getInstance().compare(nameValue1, nameValue2);
                }

                return rv;
            }
        };
        try {
            Collections.sort(objPropStmtsList, dpComp);
        } catch (Exception e) {
            log.error("Exception sorting object property statements " + "for object property " + prop.getURI(),
                    e);
        }
    }
    return objPropStmtsList;
}