List of usage examples for org.apache.commons.lang StringUtils defaultIfBlank
public static String defaultIfBlank(String str, String defaultStr)
Returns either the passed in String, or if the String is whitespace, empty ("") or null
, the value of defaultStr
.
From source file:org.niord.core.message.MessagePrintParams.java
/** * Returns a valid PDF file name "Content-Disposition" header * @param defaultName the default name to use if no file name has been set * @return a valid PDF file name "Content-Disposition" header *///from w ww .j ava 2 s . c o m public String getFileNameHeader(String defaultName) { String name = StringUtils.defaultIfBlank(fileName, defaultName); if (!name.toLowerCase().endsWith(".pdf")) { name += ".pdf"; } return "attachment; filename=\"" + WebUtils.encodeURIComponent(name) + "\""; }
From source file:org.niord.core.message.MessageScriptFilterService.java
/** * Check if the message is included in the filter or not * @param filter the filter/*w w w. ja v a 2 s. com*/ * @param message the message to check * @return if the message is included in the filter or not */ public boolean includeMessage(String filter, Message message, Object data) { filter = StringUtils.defaultIfBlank(filter, ""); // Look up or create the evaluator for the filter MessageScriptFilterEvaluator evaluator = filters.get(filter); if (evaluator == null) { synchronized (filters) { evaluator = filters.get(filter); if (evaluator == null) { try { evaluator = new MessageScriptFilterEvaluator(filter); log.info("instantiated message script filter " + filter); } catch (Exception ex) { evaluator = MessageScriptFilterEvaluator.EXCLUDE_ALL; log.error("Error instantiating message script filter " + filter, ex); } filters.put(filter, evaluator); } } } return evaluator.includeMessage(message, data); }
From source file:org.niord.core.message.MessageTagService.java
/** * Searches for message tags matching the given search parameters * * @param params the search parameters// ww w .j ava 2 s .c om * @return the search result */ @SuppressWarnings("ResultOfMethodCallIgnored") public List<MessageTag> searchMessageTags(MessageTagSearchParams params) { User user = userService.currentUser(); Domain domain = domainService.currentDomain(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MessageTag> query = cb.createQuery(MessageTag.class); Root<MessageTag> tagRoot = query.from(MessageTag.class); // Build the predicate CriteriaHelper<MessageTag> criteriaHelper = new CriteriaHelper<>(cb, query); // Name filtering criteriaHelper.like(tagRoot.get("name"), params.getName()); // Locked filtering criteriaHelper.equals(tagRoot.get("locked"), params.getLocked()); // Type filtering Set<MessageTagType> types = params.getTypes() != null ? params.getTypes() : new HashSet<>(); if (types.isEmpty()) { types.add(PUBLIC); types.add(DOMAIN); types.add(PRIVATE); } List<Predicate> typePredicates = new LinkedList<>(); if (types.contains(PUBLIC)) { typePredicates.add(cb.equal(tagRoot.get("type"), MessageTagType.PUBLIC)); } if (types.contains(DOMAIN) && domain != null) { Join<MessageTag, Domain> domains = tagRoot.join("domain", JoinType.LEFT); typePredicates.add(cb.and(cb.equal(tagRoot.get("type"), MessageTagType.DOMAIN), cb.equal(domains.get("id"), domain.getId()))); } if (types.contains(PRIVATE) && user != null) { Join<MessageTag, User> users = tagRoot.join("user", JoinType.LEFT); typePredicates.add(cb.and(cb.equal(tagRoot.get("type"), MessageTagType.PRIVATE), cb.equal(users.get("id"), user.getId()))); } if (types.contains(TEMP)) { typePredicates.add(cb.equal(tagRoot.get("type"), MessageTagType.TEMP)); } criteriaHelper.add(cb.or(typePredicates.toArray(new Predicate[typePredicates.size()]))); // Compute the sorting List<Order> sortOrders = new ArrayList<>(); Order nameAscSortOrder = cb.asc(cb.lower(tagRoot.get("name"))); if (params.sortByType()) { Expression sortBy = tagRoot.get("type"); sortOrders.add(params.getSortOrder() == DESC ? cb.desc(sortBy) : cb.asc(sortBy)); sortOrders.add(nameAscSortOrder); } else if (params.sortByCreated()) { Expression sortBy = tagRoot.get("created"); sortOrders.add(params.getSortOrder() == DESC ? cb.desc(sortBy) : cb.asc(sortBy)); sortOrders.add(nameAscSortOrder); } else if (params.sortByExpiryDate()) { Expression sortBy = tagRoot.get("expiryDate"); sortOrders.add(params.getSortOrder() == DESC ? cb.desc(sortBy) : cb.asc(sortBy)); sortOrders.add(nameAscSortOrder); } else if (params.sortByMessageCount()) { Expression sortBy = tagRoot.get("messageCount"); sortOrders.add(params.getSortOrder() == DESC ? cb.desc(sortBy) : cb.asc(sortBy)); sortOrders.add(nameAscSortOrder); } else { if (StringUtils.isNotBlank(params.getName())) { sortOrders.add(cb.asc(cb.locate(cb.lower(tagRoot.get("name")), params.getName().toLowerCase()))); } String name = StringUtils.defaultIfBlank(params.getName(), ""); Expression sortBy = cb.lower(tagRoot.get("name")); sortOrders.add(params.getSortOrder() == DESC ? cb.desc(sortBy) : cb.asc(sortBy)); } // Complete the query query.select(tagRoot).distinct(true).where(criteriaHelper.where()).orderBy(sortOrders); // Execute the query and update the search result return em.createQuery(query).setMaxResults(params.getMaxSize()).getResultList(); }
From source file:org.niord.core.NiordApp.java
/** * Registers the server name associated with the current thread (i.e. servlet request) * @param req the servlet request/* w ww . ja v a 2 s . co m*/ */ public void registerServerNameForCurrentThread(ServletRequest req) { String scheme = StringUtils.defaultIfBlank(req.getScheme(), "http"); String serverName = StringUtils.defaultIfBlank(req.getServerName(), "localhost"); String port = (scheme.equalsIgnoreCase("https")) ? (req.getServerPort() == 443 ? "" : ":" + req.getServerPort()) : (req.getServerPort() == 80 ? "" : ":" + req.getServerPort()); if (StringUtils.isNotBlank(serverName)) { THREAD_LOCAL_SERVER_NAME.set(scheme + "://" + serverName + port); } }
From source file:org.niord.core.NiordApp.java
/** * Returns the server name associated with the current thread (i.e. servlet request) * or the base URI if the server name is undefined. * @return the server name associated with the current thread or the base URI if the server name is undefined */// w w w. jav a 2 s. co m public String getServerNameForCurrentThreadOrBaseUri() { return StringUtils.defaultIfBlank(getServerNameForCurrentThread(), getBaseUri()); }
From source file:org.niord.core.publication.PublicationService.java
/** * Check if the message should be assigned to the associated message tag of the recording publication * @param publication the publication//from ww w . j ava 2 s. c om * @param message the message * @param phase the phase */ private void checkMessageForRecordingPublication(Publication publication, Message message, String phase) { MessageTag tag = publication.getMessageTag(); boolean isIncluded = tag.getMessages().contains(message); // "data" parameter for the message tag filter function Map<String, Object> data = new HashMap<>(); data.put("phase", phase); data.put("isIncluded", isIncluded); // Determine the message tag filter to test String messageTagFilter = StringUtils.defaultIfBlank(publication.getMessageTagFilter(), DEFAULT_MESSAGE_TAG_FILTER); // Check if the message should be included in the associated message tag boolean includeMessage = messageScriptFilterService.includeMessage(messageTagFilter, message, data); if (includeMessage && !isIncluded) { tag.getMessages().add(message); tag.updateMessageCount(); log.info("Added message " + message.getUid() + " to tag: " + tag.getName()); } else if (!includeMessage && isIncluded) { tag.getMessages().remove(message); tag.updateMessageCount(); log.info("Removed message " + message.getUid() + " from tag: " + tag.getName()); } }
From source file:org.niord.core.publication.PublicationUtils.java
/** * Updates the message publications from the publication, parameters and link * * @param message the message//from w w w . j av a 2s . c o m * @param publication the publication to extract * @param parameters the optional parameters * @param link the optional link * @param lang either a specific language or null for all languages * @return the message publication or null if not found */ public static MessageVo updateMessagePublications(MessageVo message, SystemPublicationVo publication, String parameters, String link, String lang) { // Sanity check if (message == null || publication == null) { return null; } boolean internal = publication.getMessagePublication() == MessagePublication.INTERNAL; message.getDescs().stream().filter(msgDesc -> lang == null || lang.equals(msgDesc.getLang())) .forEach(msgDesc -> { String updatedPubHtml = computeMessagePublication(publication, parameters, link, msgDesc.getLang()); String pubHtml = internal ? msgDesc.getInternalPublication() : msgDesc.getPublication(); pubHtml = StringUtils.defaultIfBlank(pubHtml, ""); Document doc = Jsoup.parseBodyFragment(pubHtml); String pubAttr = "[publication=" + publication.getPublicationId() + "]"; Element e = doc.select("a" + pubAttr + ",span" + pubAttr).first(); if (e != null) { // TODO: Is there a better way to replace an element? e.replaceWith(Jsoup.parse(updatedPubHtml).body().child(0)); pubHtml = doc.body().html(); } else { pubHtml += " " + updatedPubHtml; } // Lastly, clean up html for artifacts often added by TinyMCE if (StringUtils.isNotBlank(pubHtml)) { pubHtml = pubHtml.replace("<p>", "").replace("</p>", "").trim(); if (internal) { msgDesc.setInternalPublication(pubHtml); } else { msgDesc.setPublication(pubHtml); } } }); return message; }
From source file:org.niord.core.publication.PublicationUtils.java
/** * Computes the message publication text * @param lang the language//from ww w .ja v a 2 s . c om * @return the message publication text */ public static String computeMessagePublication(SystemPublicationVo publication, String parameters, String link, String lang) { String result = null; PublicationDescVo pubDesc = publication.getDesc(lang); if (pubDesc != null && StringUtils.isNotBlank(pubDesc.getMessagePublicationFormat())) { String params = StringUtils.defaultIfBlank(parameters, ""); result = pubDesc.getMessagePublicationFormat().replace("${parameters}", params); if (publication.getMessagePublication() == MessagePublication.INTERNAL) { result = "[" + result + "]"; } result = TextUtils.trailingDot(result); String href = StringUtils.defaultIfBlank(link, pubDesc.getLink()); if (StringUtils.isNotBlank(href)) { result = String.format("<a publication=\"%s\" href=\"%s\" target=\"_blank\">%s</a>", publication.getPublicationId(), href, result); } else { result = String.format("<span publication=\"%s\">%s</span>", publication.getPublicationId(), result); } } return result; }
From source file:org.niord.core.source.SourceService.java
/** * Searches for sources matching the given term * * @param term the search term/* ww w . j a v a2 s . c om*/ * @param lang the search language * @param inactive whether to include inactive sources as well as active * @param limit the maximum number of results * @return the search result */ public List<Source> searchSources(String lang, String term, boolean inactive, int limit) { term = StringUtils.defaultIfBlank(term, ""); Set<Boolean> activeFlag = new HashSet<>(); activeFlag.add(Boolean.TRUE); if (inactive) { activeFlag.add(Boolean.FALSE); } return em.createNamedQuery("Source.searchSources", Source.class).setParameter("active", activeFlag) .setParameter("lang", lang).setParameter("term", "%" + term.toLowerCase() + "%").getResultList() .stream().limit(limit).collect(Collectors.toList()); }
From source file:org.niord.web.BatchRestService.java
/** * Executes the given javascript via the "script-executor" batch job * * NB: Important to only let sysadmin access this operation. * * @param params the javascript parameter *///from w w w . j a va2 s . c o m @POST @Path("/execute-javascript") @Consumes("application/json;charset=UTF-8") @Produces("text/plain") @RolesAllowed(Roles.SYSADMIN) public String executeJavaScript(ExecuteJavaScriptParams params) throws Exception { if (StringUtils.isNotBlank(params.getJavaScript())) { log.warn("User " + userService.currentUser().getName() + " scheduled execution of JavaScript:\n" + params.getJavaScript()); batchService.startBatchJobWithDataFile("script-executor", IOUtils.toInputStream(params.getJavaScript(), "UTF-8"), StringUtils.defaultIfBlank(params.getScriptName(), "javascript.js"), new HashMap<>()); } return "OK"; }