Example usage for java.util Formatter toString

List of usage examples for java.util Formatter toString

Introduction

In this page you can find the example usage for java.util Formatter toString.

Prototype

public String toString() 

Source Link

Document

Returns the result of invoking toString() on the destination for the output.

Usage

From source file:nl.basjes.parse.useragent.UserAgentAnalyzer.java

public void loadResources(String resourceString, boolean showMatcherStats) {
    LOG.info("Loading from: \"{}\"", resourceString);

    flattener = new UserAgentTreeFlattener(this);
    yaml = new Yaml();

    Map<String, Resource> resources = new TreeMap<>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {/*from  w  ww.  j a v  a  2  s.  c  o  m*/
        Resource[] resourceArray = resolver.getResources(resourceString);
        for (Resource resource : resourceArray) {
            resources.put(resource.getFilename(), resource);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    doingOnlyASingleTest = false;
    int maxFilenameLength = 0;

    if (resources.isEmpty()) {
        throw new InvalidParserConfigurationException("Unable to find ANY config files");
    }

    for (Map.Entry<String, Resource> resourceEntry : resources.entrySet()) {
        try {
            Resource resource = resourceEntry.getValue();
            String filename = resource.getFilename();
            maxFilenameLength = Math.max(maxFilenameLength, filename.length());
            loadResource(resource.getInputStream(), filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    LOG.info("Loaded {} files", resources.size());

    if (lookups != null && !lookups.isEmpty()) {
        // All compares are done in a case insensitive way. So we lowercase ALL keys of the lookups beforehand.
        Map<String, Map<String, String>> cleanedLookups = new HashMap<>(lookups.size());
        for (Map.Entry<String, Map<String, String>> lookupsEntry : lookups.entrySet()) {
            Map<String, String> cleanedLookup = new HashMap<>(lookupsEntry.getValue().size());
            for (Map.Entry<String, String> entry : lookupsEntry.getValue().entrySet()) {
                cleanedLookup.put(entry.getKey().toLowerCase(), entry.getValue());
            }
            cleanedLookups.put(lookupsEntry.getKey(), cleanedLookup);
        }
        lookups = cleanedLookups;
    }

    LOG.info("Building all matchers");
    int totalNumberOfMatchers = 0;
    int skippedMatchers = 0;
    if (matcherConfigs != null) {
        long fullStart = System.nanoTime();
        for (Map.Entry<String, Resource> resourceEntry : resources.entrySet()) {
            Resource resource = resourceEntry.getValue();
            String configFilename = resource.getFilename();
            List<Map<String, List<String>>> matcherConfig = matcherConfigs.get(configFilename);
            if (matcherConfig == null) {
                continue; // No matchers in this file (probably only lookups and/or tests)
            }

            long start = System.nanoTime();
            int startSize = informMatcherActions.size();
            for (Map<String, List<String>> map : matcherConfig) {
                try {
                    allMatchers.add(new Matcher(this, lookups, wantedFieldNames, map));
                    totalNumberOfMatchers++;
                } catch (UselessMatcherException ume) {
                    skippedMatchers++;
                }
            }
            long stop = System.nanoTime();
            int stopSize = informMatcherActions.size();

            if (showMatcherStats) {
                Formatter msg = new Formatter(Locale.ENGLISH);
                msg.format(
                        "Building %4d matchers from %-" + maxFilenameLength
                                + "s took %5d msec resulted in %8d extra hashmap entries",
                        matcherConfig.size(), configFilename, (stop - start) / 1000000, stopSize - startSize);
                LOG.info(msg.toString());
            }
        }
        long fullStop = System.nanoTime();

        Formatter msg = new Formatter(Locale.ENGLISH);
        msg.format(
                "Building %4d (dropped %4d) matchers from %4d files took %5d msec resulted in %8d hashmap entries",
                totalNumberOfMatchers, skippedMatchers, matcherConfigs.size(), (fullStop - fullStart) / 1000000,
                informMatcherActions.size());
        LOG.info(msg.toString());

    }
    LOG.info("Analyzer stats");
    LOG.info("Lookups      : {}", (lookups == null) ? 0 : lookups.size());
    LOG.info("Matchers     : {} (total:{} ; dropped: {})", allMatchers.size(), totalNumberOfMatchers,
            skippedMatchers);
    LOG.info("Hashmap size : {}", informMatcherActions.size());
    LOG.info("Testcases    : {}", testCases.size());
    //        LOG.info("All possible field names:");
    //        int count = 1;
    //        for (String fieldName : getAllPossibleFieldNames()) {
    //            LOG.info("- {}: {}", count++, fieldName);
    //        }
}

From source file:com.itemanalysis.jmetrik.stats.transformation.LinearTransformationAnalysis.java

private String publishHeader() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    String dString = "";
    String title = "LINEAR TRANSFORMATION";

    try {/*from  w  ww.  j av  a 2  s  . c  om*/
        dString = command.getDataString();
    } catch (IllegalArgumentException ex) {
        dString = "";
        throw new IllegalArgumentException(ex);
    }

    //create header
    int len1 = 25 + Double.valueOf(Math.floor(Double.valueOf(title.length()).doubleValue() / 2.0)).intValue();
    int len2 = 25 + Double.valueOf(Math.floor(Double.valueOf(dString.length()).doubleValue() / 2.0)).intValue();

    String date = String.format("%1$tB %1$te, %1$tY  %tT", Calendar.getInstance());
    int len3 = 25 + Double.valueOf(Math.floor(Double.valueOf(date.length()).doubleValue() / 2.0)).intValue();

    f.format("%" + len1 + "s", title);
    f.format("%n");
    f.format("%" + len2 + "s", dString);
    f.format("%n");
    f.format("%" + len3 + "s", date);
    f.format("%n");
    f.format("%n");
    f.format("%n");
    f.format("%n");

    return f.toString();
}

From source file:net.sourceforge.fenixedu.domain.candidacy.PersonalInformationBean.java

public String getFormattedValues() {
    Formatter result = new Formatter();

    final Student student = getStudent();
    result.format("Student Number: %d\n", student.getNumber());
    result.format("Name: %s\n", student.getPerson().getName());
    if (hasPhdIndividualProgramProcess()) {
        result.format("Degree: %s\n", getPhdIndividualProgramProcess().getDisplayName());
    } else {/* ww  w  . j ava 2 s  . co m*/
        result.format("Degree: %s\n", getRegistration().getDegree().getPresentationName());
    }

    return result.toString();
}

From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java

protected List<Document> checkAccounts(final Parameter _parameter, final File _file,
        final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse)
        throws IOException, EFapsException {
    final List<Document> ret = new ArrayList<>();
    final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"));
    final List<String[]> entries = reader.readAll();
    reader.close();//ww w  . ja  v a 2 s. c o  m
    entries.remove(0);
    int i = 1;
    final Map<String, Document> map = new HashMap<>();
    for (final String[] row : entries) {
        i++;
        final String docNumber = row[0];
        final String ruc = row[1];
        final String dateStr = row[2];
        final String accountStr = row[5];
        final String accountDesc = row[4];
        final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
        formater.setParseBigDecimal(true);
        final String amountMEStr = row[6];
        final String amountMNStr = row[7];

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
        queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim());
        final InstanceQuery query = queryBldr.getQuery();
        query.executeWithoutAccessCheck();
        if (query.next()) {
            ImportDetails.LOG.info("Found account: '{}' ", accountStr);
            final String[] docSplit = docNumber.split("-");
            if (docSplit.length != 2 && _docMap != null) {
                ImportDetails.LOG.warn(
                        "Document '{}'  - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber,
                        i);
            } else {
                try {
                    final Formatter criteria = new Formatter();
                    String name = docNumber;
                    if (_docMap != null) {
                        final String serialNo = docSplit[0];
                        final String docNo = docSplit[1];
                        final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", ""));
                        final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", ""));
                        criteria.format("%03d-%06d", serial, no);
                        name = criteria.toString();
                    }

                    Document doc;
                    if (map.containsKey(name)) {
                        doc = map.get(name);
                    } else {
                        if (_docMap != null && _docMap.containsKey(name)) {
                            doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc);
                        } else {
                            doc = new Document(name, null, ruc, dateStr, accountDesc);
                        }
                    }

                    BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr);
                    BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr);

                    if (_inverse) {
                        amountME = amountME.negate();
                        amountMN = amountMN.negate();
                    }

                    if (amountMN.compareTo(BigDecimal.ZERO) >= 0) {
                        doc.addAmountMECredit(amountME);
                        doc.addAmountMNCredit(amountMN);
                    } else {
                        doc.addAmountMEDebit(amountME);
                        doc.addAmountMNDebit(amountMN);
                    }

                    final Map<String, Account> accounts = doc.getAccounts();
                    Account acc;
                    if (accounts.containsKey(accountStr)) {
                        acc = accounts.get(accountStr);
                    } else {
                        acc = new Account(accountStr, accountDesc);
                        accounts.put(accountStr, acc);
                    }
                    acc.addAmountME(amountME);
                    acc.addAmountMN(amountMN);
                    acc.setInstance(query.getCurrentValue());

                    map.put(name, doc);

                    criteria.close();
                } catch (final NumberFormatException e) {
                    ImportDetails.LOG.error("wrong format for document '{}'", docNumber);
                } catch (final ParseException e) {
                    ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr);
                }
            }
        } else {
            ImportDetails.LOG.error("Not found account: {}", accountStr);
        }
    }

    final Instance periodInst = getPeriodInstance();
    for (final Document doc : map.values()) {
        final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountMN = amountCreditMN.add(amountDebitMN);
        final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountME = amountCreditME.add(amountDebitME);
        if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) {
            ImportDetails.LOG.info(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)",
                    doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN);
        } else {
            ImportDetails.LOG.error(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'",
                    doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN,
                    amountMN);
        }

        final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
        insert.add(CIAccounting.TransactionOpeningBalance.Date, _date);
        final StringBuilder descBldr = new StringBuilder()
                .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento")
                .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ")
                .append(doc.getDate()).append(" - ").append(doc.getDesc());

        insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString());
        insert.add(CIAccounting.TransactionOpeningBalance.Status,
                Status.find(CIAccounting.TransactionStatus.Open));
        insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst);
        insert.executeWithoutAccessCheck();

        if (_docMap != null) {
            final Instance instance = insert.getInstance();
            new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance());
        }

        final Map<String, Account> accounts = doc.getAccounts();
        final Instance basCur = Currency.getBaseCurrency();
        for (final Account acc : accounts.values()) {
            final Insert insertpos = new Insert(
                    acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                            : CIAccounting.TransactionPositionDebit);
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }

        if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) {
            Insert insertpos = null;
            Account acc = null;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT);
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT);
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) {
            Insert insertpos = null;
            final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT);
            ;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }
    }

    return ret;
}

From source file:com.itemanalysis.jmetrik.stats.itemanalysis.ItemAnalysis.java

public String getResults() throws IllegalArgumentException {
    StringBuilder headerBuffer = new StringBuilder();
    Formatter f = new Formatter(headerBuffer);

    int outputMidpoint = 37;
    String s1 = String.format("%1$tB %1$te, %1$tY  %tT", Calendar.getInstance());
    int len = outputMidpoint
            + Double.valueOf(Math.floor(Double.valueOf(s1.length()).doubleValue() / 2.0)).intValue();
    String dString = "";

    dString = command.getDataString();/*from w ww.  ja v a 2s.  c om*/

    int len2 = outputMidpoint
            + Double.valueOf(Math.floor(Double.valueOf(dString.length()).doubleValue() / 2.0)).intValue();

    f.format("%43s", "ITEM ANALYSIS");
    f.format("%n");
    f.format("%" + len2 + "s", dString);
    f.format("%n");
    f.format("%" + len + "s", s1);
    f.format("%n");
    f.format("%-70s", "======================================================================");
    f.format("%n");
    f.format("%n");

    StringBuilder buffer = new StringBuilder();
    buffer.append(f.toString());

    int counter = 0;
    int nItems = item.size();
    ClassicalItem temp;
    if (showItemStats) {
        for (Integer i : item.keySet()) {
            temp = item.get(i);
            if (counter == 0 || command.getSelectAllOption("options").isArgumentSelected("header")) {
                buffer.append(temp.printHeader());
            }
            buffer.append(temp.toString());

            if (command.getSelectAllOption("options").isArgumentSelected("all")
                    || command.getSelectAllOption("options").isArgumentSelected("header")) {
                if (counter < (nItems - 1))
                    buffer.append("\n");
            }
            counter++;
        }
    }
    buffer.append("======================================================================");
    buffer.append("\n\n");
    buffer.append(testSummary.print());
    return buffer.toString();

}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java

/**
 * Format a data object using a named formatter
 * @param dataObj the data object for which fields will be formatted for it
 * @return the string result of the format
 *//* w  w  w.  j av  a2s  .c  o m*/
protected String formatInternal(final DataObjDataFieldFormat format, final Object[] dataObjs) {
    if (format != null) {
        DataObjectGettable getter = DataObjectGettableFactory.get(format.getDataClass().getName(),
                FormHelper.DATA_OBJ_GETTER);
        if (getter != null) {
            StringBuilder strBuf = new StringBuilder(128);

            if (dataObjs.length == format.getFields().length) {
                int inx = 0;
                for (DataObjDataField field : format.getFields()) {
                    Object value = dataObjs[inx++];
                    if (value != null) {
                        if (field.getDataObjFormatterName() != null) {
                            String fmtStr = formatInternal(
                                    getDataFormatter(value, field.getDataObjFormatterName()), value);
                            if (fmtStr != null) {
                                strBuf.append(fmtStr);
                            }

                        } else if (field.getUiFieldFormatterName() != null) {
                            UIFieldFormatterIFace fmt = UIFieldFormatterMgr.getInstance()
                                    .getFormatter(field.getUiFieldFormatterName());
                            if (fmt != null) {
                                strBuf.append(fmt.formatToUI(value));
                            } else {
                                strBuf.append(value);
                            }

                        } else if (value.getClass() == field.getType()) {
                            // When format is null then it is a string
                            if (field.getType() == String.class
                                    && (field.getFormat() == null || format.equals("%s"))) {
                                if (field.getSep() != null) {
                                    strBuf.append(field.getSep());
                                }
                                strBuf.append(value.toString());
                            } else {
                                Object[] arg = { value };
                                Formatter formatter = new Formatter();
                                formatter.format(format.getFormat(), arg);
                                strBuf.append(formatter.toString());
                            }
                        } else {
                            log.error("Mismatch of types data retrieved as class["
                                    + value.getClass().getSimpleName() + "] and the format requires ["
                                    + field.getType().getSimpleName() + "]");
                        }
                    }
                }
            } else {
                log.error("Data Array sent to formatter is not the same length [" + dataObjs.length
                        + "] as the formatter [" + format.getFields().length + "]");
            }
            return strBuf.toString();
        }
    }
    return "";
}

From source file:org.xwiki.rest.internal.resources.BaseSearchResult.java

/**
 * Execute a database query using a supported query language. Limit search to documents.
 *
 * @param number number of results to be returned
 * @param start 0-based start offset//from   www .  j av  a 2 s  .c  o m
 * @param withPrettyNames Add the pretty names for users
 * @param className Add object of type className
 * @return list of results
 */
protected List<SearchResult> searchDatabaseQuery(String query, String queryLanguage, String wikiName,
        boolean hasProgrammingRights, boolean distinct, int number, int start, Boolean withPrettyNames,
        String className) throws QueryException, IllegalArgumentException, UriBuilderException, XWikiException {
    XWiki xwikiApi = Utils.getXWikiApi(componentManager);
    XWikiContext xwikiContext = Utils.getXWikiContext(componentManager);

    String database = Utils.getXWikiContext(componentManager).getDatabase();

    /* This try is just needed for executing the finally clause. */
    try {
        List<SearchResult> result = new ArrayList<SearchResult>();

        if (query == null || query.trim().startsWith("select")) {
            return result;
        }

        Formatter f = new Formatter();
        if (distinct) {
            f.format(
                    "select distinct doc.fullName, doc.space, doc.name, doc.language from XWikiDocument as doc %s",
                    query);
        } else {
            f.format("select doc.fullName, doc.space, doc.name, doc.language from XWikiDocument as doc %s",
                    query);
        }
        String squery = f.toString();

        if (!hasProgrammingRights) {
            squery.replace("where ",
                    "where doc.space<>'XWiki' and doc.space<>'Admin' and doc.space<>'Panels' and doc.name<>'WebPreferences' and ");
        }

        List<Object> queryResult = null;

        queryResult = queryManager.createQuery(squery, queryLanguage).setLimit(number).setOffset(start)
                .execute();

        /* Build the result. */
        for (Object object : queryResult) {
            Object[] fields = (Object[]) object;

            String spaceName = (String) fields[1];
            String pageName = (String) fields[2];
            String language = (String) fields[3];

            String pageId = Utils.getPageId(wikiName, spaceName, pageName);
            String pageFullName = Utils.getPageFullName(wikiName, spaceName, pageName);

            /* Check if the user has the right to see the found document */
            if (xwikiApi.hasAccessLevel("view", pageId)) {
                Document doc = xwikiApi.getDocument(pageFullName);
                String title = doc.getDisplayTitle();

                SearchResult searchResult = objectFactory.createSearchResult();
                searchResult.setType("page");
                searchResult.setId(pageId);
                searchResult.setPageFullName(pageFullName);
                searchResult.setTitle(title);
                searchResult.setWiki(wikiName);
                searchResult.setSpace(spaceName);
                searchResult.setPageName(pageName);
                searchResult.setVersion(doc.getVersion());
                searchResult.setAuthor(doc.getAuthor());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(doc.getDate());
                searchResult.setModified(calendar);

                if (withPrettyNames) {
                    searchResult.setAuthorName(Utils.getAuthorName(doc.getAuthor(), componentManager));
                }

                /*
                 * Avoid to return object information if the user is not authenticated. This will prevent crawlers
                 * to retrieve information such as email addresses and passwords from user's profiles.
                 */
                if (className != null && !className.equals("") && xwikiContext.getUserReference() != null) {
                    BaseObject baseObject = Utils.getBaseObject(doc, className, 0, componentManager);
                    if (baseObject != null) {
                        searchResult.setObject(DomainObjectFactory.createObject(objectFactory,
                                uriInfo.getBaseUri(), xwikiContext, doc, baseObject, false, xwikiApi, false));
                    }
                }

                String pageUri = null;
                try {
                    if (StringUtils.isBlank(language)) {
                        pageUri = UriBuilder.fromUri(this.uriInfo.getBaseUri()).path(PageResource.class)
                                .buildFromEncoded(URLEncoder.encode(wikiName, "UTF-8"),
                                        URLEncoder.encode(spaceName, "UTF-8"),
                                        URLEncoder.encode(pageName, "UTF-8"))
                                .toString();
                    } else {
                        searchResult.setLanguage(language);
                        pageUri = UriBuilder.fromUri(this.uriInfo.getBaseUri())
                                .path(PageTranslationResource.class)
                                .buildFromEncoded(URLEncoder.encode(wikiName, "UTF-8"),
                                        URLEncoder.encode(spaceName, "UTF-8"),
                                        URLEncoder.encode(pageName, "UTF-8"), language)
                                .toString();
                    }
                } catch (UnsupportedEncodingException ex) {
                    // This should never happen, UTF-8 is always valid.
                }

                Link pageLink = new Link();
                pageLink.setHref(pageUri);
                pageLink.setRel(Relations.PAGE);
                searchResult.getLinks().add(pageLink);

                result.add(searchResult);
            }
        }

        return result;
    } finally {
        Utils.getXWikiContext(componentManager).setDatabase(database);
    }
}

From source file:com.itemanalysis.psychometrics.scaling.PercentileRank.java

@Override
public String toString() {
    if (freqTable.getUniqueCount() == 0 || freqTable.getSumFreq() == 0) {
        return "Percentile ranks not computed.";
    }//from www. ja v  a 2 s  . c  o  m
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    String f1 = "%10.4f";
    String f2 = "%10s";

    //        double[][] prank = this.evaluate();
    this.createLookupTable();

    //add header
    f.format("%28s", "SCORE TABLE");
    f.format("%n");
    f.format("%45s", "=============================================");
    f.format("%n");
    f.format(f2, "Original");
    f.format("%5s", "");
    f.format(f2, "Percentile");
    f.format("%n");

    f.format(f2, "Value");
    f.format("%5s", "");
    f.format(f2, "Rank");
    f.format("%n");
    f.format("%45s", "---------------------------------------------");
    f.format("%n");

    Iterator<Integer> iter = prankTable.keySet().iterator();
    Integer key = 1;
    while (iter.hasNext()) {
        key = iter.next();
        f1 = "%10." + precision + "f";

        f.format(f2, key);
        f.format("%5s", "");
        f.format(f1, prankTable.get(key));
        f.format("%5s", "");
        f.format("%n");
    }
    f.format("%45s", "=============================================");
    f.format("%n");
    return f.toString();
}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java

/**
 * Format a data object using a named formatter
 * @param dataObj the data object for which fields will be formatted for it
 * @return the string result of the format
 *///w w  w .  j a  v  a2s.  c o  m
protected String formatInternal(final DataObjDataFieldFormatIFace format, final Object dataObj) {
    String restricted = FormHelper.checkForRestrictedValue(dataObj);
    if (restricted != null) {
        return restricted;
    }

    if (format != null) {
        if (format.isDirectFormatter()) {
            return format.format(dataObj);
        }

        DataObjectGettable getter = DataObjectGettableFactory.get(format.getDataClass().getName(),
                FormHelper.DATA_OBJ_GETTER);

        if (getter != null) {
            StringBuilder strBuf = new StringBuilder(128);
            for (DataObjDataField field : format.getFields()) {
                Class<?> fieldClass = field.getType();

                Object[] values = getFieldValues(new String[] { field.getName() }, dataObj, getter);
                Object value = values != null ? values[0] : null;

                // NOTE: if the field was a Date or Calendar object it has already been reformatted to a String
                // so we change the fieldClass to string so everything works out.
                if (fieldClass == Date.class || fieldClass == Calendar.class) {
                    fieldClass = String.class;
                }

                if (value != null) {
                    if (AppContextMgr.isSecurityOn() && value instanceof FormDataObjIFace) {
                        DBTableInfo tblInfo = DBTableIdMgr.getInstance()
                                .getByShortClassName(value.getClass().getSimpleName());
                        if (tblInfo != null) {
                            PermissionSettings perm = tblInfo.getPermissions();
                            if (perm != null) {
                                if (!perm.canView()) {
                                    return "";
                                }
                            }
                        }
                    }

                    if (field.getDataObjFormatterName() != null) {
                        String fmtStr = formatInternal(getDataFormatter(value, field.getDataObjFormatterName()),
                                value);
                        if (fmtStr != null) {
                            strBuf.append(fmtStr);
                        }

                    } else if (field.getUiFieldFormatterName() != null) {
                        UIFieldFormatterIFace fmt = UIFieldFormatterMgr.getInstance()
                                .getFormatter(field.getUiFieldFormatterName());
                        DBTableInfo tblInfo = DBTableIdMgr.getInstance()
                                .getByShortClassName(dataObj.getClass().getSimpleName());
                        if (tblInfo != null) {
                            DBFieldInfo fi = tblInfo.getFieldByName(field.getName());
                            if (fi != null && fi.getFormatter() != null) {
                                fmt = fi.getFormatter();
                            }
                        }

                        if (fmt != null) {
                            strBuf.append(fmt.formatToUI(value));
                        } else {
                            strBuf.append(value);
                        }

                    } else if (value.getClass() == fieldClass) {
                        // When format is null then it is a string
                        if (fieldClass == String.class && (field.getFormat() == null || format.equals("%s"))) {
                            if (field.getSep() != null) {
                                strBuf.append(field.getSep());
                            }
                            strBuf.append(value.toString());
                        } else {
                            String sep = field.getSep();
                            if (sep != null) {
                                strBuf.append(sep);
                            }
                            //log.debug("["+value+"]["+format+"]");
                            if (field.getFormat() != null) {
                                Object[] arg = { value };
                                Formatter formatter = new Formatter();
                                formatter.format(field.getFormat(), arg);
                                strBuf.append(formatter.toString());

                            } else {
                                strBuf.append(value.toString());
                            }
                        }
                    } else {
                        log.error("Mismatch of types data retrieved as class["
                                + (value != null ? value.getClass().getSimpleName() : "N/A")
                                + "] and the format requires ["
                                + (field != null ? (fieldClass != null ? fieldClass.getSimpleName() : "N/A 2")
                                        : "N/A")
                                + "]");
                    }
                }
            }
            return strBuf.toString();
        }
    }
    return "";
}

From source file:org.xwiki.rest.internal.resources.BaseSearchResult.java

/**
 * Search for keyword in the given scopes. Limit the search only to spaces.
 *
 * @param keywords the string that will be used in a "like" XWQL clause
 * @param number number of results to be returned
 * @param start 0-based start offset// w w  w.jav a2 s.  c  o  m
 * @return the results.
 */
protected List<SearchResult> searchSpaces(String keywords, String wikiName, boolean hasProgrammingRights,
        int number, int start)
        throws QueryException, IllegalArgumentException, UriBuilderException, XWikiException {
    XWiki xwikiApi = Utils.getXWikiApi(componentManager);

    String database = Utils.getXWikiContext(componentManager).getDatabase();

    /* This try is just needed for executing the finally clause. */
    try {
        List<SearchResult> result = new ArrayList<SearchResult>();

        if (keywords == null) {
            return result;
        }

        Formatter f = new Formatter();

        f.format("select distinct doc.space from XWikiDocument as doc where upper(doc.space) like :keywords ");

        /* Add some filters if the user doesn't have programming rights. */
        if (hasProgrammingRights) {
            f.format(" order by doc.space asc");
        } else {
            f.format(
                    " and doc.space<>'XWiki' and doc.space<>'Admin' and doc.space<>'Panels' order by doc.space asc");
        }

        String query = f.toString();

        List<Object> queryResult = null;
        queryResult = queryManager.createQuery(query, Query.XWQL)
                .bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())).setLimit(number)
                .setOffset(start).execute();

        for (Object object : queryResult) {
            String spaceName = (String) object;
            Document spaceDoc = xwikiApi.getDocument(String.format("%s.WebHome", spaceName));

            /* Check if the user has the right to see the found document */
            if (xwikiApi.hasAccessLevel("view", spaceDoc.getPrefixedFullName())) {
                String title = spaceDoc.getDisplayTitle();

                SearchResult searchResult = objectFactory.createSearchResult();
                searchResult.setType("space");
                searchResult.setId(String.format("%s:%s", wikiName, spaceName));
                searchResult.setWiki(wikiName);
                searchResult.setSpace(spaceName);
                searchResult.setTitle(title);

                /* Add a link to the space information */
                Link spaceLink = new Link();
                spaceLink.setRel(Relations.SPACE);
                String spaceUri = UriBuilder.fromUri(uriInfo.getBaseUri()).path(SpaceResource.class)
                        .build(wikiName, spaceName).toString();
                spaceLink.setHref(spaceUri);
                searchResult.getLinks().add(spaceLink);

                /* Add a link to the webhome if it exists */
                String webHomePageId = Utils.getPageId(wikiName, spaceName, "WebHome");
                if (xwikiApi.exists(webHomePageId) && xwikiApi.hasAccessLevel("view", webHomePageId)) {
                    String pageUri = UriBuilder.fromUri(uriInfo.getBaseUri()).path(PageResource.class)
                            .build(wikiName, spaceName, "WebHome").toString();

                    Link pageLink = new Link();
                    pageLink.setHref(pageUri);
                    pageLink.setRel(Relations.HOME);
                    searchResult.getLinks().add(pageLink);
                }

                result.add(searchResult);
            }
        }

        return result;
    } finally {
        Utils.getXWikiContext(componentManager).setDatabase(database);
    }
}