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.joyent.manta.client.MantaObjectConversionFunction.java

@Override
public MantaObject apply(final Map<String, Object> item) {
    String name = Validate.notNull(item.get(NAME_FIELD_KEY), "Filename is null").toString();
    String mtime = Validate.notNull(item.get(MTIME_FIELD_KEY), "Modification time is null").toString();
    String type = Validate.notNull(item.get(TYPE_FIELD_KEY), "File type is null").toString();

    String objPath = String.format("%s%s%s",
            StringUtils.removeEnd(item.get(PATH_FIELD_KEY).toString(), SEPARATOR), SEPARATOR,
            StringUtils.removeStart(name, SEPARATOR));
    MantaHttpHeaders headers = new MantaHttpHeaders();
    headers.setLastModified(mtime);/*from  w  w w.j a va2 s.  com*/

    /* We look for contentType explicitly because it is being added to Manta
     * in a future version and this property may not be available on all
     * Manta installs for quite some time. */
    if (item.containsKey(CONTENT_TYPE_FIELD_KEY)) {
        String contentType = Objects.toString(item.get(CONTENT_TYPE_FIELD_KEY), null);
        headers.setContentType(contentType);
    } else if (type.equals(MantaObject.MANTA_OBJECT_TYPE_DIRECTORY)) {
        headers.setContentType(MantaObjectResponse.DIRECTORY_RESPONSE_CONTENT_TYPE);
    }

    if (item.containsKey(ETAG_FIELD_KEY)) {
        headers.setETag(Objects.toString(item.get(ETAG_FIELD_KEY)));
    }

    if (item.containsKey(SIZE_FIELD_KEY)) {
        long size = Long.parseLong(Objects.toString(item.get(SIZE_FIELD_KEY)));
        headers.setContentLength(size);
    }

    if (item.containsKey(DURABILITY_FIELD_KEY)) {
        String durabilityString = Objects.toString(item.get(DURABILITY_FIELD_KEY));
        if (durabilityString != null) {
            int durability = Integer.parseInt(durabilityString);
            headers.setDurabilityLevel(durability);
        }
    }

    // This property may not be available on all Manta installs for quite some time
    if (item.containsKey(CONTENT_MD5_FIELD_KEY)) {
        String contentMD5 = Objects.toString(item.get(CONTENT_MD5_FIELD_KEY), null);
        headers.setContentMD5(contentMD5);
    }

    return new MantaObjectResponse(formatPath(objPath), headers);
}

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

/**
 * Converts a typed value to it's string representation.
 * @param value Typed value/*from  w  w w  .  jav  a 2s . c  o m*/
 * @return String value
 */
public static String objectToString(Object value) {
    if (value == null) {
        return null;
    }
    if (value instanceof String) {
        return (String) value;
    }
    if (value instanceof String[]) {
        return StringUtils.join((String[]) value, ARRAY_DELIMITER);
    } else if (value instanceof Integer) {
        return Integer.toString((Integer) value);
    } else if (value instanceof Long) {
        return Long.toString((Long) value);
    } else if (value instanceof Double) {
        return Double.toString((Double) value);
    } else if (value instanceof Boolean) {
        return Boolean.toString((Boolean) value);
    } else if (value instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) value;
        StringBuilder stringValue = new StringBuilder();
        Map.Entry<?, ?>[] entries = Iterators.toArray(map.entrySet().iterator(), Map.Entry.class);
        for (int i = 0; i < entries.length; i++) {
            Map.Entry<?, ?> entry = entries[i];
            String entryKey = Objects.toString(entry.getKey(), "");
            String entryValue = Objects.toString(entry.getValue(), "");
            stringValue.append(entryKey).append(KEY_VALUE_DELIMITER).append(entryValue);
            if (i < entries.length - 1) {
                stringValue.append(ARRAY_DELIMITER);
            }
        }
        return stringValue.toString();
    }
    throw new IllegalArgumentException("Unsupported type: " + value.getClass().getName());
}

From source file:de.knightsoftnet.validators.shared.impl.PhoneNumberValueRestValidator.java

/**
 * {@inheritDoc} check if given string is a valid gln.
 *
 * @see javax.validation.ConstraintValidator#isValid(java.lang.Object,
 *      javax.validation.ConstraintValidatorContext)
 *//*from   w ww.j  a  v  a2  s . c o m*/
@Override
public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) {
    final String valueAsString = Objects.toString(pvalue, null);

    if (StringUtils.isEmpty(valueAsString)) {
        // empty field is ok
        return true;
    }
    try {
        String countryCode = BeanUtils.getProperty(pvalue, this.fieldCountryCode);
        final String phoneNumber = BeanUtils.getProperty(pvalue, this.fieldPhoneNumber);
        if (StringUtils.isEmpty(phoneNumber)) {
            return true;
        }

        if (this.allowLowerCaseCountryCode) {
            countryCode = StringUtils.upperCase(countryCode);
        }
        final String url = StringUtils
                .removeEnd(StringUtils.removeEnd(StringUtils.removeEnd(GWT.getModuleBaseURL(), "/"),
                        GWT.getModuleName()), "/")
                + PhoneNumber.ROOT + PhoneNumber.VALIDATE //
                + "?" + Parameters.COUNTRY + "=" + countryCode //
                + "&" + Parameters.PHONE_NUMBER + "=" + this.urlEncode(phoneNumber) //
                + "&" + Parameters.DIN_5008 + "=" + PhoneNumberValueRestValidator.this.allowDin5008 //
                + "&" + Parameters.E123 + "=" + PhoneNumberValueRestValidator.this.allowE123 //
                + "&" + Parameters.URI + "=" + PhoneNumberValueRestValidator.this.allowUri //
                + "&" + Parameters.MS + "=" + PhoneNumberValueRestValidator.this.allowMs //
                + "&" + Parameters.COMMON + "=" + PhoneNumberValueRestValidator.this.allowCommon;
        final String restResult = CachedSyncHttpGetCall.syncRestCall(url);
        if (StringUtils.equalsIgnoreCase("TRUE", restResult)) {
            return true;
        }
        this.switchContext(pcontext);
        return false;
    } catch (final Exception ignore) {
        this.switchContext(pcontext);
        return false;
    }
}

From source file:org.openhab.binding.km200.internal.KM200Binding.java

/**
 * {@inheritDoc}//from   www  .j a v a  2 s  .  c  om
 */
@Override
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {

    if (config == null) {
        return;
    } else {
        if (config.isEmpty()) {
            return;
        }
        logger.info("Update KM200 Binding configuration, it takes a minute....");
        String ip = Objects.toString(config.get("ip4_address"), null);
        if (StringUtils.isNotBlank(ip)) {
            try {
                InetAddresses.forString(ip);
            } catch (IllegalArgumentException e) {
                logger.error("IP4_address in openhab.cfg is not valid!");
                throw new ConfigurationException("ip4_address", "ip4_address in openhab.cfg is not valid!");
            }
            device.setIP4Address(ip);
        } else {
            logger.error("No ip4_address in openhab.cfg set!");
            throw new ConfigurationException("ip4_address", "No ip4_address in openhab.cfg set!");
        }
        /* There a two possibilities of configuratiom */
        /* 1. With a private key */
        String PrivKey = Objects.toString(config.get("PrivKey"), null);
        if (StringUtils.isNotBlank(PrivKey)) {
            device.setCryptKeyPriv(PrivKey);

        } else { /* 2. With the MD5Salt, the device and user private password */
            String MD5Salt = Objects.toString(config.get("MD5Salt"), null);
            if (StringUtils.isNotBlank(MD5Salt)) {
                device.setMD5Salt(MD5Salt);
            } else {
                logger.error("No MD5Salt in openhab.cfg set!");
                throw new ConfigurationException("MD5Salt", "No MD5Salt in openhab.cfg set!");
            }

            String gpassword = Objects.toString(config.get("GatewayPassword"), null);
            if (StringUtils.isNotBlank(gpassword)) {
                device.setGatewayPassword(gpassword);
            } else {
                logger.error("No GatewayPassword in openhab.cfg set!");
                throw new ConfigurationException("GatewayPassword", "No GatewayPassword in openhab.cfg set!");
            }

            String ppassword = Objects.toString(config.get("PrivatePassword"), null);
            if (StringUtils.isNotBlank(ppassword)) {
                device.setPrivatePassword(ppassword);
            } else {
                logger.error("No PrivatePassword in openhab.cfg set!");
                throw new ConfigurationException("PrivatePassword", "No PrivatePassword in openhab.cfg set!");
            }
        }
        logger.info("Starting communication test..");
        /* Get HTTP Data from device */
        byte[] recData = comm.getDataFromService("/gateway/DateTime");
        if (recData == null) {
            throw new RuntimeException("Communication is not possible!");
        }
        if (recData.length == 0) {
            throw new RuntimeException("No reply from KM200!");
        }
        logger.info("Received data..");
        /* Derypt the message */
        String decodedData = comm.decodeMessage(recData);
        if (decodedData == null) {
            throw new RuntimeException("Decoding of the KM200 message is not possible!");
        }

        if (decodedData == "SERVICE NOT AVAILABLE") {
            logger.error("/gateway/DateTime: SERVICE NOT AVAILABLE");
        } else {
            logger.info("Test of the communication to the gateway was successful..");
        }
        logger.info("Init services..");
        /* communication is working */
        /* Checking of the devicespecific services and creating of a service list */
        for (KM200ServiceTypes service : KM200ServiceTypes.values()) {
            try {
                logger.debug(service.getDescription());
                comm.initObjects(service.getDescription());
            } catch (Exception e) {
                logger.error("Couldn't init service: {} error: {}", service, e.getMessage());
            }
        }
        /* Now init the virtual services */
        logger.debug("init Virtual Objects");
        try {
            comm.initVirtualObjects();
        } catch (Exception e) {
            logger.error("Couldn't init virtual services: {}", e.getMessage());
        }
        /* Output all availible services in the log file */
        /* Now init the virtual services */
        logger.debug("list All Services");
        device.listAllServices();
        logger.info("... Update of the KM200 Binding configuration completed");

        device.setInited(true);
        setProperlyConfigured(true);
    }

}

From source file:org.openhab.binding.fritzboxtr064.internal.FritzboxTr064Binding.java

/**
 * Called by the SCR to activate the component with its configuration read from CAS
 *
 * @param bundleContext BundleContext of the Bundle that defines this component
 * @param configuration Configuration properties for this component obtained from the ConfigAdmin service
 *//* www  . j  a  v a  2 s  .c  o m*/
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
    logger.debug("FritzBox TR064 Binding activated!");

    // to override the default refresh interval one has to add a
    // parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
    String refreshIntervalString = Objects.toString(configuration.get("refresh"), null);
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
        logger.debug("Custom refresh interval set to {}", refreshInterval);
    }

    // Check if fritzbox parameters were provided in config, otherwise does not make sense going on...
    String fboxurl = Objects.toString(configuration.get("url"), null);
    String fboxuser = Objects.toString(configuration.get("user"), null);
    String fboxpw = Objects.toString(configuration.get("pass"), null);
    String fboxphonebookid = Objects.toString(configuration.get("phonebookid"), null);
    if (fboxurl == null) {
        logger.warn("Fritzbox URL was not provided in config. Shutting down binding.");
        // how to shutdown??
        setProperlyConfigured(false);
        return;
    }
    if (fboxuser == null) {
        logger.warn("Fritzbox User was not provided in config. Using default username.");
    }
    if (fboxpw == null) {
        logger.warn("Fritzbox Password was not provided in config. Shutting down binding.");
        // how to shutdown??
        setProperlyConfigured(false);
        return;
    }
    if (fboxphonebookid == null) {
        logger.debug("No Phonebookid provided. Use default: 0");
        fboxphonebookid = "0";
    }
    this._pw = fboxpw;
    this._user = fboxuser;
    this._url = fboxurl;

    try {
        this._pbid = Integer.valueOf(fboxphonebookid);
    } catch (NumberFormatException ex) { // set fallback to 0
        this._pbid = 0;
    }

    if (_fboxComm == null) {
        _fboxComm = new Tr064Comm(_url, _user, _pw);
    }

    setProperlyConfigured(true);

}

From source file:org.apache.struts2.convention.config.entities.ConventionConstantConfig.java

@Override
public Map<String, String> getAllAsStringsMap() {
    Map<String, String> map = super.getAllAsStringsMap();

    map.put(ConventionConstants.CONVENTION_ACTION_CONFIG_BUILDER,
            beanConfToString(conventionActionConfigBuilder));
    map.put(ConventionConstants.CONVENTION_ACTION_NAME_BUILDER, beanConfToString(conventionActionNameBuilder));
    map.put(ConventionConstants.CONVENTION_RESULT_MAP_BUILDER, beanConfToString(conventionResultMapBuilder));
    map.put(ConventionConstants.CONVENTION_INTERCEPTOR_MAP_BUILDER,
            beanConfToString(conventionInterceptorMapBuilder));
    map.put(ConventionConstants.CONVENTION_CONVENTIONS_SERVICE, beanConfToString(conventionConventionsService));
    map.put(ConventionConstants.CONVENTION_ACTION_NAME_LOWERCASE,
            Objects.toString(conventionActionNameLowercase, null));
    map.put(ConventionConstants.CONVENTION_ACTION_NAME_SEPARATOR, conventionActionNameSeparator);
    map.put(ConventionConstants.CONVENTION_ACTION_SUFFIX, StringUtils.join(conventionActionSuffix, ','));
    map.put(ConventionConstants.CONVENTION_CLASSES_RELOAD, Objects.toString(conventionClassesReload, null));
    map.put(ConventionConstants.CONVENTION_RESULT_PATH, conventionResultPath);
    map.put(ConventionConstants.CONVENTION_DEFAULT_PARENT_PACKAGE, conventionDefaultParentPackage);
    map.put(ConventionConstants.CONVENTION_REDIRECT_TO_SLASH,
            Objects.toString(conventionRedirectToSlash, null));
    map.put(ConventionConstants.CONVENTION_RELATIVE_RESULT_TYPES,
            StringUtils.join(conventionRelativeResultTypes, ','));
    map.put(ConventionConstants.CONVENTION_EXCLUDE_PARENT_CLASS_LOADER,
            Objects.toString(conventionExcludeParentClassLoader, null));
    map.put(ConventionConstants.CONVENTION_ACTION_ALWAYS_MAP_EXECUTE,
            Objects.toString(conventionActionAlwaysMapExecute, null));
    map.put(ConventionConstants.CONVENTION_ACTION_FILE_PROTOCOLS,
            StringUtils.join(conventionActionFileProtocols, ','));
    map.put(ConventionConstants.CONVENTION_ACTION_DISABLE_SCANNING,
            Objects.toString(conventionActionDisableScanning, null));
    map.put(ConventionConstants.CONVENTION_ACTION_INCLUDE_JARS,
            StringUtils.join(conventionActionIncludeJars, ','));
    map.put(ConventionConstants.CONVENTION_PACKAGE_LOCATORS_DISABLE,
            Objects.toString(conventionPackageLocatorsDisable, null));
    map.put(ConventionConstants.CONVENTION_ACTION_PACKAGES, StringUtils.join(conventionActionPackages, ','));
    map.put(ConventionConstants.CONVENTION_ACTION_CHECK_IMPLEMENTS_ACTION,
            Objects.toString(conventionActionCheckImplementsAction, null));
    map.put(ConventionConstants.CONVENTION_EXCLUDE_PACKAGES, StringUtils.join(conventionExcludePackages, ','));
    map.put(ConventionConstants.CONVENTION_PACKAGE_LOCATORS, StringUtils.join(conventionPackageLocators, ','));
    map.put(ConventionConstants.CONVENTION_PACKAGE_LOCATORS_BASE_PACKAGE, conventionPackageLocatorsBasePackage);
    map.put(ConventionConstants.CONVENTION_ACTION_MAP_ALL_MATCHES,
            Objects.toString(conventionActionMapAllMatches, null));
    map.put(ConventionConstants.CONVENTION_ACTION_EAGER_LOADING,
            Objects.toString(conventionActionEagerLoading, null));
    map.put(ConventionConstants.CONVENTION_RESULT_FLAT_LAYOUT,
            Objects.toString(conventionResultFlatLayout, null));
    map.put(ConventionConstants.CONVENTION_ENABLE_SMI_INHERITANCE,
            Objects.toString(conventionEnableSmiInheritance, null));

    return map;// w  ww.  j a  va  2  s .c  o  m
}

From source file:no.digipost.api.client.representations.Document.java

public Document(String uuid, String subject, FileType fileType, String openingReceipt,
        SmsNotification smsNotification, EmailNotification emailNotification,
        AuthenticationLevel authenticationLevel, SensitivityLevel sensitivityLevel, Boolean opened,
        String technicalType) {/*from  w  w  w .  j a  va  2  s .c  o m*/
    this.uuid = lowerCase(uuid);
    this.subject = subject;
    this.digipostFileType = Objects.toString(fileType, null);
    this.openingReceipt = defaultIfBlank(openingReceipt, null);
    this.opened = opened == Boolean.TRUE ? true : null;
    this.smsNotification = smsNotification;
    this.emailNotification = emailNotification;
    this.authenticationLevel = authenticationLevel;
    this.sensitivityLevel = sensitivityLevel;
    this.technicalType = technicalType;
    validate();
}

From source file:com.norconex.importer.handler.filter.impl.RegexMetadataFilter.java

@Override
protected boolean isDocumentMatched(String reference, InputStream input, ImporterMetadata metadata,
        boolean parsed) throws ImporterHandlerException {

    if (StringUtils.isBlank(regex)) {
        return true;
    }//from   w w  w  .ja  v a 2 s  .  co m
    Collection<String> values = metadata.getStrings(field);
    for (Object value : values) {
        String strVal = Objects.toString(value, StringUtils.EMPTY);
        if (pattern.matcher(strVal).matches()) {
            return true;
        }
    }
    return false;
}

From source file:de.micromata.genome.logging.spi.log4j.GLogAppender.java

/**
 * Gets the message./*  w  w  w  .  j a  va 2s. co m*/
 *
 * @param lmsg the lmsg
 * @param logAttributes the log attributes
 * @return the message
 */
private String getMessage(Object lmsg, List<LogAttribute> logAttributes) {
    return Objects.toString(lmsg, StringUtils.EMPTY);
}

From source file:org.openhab.binding.garadget.internal.GaradgetBinding.java

/**
 * Called by the SCR when the configuration of a binding has been changed
 * through the ConfigAdmin service./*from  w ww  . ja v  a 2s .  c o m*/
 *
 * @param configuration
 *            Updated configuration properties
 */
public void modified(final Map<String, Object> configuration) {

    // to override the default granularity one has to add a
    // parameter to the .cfg like [garadget:]granularity=2000
    String granularityString = Objects.toString(configuration.get(CONFIG_GRANULARITY), null);
    granularity = isNotBlank(granularityString) ? Long.parseLong(granularityString) : DEFAULT_GRANULARITY;

    // to override the default refresh interval one has to add a
    // parameter to .cfg like [garadget:]refresh=240000
    String refreshIntervalString = Objects.toString(configuration.get(CONFIG_REFRESH), null);
    refreshInterval = isNotBlank(refreshIntervalString) ? Long.parseLong(refreshIntervalString)
            : DEFAULT_REFRESH;

    // to override the default quickPoll interval one has to add a
    // parameter to .cfg like [garadget:]quickpoll=4000
    String quickPollIntervalString = Objects.toString(configuration.get(CONFIG_QUICKPOLL), null);
    quickPollInterval = isNotBlank(quickPollIntervalString) ? Long.parseLong(quickPollIntervalString)
            : DEFAULT_QUICKPOLL;

    // to override the default HTTP timeout one has to add a
    // parameter to .cfg like [garadget:]timeout=20000
    String timeoutString = Objects.toString(configuration.get(CONFIG_TIMEOUT), null);
    int timeout = isNotBlank(timeoutString) ? Integer.parseInt(timeoutString) : DEFAULT_TIMEOUT;

    String username = Objects.toString(configuration.get("username"), null);
    String password = Objects.toString(configuration.get("password"), null);

    if (isNotBlank(username) && isNotBlank(password)) {
        connection = new Connection(username, password, timeout);
        connection.login();
        // Poll at the earliest opportunity
        schedulePoll(0);
        setProperlyConfigured(true);
    } else {
        setProperlyConfigured(false);
    }
}