List of usage examples for org.apache.commons.lang StringUtils defaultString
public static String defaultString(String str)
Returns either the passed in String, or if the String is null
, an empty String ("").
From source file:com.redhat.rhn.frontend.action.systems.SystemSearchSetupAction.java
protected DataResult performSearch(RequestContext context) { HttpServletRequest request = context.getRequest(); String searchString = context.getParam(SEARCH_STRING, false); String viewMode = context.getParam(VIEW_MODE, false); String whereToSearch = context.getParam(WHERE_TO_SEARCH, false); Boolean invertResults = StringUtils.defaultString(context.getParam(INVERT_RESULTS, false)).equals("on"); if (invertResults == null) { invertResults = Boolean.FALSE; }/*from www. ja va2 s . c o m*/ ActionErrors errs = new ActionErrors(); DataResult dr = null; try { dr = SystemSearchHelper.systemSearch(context, searchString, viewMode, invertResults, whereToSearch); } catch (MalformedURLException e) { log.info("Caught Exception :" + e); e.printStackTrace(); errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.connection_error")); } catch (XmlRpcFault e) { log.info("Caught Exception :" + e); log.info("ErrorCode = " + e.getErrorCode()); e.printStackTrace(); if (e.getErrorCode() == 100) { log.error("Invalid search query", e); errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.could_not_parse_query", searchString)); } else if (e.getErrorCode() == 200) { log.error("Index files appear to be missing: ", e); errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.index_files_missing", searchString)); } else { errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.could_not_execute_query", searchString)); } } catch (XmlRpcException e) { log.info("Caught Exception :" + e); e.printStackTrace(); errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.connection_error")); } if (dr == null) { ActionMessages messages = new ActionMessages(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("systemsearch_no_matches_found")); getStrutsDelegate().saveMessages(request, messages); } if (!errs.isEmpty()) { addErrors(request, errs); } return dr; }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
@SuppressWarnings("PMD.ReplaceHashtableWithMap") // Map required by bouncycastle X509 implementation private Hashtable<DERObjectIdentifier, String> buildAttributes( DigitalSigningDistinguishedName distinguishedName) { Hashtable<DERObjectIdentifier, String> attributes = new Hashtable<DERObjectIdentifier, String>(); attributes.put(X509Principal.C, StringUtils.defaultString(distinguishedName.getCountryName())); attributes.put(X509Principal.ST, StringUtils.defaultString(distinguishedName.getStateOrProvinceName())); attributes.put(X509Principal.L, StringUtils.defaultString(distinguishedName.getLocalityName())); attributes.put(X509Principal.O, StringUtils.defaultString(distinguishedName.getOrganizationName())); attributes.put(X509Principal.OU, StringUtils.defaultString(distinguishedName.getOrganizationalUnitName())); attributes.put(X509Principal.CN, StringUtils.defaultString(distinguishedName.getCommonName())); attributes.put(X509Principal.EmailAddress, StringUtils.defaultString(distinguishedName.getEmailAddress())); return attributes; }
From source file:jp.co.nemuzuka.service.impl.TodoServiceImpl.java
/** * Form./*w w w . j ava2s . c om*/ * @param form Form * @param model Model */ private void setForm(TodoForm form, TodoModel model) { if (model == null) { return; } SimpleDateFormat sdf = DateTimeUtils.createSdf("yyyyMMdd"); form.keyToString = model.getKeyToString(); form.todoStatus = model.getStatus().getCode(); form.title = model.getTitle(); form.tag = StringUtils.defaultString(model.getTag()); form.content = model.getContent().getValue(); form.period = ConvertUtils.toString(model.getPeriod(), sdf); form.versionNo = ConvertUtils.toString(model.getVersion()); }
From source file:com.manydesigns.elements.fields.SelectField.java
public void valueToXhtmlEditDropDown(XhtmlBuffer xb) { Object value = selectionModel.getValue(selectionModelIndex); Map<Object, SelectionModel.Option> options = selectionModel.getOptions(selectionModelIndex); xb.openElement("select"); xb.addAttribute("id", id); xb.addAttribute("name", inputName); xb.addAttribute("class", fieldCssClass); boolean checked = (value == null); if (comboLabel != null && !options.isEmpty()) { SelectionModel.Option option = options.remove(null); if (options.isEmpty()) { // Uh-oh, wrong decision options.put(null, option);//from www . java2s . co m } else { xb.writeOption("", checked, comboLabel); } } for (Map.Entry<Object, SelectionModel.Option> option : options.entrySet()) { if (!option.getValue().active) { continue; } Object optionValue = option.getKey(); String optionStringValue = (String) OgnlUtils.convertValue(optionValue, String.class); optionStringValue = StringUtils.defaultString(optionStringValue); String optionLabel = option.getValue().label; checked = (optionValue == value) || (optionValue != null && optionValue.equals(value)); xb.writeOption(optionStringValue, checked, optionLabel); } xb.closeElement("select"); if (nextSelectField != null) { String js = composeDropDownJs(); xb.writeJavaScript(js); } }
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
@Override public void onStart() throws ConnectorTaskException { String channelId = getChannelId(); String channelName = getChannel().getName(); host = replacer.replaceValues(connectorProperties.getListenerConnectorProperties().getHost(), channelId, channelName);/*from www. j a v a 2 s.c o m*/ port = NumberUtils.toInt(replacer.replaceValues( connectorProperties.getListenerConnectorProperties().getPort(), channelId, channelName)); timeout = NumberUtils .toInt(replacer.replaceValues(connectorProperties.getTimeout(), channelId, channelName), 0); // Initialize contextPath to "" or its value after replacements String contextPath = (connectorProperties.getContextPath() == null ? "" : replacer.replaceValues(connectorProperties.getContextPath(), channelId, channelName)).trim(); /* * Empty string and "/" are both valid and equal functionally. However if there is a * resource defined, we need to make sure that the context path starts with a slash and * doesn't end with one. */ if (!contextPath.startsWith("/")) { contextPath = "/" + contextPath; } if (contextPath.endsWith("/")) { contextPath = contextPath.substring(0, contextPath.length() - 1); } try { server = new Server(); configuration.configureReceiver(this); HandlerCollection handlers = new HandlerCollection(); Handler serverHandler = handlers; // Add handlers for each static resource if (connectorProperties.getStaticResources() != null) { NavigableMap<String, List<HttpStaticResource>> staticResourcesMap = new TreeMap<String, List<HttpStaticResource>>(); // Add each static resource to a map first to allow sorting and deduplication for (HttpStaticResource staticResource : connectorProperties.getStaticResources()) { String resourceContextPath = replacer.replaceValues(staticResource.getContextPath(), channelId, channelName); Map<String, List<String>> queryParameters = new HashMap<String, List<String>>(); // If query parameters were specified, extract them here int queryIndex = resourceContextPath.indexOf('?'); if (queryIndex >= 0) { String query = resourceContextPath.substring(queryIndex + 1); resourceContextPath = resourceContextPath.substring(0, queryIndex); for (NameValuePair param : URLEncodedUtils.parse(query, Charset.defaultCharset())) { List<String> currentValue = queryParameters.get(param.getName()); String value = StringUtils.defaultString(param.getValue()); if (currentValue == null) { currentValue = new ArrayList<String>(); queryParameters.put(param.getName(), currentValue); } currentValue.add(value); } } // We always want to append resources starting with "/" to the base context path if (resourceContextPath.endsWith("/")) { resourceContextPath = resourceContextPath.substring(0, resourceContextPath.length() - 1); } if (!resourceContextPath.startsWith("/")) { resourceContextPath = "/" + resourceContextPath; } resourceContextPath = contextPath + resourceContextPath; List<HttpStaticResource> staticResourcesList = staticResourcesMap.get(resourceContextPath); if (staticResourcesList == null) { staticResourcesList = new ArrayList<HttpStaticResource>(); staticResourcesMap.put(resourceContextPath, staticResourcesList); } staticResourcesList .add(new HttpStaticResource(resourceContextPath, staticResource.getResourceType(), staticResource.getValue(), staticResource.getContentType(), queryParameters)); } // Iterate through each context path in reverse so that more specific contexts take precedence for (List<HttpStaticResource> staticResourcesList : staticResourcesMap.descendingMap().values()) { for (HttpStaticResource staticResource : staticResourcesList) { logger.debug("Adding static resource handler for context path: " + staticResource.getContextPath()); ContextHandler resourceContextHandler = new ContextHandler(); resourceContextHandler.setContextPath(staticResource.getContextPath()); // This allows resources to be requested without a relative context path (e.g. "/") resourceContextHandler.setAllowNullPathInfo(true); resourceContextHandler.setHandler(new StaticResourceHandler(staticResource)); handlers.addHandler(resourceContextHandler); } } } // Add the main request handler ContextHandler contextHandler = new ContextHandler(); contextHandler.setContextPath(contextPath); contextHandler.setHandler(new RequestHandler()); handlers.addHandler(contextHandler); // Wrap the handler collection in a security handler if needed if (authenticatorProvider != null) { serverHandler = createSecurityHandler(handlers); } server.setHandler(serverHandler); logger.debug("starting HTTP server with address: " + host + ":" + port); server.start(); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(), ConnectionStatusEventType.IDLE)); } catch (Exception e) { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(), ConnectionStatusEventType.FAILURE)); throw new ConnectorTaskException("Failed to start HTTP Listener", e); } }
From source file:com.redhat.rhn.frontend.xmlrpc.user.UserHandler.java
/** * Sets the details for a given user. Settable details include: first names, * last name, email, prefix, and password. * @param loggedInUser The current user/* w ww.j a v a 2 s . c om*/ * user. * @param login The login for the user you want to edit * @param details A map containing the new details values * @return Returns 1 if edit was successful, an error is thrown otherwise * @throws FaultException A FaultException is thrown if the user doesn't * have access to lookup the user corresponding to login or if the user * does not exist. * * @xmlrpc.doc Updates the details of a user. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param * #struct("user details") * #prop_desc("string", "first_names", "deprecated, use first_name") * #prop("string", "first_name") * #prop("string", "last_name") * #prop("string", "email") * #prop("string", "prefix") * #prop("string", "password") * #struct_end() * @xmlrpc.returntype #return_int_success() */ public int setDetails(User loggedInUser, String login, Map details) throws FaultException { validateMap(USER_EDITABLE_DETAILS.keySet(), details); // Lookup user handles the logic for making sure that the loggedInUser // has access to the login they are trying to edit. User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); UpdateUserCommand uuc = new UpdateUserCommand(target); // Process each entry passed in by the user for (Object userKey : details.keySet()) { // Check to make sure we have an internal key mapping to prevent issues // if the user passes in cruft String internalKey = USER_EDITABLE_DETAILS.get(userKey); if (internalKey != null) { String newValue = StringUtils.defaultString((String) details.get(userKey)); prepareAttributeUpdate(internalKey, uuc, newValue); } } try { uuc.updateUser(); } catch (IllegalArgumentException iae) { throw new UserNotUpdatedException(iae.getMessage()); } // If we made it here without an exception, then we are a.o.k. return 1; }
From source file:edu.cornell.med.icb.geo.GEOPlatformIndexed.java
/** * Set the current state of the object from a map of properties. * @param propertyMap A map of properties indexed by string key names that can be then * used to reconstruct the object state. *///w w w. j a v a 2s . c o m public void fromPropertyMap(final Map<String, Properties> propertyMap) { if (propertyMap == null) { throw new IllegalArgumentException("Property map cannot be null"); } // IndexedIdentifier probeIds2ProbeIndex final Map<String, Properties> probeIds2ProbeIndexPropertyMap = new HashMap<String, Properties>(); for (final Map.Entry<String, Properties> entry : propertyMap.entrySet()) { final String key = entry.getKey(); if (key.startsWith(PROBE_IDS2_PROBE_INDEX_KEY)) { probeIds2ProbeIndexPropertyMap.put(StringUtils.removeStart(key, PROBE_IDS2_PROBE_INDEX_KEY), entry.getValue()); } } probeIds2ProbeIndex.fromPropertyMap(probeIds2ProbeIndexPropertyMap); // IndexedIdentifier externalIds2TranscriptIndex final Map<String, Properties> externalIds2TranscriptIndexPropertyMap = new HashMap<String, Properties>(); for (final Map.Entry<String, Properties> entry : propertyMap.entrySet()) { final String key = entry.getKey(); if (key.startsWith(EXTERNAL_IDS2_TRANSCRIPT_INDEX_KEY)) { externalIds2TranscriptIndexPropertyMap .put(StringUtils.removeStart(key, EXTERNAL_IDS2_TRANSCRIPT_INDEX_KEY), entry.getValue()); } } externalIds2TranscriptIndex.fromPropertyMap(externalIds2TranscriptIndexPropertyMap); // Int2IntMap probeIndex2ExternalIDIndex probeIndex2ExternalIDIndex.clear(); // reset any previous state final Properties probeIndex2ExternalIDIndexProperties = propertyMap.get(PROBE_INDEX2_EXTERNAL_IDINDEX_KEY); if (probeIndex2ExternalIDIndexProperties != null) { for (final Map.Entry<Object, Object> entry : probeIndex2ExternalIDIndexProperties.entrySet()) { probeIndex2ExternalIDIndex.put(NumberUtils.toInt(entry.getKey().toString()), NumberUtils.toInt(entry.getValue().toString())); } } // MutableString externalIdType final Properties externalIdTypeProperties = propertyMap.get(EXTERNAL_ID_TYPE_KEY); if (externalIdTypeProperties != null) { externalIdType = new MutableString( StringUtils.defaultString(externalIdTypeProperties.getProperty(EXTERNAL_ID_TYPE_KEY))); } else { externalIdType = null; } // MutableString name final Properties nameProperties = propertyMap.get(NAME_KEY); if (nameProperties != null) { name = new MutableString(StringUtils.defaultString(nameProperties.getProperty(NAME_KEY))); } else { name = null; } // Int2ObjectMap<MutableString> externalIndex2Id externalIndex2Id.clear(); // reset any previous state final Properties externalIndex2IdProperties = propertyMap.get(EXTERNAL_INDEX2_ID_KEY); if (externalIndex2IdProperties != null) { for (final Map.Entry<Object, Object> entry : externalIndex2IdProperties.entrySet()) { externalIndex2Id.put(NumberUtils.toInt(entry.getKey().toString()), new MutableString(entry.getValue().toString())); } } // Int2ObjectMap<MutableString> probeIndex2probeId probeIndex2probeId.clear(); // reset any previous state final Properties probeIndex2probeIdProperties = propertyMap.get(PROBE_INDEX2PROBE_ID_KEY); if (probeIndex2probeIdProperties != null) { for (final Map.Entry<Object, Object> entry : probeIndex2probeIdProperties.entrySet()) { probeIndex2probeId.put(NumberUtils.toInt(entry.getKey().toString()), new MutableString(entry.getValue().toString())); } } }
From source file:jp.co.nemuzuka.service.impl.TodoServiceImpl.java
/** * Model./*from w ww. j av a 2 s. co m*/ * @param model Model * @param form Form */ private void setModel(TodoModel model, TodoForm form) { SimpleDateFormat sdf = DateTimeUtils.createSdf("yyyyMMdd"); TodoStatus status = TodoStatus.fromCode(form.todoStatus); if (status == null) { status = TodoStatus.nothing; } model.setStatus(status); model.setTitle(form.title); model.setTag(reCreateTag(form.tag)); model.setContent(new Text(StringUtils.defaultString(form.content))); model.setPeriod(ConvertUtils.toDate(form.period, sdf)); model.setVersion(ConvertUtils.toLong(form.versionNo)); }
From source file:mitm.application.djigzo.ws.impl.X509CertStoreWSImpl.java
@Override @StartTransaction/* www. ja va2 s .c o m*/ public long getSearchBySubjectCount(String subject, Expired expired, MissingKeyAlias missingKeyAlias) throws WebServiceCheckedException { subject = StringUtils.defaultString(subject); if (expired == null) { throw new WebServiceCheckedException("expired is missing."); } if (missingKeyAlias == null) { throw new WebServiceCheckedException("missingKeyAlias is missing."); } try { return certStore.getSearchBySubjectCount(subject, expired, missingKeyAlias); } catch (CertStoreException e) { logger.error("getSearchBySubjectCount failed.", e); throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e)); } catch (RuntimeException e) { logger.error("getSearchBySubjectCount failed.", e); throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e)); } }
From source file:fr.paris.lutece.plugins.document.service.search.DocumentIndexer.java
/** * Get the content from the document/*from w w w .jav a 2 s. c o m*/ * @param document the document to index * @return the content */ private static String getContentToIndex(Document document) { StringBuilder sbContentToIndex = new StringBuilder(); sbContentToIndex.append(document.getTitle()); for (DocumentAttribute attribute : document.getAttributes()) { if (attribute.isSearchable()) { if (!attribute.isBinary()) { // Text attributes sbContentToIndex.append(" "); sbContentToIndex.append(attribute.getTextValue()); } else { // Binary file attribute // Gets indexer depending on the ContentType (ie: "application/pdf" should use a PDF indexer) IFileIndexerFactory factoryIndexer = (IFileIndexerFactory) SpringContextService .getBean(IFileIndexerFactory.BEAN_FILE_INDEXER_FACTORY); IFileIndexer indexer = factoryIndexer.getIndexer(attribute.getValueContentType()); if (indexer != null) { try { ByteArrayInputStream bais = new ByteArrayInputStream(attribute.getBinaryValue()); sbContentToIndex.append(" "); sbContentToIndex.append(indexer.getContentToIndex(bais)); bais.close(); } catch (IOException e) { AppLogService.error(e.getMessage(), e); } } } } } // Index Metadata sbContentToIndex.append(" "); sbContentToIndex.append(StringUtils.defaultString(document.getXmlMetadata())); return sbContentToIndex.toString(); }