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:org.eclipse.smarthome.io.rest.sitemap.SitemapSubscriptionService.java

private void applyConfig(Map<String, Object> config) {
    if (config == null) {
        return;// w w  w  .  j a va2  s .  c o  m
    }
    final String max = Objects.toString(config.get("maxSubscriptions"), null);
    if (max != null) {
        try {
            maxSubscriptions = Integer.parseInt(max);
        } catch (NumberFormatException e) {
            logger.debug("Setting 'maxSubscriptions' must be a number; value '{}' ignored.", max);
        }
    }
}

From source file:org.codice.ddf.configuration.admin.ExportMigrationConfigurationAdminContext.java

/**
 * This method is designed to circumvent a bug in Felix where it has been seen that a config
 * object that is meant to represent a managed service factory is not properly created. Instead of
 * being created using the createFactoryConfiguration(), it is obtained using getConfiguration().
 * After that, the properties are updated with the service factory pid as a property. Although it
 * has that property, it ain't a real managed service factory as the factory or blueprint was
 * never called to instantiate a corresponding service. In such case, we end up with a dummy
 * config object in memory that is not attached to an actual instance of manager service.
 *
 * <p>If we were to export that object, we would end up re-creating it as a managed service
 * factory on the other system and we potentially could end up with multiple instances of that
 * manager service which could create problem. In addition, the system would not be a proper
 * representation of the original system which didn't have that associated managed service.
 *
 * <p>We do not intent to protect against all possible stupidity they could do (e.g. different
 * factory pid in properties than reported by the config object's interface). We only protect
 * against the object not being created as a managed service factory when it should have been.
 *
 * @param cfg the config to check its validity
 * @return <code>true</code> if the config is valid; <code>false</code> otherwise
 *///from   w  w w.  j av a  2s  . co  m
private boolean isValid(Configuration cfg) {
    final String fpid = Objects.toString(cfg.getProperties().get(ConfigurationAdmin.SERVICE_FACTORYPID), null);

    if (fpid == null) {
        return true;
    } // else - property reports it should be a managed service factory, so it is valid only if the
      // cfg object reports it is too
    return ConfigurationAdminMigratable.isManagedServiceFactory(cfg);
}

From source file:org.xwiki.filter.xar.internal.output.XAROutputFilterStream.java

public String toString(Object obj) {
    return Objects.toString(obj, null);
}

From source file:org.craftercms.deployer.impl.rest.TargetController.java

/**
 * Creates a Deployer {@link Target}./*from   w  w w .  j av  a2  s.co m*/
 *
 * @param params the body of the request with the template parameters that will be used to create the target. The body must
 *                   contain at least a {@code env} and {@code site_name} parameter. Other required parameters depend on the
 *                   template used.
 *
 * @return the response entity 201 CREATED status
 *
 * @throws DeployerException   if an error ocurred during target creation
 * @throws ValidationException if a required parameter is missing
 */
@RequestMapping(value = CREATE_TARGET_URL, method = RequestMethod.POST)
public ResponseEntity<Result> createTarget(@RequestBody Map<String, Object> params)
        throws DeployerException, ValidationException {
    String env = "";
    String siteName = "";
    boolean replace = false;
    String templateName = "";
    Map<String, Object> templateParams = new HashMap<>();

    for (Map.Entry<String, Object> param : params.entrySet()) {
        switch (param.getKey()) {
        case ENV_PATH_VAR_NAME:
            env = Objects.toString(param.getValue(), "");
            break;
        case SITE_NAME_PATH_VAR_NAME:
            siteName = Objects.toString(param.getValue(), "");
            break;
        case REPLACE_PARAM_NAME:
            replace = BooleanUtils.toBoolean(param.getValue());
            break;
        case TEMPLATE_NAME_PARAM_NAME:
            templateName = Objects.toString(param.getValue(), "");
            break;
        default:
            templateParams.put(param.getKey(), param.getValue());
            break;
        }
    }

    ValidationResult validationResult = new ValidationResult();

    if (StringUtils.isEmpty(env)) {
        validationResult.addError(ENV_PATH_VAR_NAME, ErrorCodes.FIELD_MISSING_ERROR_CODE);
    }
    if (StringUtils.isEmpty(siteName)) {
        validationResult.addError(SITE_NAME_PATH_VAR_NAME, ErrorCodes.FIELD_MISSING_ERROR_CODE);
    }
    if (validationResult.hasErrors()) {
        throw new ValidationException(validationResult);
    }

    targetService.createTarget(env, siteName, replace, templateName, templateParams);

    return new ResponseEntity<>(Result.OK,
            RestServiceUtils.setLocationHeader(new HttpHeaders(), BASE_URL + GET_TARGET_URL, env, siteName),
            HttpStatus.CREATED);
}

From source file:org.openhab.binding.denon.internal.DenonBinding.java

/**
 * {@inheritDoc}// w  w w.j a v a 2 s .  c om
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("Denon binding updated");

    if (config == null) {
        return;
    }

    Enumeration<String> keys = config.keys();

    while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        if (CONFIG_SERVICE_PID.equals(key)) {
            continue;
        }

        String[] parts = key.split("\\.");
        String value = Objects.toString(config.get(key), null);

        if (parts.length == 1) {
            String option = parts[0];
            if (CONFIG_REFRESH.equals(option)) {
                refreshInterval = Integer.valueOf(value);
            }
        } else {
            String instance = parts[0];

            DenonConnectionProperties connection = connections.get(instance);
            if (connection == null) {
                connection = new DenonConnectionProperties();
                connection.setInstance(instance);
                connections.put(instance, connection);
            }

            String option = parts[1].trim();

            if (CONFIG_HOST.equals(option)) {
                connection.setHost(value);
            } else if (CONFIG_UPDATE_TYPE.equals(option)) {
                connection.setTelnet(value.equals(CONFIG_UPDATE_TYPE_TELNET));
                connection.setHttp(value.equals(CONFIG_UPDATE_TYPE_HTTP));

                if (!value.equals(CONFIG_UPDATE_TYPE_TELNET) && !value.equals(CONFIG_UPDATE_TYPE_HTTP)) {
                    logger.warn("Invalid connection type {} for instance {}, using default", value, instance);
                }
            }
        }
    }

    boolean isActiveBinding = false;

    for (Entry<String, DenonConnectionProperties> entry : connections.entrySet()) {
        DenonConnectionProperties connection = entry.getValue();

        if (!StringUtils.isBlank(connection.getHost())) {
            logger.debug("Denon receiver configured at {}", connection.getHost());
            DenonConnector connector = new DenonConnector(connection, new DenonPropertyUpdatedCallback() {
                @Override
                public void updated(String instance, String property, State state) {
                    processPropertyUpdated(instance, property, state);
                }
            });
            connection.setConnector(connector);
            connector.connect();

            if (connection.isHttp()) {
                isActiveBinding = true;
            }
        } else {
            logger.debug("No host configured for receiver {}", connection.getInstance());
        }
    }

    setProperlyConfigured(isActiveBinding);
}

From source file:jvmoptions.OptionAnalyzer.java

static Map<String, Map<String, String>> parse(Path hpp) {
    System.out.printf("process %s %n", hpp);
    String file = hpp.subpath(4, hpp.getNameCount()).toString().replace(File.separatorChar, '/');
    try {//from  w  w w .j  a v a2  s  .co m
        String all = preprocess(hpp);

        String categories = "(?<kind>develop|develop_pd|product|product_pd|diagnostic|experimental|notproduct|manageable|product_rw|lp64_product)";

        // detect Regex bugs.
        List<String> names = parseNames(all, categories);
        Set<String> nameSet = new HashSet<>();

        Pattern descPtn = Pattern.compile("\"((\\\\\"|[^\"])+)\"");
        Pattern pattern = Pattern.compile(categories
                + "\\((?<type>\\w+?),[ ]*(?<name>\\w+)[ ]*(,[ ]*(?<default>[\\w ()\\-+/*.\"]+))?,[ ]*(?<desc>("
                + descPtn.pattern() + "[ ]*)+)\\)");

        Map<String, Map<String, String>> result = new HashMap<>();

        int times = 0;
        for (Matcher matcher = pattern.matcher(all); matcher.find(); times++) {
            String name = matcher.group("name");
            verify(names, nameSet, times, name);

            String def = Objects.toString(matcher.group("default"), "");

            String d = matcher.group("desc");
            StringBuilder desc = new StringBuilder();
            for (Matcher m = descPtn.matcher(d); m.find();) {
                desc.append(m.group(1).replaceAll("\\\\", ""));
            }

            Map<String, String> m = new HashMap<>();
            m.put("kind", matcher.group("kind"));
            m.put("type", matcher.group("type"));
            m.put("default", def);
            m.put("description", desc.toString());
            m.put("file", file);
            result.put(name, m);
        }
        System.out.printf("        %s contains %d options%n", hpp, times);

        return result;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.eclipse.smarthome.ui.internal.chart.ChartServlet.java

/**
 * Handle the initial or a changed configuration.
 *
 * @param config the configuration/*from   w w  w.j a v a  2 s. c o  m*/
 */
private void applyConfig(Map<String, Object> config) {
    if (config == null) {
        return;
    }

    final String providerNameString = Objects.toString(config.get("provider"), null);
    if (providerNameString != null) {
        providerName = providerNameString;
    }

    final String defaultHeightString = Objects.toString(config.get("defaultHeight"), null);
    if (defaultHeightString != null) {
        try {
            defaultHeight = Integer.parseInt(defaultHeightString);
        } catch (NumberFormatException e) {
            logger.warn("'{}' is not a valid integer value for the defaultHeight parameter.",
                    defaultHeightString);
        }
    }

    final String defaultWidthString = Objects.toString(config.get("defaultWidth"), null);
    if (defaultWidthString != null) {
        try {
            defaultWidth = Integer.parseInt(defaultWidthString);
        } catch (NumberFormatException e) {
            logger.warn("'{}' is not a valid integer value for the defaultWidth parameter.",
                    defaultWidthString);
        }
    }

    final String scaleString = Objects.toString(config.get("scale"), null);
    if (scaleString != null) {
        try {
            scale = Double.parseDouble(scaleString);
            // Set scale to normal if the custom value is unrealistically low
            if (scale < 0.1) {
                scale = 1.0;
            }
        } catch (NumberFormatException e) {
            logger.warn("'{}' is not a valid number value for the scale parameter.", scaleString);
        }
    }

    final String maxWidthString = Objects.toString(config.get("maxWidth"), null);
    if (maxWidthString != null) {
        try {
            maxWidth = Integer.parseInt(maxWidthString);
        } catch (NumberFormatException e) {
            logger.warn("'{}' is not a valid integer value for the maxWidth parameter.", maxWidthString);
        }
    }
}

From source file:info.bunji.mongodb.synces.SyncOperation.java

/**
 **********************************//  w  ww  .  ja va2  s  .co  m
 * 
 * @param oplogDoc
 * @param destDbName
 **********************************
 */
public SyncOperation(Document oplogDoc, String destDbName) {

    this.op = Operation.valueOf(oplogDoc.get("op"));
    this.destDbName = destDbName;

    String ns = oplogDoc.getString("ns");

    String[] nsVals = ns.split("\\.", 2);
    this.srcDbName = nsVals[0];
    this.collection = nsVals[1];

    this.ts = oplogDoc.get("ts", BsonTimestamp.class);

    Document o1Doc = oplogDoc.get("o", Document.class);
    Document o2Doc = oplogDoc.get("o2", Document.class);

    switch (op) {
    case INSERT:
        if (o1Doc != null && o1Doc.containsKey(SyncConfig.ID_FIELD)) {
            this.id = o1Doc.remove(SyncConfig.ID_FIELD).toString();
            this.doc = o1Doc;
        }
        break;
    case DELETE:
        if (o1Doc != null && o1Doc.containsKey(SyncConfig.ID_FIELD)) {
            this.id = o1Doc.remove(SyncConfig.ID_FIELD).toString();
        }
        break;
    case UPDATE:
        if (o1Doc.containsKey("$unset") || o1Doc.containsKey("$set")) {
            this.isPartialUpdate = true;
            //         } else {
            //            this.doc = o1Doc;
        }
        this.doc = o1Doc;
        //this.id = o2Doc.get("_id").toString();
        this.id = Objects.toString(o2Doc.get("_id"), null);
        if (this.id == null)
            this.op = Operation.UNKNOWN;
        break;
    case COMMAND:
        if (o1Doc.containsKey("drop")) {
            // drop collection
            this.op = Operation.DROP_COLLECTION;
            this.collection = o1Doc.getString("drop");
        } else if (o1Doc.containsKey("create")) {
            // create collection
            this.collection = o1Doc.getString("create");
            this.op = Operation.CREATE_COLLECTION;
        } else if (o1Doc.containsKey("renameCollection")) {
            // rename collection(drop source collection)
            //            this.doc = o1Doc;
            //            doc.append("from", doc.remove("renameCollection"));
            //            this.op = Operation.RENAME_COLLECTION;
            nsVals = o1Doc.getString("renameCollection").split("\\.", 2);
            this.srcDbName = nsVals[0];
            this.op = Operation.DROP_COLLECTION;
            this.collection = o1Doc.getString("renameCollection");
            logger.debug(this.toString());

            // TODO rename?collection??oplog????(mongodb??????)
            // rename????(oplog??????????)

        } else {
            this.op = Operation.UNKNOWN;
        }
        break;
    default:
        break;
    }
}

From source file:io.wcm.config.core.management.util.TypeConversion.java

/**
 * Converts a OSGi configuration property value to an object with the given parameter type.
 * @param value String value (not null)//from  w  w w . ja  v a 2s  .  co m
 * @param type Parameter type
 * @param defaultValue Default value is used if not OSGi configuration value is set
 * @return Converted value
 * @throws IllegalArgumentException If type is not supported
 */
@SuppressWarnings("unchecked")
public static <T> T osgiPropertyToObject(Object value, Class<T> type, T defaultValue) {
    // only selected parameter types are supported
    if (type == String.class) {
        return (T) PropertiesUtil.toString(value, (String) defaultValue);
    }
    if (type == String[].class) {
        return (T) PropertiesUtil.toStringArray(value, (String[]) defaultValue);
    } else if (type == Integer.class) {
        Integer defaultIntValue = (Integer) defaultValue;
        if (defaultIntValue == null) {
            defaultIntValue = 0;
        }
        return (T) (Integer) PropertiesUtil.toInteger(value, defaultIntValue);
    } else if (type == Long.class) {
        Long defaultLongValue = (Long) defaultValue;
        if (defaultLongValue == null) {
            defaultLongValue = 0L;
        }
        return (T) (Long) PropertiesUtil.toLong(value, defaultLongValue);
    } else if (type == Double.class) {
        Double defaultDoubleValue = (Double) defaultValue;
        if (defaultDoubleValue == null) {
            defaultDoubleValue = 0d;
        }
        return (T) (Double) PropertiesUtil.toDouble(value, defaultDoubleValue);
    } else if (type == Boolean.class) {
        Boolean defaultBooleanValue = (Boolean) defaultValue;
        if (defaultBooleanValue == null) {
            defaultBooleanValue = false;
        }
        return (T) (Boolean) PropertiesUtil.toBoolean(value, defaultBooleanValue);
    } else if (type == Map.class) {
        Map<?, ?> defaultMap = (Map) defaultValue;
        String[] defaultMapValue;
        if (defaultMap == null) {
            defaultMapValue = new String[0];
        } else {
            defaultMapValue = new String[defaultMap.size()];
            Map.Entry<?, ?>[] entries = Iterators.toArray(defaultMap.entrySet().iterator(), Map.Entry.class);
            for (int i = 0; i < entries.length; i++) {
                defaultMapValue[i] = Objects.toString(entries[i].getKey(), "") + KEY_VALUE_DELIMITER
                        + Objects.toString(entries[i].getValue(), "");
            }
        }
        return (T) PropertiesUtil.toMap(value, defaultMapValue);
    }
    throw new IllegalArgumentException("Unsupported type: " + type.getName());
}

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

/**
 * ?//from   ww w.j  a v a2 s . c om
 * 
 * @param params
 * @return
 */
@POST
@Path("/getCallHistory")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> getCallHistory(String params) {
    JSONObject obj = JSONObject.parseObject(params);
    Map<String, Object> req = new HashMap<>();
    //String uid = Objects.toString(obj.get("uid"), "0");
    String uno = Objects.toString(obj.get("uno"), "0");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date start = null;
    Date end = null;
    //      try {
    //         start = sdf.parse(Objects.toString(obj.get("start"), "0"));
    //         end = sdf.parse(Objects.toString(obj.get("end"), "0"));
    //      } catch (ParseException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }

    // ?
    List<CallRecord> list = callHistoryBean.findByUid(uno);

    //      Integer total = callHistoryBean.findByUid(uno).size();
    //req.put("count", Objects.toString(list.size(), "0"));
    req.put("total", Objects.toString(list.size(), "0"));
    req.put("callList", list);
    req.put("result", "success");
    req.put("error_code", "000000");
    req.put("error_msg", "");
    return req;
}