Java Code Examples for org.apache.commons.lang3.StringUtils#defaultIfEmpty()

The following examples show how to use org.apache.commons.lang3.StringUtils#defaultIfEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringSwaggerExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Parameter extractRequestParam(Type type, RequestParam requestParam) {
    if (requestParam == null) {
        requestParam = DEFAULT_REQUEST_PARAM;
    }

    String paramName = StringUtils.defaultIfEmpty(requestParam.value(), requestParam.name());
    QueryParameter queryParameter = new QueryParameter().name(paramName)
            .required(requestParam.required());

    if (!DEFAULT_VALUE.equals(requestParam.defaultValue())) {
        queryParameter.setDefaultValue(requestParam.defaultValue());
        // Supplying a default value implicitly sets required() to false.
        queryParameter.setRequired(false);
    }
    Property schema = readAsPropertyIfPrimitive(type);
    if (schema != null) {
        queryParameter.setProperty(schema);
    }

    return queryParameter;
}
 
Example 2
Source File: ReflectionTableParser.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private Map<String, String> getRowColumnsFromObjectFields(Object object) {
    Class<?> clazz = object.getClass();
    if (Objects.isNull(AnnotationUtils.findAnnotation(clazz, textTableClass))) {
        return Collections.emptyMap();
    }

    Map<String, String> columns = new LinkedHashMap<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(textColumnClass)) {
            TextColumn textColumn = field.getAnnotation(textColumnClass);
            String columnKey = StringUtils.defaultIfEmpty(textColumn.key(), field.getName());
            columns.put(columnKey, getColumnValueFromField(field, object));
        }
    }

    return columns;
}
 
Example 3
Source File: MysqlJdbcImpl.java    From metadata with Apache License 2.0 6 votes vote down vote up
/**
 * Mysql 的链接信息
 * @param port     端口号
 * @param database 数据库
 * @param username 用户名称
 * @param password 密码
 * @return 链接信息
 */
private JdbcVo buildMySqlJdbcVo(final String host, final String port,
                                final String database, final String username, final String password) {
    final String hostActual = StringUtils.defaultIfEmpty(host, "127.0.0.1");
    final String portActual = StringUtils.defaultIfEmpty(port, "3306");
    final String usernameActual = StringUtils.defaultIfEmpty(username, "root");
    final String passwordActual = StringUtils.defaultIfEmpty(password, "123456");

    JdbcVo jdbcVo = new JdbcVo();
    jdbcVo.setDriverClassName(DriverNameConstant.MYSQL);
    jdbcVo.setUrl(String.format("jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8&useOldAlias",
            hostActual, portActual, database));
    jdbcVo.setUsername(usernameActual);
    jdbcVo.setPassword(passwordActual);
    return jdbcVo;
}
 
Example 4
Source File: AgnUtils.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String normalizeNumber(String decimalSeparator, String groupingSeparator, String numberString) {
	if (StringUtils.isBlank(numberString)) {
		return "";
	} else {
		decimalSeparator = StringUtils.defaultIfEmpty(decimalSeparator, DEFAULT_DECIMAL_SEPARATOR);
		groupingSeparator = StringUtils.defaultIfEmpty(groupingSeparator, DEFAULT_GROUPING_SEPARATOR);

		String result;
		if (StringUtils.equals(decimalSeparator, ".")) {
			result = StringUtils.replaceEach(numberString, new String[] { groupingSeparator, " " }, new String[] { "", "" });
		} else {
			result = StringUtils.replaceEach(numberString, new String[] { decimalSeparator, groupingSeparator, " " }, new String[] { ".", "", "" });
		}
		return StringUtils.trimToEmpty(result);
	}
}
 
Example 5
Source File: ReflectionTableParser.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private ColumnDefinition getColumnDefinition(TextColumn textColumn, Member member) {
    String translationKey = textColumn.translationKey();
    String defaultName = StringUtils.defaultIfEmpty(textColumn.defaultValue(), member.getName());
    int width = textColumn.width();

    return new ColumnDefinitionImpl(defaultName, translationKey, width);
}
 
Example 6
Source File: AgnTagUtils.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<String> getOptionalParametersForTag(final String tagName) {
	final String safeTagName = StringUtils.defaultIfEmpty(tagName, "");
	switch (safeTagName) {
		case "agnVOUCHER":
			return Collections.singletonList("default");

		default:
			return Collections.emptyList();
	}
}
 
Example 7
Source File: ImportProfileColumnsAction.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private void appendNewColumnLog(ColumnMapping newMapping, StringBuilder log) {
    String dbColumn = StringUtils.defaultIfEmpty(newMapping.getDatabaseColumn(), NO_VALUE),
            defaultValue = StringUtils.defaultIfEmpty(newMapping.getDefaultValue(), NO_VALUE);
    log.append(", ").append(String.format("database mapping set to %s", dbColumn))
            .append(String.format(", mandatory set to %b", newMapping.isMandatory()))
            .append(String.format(", default value set to %s", defaultValue));
}
 
Example 8
Source File: DataSourceServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public PaginatedListImpl<DataSource> getPaginatedDataSources(@VelocityCheck int companyId, String sortColumn,
											int pageNumber, int pageSize, String direction) {
	pageNumber = pageNumber <= 0 ? 1 : pageNumber;
	pageSize = pageSize <= 0 ? 20 : pageSize;
	boolean isAscending = AgnUtils.sortingDirectionToBoolean(direction, false);
	sortColumn = StringUtils.defaultIfEmpty(sortColumn, "datasource_id");
	return datasourceDescriptionDao.getPaginatedDataSources(companyId, sortColumn, pageNumber, pageSize, isAscending);
}
 
Example 9
Source File: DebugFrameImpl.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private static String stringValue(final Object arg) {
    if (arg instanceof NativeFunction) {
        // Don't return the string value of the function, because it's usually
        // multiple lines of content and messes up the log.
        final String name = StringUtils.defaultIfEmpty(((NativeFunction) arg).getFunctionName(), "anonymous");
        return "[function " + name + "]";
    }
    else if (arg instanceof IdFunctionObject) {
        return "[function " + ((IdFunctionObject) arg).getFunctionName() + "]";
    }
    else if (arg instanceof Function) {
        return "[function anonymous]";
    }
    String asString = null;
    try {
        // try to get the js representation
        asString = Context.toString(arg);
        if (arg instanceof Event) {
            asString += "<" + ((Event) arg).getType() + ">";
        }
    }
    catch (final Throwable e) {
        // seems to be a bug (many bugs) in rhino (TODO: investigate it)
        asString = String.valueOf(arg);
    }
    return asString;
}
 
Example 10
Source File: ChartResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Executes the result. Writes the given chart as a PNG to the servlet
 * output stream.
 *
 * @param invocation an encapsulation of the action execution state.
 * @throws Exception if an error occurs when creating or writing the chart
 *                   to the servlet output stream.
 */
@Override
public void execute( ActionInvocation invocation )
    throws Exception
{
    JFreeChart stackChart = (JFreeChart) invocation.getStack().findValue( "chart" );

    chart = stackChart != null ? stackChart : chart;

    Integer stackHeight = (Integer) invocation.getStack().findValue( "height" );

    height = stackHeight != null && stackHeight > 0 ? stackHeight : height != null ? height : DEFAULT_HEIGHT;

    Integer stackWidth = (Integer) invocation.getStack().findValue( "width" );

    width = stackWidth != null && stackWidth > 0 ? stackWidth : width != null ? width : DEFAULT_WIDTH;

    String stackFilename = (String) invocation.getStack().findValue( "filename" );

    filename = StringUtils.defaultIfEmpty( stackFilename, DEFAULT_FILENAME );

    if ( chart == null )
    {
        log.warn( "No chart found" );
        return;
    }

    HttpServletResponse response = ServletActionContext.getResponse();
    ContextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, true, filename, false );

    OutputStream os = response.getOutputStream();
    ChartUtils.writeChartAsPNG( os, chart, width, height );
    os.flush();
}
 
Example 11
Source File: EmmProfileFieldResolverImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String resolveProfileFieldColumnName(String dbName) throws ProfileFieldResolveException {
	try {
		String shortname = resolvedNames.get(dbName);
		if(shortname == null) {
			shortname = getProfileFieldName(dbName);
			
			resolvedNames.put(dbName, shortname);
		}
		return "`" + StringUtils.defaultIfEmpty(shortname, dbName) + "`";
	} catch(Exception e) {
		throw new ProfileFieldResolveException("Cannot resolve dbName of profile field'" + dbName + "'", e);
	}
}
 
Example 12
Source File: FlightRecorderService.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private String getJdkFolder() {
    return StringUtils.defaultIfEmpty(System.getenv("JAVA_HOME"), System.getProperty("java.home"));
}
 
Example 13
Source File: QueryParameterExtractor.java    From jerseyoauth2 with MIT License 4 votes vote down vote up
@Override
public String extractValue(IHttpRequest request) {
	return StringUtils.defaultIfEmpty(request.getQueryParameter(key), null);
}
 
Example 14
Source File: FindBugsParser.java    From analysis-model with MIT License 4 votes vote down vote up
private String createMessage(final Map<String, String> hashToMessageMapping, final BugInstance warning,
        final String message) {
    return StringUtils.defaultIfEmpty(hashToMessageMapping.get(warning.getInstanceHash()), message);
}
 
Example 15
Source File: SourcePrinter.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
@SuppressWarnings({"javancss", "PMD.CyclomaticComplexity"})
private String selectLanguageClass(final Issue issue) {
    switch (StringUtils.defaultIfEmpty(StringUtils.substringAfterLast(issue.getBaseName(), "."),
            issue.getBaseName())) {
        case "htm":
        case "html":
        case "xml":
        case "xsd":
            return "language-markup";
        case "css":
            return "language-css";
        case "js":
            return "language-javascript";
        case "c":
            return "language-c";
        case "cs":
            return "language-csharp";
        case "cpp":
            return "language-cpp";
        case "Dockerfile":
            return "language-docker";
        case "go":
            return "language-go";
        case "groovy":
            return "language-groovy";
        case "json":
            return "language-json";
        case "md":
            return "language-markdown";
        case "erb":
        case "jsp":
        case "tag":
            return "language-erb";
        case "jav":
        case "java":
            return "language-java";
        case "rb":
            return "language-ruby";
        case "kt":
            return "language-kotlin";
        case "vb":
            return "language-vbnet";
        case "pl":
            return "language-perl";
        case "php":
            return "language-php";
        case "py":
            return "language-python";
        case "sql":
            return "language-sql";
        case "scala":
        case "sc":
            return "language-scala";
        case "swift":
            return "language-swift";
        case "ts":
            return "language-typescript";
        case "yaml":
            return "language-yaml";
        default:
            return "language-clike"; // Best effort for unknown extensions
    }
}
 
Example 16
Source File: SwapAttendeeEmail.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public String getFromAddress() {
	return StringUtils.defaultIfEmpty(organizer.getEmail(), getServerFromAddress());
}
 
Example 17
Source File: MoveAttendeeEmail.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public String getFromAddress() {
	return StringUtils.defaultIfEmpty(organizer.getEmail(), getServerFromAddress());
}
 
Example 18
Source File: AttendeeSignupEmail.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public String getFromAddress() {
	return StringUtils.defaultIfEmpty(currentUser.getEmail(), getServerFromAddress());
}
 
Example 19
Source File: CommerceFormatters.java    From template-compiler with Apache License 2.0 4 votes vote down vote up
private static void resolveTemplateVariablesForSubscriptionProduct(
    Context ctx, JsonNode productNode, ObjectNode args) {
  JsonNode billingPeriodNode = CommerceUtils.getSubscriptionPlanBillingPeriodNode(productNode);

  if (billingPeriodNode.isMissingNode()) {
    args.put("formattedFromPrice", true);
    args.put("fromText", StringUtils.defaultIfEmpty(
        ctx.resolve(new String[] {"localizedStrings", "productPriceUnavailable"}).asText(), "Unavailable"));
    return;
  }

  boolean hasMultiplePrices = CommerceUtils.hasVariedPrices(productNode);
  int billingPeriodValue = CommerceUtils.getValueFromSubscriptionPlanBillingPeriod(billingPeriodNode);
  String billingPeriodUnit = CommerceUtils.getUnitFromSubscriptionPlanBillingPeriod(billingPeriodNode);

  int durationValue = billingPeriodValue * CommerceUtils.getNumBillingCyclesFromSubscriptionPlanNode(productNode);
  String durationUnit = billingPeriodUnit;

  // If the duration is a multiple of 52 weeks or 12 months, convert to years.
  // Otherwise, use the billing period unit for the duration unit.
  if (durationValue > 0 && PER_YEAR.containsKey(durationUnit) && durationValue % PER_YEAR.get(durationUnit) == 0) {
    durationValue /= PER_YEAR.get(durationUnit);
    durationUnit = BILLING_PERIOD_YEARLY;
  }

  args.put("billingPeriodValue", billingPeriodValue);
  args.put("duration", durationValue);

  // This string needs to match the correct translation template in v6 products-2.0-en-US.json.
  StringBuilder i18nKeyBuilder = new StringBuilder("productPrice")
      .append("__")
      .append(hasMultiplePrices ? "multiplePrices" : "singlePrice")
      .append("__")
      .append(billingPeriodValue == 1 ? "1" : "n")
      .append(StringUtils.capitalize(billingPeriodUnit.toLowerCase()) + "ly").append("__");

  if (durationValue == 0) {
    i18nKeyBuilder.append("indefinite");
  } else {
    i18nKeyBuilder.append("limited__")
        .append(durationValue == 1 ? "1" : "n")
        .append(StringUtils.capitalize(durationUnit.toLowerCase()) + "s");
  }

  String templateForPrice = StringUtils.defaultIfEmpty(
      ctx.resolve(new String[] {"localizedStrings",
          i18nKeyBuilder.toString()}).asText(), defaultSubscriptionPriceString(productNode));

  if (hasMultiplePrices) {
    args.put("fromText", templateForPrice);
    args.put("formattedFromPrice", getMoneyString(CommerceUtils.getLowestPriceAmongVariants(productNode), ctx));
  }

  if (CommerceUtils.isOnSale(productNode)) {
    args.put("formattedSalePriceText", templateForPrice);
    args.put("formattedSalePrice", getMoneyString(CommerceUtils.getSalePriceMoneyNode(productNode), ctx));
  }

  args.put("formattedNormalPriceText", templateForPrice);
  args.put("formattedNormalPrice", getMoneyString(CommerceUtils.getHighestPriceAmongVariants(productNode), ctx));
}
 
Example 20
Source File: AttendeeSignupEmail.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public String getFromAddress() {
	return StringUtils.defaultIfEmpty(currentUser.getEmail(), getServerFromAddress());
}