List of usage examples for java.util Objects toString
public static String toString(Object o, String nullDefault)
From source file:org.openhab.binding.cardio2e.internal.Cardio2eBinding.java
public void initializeCardio2eBinding(final Map<String, Object> configuration) { int minDelayBetweenReceivingAndSending = 0; int minDelayBetweenSendings = 0; // Set default values port = null;/* www . ja v a 2 s.c o m*/ programCode = "00000"; securityCode = null; zoneStateDetection = false; zoneUnchangedMinRefreshDelay = 600000; datetimeMaxOffset = 15; firstUpdateWillSetDatetime = false; allowedDatetimeUpdateHour = -1; testMode = false; Cardio2eTransactionParser.filterUnnecessaryCommand = false; Cardio2eTransactionParser.filterUnnecessaryReverseModeUpdate = true; Cardio2eLightingTransaction.setSmartSendingEnabledClass(false); Cardio2eRelayTransaction.setSmartSendingEnabledClass(false); Cardio2eHvacControlTransaction.setSmartSendingEnabledClass(false); Cardio2eDateTimeTransaction.setSmartSendingEnabledClass(false); Cardio2eScenarioTransaction.setSmartSendingEnabledClass(false); Cardio2eSecurityTransaction.setSmartSendingEnabledClass(false); Cardio2eZonesBypassTransaction.setSmartSendingEnabledClass(false); Cardio2eCurtainTransaction.setSmartSendingEnabledClass(false); // Load config values String portString = Objects.toString(configuration.get("port"), null); if (StringUtils.isNotBlank(portString)) { port = portString; logger.info("Serial port set from config file: {}", port); } if (port != null) { String programcodeString = Objects.toString(configuration.get("programcode"), null); if (StringUtils.isNotBlank(programcodeString)) { programCode = programcodeString; logger.info("Program code updated from config file"); } String securitycodeString = Objects.toString(configuration.get("securitycode"), null); if (StringUtils.isNotBlank(securitycodeString)) { securityCode = securitycodeString; logger.info("Security code updated from config file"); } String zonesString = Objects.toString(configuration.get("zones"), null); if (StringUtils.isNotBlank(zonesString)) { zoneStateDetection = Boolean.parseBoolean(zonesString); logger.info("Zone state detection {} in config file", (zoneStateDetection ? "enabled" : "disabled")); } String zoneUnchangedMinRefreshDelayString = Objects .toString(configuration.get("zoneUnchangedMinRefreshDelay"), null); if (StringUtils.isNotBlank(zoneUnchangedMinRefreshDelayString)) { zoneUnchangedMinRefreshDelay = Long.parseLong(zoneUnchangedMinRefreshDelayString); logger.info( "Zone state unchanged minimum refresh delay updated to {} milliseconds from config file", zoneUnchangedMinRefreshDelayString); } String datetimeMaxOffsetString = Objects.toString(configuration.get("datetimeMaxOffset"), null); if (StringUtils.isNotBlank(datetimeMaxOffsetString)) { datetimeMaxOffset = Short.parseShort(datetimeMaxOffsetString); if (datetimeMaxOffset < -1) { logger.info( "Date and time direct update selected from config file (always sends updates, no filters, even if current date and time of Cardio 2 matches the update)"); } else { if (datetimeMaxOffset > 0) { logger.info("Date and time maximum offset updated to {} minutes from config file", datetimeMaxOffsetString); } else { if (datetimeMaxOffset == 0) logger.info("Date and time maximum offset disabled from config file"); if (datetimeMaxOffset == -1) logger.info( "Date and time both, progressive update and maximum offset, disabled from config file"); } } } String firstUpdateWillSetDatetimeString = Objects .toString(configuration.get("firstUpdateWillSetDatetime"), null); if (StringUtils.isNotBlank(firstUpdateWillSetDatetimeString)) { firstUpdateWillSetDatetime = Boolean.parseBoolean(firstUpdateWillSetDatetimeString); logger.info("In the configuration file was {} that the first update always sets the date and time", (firstUpdateWillSetDatetime ? "enabled" : "disabled")); } String allowedDatetimeUpdateHourString = Objects .toString(configuration.get("allowedDatetimeUpdateHour"), null); if (StringUtils.isNotBlank(allowedDatetimeUpdateHourString)) { allowedDatetimeUpdateHour = Short.parseShort(allowedDatetimeUpdateHourString); if ((allowedDatetimeUpdateHour >= 0) && (allowedDatetimeUpdateHour <= 23)) { logger.info("Allowed date and time update hour set to '{}' in config file", allowedDatetimeUpdateHour); } else { allowedDatetimeUpdateHour = -1; logger.info("Allowed date and time update hour limit disabled in config file"); } } String testmodeString = Objects.toString(configuration.get("testmode"), null); if (StringUtils.isNotBlank(testmodeString)) { testMode = Boolean.parseBoolean(testmodeString); logger.info("Test mode {} in config file", (testMode ? "enabled" : "disabled")); } String minDelayBetweenReceivingAndSendingString = Objects .toString(configuration.get("minDelayBetweenReceivingAndSending"), null); if (StringUtils.isNotBlank(minDelayBetweenReceivingAndSendingString)) { minDelayBetweenReceivingAndSending = Integer.parseInt(minDelayBetweenReceivingAndSendingString); if (minDelayBetweenReceivingAndSending > 0) logger.info("Minimum delay between receiving and sending updated to {} ms. from config file", minDelayBetweenReceivingAndSending); } String minDelayBetweenSendingsString = Objects.toString(configuration.get("minDelayBetweenSendings"), null); if (StringUtils.isNotBlank(minDelayBetweenSendingsString)) { minDelayBetweenSendings = Integer.parseInt(minDelayBetweenSendingsString); if (minDelayBetweenSendings > 0) logger.info("Minimum delay between sendings updated to {} ms. from config file", minDelayBetweenSendings); } String filterUnnecessaryCommandString = Objects.toString(configuration.get("filterUnnecessaryCommand"), null); if (StringUtils.isNotBlank(filterUnnecessaryCommandString)) { Cardio2eTransactionParser.filterUnnecessaryCommand = Boolean .parseBoolean(filterUnnecessaryCommandString); logger.info("Filter unnecessary command {} in config file", (Cardio2eTransactionParser.filterUnnecessaryCommand ? "enabled" : "disabled")); } String filterUnnecessaryReverseModeUpdateFilterString = Objects .toString(configuration.get("filterUnnecessaryReverseModeUpdate"), null); if (StringUtils.isNotBlank(filterUnnecessaryReverseModeUpdateFilterString)) { Cardio2eTransactionParser.filterUnnecessaryReverseModeUpdate = Boolean .parseBoolean(filterUnnecessaryReverseModeUpdateFilterString); logger.info("Filter unnecessary reverse mode update {} in config file", (Cardio2eTransactionParser.filterUnnecessaryReverseModeUpdate ? "enabled" : "disabled")); } String smartSendingEnabledObjectTypesString = Objects .toString(configuration.get("smartSendingEnabledObjectTypes"), null); if (StringUtils.isNotBlank(smartSendingEnabledObjectTypesString)) { smartSendingEnabledObjectTypesString = smartSendingEnabledObjectTypesString.toUpperCase(); if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.LIGHTING.name())) { Cardio2eLightingTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for LIGHTING object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.RELAY.name())) { Cardio2eRelayTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for RELAY object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.HVAC_CONTROL.name())) { Cardio2eHvacControlTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for HVAC_CONTROL object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.DATE_AND_TIME.name())) { Cardio2eDateTimeTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for DATE_AND_TIME object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.SCENARIO.name())) { Cardio2eScenarioTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for SCENARIO object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.SECURITY.name())) { Cardio2eSecurityTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for SECURITY object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.ZONES_BYPASS.name())) { Cardio2eZonesBypassTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for ZONES_BYPASS object type in config file"); } if (smartSendingEnabledObjectTypesString.contains(Cardio2eObjectTypes.CURTAIN.name())) { Cardio2eCurtainTransaction.setSmartSendingEnabledClass(true); logger.info("Smart sending enabled for CURTAIN object type in config file"); } } // Read further config parameters here ... com = new Cardio2eCom(); decoder = com.decoder; receivedDataListener = new ReceivedDataListener(); decodedTransactionListener = new DecodedTransactionListener(); com.addReceivedDataListener(receivedDataListener); decoder.addDecodedTransactionListener(decodedTransactionListener); com.testMode = testMode; decoder.decodeZonesStateTransaction = zoneStateDetection; com.setSerialPort(port); if (minDelayBetweenReceivingAndSending > 0) com.setMinDelayBetweenReceivingAndSending(minDelayBetweenReceivingAndSending); if (minDelayBetweenSendings > 0) com.setMinDelayBetweenSendings(minDelayBetweenSendings); try { com.sendTransaction(new Cardio2eLoginTransaction(programCode)); // Login // request } catch (Exception ex) { logger.warn("Failed to send login request: '{}'", ex.toString()); } if (testMode) loggedIn = true; setProperlyConfigured(true); logger.debug("Cardio2e binding activated"); } else logger.warn("Cardio2e binding cannot be activated because no serial port is set in config file"); }
From source file:de.micromata.genome.util.runtime.jndi.SimpleNamingContextBuilder.java
/** * Jndi object to string./*from w w w . j ava2 s . c om*/ * * @param obj the obj * @return the string */ public static String jndiObjectToString(Object obj) { if (obj instanceof BasicDataSource) { BasicDataSource bds = (BasicDataSource) obj; return "BasicDataSource: " + bds.getUsername() + "@" + bds.getUrl(); } else { return Objects.toString(obj, StringUtils.EMPTY); } }
From source file:com.qcadoo.mes.technologies.TechnologyService.java
public void generateTechnologyNumber(final ViewDefinitionState view, final ComponentState state, final String[] args) { if (!(state instanceof FieldComponent)) { throw new IllegalStateException("component is not FieldComponentState"); }//w w w .j a va2 s . com FieldComponent numberField = (FieldComponent) view.getComponentByReference(TechnologyFields.NUMBER); LookupComponent productLookup = (LookupComponent) state; Entity product = productLookup.getEntity(); if (product == null || StringUtils.isNotEmpty(Objects.toString(numberField.getFieldValue(), ""))) { return; } numberField.setFieldValue(technologyNameAndNumberGenerator.generateNumber(product)); numberField.requestComponentUpdateState(); }
From source file:interfaz.ConsultarHorasTotales.java
private void ObtenerDatos(Periodo periodo, String diaSeleccionado) { if (diaSeleccionado != "TODOS") { EstadisticasRapla estadisticas = new EstadisticasRapla(); ArrayList<HorasTotales> listaHorasTotales = estadisticas.obtenerHorasTotalesPorDia(diaSeleccionado, periodo);/*from w w w . j ava 2s. c o m*/ long promedio = listaHorasTotales.get(0).getHorasTotales() / listaHorasTotales.get(0).getCantidadDias(); long hours = TimeUnit.SECONDS.toHours(listaHorasTotales.get(0).getHorasTotales()); long minute = TimeUnit.SECONDS.toMinutes(listaHorasTotales.get(0).getHorasTotales()) - (TimeUnit.SECONDS.toHours(listaHorasTotales.get(0).getHorasTotales()) * 60); long second = TimeUnit.SECONDS.toSeconds(listaHorasTotales.get(0).getHorasTotales()) - (TimeUnit.SECONDS.toMinutes(listaHorasTotales.get(0).getHorasTotales()) * 60); String horasPromedio = Objects.toString(hours, null) + ':' + Objects.toString(minute, null) + ':' + Objects.toString(second, null); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(promedio, "Serie", diaSeleccionado); JFreeChart chartpanel = ChartFactory.createBarChart("titulo", "ALGO", "NOSE", dataset, PlotOrientation.VERTICAL, true, true, false); ChartFrame frame = new ChartFrame("TOTULOSADAS", chartpanel); frame.pack(); frame.setVisible(true); } else { } }
From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManager.java
@Override protected void populateAuthenticationAttributes(UaaAuthentication authentication, Authentication request, AuthenticationData authenticationData) { Map<String, Object> claims = authenticationData.getClaims(); if (claims != null) { if (claims.get("amr") != null) { if (authentication.getAuthenticationMethods() == null) { authentication.setAuthenticationMethods(new HashSet<>((Collection<String>) claims.get("amr"))); } else { authentication.getAuthenticationMethods().addAll((Collection<String>) claims.get("amr")); }//from w w w . j a v a2 s . c o m } Object acr = claims.get(ClaimConstants.ACR); if (acr != null) { if (acr instanceof Map) { Map<String, Object> acrMap = (Map) acr; Object values = acrMap.get("values"); if (values instanceof Collection) { authentication.setAuthContextClassRef(new HashSet<>((Collection) values)); } else if (values instanceof String[]) { authentication.setAuthContextClassRef(new HashSet<>(Arrays.asList((String[]) values))); } else { logger.debug(String.format("Unrecognized ACR claim[%s] for user_id: %s", values, authentication.getPrincipal().getId())); } } else if (acr instanceof String) { authentication.setAuthContextClassRef(new HashSet(Arrays.asList((String) acr))); } else { logger.debug(String.format("Unrecognized ACR claim[%s] for user_id: %s", acr, authentication.getPrincipal().getId())); } } MultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>(); logger.debug("Mapping XOauth custom attributes"); for (Map.Entry<String, Object> entry : authenticationData.getAttributeMappings().entrySet()) { if (entry.getKey().startsWith(USER_ATTRIBUTE_PREFIX) && entry.getValue() != null) { String key = entry.getKey().substring(USER_ATTRIBUTE_PREFIX.length()); Object values = claims.get(entry.getValue()); if (values != null) { logger.debug(String.format("Mapped XOauth attribute %s to %s", key, values)); if (values instanceof List) { List list = (List) values; List<String> strings = (List<String>) list.stream() .map(object -> Objects.toString(object, null)).collect(Collectors.toList()); userAttributes.put(key, strings); } else if (values instanceof String) { userAttributes.put(key, Arrays.asList((String) values)); } else { userAttributes.put(key, Arrays.asList(values.toString())); } } } } authentication.setUserAttributes(userAttributes); authentication.setExternalGroups(ofNullable(authenticationData.getAuthorities()).orElse(emptyList()) .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet())); } super.populateAuthenticationAttributes(authentication, request, authenticationData); }
From source file:org.ligoj.app.plugin.vm.aws.VmAwsPluginResource.java
/** * Build a described {@link AwsVm} bean from a XML VMRecord entry. *//* w w w . j a v a 2 s . c o m*/ private AwsVm toVm(final Element record) { final AwsVm result = new AwsVm(); result.setId(xml.getTagText(record, "instanceId")); result.setName(Objects.toString(getName(record), result.getId())); result.setDescription(getResourceTag(record, "description")); final int state = getEc2State(record); result.setStatus(CODE_TO_STATUS.get(state)); result.setBusy(Arrays.binarySearch(BUSY_CODES, state) >= 0); result.setVpc(xml.getTagText(record, "vpcId")); result.setAz( xml.getTagText((Element) record.getElementsByTagName("placement").item(0), "availabilityZone")); final InstanceType type = instanceTypes.get(xml.getTagText(record, "instanceType")); // Instance type details result.setRam(Optional.ofNullable(type).map(InstanceType::getRam).map(m -> (int) (m * 1024d)).orElse(0)); result.setCpu(Optional.ofNullable(type).map(InstanceType::getCpu).orElse(0)); result.setDeployed(result.getStatus() == VmStatus.POWERED_ON); return result; }
From source file:org.apache.streams.twitter.provider.TwitterTimelineProvider.java
/** * Using the "info" list that is contained in the configuration, ensure that all * account identifiers are converted to IDs (Longs) instead of screenNames (Strings). *//*from w w w.j a v a 2 s . c o m*/ protected void consolidateToIDs() { List<String> screenNames = new ArrayList<>(); ids = new ArrayList<>(); for (String account : config.getInfo()) { try { if (new Long(account) != null) { ids.add(Long.parseLong(Objects.toString(account, null))); } } catch (NumberFormatException ex) { screenNames.add(account); } catch (Exception ex) { LOGGER.error("Exception while trying to add ID: {{}}, {}", account, ex); } } // Twitter allows for batches up to 100 per request, but you cannot mix types screenNameBatches = new ArrayList<>(); while (screenNames.size() >= 100) { screenNameBatches.add(screenNames.subList(0, 100).toArray(new String[0])); screenNames = screenNames.subList(100, screenNames.size()); } if (screenNames.size() > 0) { screenNameBatches.add(screenNames.toArray(new String[ids.size()])); } for (String[] screenNameBatche : screenNameBatches) { Collection<Long> batchIds = retrieveIds(screenNameBatche); ids.addAll(batchIds); } }
From source file:org.codice.ddf.configuration.admin.ImportMigrationConfigurationAdminContext.java
@Nullable private ImportMigrationConfigurationAdminEntry proxy(ImportMigrationEntry entry) { final Path path = entry.getPath(); final String extn = FilenameUtils.getExtension(path.toString()); final PersistenceStrategy ps = admin.getPersister(extn); if (ps == null) { context.getReport().record(new MigrationException( "Import error: persistence strategy [%s] for configuration [%s] is not defined.", extn, path)); } else {/*w ww . jav a 2 s. c o m*/ final Dictionary<String, Object> properties; InputStream is = null; try { is = entry.getInputStream().orElseThrow(() -> new MigrationException( "Import error: failed to read configuration [%s]; not exported.", path)); properties = readProperties(entry, ps, is); } catch (IOException e) { throw new MigrationException("Import error: failed to read configuration [%s]; %s.", path, e); } finally { Closeables.closeQuietly(is); } // note: we also remove bunde location, factory pid, and pid from the dictionary as we do not // want to restore those later final String pid = Objects.toString(properties.remove(Constants.SERVICE_PID), null); if (pid == null) { // this should never happen unless someone created the zip file manually and messed up the // config file context.getReport() .record(new MigrationException("Import error: missing pid from configuration [%s].", path)); } else { final String bundleLocation = Objects .toString(properties.remove(ConfigurationAdmin.SERVICE_BUNDLELOCATION), null); final String factoryPid = Objects.toString(properties.remove(ConfigurationAdmin.SERVICE_FACTORYPID), null); try { return new ImportMigrationConfigurationAdminEntry(configurationAdmin, entry, bundleLocation, factoryPid, pid, properties, getAndRemoveMemoryConfig(factoryPid, pid, properties, entry.getPath())); } catch (MigrationException e) { // don't throw it back yet as we want to detect as many as possible so just record it context.getReport().record(e); } } } this.isValid = false; return null; }
From source file:com.qcadoo.mes.technologies.TechnologyService.java
public void generateTechnologyName(final ViewDefinitionState view, final ComponentState state, final String[] args) { if (!(state instanceof FieldComponent)) { throw new IllegalStateException("component is not FieldComponentState"); }/*from w w w. j a v a 2 s . c o m*/ FieldComponent nameField = (FieldComponent) view.getComponentByReference(TechnologyFields.NAME); LookupComponent productLookup = (LookupComponent) state; Entity product = productLookup.getEntity(); if (product == null || StringUtils.isNotEmpty(Objects.toString(nameField.getFieldValue(), ""))) { return; } nameField.setFieldValue(technologyNameAndNumberGenerator.generateName(product)); nameField.requestComponentUpdateState(); }
From source file:com.formkiq.core.form.service.FormValidatorServiceImpl.java
/** * Validate Form JSON Field.//from w w w . j a va 2s .c o m * * @param archive {@link ArchiveDTO} * @param form {@link FormJSON} * @param field {@link FormJSONField} * @param errors {@link Map} * @param types {@link FormJSONRequiredType} */ private void validateFormJSONField(final ArchiveDTO archive, final FormJSON form, final FormJSONField field, final Map<String, String> errors, final FormJSONRequiredType... types) { if (!field.isHide() && !BUTTON.equals(field.getType())) { boolean isRequired = isRequired(field, types); String value = Objects.toString(field.getValue(), ""); List<String> values = field.getValues(); if (!hasText(value) && !isEmpty(values)) { value = values.stream().collect(Collectors.joining()); } if (isRequired) { if (StringUtils.isEmpty(value)) { errors.put(String.valueOf(field.getId()), "Field required"); } } validateFieldCustomFormatter(form, field, value, errors); validateFieldFormula(form, field, errors); if (isRequired || hasText(value)) { validateFieldVariable(archive, form, field, value, errors); } } }