Example usage for org.apache.commons.lang ObjectUtils toString

List of usage examples for org.apache.commons.lang ObjectUtils toString

Introduction

In this page you can find the example usage for org.apache.commons.lang ObjectUtils toString.

Prototype

public static String toString(Object obj, String nullStr) 

Source Link

Document

Gets the toString of an Object returning a specified text if null input.

 ObjectUtils.toString(null, null)           = null ObjectUtils.toString(null, "null")         = "null" ObjectUtils.toString("", "null")           = "" ObjectUtils.toString("bat", "null")        = "bat" ObjectUtils.toString(Boolean.TRUE, "null") = "true" 

Usage

From source file:org.amplafi.json.renderers.UriJsonRenderer.java

public IJsonWriter toJson(IJsonWriter jsonWriter, URI o) {
    return jsonWriter.value(ObjectUtils.toString(o, null));
}

From source file:org.apache.hawq.pxf.service.BridgeOutputBuilder.java

/**
 * Fills one GPDBWritable field./*from  w  w w .  j a v  a2 s. c o  m*/
 *
 * @param oneField field
 * @param colIdx column index
 * @throws BadRecordException if field type is not supported or doesn't
 *             match the schema
 */
void fillOneGPDBWritableField(OneField oneField, int colIdx) throws BadRecordException {
    int type = oneField.type;
    Object val = oneField.val;
    GPDBWritable gpdbOutput = (GPDBWritable) output;
    try {
        switch (DataType.get(type)) {
        case INTEGER:
            gpdbOutput.setInt(colIdx, (Integer) val);
            break;
        case FLOAT8:
            gpdbOutput.setDouble(colIdx, (Double) val);
            break;
        case REAL:
            gpdbOutput.setFloat(colIdx, (Float) val);
            break;
        case BIGINT:
            gpdbOutput.setLong(colIdx, (Long) val);
            break;
        case SMALLINT:
            gpdbOutput.setShort(colIdx, (Short) val);
            break;
        case BOOLEAN:
            gpdbOutput.setBoolean(colIdx, (Boolean) val);
            break;
        case BYTEA:
            byte[] bts = null;
            if (val != null) {
                int length = Array.getLength(val);
                bts = new byte[length];
                for (int j = 0; j < length; j++) {
                    bts[j] = Array.getByte(val, j);
                }
            }
            gpdbOutput.setBytes(colIdx, bts);
            break;
        case VARCHAR:
        case BPCHAR:
        case CHAR:
        case TEXT:
        case NUMERIC:
        case TIMESTAMP:
        case DATE:
            gpdbOutput.setString(colIdx, ObjectUtils.toString(val, null));
            break;
        default:
            String valClassName = (val != null) ? val.getClass().getSimpleName() : null;
            throw new UnsupportedOperationException(valClassName + " is not supported for HAWQ conversion");
        }
    } catch (TypeMismatchException e) {
        throw new BadRecordException(e);
    }
}

From source file:org.apache.solr.handler.clustering.carrot2.CarrotClusteringEngine.java

/**
 * Prepares Carrot2 documents for clustering.
 *///from   w w w.  ja v a 2 s . c o m
private List<Document> getDocuments(SolrDocumentList solrDocList, Map<SolrDocument, Integer> docIds,
        Query query, final SolrQueryRequest sreq) throws IOException {
    SolrHighlighter highlighter = null;
    SolrParams solrParams = sreq.getParams();
    SolrCore core = sreq.getCore();

    String urlField = solrParams.get(CarrotParams.URL_FIELD_NAME, "url");
    String titleFieldSpec = solrParams.get(CarrotParams.TITLE_FIELD_NAME, "title");
    String snippetFieldSpec = solrParams.get(CarrotParams.SNIPPET_FIELD_NAME, titleFieldSpec);
    String languageField = solrParams.get(CarrotParams.LANGUAGE_FIELD_NAME, null);

    // Maps Solr field names to Carrot2 custom field names
    Map<String, String> customFields = getCustomFieldsMap(solrParams);

    // Parse language code map string into a map
    Map<String, String> languageCodeMap = new HashMap<>();
    if (StringUtils.isNotBlank(languageField)) {
        for (String pair : solrParams.get(CarrotParams.LANGUAGE_CODE_MAP, "").split("[, ]")) {
            final String[] split = pair.split(":");
            if (split.length == 2 && StringUtils.isNotBlank(split[0]) && StringUtils.isNotBlank(split[1])) {
                languageCodeMap.put(split[0], split[1]);
            } else {
                log.warn("Unsupported format for " + CarrotParams.LANGUAGE_CODE_MAP + ": '" + pair
                        + "'. Skipping this mapping.");
            }
        }
    }

    // Get the documents
    boolean produceSummary = solrParams.getBool(CarrotParams.PRODUCE_SUMMARY, false);

    SolrQueryRequest req = null;
    String[] snippetFieldAry = null;
    if (produceSummary) {
        highlighter = HighlightComponent.getHighlighter(core);
        if (highlighter != null) {
            Map<String, Object> args = new HashMap<>();
            snippetFieldAry = snippetFieldSpec.split("[, ]");
            args.put(HighlightParams.FIELDS, snippetFieldAry);
            args.put(HighlightParams.HIGHLIGHT, "true");
            args.put(HighlightParams.SIMPLE_PRE, ""); //we don't care about actually highlighting the area
            args.put(HighlightParams.SIMPLE_POST, "");
            args.put(HighlightParams.FRAGSIZE, solrParams.getInt(CarrotParams.SUMMARY_FRAGSIZE,
                    solrParams.getInt(HighlightParams.FRAGSIZE, 100)));
            args.put(HighlightParams.SNIPPETS, solrParams.getInt(CarrotParams.SUMMARY_SNIPPETS,
                    solrParams.getInt(HighlightParams.SNIPPETS, 1)));
            req = new LocalSolrQueryRequest(core, query.toString(), "", 0, 1, args) {
                @Override
                public SolrIndexSearcher getSearcher() {
                    return sreq.getSearcher();
                }
            };
        } else {
            log.warn("No highlighter configured, cannot produce summary");
            produceSummary = false;
        }
    }

    Iterator<SolrDocument> docsIter = solrDocList.iterator();
    List<Document> result = new ArrayList<>(solrDocList.size());

    float[] scores = { 1.0f };
    int[] docsHolder = new int[1];
    Query theQuery = query;

    while (docsIter.hasNext()) {
        SolrDocument sdoc = docsIter.next();
        String snippet = null;

        // TODO: docIds will be null when running distributed search.
        // See comment in ClusteringComponent#finishStage().
        if (produceSummary && docIds != null) {
            docsHolder[0] = docIds.get(sdoc).intValue();
            DocList docAsList = new DocSlice(0, 1, docsHolder, scores, 1, 1.0f);
            NamedList<Object> highlights = highlighter.doHighlighting(docAsList, theQuery, req,
                    snippetFieldAry);
            if (highlights != null && highlights.size() == 1) {
                // should only be one value given our setup
                // should only be one document
                @SuppressWarnings("unchecked")
                NamedList<String[]> tmp = (NamedList<String[]>) highlights.getVal(0);

                final StringBuilder sb = new StringBuilder();
                for (int j = 0; j < snippetFieldAry.length; j++) {
                    // Join fragments with a period, so that Carrot2 does not create
                    // cross-fragment phrases, such phrases rarely make sense.
                    String[] highlt = tmp.get(snippetFieldAry[j]);
                    if (highlt != null && highlt.length > 0) {
                        for (int i = 0; i < highlt.length; i++) {
                            sb.append(highlt[i]);
                            sb.append(" . ");
                        }
                    }
                }
                snippet = sb.toString();
            }
        }

        // If summaries not enabled or summary generation failed, use full content.
        if (snippet == null) {
            snippet = getConcatenated(sdoc, snippetFieldSpec);
        }

        // Create a Carrot2 document
        Document carrotDocument = new Document(getConcatenated(sdoc, titleFieldSpec), snippet,
                ObjectUtils.toString(sdoc.getFieldValue(urlField), ""));

        // Store Solr id of the document, we need it to map document instances 
        // found in clusters back to identifiers.
        carrotDocument.setField(SOLR_DOCUMENT_ID, sdoc.getFieldValue(idFieldName));

        // Set language
        if (StringUtils.isNotBlank(languageField)) {
            Collection<Object> languages = sdoc.getFieldValues(languageField);
            if (languages != null) {

                // Use the first Carrot2-supported language
                for (Object l : languages) {
                    String lang = ObjectUtils.toString(l, "");

                    if (languageCodeMap.containsKey(lang)) {
                        lang = languageCodeMap.get(lang);
                    }

                    // Language detection Library for Java uses dashes to separate
                    // language variants, such as 'zh-cn', but Carrot2 uses underscores.
                    if (lang.indexOf('-') > 0) {
                        lang = lang.replace('-', '_');
                    }

                    // If the language is supported by Carrot2, we'll get a non-null value
                    final LanguageCode carrot2Language = LanguageCode.forISOCode(lang);
                    if (carrot2Language != null) {
                        carrotDocument.setLanguage(carrot2Language);
                        break;
                    }
                }
            }
        }

        // Add custom fields
        if (customFields != null) {
            for (Entry<String, String> entry : customFields.entrySet()) {
                carrotDocument.setField(entry.getValue(), sdoc.getFieldValue(entry.getKey()));
            }
        }

        result.add(carrotDocument);
    }

    return result;
}

From source file:org.apache.torque.templates.transformer.SchemaTypeHelper.java

public static SqlType getDomain(SourceElement columnElement, ControllerState controllerState)
        throws SourceTransformerException {
    String domainNameFromSchema = (String) columnElement.getAttribute(TorqueSchemaAttributeName.DOMAIN);
    if (domainNameFromSchema == null) {
        // no domain specified
        return null;
    }//from ww  w . j  a v a2s  .  co  m
    SourceElement domainElement = null;
    {
        SourceElement databaseElement = columnElement.getParent().getParent();
        List<SourceElement> domainElementList = databaseElement.getChildren(TorqueSchemaElementName.DOMAIN);
        for (SourceElement candidate : domainElementList) {
            if (domainNameFromSchema.equals(candidate.getAttribute(TorqueSchemaAttributeName.NAME))) {
                domainElement = candidate;
                break;
            }
        }
    }
    if (domainElement == null) {
        throw new SourceTransformerException("The domain named " + domainNameFromSchema
                + " referenced by the column "
                + columnElement.getParent().getAttribute(TorqueSchemaAttributeName.NAME) + " in the table "
                + columnElement.getAttribute(TorqueSchemaAttributeName.NAME) + " was not found in this schema");
    }
    String sqlType = ObjectUtils.toString(domainElement.getAttribute(TorqueSchemaAttributeName.TYPE), null);
    String defaultValue = ObjectUtils.toString(domainElement.getAttribute(TorqueSchemaAttributeName.DEFAULT),
            null);
    String size = ObjectUtils.toString(domainElement.getAttribute(TorqueSchemaAttributeName.SIZE), null);
    String scale = ObjectUtils.toString(domainElement.getAttribute(TorqueSchemaAttributeName.SCALE), null);
    return new SqlType(sqlType, size, scale, defaultValue);
}

From source file:org.apache.torque.templates.transformer.sql.SQLTransformer.java

/**
 * Creates the SQL for defining a column.
 *
 * @param columnElement the column element for which the SQL
 *        should be created, not null.//from   ww w  . j  a va  2 s  .  c o  m
 * @param controllerState the current controller state, not null.
 *
 * @return the SQL for defining the column, not null.
 *
 * @throws SourceTransformerException
 */
private String getDdlSql(SourceElement columnElement, ControllerState controllerState)
        throws SourceTransformerException {
    SchemaType schemaType = SchemaTypeHelper.getSchemaType(columnElement, controllerState);
    SqlType domainType = SchemaTypeHelper.getDomain(columnElement, controllerState);
    Object size = columnElement.getAttribute(TorqueSchemaAttributeName.SIZE);
    Object scale = columnElement.getAttribute(TorqueSchemaAttributeName.SCALE);
    Object defaultValue = columnElement.getAttribute(TorqueSchemaAttributeName.DEFAULT);
    SqlType sqlType = SchemaTypeHelper.getSqlType(schemaType, domainType, controllerState,
            ObjectUtils.toString(size, null), ObjectUtils.toString(scale, null),
            ObjectUtils.toString(defaultValue, null));
    Platform platform = getPlatform(controllerState);

    List<String> resultList = new ArrayList<String>();

    String sqlTypeName = sqlType.getSqlTypeName();

    if (platform.hasSize(sqlTypeName)) {
        sqlTypeName += sqlType.printSize(platform.getSizeSuffix(sqlTypeName));
    }

    resultList.add(sqlTypeName);

    if (StringUtils.isNotEmpty(sqlType.getDefaultValue())) {
        resultList.add("default");

        if ((SchemaType.DATE == schemaType || SchemaType.TIME == schemaType
                || SchemaType.TIMESTAMP == schemaType)) {
            if (sqlType.getDefaultValue().startsWith("CURRENT_")) {
                resultList.add(sqlType.getDefaultValue());
            } else {
                Date defaultDate = OMColumnTransformer.getDefaultValueAsDate(sqlType.getDefaultValue());
                if (SchemaType.DATE == schemaType) {
                    resultList.add(platform.getDateString(defaultDate));
                } else if (SchemaType.TIME == schemaType) {
                    resultList.add(platform.getTimeString(defaultDate));
                } else {
                    resultList.add(platform.getTimestampString(defaultDate));
                }
            }
        } else if (TypeMap.isTextType(schemaType)) {
            resultList.add(platform.quoteAndEscape(sqlType.getDefaultValue()));
        } else {
            resultList.add(sqlType.getDefaultValue());
        }
    }

    boolean primaryKey;
    {
        String primaryKeyString = (String) columnElement.getAttribute(TorqueSchemaAttributeName.PRIMARY_KEY);
        primaryKey = Boolean.parseBoolean(primaryKeyString);
    }
    boolean required;
    {
        String requiredString = (String) columnElement.getAttribute(TorqueSchemaAttributeName.REQUIRED);
        required = Boolean.parseBoolean(requiredString);
    }
    boolean isNotNull = primaryKey || required;
    String isNotNullString = platform.getNullString(isNotNull);

    if (platform.createNotNullBeforeAutoincrement() && StringUtils.isNotEmpty(isNotNullString)) {
        resultList.add(isNotNullString);
    }
    // if idMethod was not set explicitly by the user,
    // the transformTable() method sets the attribute from the
    // defaultIdMethod of the database, so this always returns
    // the id method
    Object idMethod = columnElement.getParent().getAttribute(TorqueSchemaAttributeName.ID_METHOD);
    if (primaryKey && TorqueSchemaIdMethod.NATIVE.getName().equals(idMethod)) {
        String autoIncrement = platform.getAutoIncrement();
        if (StringUtils.isNotEmpty(autoIncrement)) {
            resultList.add(autoIncrement);
        }
    }
    if (!platform.createNotNullBeforeAutoincrement() && StringUtils.isNotEmpty(isNotNullString)) {
        resultList.add(isNotNullString);
    }
    return StringUtils.join(resultList.iterator(), ' ');
}

From source file:org.biouno.unochoice.AbstractScriptableParameter.java

@Override
public ParameterValue getDefaultParameterValue() {
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.entering(AbstractUnoChoiceParameter.class.getName(), "getDefaultParameterValue");
    }/*from  w  w  w .j ava 2 s  .  c  o m*/
    Object firstElement = "";
    final Map<Object, Object> choices = getChoices(Collections.<Object, Object>emptyMap());
    if (choices != null && !choices.isEmpty()) {
        firstElement = choices.entrySet().iterator().next().getValue();
    }
    final String name = getName();
    final String value = ObjectUtils.toString(firstElement, ""); // Jenkins doesn't like null parameter values
    final StringParameterValue stringParameterValue = new StringParameterValue(name, value);
    return stringParameterValue;
}

From source file:org.carrot2.workbench.core.ui.SearchEditor.java

/**
 * Attempts to construct an input title from either query attribute or attributes
 * found in processing results.// w  ww  . j a va2 s .  c om
 */
private String getFullInputTitle(SearchResult searchResult) {
    /*
     * Initially, set to dummy name.
     */
    String title = ObjectUtils.toString(this.searchResult.getInput().getAttribute(AttributeNames.QUERY), null);

    /*
     * If we have a processing result...
     */
    if (searchResult.hasProcessingResult()) {
        final ProcessingResult result = searchResult.getProcessingResult();

        /*
         * Check if there is a query in the output attributes (may be different from
         * the one set on input).
         */

        title = ObjectUtils.toString(result.getAttributes().get(AttributeNames.QUERY), null);

        /*
         * Override with custom title, if present.
         */

        title = ObjectUtils.toString(result.getAttributes().get(AttributeNames.PROCESSING_RESULT_TITLE), title);
    }

    if (StringUtils.isEmpty(title)) {
        title = "(empty query)";
    }

    return title;
}

From source file:org.displaytag.portlet.PortletHref.java

/**
 * @see org.displaytag.util.Href#addParameter(String, Object)
 *///from  ww w.  j a  v  a 2s.c  om
public Href addParameter(String name, Object objValue) {
    String value = ObjectUtils.toString(objValue, null);

    if (name != null && name.startsWith(PARAM_PREFIX)) {
        if (PARAM_TYPE.equals(name)) {
            if (TYPE_RENDER.equals(value)) {
                this.setAction(false);
            } else if (TYPE_ACTION.equals(value)) {
                this.setAction(true);
            } else {
                throw new IllegalArgumentException("Value of parameter '" + name + "' must be equal to '"
                        + TYPE_RENDER + "' or '" + TYPE_ACTION + "'. '" + value + "' is not allowed.");
            }
        } else if (PARAM_SECURE.equals(name)) {
            if (new Boolean(value).booleanValue()) {
                this.setRequestedSecure(true);
            } else {
                this.setRequestedSecure(false);
            }
        } else if (PARAM_MODE.equals(name)) {
            if (value == null) {
                this.setRequestedMode(null);
            } else {
                final PortletMode mode = new PortletMode(value);

                if (!this.portletRequest.isPortletModeAllowed(mode)) {
                    throw new IllegalArgumentException(
                            "PortletMode '" + mode + "' is not allowed for this request.");
                }

                this.setRequestedMode(mode);
            }
        } else if (PARAM_STATE.equals(name)) {
            if (value == null) {
                this.setRequestedState(null);
            } else {
                final WindowState state = new WindowState(value);

                if (!this.portletRequest.isWindowStateAllowed(state)) {
                    throw new IllegalArgumentException(
                            "WindowState '" + state + "' is not allowed for this request.");
                }

                this.setRequestedState(state);
            }
        } else {
            throw new IllegalArgumentException(
                    "'" + name + "' is not a valid '" + PARAM_PREFIX + "' prefixed parameter.");
        }
    } else {
        this.parameters.put(name, value);
    }

    return this;
}

From source file:org.displaytag.util.DefaultHref.java

/**
 * Adds a parameter to the href.//  w  w  w.  j  av a  2  s .  c  o  m
 * @param name String
 * @param value Object
 * @return this Href instance, useful for concatenation.
 */
public Href addParameter(String name, Object value) {
    this.parameters.put(name, ObjectUtils.toString(value, null));
    return this;
}

From source file:org.eclipse.jubula.client.ui.views.TestresultSummaryView.java

/**
 * Adds a "Test job Start Time" column to the given viewer.
 * @param tableViewer The viewer to which the column will be added.
 *///  ww w  . j  a v  a 2s  .com
private void addTestJobStartTimeColumn(TableViewer tableViewer) {
    TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
    column.getColumn().setWidth(0);
    column.getColumn().setImage(IconConstants.CLOCK_IMAGE);
    column.getColumn().setText(TESTRESULT_SUMMARY_TEST_JOB_START_TIME);
    column.getColumn().setMoveable(true);
    column.setLabelProvider(new TestresultSummaryViewColumnLabelProvider() {
        public String getText(Object element) {
            Date date = ((ITestResultSummaryPO) element).getTestJobStartTime();
            if (date != null) {
                return DTF_LONG.format(date);
            }
            return ObjectUtils.toString(date, StringConstants.EMPTY);
        }
    });
    createMenuItem(m_headerMenu, column.getColumn());
    new ColumnViewerSorter(tableViewer, column) {
        @Override
        protected int doCompare(Viewer viewer, Object e1, Object e2) {
            return getCommonsComparator().compare(((ITestResultSummaryPO) e1).getTestJobStartTime(),
                    ((ITestResultSummaryPO) e2).getTestJobStartTime());
        }
    };
}