List of usage examples for org.apache.commons.lang3 StringUtils defaultIfEmpty
public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr)
Returns either the passed in CharSequence, or if the CharSequence is empty or null , the value of defaultStr .
StringUtils.defaultIfEmpty(null, "NULL") = "NULL" StringUtils.defaultIfEmpty("", "NULL") = "NULL" StringUtils.defaultIfEmpty(" ", "NULL") = " " StringUtils.defaultIfEmpty("bat", "NULL") = "bat" StringUtils.defaultIfEmpty("", null) = null
From source file:com.gargoylesoftware.htmlunit.html.HtmlArea.java
private boolean isEmpty() { final String shape = StringUtils.defaultIfEmpty(getShapeAttribute(), "rect").toLowerCase(Locale.ROOT); if ("default".equals(shape) && getCoordsAttribute() != null) { return false; }// w w w .j a va 2 s . com if ("rect".equals(shape) && getCoordsAttribute() != null) { final Rectangle2D rectangle = parseRect(); return rectangle.isEmpty(); } if ("circle".equals(shape) && getCoordsAttribute() != null) { final Ellipse2D ellipse = parseCircle(); return ellipse.isEmpty(); } if ("poly".equals(shape) && getCoordsAttribute() != null) { return false; } return false; }
From source file:com.google.code.siren4j.converter.ReflectingConverter.java
/** * The recursive method that actually does the work of converting from a resource to an entity. * * @param obj the object to be converted, this could be a <code>Resource</code> or another <code>Object</code>. Only * <code>Resource</code> objects are allowed in via public methods, other object types may come from recursing into the * original resource. May be <code>null</code>. * @param parentField the parent field, ie the field that contained this object, may be <code>null</code>. * @param parentObj the object that contains the field that contains this object, may be <code>null</code>. * @param parentFieldInfo field info for all exposed parent object fields, may be <code>null</code>. * @return the entity created from the resource. May be <code>null</code>. * @throws Exception//from ww w. j av a 2 s . c om */ @SuppressWarnings("deprecation") protected Entity toEntity(Object obj, Field parentField, Object parentObj, List<ReflectedInfo> parentFieldInfo) throws Siren4JException { if (obj == null) { return null; } EntityBuilder builder = EntityBuilder.newInstance(); Class<?> clazz = obj.getClass(); boolean embeddedLink = false; List<ReflectedInfo> fieldInfo = ReflectionUtils.getExposedFieldInfo(clazz); EntityContext context = new EntityContextImpl(obj, fieldInfo, parentField, parentObj, parentFieldInfo); String cname = null; String uri = ""; //Propagate baseUri and fullyQualified setting from parent if needed propagateBaseUriAndQualifiedSetting(obj, parentObj); boolean suppressClass = false; Siren4JEntity entityAnno = (Siren4JEntity) clazz.getAnnotation(Siren4JEntity.class); if (entityAnno != null && (StringUtils.isNotBlank(entityAnno.name()) && ArrayUtils.isNotEmpty(entityAnno.entityClass()))) { throw new Siren4JRuntimeException("Must only use one of 'name' or 'entityClass', not both."); } if (entityAnno != null) { cname = StringUtils.defaultIfEmpty(entityAnno.name(), cname); uri = StringUtils.defaultIfEmpty(entityAnno.uri(), uri); suppressClass = entityAnno.suppressClassProperty(); } if (!suppressClass) { builder.addProperty(Siren4J.CLASS_RESERVED_PROPERTY, clazz.getName()); } Siren4JSubEntity parentSubAnno = null; if (parentField != null && parentFieldInfo != null) { parentSubAnno = getSubEntityAnnotation(parentField, parentFieldInfo); } if (parentSubAnno != null) { uri = StringUtils.defaultIfEmpty(parentSubAnno.uri(), uri); //Determine if the entity is an embeddedLink embeddedLink = parentSubAnno.embeddedLink(); if (obj instanceof Resource) { Boolean overrideLink = ((Resource) obj).getOverrideEmbeddedLink(); if (overrideLink != null) { embeddedLink = overrideLink.booleanValue(); } } } // Handle uri overriding or token replacement String resolvedUri = resolveUri(uri, context, true); builder.setComponentClass(getEntityClass(obj, cname, entityAnno)); if (parentSubAnno != null) { String fname = parentField != null ? parentField.getName() : cname; builder.setRelationship(ComponentUtils.isStringArrayEmpty(parentSubAnno.rel()) ? new String[] { fname } : parentSubAnno.rel()); } if (embeddedLink) { builder.setHref(resolvedUri); } else { for (ReflectedInfo info : fieldInfo) { Field currentField = info.getField(); Object fieldVal = null; try { fieldVal = currentField.get(obj); } catch (Exception e) { throw new Siren4JConversionException(e); } if (ReflectionUtils.isSirenProperty(currentField.getType(), fieldVal, currentField)) { // Property if (!skipProperty(obj, currentField)) { String propName = currentField.getName(); Siren4JProperty propAnno = currentField.getAnnotation(Siren4JProperty.class); if (propAnno != null && StringUtils.isNotBlank(propAnno.name())) { // Override field name from annotation propName = propAnno.name(); } handleAddProperty(builder, propName, currentField, obj); } } else { // Sub Entity if (!skipProperty(obj, currentField)) { handleSubEntity(builder, obj, currentField, fieldInfo); } } } if (obj instanceof Collection) { builder.addProperty("size", ((Collection<?>) obj).size()); } if (obj instanceof Resource) { Resource res = (Resource) obj; boolean skipBaseUri = isSuppressBaseUriOnFullyQualified() && (res.isFullyQualifiedLinks() && res.getBaseUri() != null); if (!skipBaseUri) { handleBaseUriLink(builder, res.getBaseUri()); } } handleSelfLink(builder, resolvedUri); handleEntityLinks(builder, context); handleEntityActions(builder, context); } return builder.build(); }
From source file:com.xpn.xwiki.pdf.impl.PdfExportImpl.java
/** * Convert an XSL-FO document into PDF.//from w w w. j av a 2 s .co m * * @param xmlfo the source FO to render * @param out where to write the resulting document * @param type the type of the output: PDF or RTF * @throws XWikiException if the conversion fails for any reason */ private void renderXSLFO(String xmlfo, OutputStream out, ExportType type) throws XWikiException { try { FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // Construct fop with desired output format Fop fop = fopFactory.newFop(type.getMimeType(), foUserAgent, out); // Identity transformer Transformer transformer = transformerFactory.newTransformer(); // Setup input stream Source source = new StreamSource(new StringReader(xmlfo)); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(source, res); // Result processing FormattingResults foResults = fop.getResults(); if (foResults != null && LOGGER.isDebugEnabled()) { @SuppressWarnings("unchecked") java.util.List<PageSequenceResults> pageSequences = foResults.getPageSequences(); for (PageSequenceResults pageSequenceResults : pageSequences) { LOGGER.debug( "PageSequence " + StringUtils.defaultIfEmpty(pageSequenceResults.getID(), "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages."); } LOGGER.debug("Generated " + foResults.getPageCount() + " pages in total."); } } catch (IllegalStateException e) { throw createException(e, type, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION); } catch (Exception e) { throw createException(e, type, XWikiException.ERROR_XWIKI_EXPORT_PDF_FOP_FAILED); } }
From source file:io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil.java
public static String getBuildStatusReason(Build build) { if (build != null && build.getStatus() != null) { String reason = build.getStatus().getReason(); String phase = build.getStatus().getPhase(); if (StringUtils.isNotBlank(phase)) { if (StringUtils.isNotBlank(reason)) { return phase + ": " + reason; } else { return phase; }/*from w ww. j ava 2 s. c o m*/ } else { return StringUtils.defaultIfEmpty(reason, ""); } } return ""; }
From source file:com.webbfontaine.valuewebb.model.util.Utils.java
public static void setLocale(String language) { String notEmptyLanguage = StringUtils.defaultIfEmpty(StringUtils.trimToEmpty(language), EN).replaceAll("'", "");//from w w w . j a v a 2 s .co m if (Constants.FR.equals(notEmptyLanguage)) { LocaleSelector.instance().setLocale(Locale.FRENCH); } else { if (Constants.EN.equals(notEmptyLanguage)) { LocaleSelector.instance().setLocale(Locale.ENGLISH); } else { LOGGER.warn("There is no support for locale {0}. English will be set.", notEmptyLanguage); LocaleSelector.instance().setLocale(Locale.ENGLISH); } } }
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
/** * Gets the user date string.// ww w .j a va 2 s. c o m * * @param date the date * @return the user date string */ public String getUserDateString(Date date) { if (date == null) { return ""; } String tz = getWikiWeb().getAuthorization().getUserProp(this, GWikiUserAuthorization.USER_TZ); tz = StringUtils.defaultIfEmpty(tz, TimeZone.getDefault().getID()); String df = getWikiWeb().getAuthorization().getUserProp(this, GWikiUserAuthorization.USER_DATEFORMAT); df = StringUtils.defaultIfEmpty(df, TimeUtils.ISO_DATETIME); return TimeUtils.formatDate(date, df, tz); }
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
public TimeZone getUserTimeZone() { String tz = getWikiWeb().getAuthorization().getUserProp(this, GWikiUserAuthorization.USER_TZ); tz = StringUtils.defaultIfEmpty(tz, TimeZone.getDefault().getID()); TimeZone timeZone = TimeZone.getTimeZone(tz); return timeZone; }
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
/** * Parses the user date string./*ww w . j a v a 2 s . c o m*/ * * @param ds the ds * @return the date */ public Date parseUserDateString(String ds) { if (StringUtils.isBlank(ds) == true) { return null; } String tz = getWikiWeb().getAuthorization().getUserProp(this, GWikiUserAuthorization.USER_TZ); tz = StringUtils.defaultIfEmpty(tz, TimeZone.getDefault().getID()); String df = getWikiWeb().getAuthorization().getUserProp(this, GWikiUserAuthorization.USER_DATEFORMAT); df = StringUtils.defaultIfEmpty(df, TimeUtils.ISO_DATETIME); return TimeUtils.parseDate(ds, df, tz); }
From source file:com.simpligility.maven.plugins.android.phase08preparepackage.DexMojo.java
/** * Makes sure the string ends with "/"// w w w. j a v a 2s. com * * @param prefix * any string, or null. * @return the prefix with a "/" at the end, never null. */ protected String endWithSlash(String prefix) { prefix = StringUtils.defaultIfEmpty(prefix, "/"); if (!prefix.endsWith("/")) { prefix = prefix + "/"; } return prefix; }
From source file:com.streamsets.pipeline.stage.origin.salesforce.ForceSource.java
private String soapProduce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { String nextSourceOffset = (null == lastSourceOffset) ? RECORD_ID_OFFSET_PREFIX + conf.initialOffset : lastSourceOffset;//from ww w .j av a 2s. c om if (queryResult == null) { try { String id = (lastSourceOffset == null) ? null : lastSourceOffset.substring(lastSourceOffset.indexOf(':') + 1); final String preparedQuery = prepareQuery(conf.soqlQuery, id); LOG.info("preparedQuery: {}", preparedQuery); queryResult = conf.queryAll ? partnerConnection.queryAll(preparedQuery) : partnerConnection.query(preparedQuery); recordIndex = 0; } catch (ConnectionException e) { throw new StageException(Errors.FORCE_08, e); } } SObject[] records = queryResult.getRecords(); LOG.info("Retrieved {} records", records.length); if (recordCreator.isCountQuery()) { // Special case for old-style COUNT() query Record rec = getContext().createRecord(conf.soqlQuery); LinkedHashMap<String, Field> map = new LinkedHashMap<>(); map.put(COUNT, Field.create(Field.Type.INTEGER, queryResult.getSize())); rec.set(Field.createListMap(map)); rec.getHeader().setAttribute(ForceRecordCreator.SOBJECT_TYPE_ATTRIBUTE, sobjectType); batchMaker.addRecord(rec); } else { int endIndex = Math.min(recordIndex + maxBatchSize, records.length); for (; recordIndex < endIndex; recordIndex++) { SObject record = records[recordIndex]; String offsetColumn = StringUtils.defaultIfEmpty(conf.offsetColumn, ID); XmlObject offsetField = getChildIgnoreCase(record, offsetColumn); String offset; if (offsetField == null || offsetField.getValue() == null) { if (!conf.disableValidation) { throw new StageException(Errors.FORCE_22, offsetColumn); } // Aggregate query - set the offset to the record index, since we have no offset column offset = String.valueOf(recordIndex); } else { offset = fixOffset(offsetColumn, offsetField.getValue().toString()); nextSourceOffset = RECORD_ID_OFFSET_PREFIX + offset; } final String sourceId = StringUtils.substring(conf.soqlQuery.replaceAll("[\n\r]", " "), 0, 100) + "::rowCount:" + recordIndex + (StringUtils.isEmpty(conf.offsetColumn) ? "" : ":" + offset); Record rec = recordCreator.createRecord(sourceId, record); batchMaker.addRecord(rec); } } if (recordIndex == records.length) { try { if (queryResult.isDone()) { // We're out of results queryResult = null; lastQueryCompletedTime = System.currentTimeMillis(); LOG.info("Query completed at: {}", lastQueryCompletedTime); shouldSendNoMoreDataEvent = true; if (conf.subscribeToStreaming) { // Switch to processing events nextSourceOffset = READ_EVENTS_FROM_NOW; } else if (conf.repeatQuery == ForceRepeatQuery.FULL) { nextSourceOffset = RECORD_ID_OFFSET_PREFIX + conf.initialOffset; } else if (conf.repeatQuery == ForceRepeatQuery.NO_REPEAT) { nextSourceOffset = null; } } else { queryResult = partnerConnection.queryMore(queryResult.getQueryLocator()); recordIndex = 0; } } catch (ConnectionException e) { throw new StageException(Errors.FORCE_08, e); } } return nextSourceOffset; }