Example usage for java.util Objects toString

List of usage examples for java.util Objects toString

Introduction

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

Prototype

public static String toString(Object o, String nullDefault) 

Source Link

Document

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

Usage

From source file:com.norconex.commons.lang.map.Properties.java

/**
 * <p>Reads all key/value pairs in the given map, and 
 * add them to this <code>Map</code>.  Keys are converted to strings
 * using their toString() method, with exception
 * of values being arrays or collections.  In such case, the entry
 * is considered a multi-value one and each value will be converted
 * to individual strings. <code>null</code> keys are ignored.
 * <code>null</code> values are converted to an empty string.</p> 
 * <p>Changes to this instance/*w  w w  .jav a 2s  .com*/
 * won't be reflected in the given <code>Map</code>.  If you want otherwise,
 * use invoke the constructor with a <code>Map</code> argument.</p>
 * 
 * @param map the map containing values to load
 */
public synchronized void load(Map<?, ?> map) {
    if (map != null) {
        for (Entry<?, ?> entry : map.entrySet()) {
            Object keyObj = entry.getKey();
            if (keyObj == null) {
                continue;
            }
            String key = Objects.toString(keyObj, null);
            Object valObj = entry.getValue();
            if (valObj == null) {
                valObj = StringUtils.EMPTY;
            }
            Iterable<?> it = null;
            if (valObj.getClass().isArray()) {
                it = Arrays.asList((Object[]) valObj);
            } else if (valObj instanceof Iterable) {
                it = (Iterable<?>) valObj;
            }
            if (it == null) {
                addString(key, Objects.toString(valObj, null));
            } else {
                for (Object val : it) {
                    addString(key, Objects.toString(val, null));
                }
            }
        }
    }
}

From source file:com.yinghua.translation.rest.PhoneResourceRESTService.java

/**
 * ??/*from   w  w w . j a  v  a2  s.  c o  m*/
 * 
 * @param params
 * @return
 */
@POST
@Path("/preBankOrder")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> preBankOrder(String params) {
    Map<String, Object> req = new HashMap<>();
    JSONObject obj = JSONObject.parseObject(params);

    //????

    String uno = obj.getString("uno");
    String prod_no = Objects.toString(obj.getString("packageNo"), "0");
    Float orderPrice = obj.getFloat("price");
    String pay_way = obj.getString("pay_way");
    String service_time = obj.getString("service_time");
    int use_date = obj.getIntValue("use_date");

    PackageProduct packageProduct = packageProductBean.findByPackageNo(prod_no);

    if (packageProduct != null) {
        //??
        MemberOrder order = new MemberOrder();
        order.setMemberNumber(uno);
        order.setOrderTime(new Date());
        order.setPackageNo(prod_no);
        order.setPackageName(packageProduct.getSubject());
        order.setPackageType(packageProduct.getType());
        order.setPackageDesc(packageProduct.getDesc());
        order.setOrderNo(OrderNoUtil.getOrderNo("OR"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            order.setServiceTime(sdf.parse(service_time));
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        order.setSurplusCallDuration(packageProduct.getSurplusCallDuration() * use_date);
        order.setUseDate(use_date);
        order.setUseState(OrderUseStatus.PERPARE);
        order.setState(OrderStatus.CREATED);
        order.setOrderPrice(String.valueOf(orderPrice));
        order.setPayWay(pay_way);

        Long id = memberOrderBean.createOrder(order);

        if (id > 0) {
            //??app
            req.put("result", "success");
            req.put("error_code", "000000");
            req.put("error_msg", "");
        }

    } else {
        req.put("result", "fail");
        req.put("error_code", "5005");
        req.put("error_msg", "??");
    }
    return req;
}

From source file:de.micromata.genome.util.types.Converter.java

/**
 * Object to debug string./*w  w w  . j  a  v a2 s.  com*/
 *
 * @param obj the obj
 * @return the string
 */
public static String objectToDebugString(Object obj) {
    if (obj == null) {
        return "";
    }
    if (obj instanceof java.util.Date) {
        return dateToDebugString((java.util.Date) obj);
    }
    return Objects.toString(obj, StringUtils.EMPTY);
}

From source file:org.openecomp.sdnc.sli.SliPluginUtils.SliPluginUtils.java

/**
 * Sets a key in context memory to the output of object's toString().
 * <p>/*ww w  .j av  a2s  .c  o  m*/
 * The key is deleted from context memory if object is null. The key and
 * value set in context memory are logged to the Logger at the provided
 * logLevel level.
 * @param <O> Any Java object
 * @param ctx Reference to context memory.
 * @param key Key to set.
 * @param obj Object whose toString() will be the value set
 * @param LOG Logger to log to
 * @param logLevel level to log at in Logger
 */
public static final <O extends Object> void ctxSetAttribute(SvcLogicContext ctx, String key, O obj, Logger LOG,
        LogLevel logLevel) {
    String value = Objects.toString(obj, null);
    ctx.setAttribute(key, value);
    if (logLevelIsEnabled(LOG, logLevel)) {
        if (value == null) {
            logMessageAtLevel(LOG, logLevel, "Deleting " + key);
        } else {
            logMessageAtLevel(LOG, logLevel, "Setting " + key + " = " + value);
        }
    }
}

From source file:org.openhab.binding.powermax.internal.PowerMaxBinding.java

/**
 * {@inheritDoc}//from   ww w. j a  va 2s . c o m
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("updated(): updating configuration");

    closeConnection();

    serialPort = null;
    ipAddress = null;
    tcpPort = 0;
    motionOffDelay = DEFAULT_MOTION_OFF_DELAY;
    allowArming = false;
    allowDisarming = false;
    forceStandardMode = false;
    panelType = PowerMaxPanelType.POWERMAX_PRO;
    autoSyncTime = false;
    pinCode = null;

    PowerMaxReceiveType.POWERLINK.setHandlerClass(PowerMaxPowerlinkMessage.class);

    if (config != null) {
        String serialPortString = Objects.toString(config.get("serialPort"), null);
        if (StringUtils.isNotBlank(serialPortString)) {
            serialPort = serialPortString;
        }

        String ipString = Objects.toString(config.get("ip"), null);
        if (StringUtils.isNotBlank(ipString)) {
            ipAddress = ipString;
        }

        if (serialPort == null && ipAddress == null) {
            logger.warn(
                    "PowerMax alarm binding: one connection type (Serial Port or IP Address) must be defined");
            this.setProperlyConfigured(false);
            throw new ConfigurationException(null,
                    "one connection type (Serial Port or IP Address) must be defined");
        }

        if (serialPort != null && ipAddress != null) {
            logger.warn(
                    "PowerMax alarm binding: can only configure one connection type at a time: Serial Port or IP Address");
            this.setProperlyConfigured(false);
            throw new ConfigurationException(null,
                    "can only configure one connection type at a time: Serial Port or IP Address");
        }

        if (ipAddress != null) {
            String tcpPortString = Objects.toString(config.get("tcpPort"), null);
            if (StringUtils.isNotBlank(tcpPortString)) {
                try {
                    tcpPort = Integer.parseInt(tcpPortString);
                } catch (NumberFormatException numberFormatException) {
                    tcpPort = 0;
                    logger.warn(
                            "PowerMax alarm binding: TCP port not configured correctly (number expected, received '{}')",
                            tcpPortString);
                    this.setProperlyConfigured(false);
                    throw new ConfigurationException("tcpPort",
                            "TCP port not configured correctly (number expected, received '" + tcpPortString
                                    + "')");
                }
            }
        }

        String motionOffDelayString = Objects.toString(config.get("motionOffDelay"), null);
        if (StringUtils.isNotBlank(motionOffDelayString)) {
            try {
                motionOffDelay = Integer.parseInt(motionOffDelayString) * 60000;
            } catch (NumberFormatException numberFormatException) {
                motionOffDelay = DEFAULT_MOTION_OFF_DELAY;
                logger.warn(
                        "PowerMax alarm binding: motion off delay not configured correctly (number expected, received '{}')",
                        motionOffDelayString);
            }
        }

        String allowArmingString = Objects.toString(config.get("allowArming"), null);
        if (StringUtils.isNotBlank(allowArmingString)) {
            allowArming = Boolean.valueOf(allowArmingString);
        }
        String allowDisarmingString = Objects.toString(config.get("allowDisarming"), null);
        if (StringUtils.isNotBlank(allowDisarmingString)) {
            allowDisarming = Boolean.valueOf(allowDisarmingString);
        }
        String forceStandardModeString = Objects.toString(config.get("forceStandardMode"), null);
        if (StringUtils.isNotBlank(forceStandardModeString)) {
            forceStandardMode = Boolean.valueOf(forceStandardModeString);
            PowerMaxReceiveType.POWERLINK.setHandlerClass(
                    forceStandardMode ? PowerMaxBaseMessage.class : PowerMaxPowerlinkMessage.class);
        }

        String panelTypeString = Objects.toString(config.get("panelType"), null);
        if (StringUtils.isNotBlank(panelTypeString)) {
            try {
                panelType = PowerMaxPanelType.fromLabel(panelTypeString);
            } catch (IllegalArgumentException exception) {
                panelType = PowerMaxPanelType.POWERMAX_PRO;
                logger.warn("PowerMax alarm binding: panel type not configured correctly");
            }
        }
        PowerMaxPanelSettings.initPanelSettings(panelType);

        String autoSyncTimeString = Objects.toString(config.get("autoSyncTime"), null);
        if (StringUtils.isNotBlank(autoSyncTimeString)) {
            autoSyncTime = Boolean.valueOf(autoSyncTimeString);
        }

        String pinCodeString = Objects.toString(config.get("pinCode"), null);
        if (StringUtils.isNotBlank(pinCodeString)) {
            pinCode = pinCodeString;
        }

        this.setProperlyConfigured(true);
    }
}

From source file:org.apache.carbondata.presto.impl.CarbonTableReader.java

public Configuration updateS3Properties(Configuration configuration) {
    configuration.set(ACCESS_KEY, Objects.toString(config.getS3A_AcesssKey(), ""));
    configuration.set(SECRET_KEY, Objects.toString(config.getS3A_SecretKey()));
    configuration.set(CarbonCommonConstants.S3_ACCESS_KEY, Objects.toString(config.getS3_AcesssKey(), ""));
    configuration.set(CarbonCommonConstants.S3_SECRET_KEY, Objects.toString(config.getS3_SecretKey()));
    configuration.set(CarbonCommonConstants.S3N_ACCESS_KEY, Objects.toString(config.getS3N_AcesssKey(), ""));
    configuration.set(CarbonCommonConstants.S3N_SECRET_KEY, Objects.toString(config.getS3N_SecretKey(), ""));
    configuration.set(ENDPOINT, Objects.toString(config.getS3EndPoint(), ""));
    return configuration;
}

From source file:com.github.helenusdriver.driver.impl.RootClassInfoImpl.java

/**
 * {@inheritDoc}//from   w  w  w  .j  a v  a2 s  .c om
 *
 * @author paouelle
 *
 * @see com.github.helenusdriver.driver.impl.ClassInfoImpl#getObject(com.datastax.driver.core.Row, java.util.Map)
 */
@Override
public T getObject(Row row, Map<String, Object> suffixes) {
    if (row == null) {
        return null;
    }
    // extract the type so we know which object we are creating
    for (final ColumnDefinitions.Definition coldef : row.getColumnDefinitions()) {
        // find the table for this column
        final TableInfoImpl<T> table = (TableInfoImpl<T>) getTable(coldef.getTable());

        if (table != null) {
            // find the field in the table for this column
            final FieldInfoImpl<T> field = table.getColumn(coldef.getName());

            if ((field != null) && field.isTypeKey()) { // get the POJO type
                final String type = Objects.toString(field.decodeValue(row), null);
                final TypeClassInfoImpl<? extends T> tcinfo = ntypes.get(type);

                if (tcinfo == null) {
                    throw new ObjectConversionException(clazz, row, "unknown POJO type: " + type);
                }
                return tcinfo.getObject(row, type, suffixes);
            }
        }
    }
    throw new ObjectConversionException(clazz, row, "missing POJO type column");
}

From source file:com.yinghua.translation.rest.PhoneResourceRESTService.java

/**
 * //w w  w. j a va 2  s .  c om
 * 
 * @param params
 * @return
 */
@POST
@Path("/makeOrder")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> makeOrder(String params) {
    Map<String, Object> req = new HashMap<>();
    JSONObject obj = JSONObject.parseObject(params);
    String uid = obj.getString("uid");
    String uno = obj.getString("uno");
    String prod_no = Objects.toString(obj.getString("productNo"), "0");
    String price = obj.getString("price");
    String pay_way = obj.getString("pay_way");

    Product product = productBean.findByProductNo(prod_no);
    Account account = accountBean.findByMemberNo(uno);
    if (product != null) {
        Map<String, Object> chargeMap = new HashMap<String, Object>();

        Order order = new Order();
        order.setAmount(product.getPrice());
        order.setCreateTime(new Date(System.currentTimeMillis()));
        order.setLanguages(product.getLanguages());
        order.setProdType(product.getType());
        order.setProdId(product.getProductNo());
        order.setProdName(product.getSubject());
        order.setPayWay(pay_way);
        order.setState(OrderStatus.CREATED);
        order.setOrderNo(OrderNoUtil.getOrderNo("OR"));
        order.setMemberNumber(uno);

        Long id = orderBean.createOrder(order);
        Charge charge;
        if (id > 0) {
            chargeMap.put("amount", order.getPrice());
            chargeMap.put("currency", "cny");
            chargeMap.put("subject", order.getProdName());
            chargeMap.put("body", "Your Body");
            chargeMap.put("order_no", order.getOrderNo());

            switch (pay_way) {
            case "0":
                req.put("order_no", order.getOrderNo());
                req.put("amount", order.getAmount().toString());
                req.put("pay_way", order.getPayWay());
                req.put("credential", "");
                req.put("error_code", "000000");
                req.put("error_msg", "");
                break;
            case "1":
                chargeMap.put("channel", "alipay");
                chargeMap.put("client_ip", "127.0.0.1");
                try {
                    charge = paymentBean.charge(chargeMap);
                    order.setCredential(JSONObject.toJSONString(charge).toString());
                    orderBean.updateOrder(order);
                    req.put("charge", JSONObject.toJSONString(charge).toString());
                    req.put("order_no", order.getOrderNo());
                    req.put("amount", order.getPrice());
                    req.put("pay_way", order.getPayWay());
                    req.put("credential", order.getCredential());
                    req.put("error_code", "000000");
                    req.put("error_msg", "");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    log.info(e.getMessage());
                    req.put("result", "fail");
                    req.put("error_code", "5001");
                    req.put("error_msg", "");
                }
                break;
            case "2":
                chargeMap.put("channel", "wx");
                chargeMap.put("client_ip", "127.0.0.1");
                chargeMap.put("order_no", order.getOrderNo());
                //Integer am = order.getAmount().multiply(new BigDecimal(100)).;
                chargeMap.put("amount", order.getAmount().multiply(new BigDecimal(100)).intValue());
                try {
                    charge = paymentBean.charge(chargeMap);
                    order.setCredential(JSONObject.toJSONString(charge).toString());
                    orderBean.updateOrder(order);
                    req.put("charge", JSONObject.toJSONString(charge).toString());
                    req.put("charge_id", charge.getId());
                    req.put("order_no", order.getOrderNo());
                    req.put("amount", order.getAmount());
                    req.put("pay_way", order.getPayWay());
                    req.put("credential", order.getCredential());
                    req.put("error_code", "000000");
                    req.put("error_msg", "");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    log.info(e.getMessage());
                    req.put("result", "fail");
                    req.put("error_code", "5001");
                    req.put("error_msg", "");
                }
                break;
            case "3":
                req.put("order_no", order.getOrderNo());
                req.put("amount", order.getPrice());
                req.put("pay_way", order.getPayWay());
                req.put("credential", "");
                req.put("error_code", "000000");
                req.put("error_msg", "");
                break;
            case "4":
                req.put("order_no", order.getOrderNo());
                req.put("amount", order.getPrice());
                req.put("pay_way", order.getPayWay());
                req.put("credential", "");
                req.put("error_code", "000000");
                req.put("error_msg", "");
                break;
            }
        }
    } else {
        req.put("result", "fail");
        req.put("error_code", "5005");
        req.put("error_msg", "??");
    }
    return req;
}

From source file:org.xwiki.xar.XarPackage.java

/**
 * Write the package descriptor to the passed XML stream.
 * /*from  w ww.ja  v a  2s . c  o  m*/
 * @param writer the XML stream where to write
 * @throws XMLStreamException when failing to write the file
 */
public void write(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartElement(XarModel.ELEMENT_PACKAGE);

    writer.writeStartElement(XarModel.ELEMENT_INFOS);
    writeElement(writer, XarModel.ELEMENT_INFOS_NAME, getPackageName(), true);
    writeElement(writer, XarModel.ELEMENT_INFOS_DESCRIPTION, getPackageDescription(), true);
    writeElement(writer, XarModel.ELEMENT_INFOS_LICENSE, getPackageLicense(), true);
    writeElement(writer, XarModel.ELEMENT_INFOS_AUTHOR, getPackageAuthor(), true);
    writeElement(writer, XarModel.ELEMENT_INFOS_VERSION, getPackageVersion(), true);
    writeElement(writer, XarModel.ELEMENT_INFOS_ISBACKUPPACK, String.valueOf(isPackageBackupPack()), true);
    writeElement(writer, XarModel.ELEMENT_INFOS_ISPRESERVEVERSION, String.valueOf(isPackagePreserveVersion()),
            true);
    writeElement(writer, XarModel.ELEMENT_INFOS_EXTENSIONID, getPackageExtensionId(), false);
    writer.writeEndElement();

    writer.writeStartElement(XarModel.ELEMENT_FILES);
    for (XarEntry entry : this.entries.values()) {
        writer.writeStartElement(XarModel.ELEMENT_FILES_FILE);
        writer.writeAttribute(XarModel.ATTRIBUTE_DEFAULTACTION, String.valueOf(entry.getDefaultAction()));
        writer.writeAttribute(XarModel.ATTRIBUTE_LOCALE, Objects.toString(entry.getLocale(), ""));
        writer.writeCharacters(TOSTRING_SERIALIZER.serialize(entry));
        writer.writeEndElement();
    }
    writer.writeEndElement();
}

From source file:com.github.fengtan.sophie.tables.DocumentsTable.java

/**
 * Upload local changes to the Solr server.
 * //from   w ww  .j  a  v a  2s  . c o m
 * @throws SophieException
 *             If the local changes could not be uploaded to the Solr
 *             server.
 */
public void upload() throws SophieException {
    // Upload local updates.
    for (SolrDocument document : documentsUpdated) {
        SolrInputDocument input = new SolrInputDocument();
        for (String name : document.getFieldNames()) {
            input.addField(name, document.getFieldValue(name), 1.0f);
        }
        try {
            // Returned object seems to have no relevant information.
            Sophie.client.add(input);
        } catch (SolrServerException | IOException | SolrException e) {
            throw new SophieException("Unable to update document in index: " + input.toString(), e);
        }
    }
    // Upload local deletions.
    for (SolrDocument document : documentsDeleted) {
        String id = Objects.toString(document.getFieldValue(uniqueField), StringUtils.EMPTY);
        try {
            Sophie.client.deleteById(id);
        } catch (SolrServerException | IOException | SolrException e) {
            throw new SophieException("Unable to delete document from index: " + id, e);
        }
    }
    // Upload local additions.
    for (SolrDocument document : documentsAdded) {
        SolrInputDocument input = new SolrInputDocument();
        for (String name : document.getFieldNames()) {
            input.addField(name, document.getFieldValue(name), BOOST);
        }
        try {
            // Returned object seems to have no relevant information.
            Sophie.client.add(input);
        } catch (SolrServerException | IOException | SolrException e) {
            throw new SophieException("Unable to add document to index: " + input.toString(), e);
        }
    }
    // Commit the index.
    try {
        Sophie.client.commit();
    } catch (SolrServerException | IOException | SolrException e) {
        throw new SophieException("Unable to commit index", e);
    }

    // Refresh so user can see the new state of the server.
    refresh();
}