List of usage examples for org.apache.commons.lang StringUtils defaultIfEmpty
public static String defaultIfEmpty(String str, String defaultStr)
Returns either the passed in String, or if the String is empty or null
, the value of defaultStr
.
From source file:com.iyonger.apm.web.configuration.Config.java
/** * Resolve nGrinder home path./* w w w .j a v a 2 s.c o m*/ * * @return resolved home */ protected Home resolveHome() { if (StringUtils.isNotBlank(System.getProperty("unit-test"))) { final String tempDir = System.getProperty("java.io.tmpdir"); final File tmpHome = new File(tempDir, ".ngrinder"); if (tmpHome.mkdirs()) { LOG.info("{} is created", tmpHome.getPath()); } try { FileUtils.forceDeleteOnExit(tmpHome); } catch (IOException e) { LOG.error("Error while setting forceDeleteOnExit on {}", tmpHome); } return new Home(tmpHome); } String userHomeFromEnv = System.getenv("NGRINDER_HOME"); String userHomeFromProperty = System.getProperty("ngrinder.home"); if (!StringUtils.equals(userHomeFromEnv, userHomeFromProperty)) { CoreLogger.LOGGER.warn("The path to ngrinder-home is ambiguous:"); CoreLogger.LOGGER.warn(" System Environment: NGRINDER_HOME=" + userHomeFromEnv); CoreLogger.LOGGER.warn(" Java System Property: ngrinder.home=" + userHomeFromProperty); CoreLogger.LOGGER.warn(" '" + userHomeFromProperty + "' is accepted."); } String userHome = StringUtils.defaultIfEmpty(userHomeFromProperty, userHomeFromEnv); if (StringUtils.isEmpty(userHome)) { userHome = System.getProperty("user.home") + File.separator + NGRINDER_DEFAULT_FOLDER; } else if (StringUtils.startsWith(userHome, "~" + File.separator)) { userHome = System.getProperty("user.home") + File.separator + userHome.substring(2); } else if (StringUtils.startsWith(userHome, "." + File.separator)) { userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2); } userHome = FilenameUtils.normalize(userHome); File homeDirectory = new File(userHome); CoreLogger.LOGGER.info("nGrinder home directory:{}.", homeDirectory.getPath()); return new Home(homeDirectory); }
From source file:com.flexive.core.search.genericSQL.GenericSQLDataFilter.java
/** * Builds the filter./*from www . j av a 2s. co m*/ * * @throws FxSqlSearchException if the build failed */ @Override public void build() throws FxSqlSearchException, SQLException { Statement stmt = null; String sql = null; try { final String dataSelect; final String columnFilter = "SELECT search_id, id, ver, tdef, created_by FROM "; if (getStatement().getType() == FxStatement.Type.ALL) { // The statement will not filter the data final String securityFilter = getSecurityFilter("data2"); final String filters = StringUtils.defaultIfEmpty(securityFilter, "1=1") + (getStatement().getBriefcaseFilter().length == 0 ? getVersionFilter("data2") : "") + getDeactivatedTypesFilter("data2") + getInactiveMandatorsFilter("data2"); dataSelect = columnFilter + "(" + selectOnMainTable(filters, "data2") + ") r"; } else if (isMainTableQuery(getStatement().getRootBrace())) { // optimize queries that operate only on FX_CONTENT final String securityFilter = getSecurityFilter("cd"); final String filters = StringUtils.defaultIfEmpty(securityFilter, "1=1") + (getStatement().getBriefcaseFilter().length == 0 ? getVersionFilter("cd") : "") + getDeactivatedTypesFilter("cd") + getInactiveMandatorsFilter("cd") + " AND (" + getOptimizedMainTableConditions(getStatement().getRootBrace(), "cd") + ")"; dataSelect = columnFilter + "(" + selectOnMainTable(filters, "cd") + ") r"; } else { // The statement filters the data StringBuilder result = new StringBuilder(5000); // extract top-level conditions on the main table final Brace mainTableConditions = getStatement().getRootBrace() .extractConditions(new Brace.ExtractFunction() { @Override public boolean shouldExtract(Condition cond) { try { final Pair<String, ConditionTableInfo> pi = getPropertyInfo(cond); return getStatement().getRootBrace().isAnd() && DatabaseConst.TBL_CONTENT.equals(pi.getFirst()); } catch (FxSqlSearchException e) { throw e.asRuntimeException(); } } }); // build main condition (without top-level main table conditions) build(result, getStatement().getRootBrace()); // Remove leading and ending brace result.deleteCharAt(0); result.deleteCharAt(result.length() - 1); // Finalize the select final String securityFilter = getSecurityFilter("data2"); final String mainConditions = mainTableConditions.getSize() > 0 ? getOptimizedMainTableConditions(mainTableConditions, "main") : null; dataSelect = columnFilter + "(SELECT DISTINCT " + search.getSearchId() + " AS search_id,data.id,data.ver,main.tdef,main.created_by,main.step,main.acl,main.mandator \n" + "FROM (" + result.toString() + ") data, " + DatabaseConst.TBL_CONTENT + " main\n" + "WHERE data.ver=main.ver AND data.id=main.id" + (StringUtils.isNotBlank(mainConditions) ? " AND " + mainConditions : "") + ") data2\n" + (StringUtils.isNotBlank(securityFilter) // Limit by the specified max items ? "WHERE " + securityFilter + getResultRowsLimit(true) : getResultRowsLimit(false)); } this.dataSelectSql = dataSelect; if (!search.getParams().isHintNoResultInfo() || !search.getStorage().isDirectSearchSupported()) { // Find all matching data entities and store them sql = "INSERT INTO " + search.getCacheTable() + " " + dataSelect; if (LOG.isDebugEnabled()) { LOG.debug("Filter SQL: " + sql); } stmt = getConnection().createStatement(); if (isQueryTimeoutSupported()) stmt.setQueryTimeout(search.getParams().getQueryTimeout()); stmt.executeUpdate(sql); if (!search.getParams().isHintNoResultInfo()) { analyzeResult(); } } } catch (SQLException exc) { LOG.error("Failed to execute (" + exc.getMessage() + "): " + sql); throw exc; } catch (Exception e) { throw new FxSqlSearchException(LOG, e, "ex.sqlSearch.failedToBuildDataFilter", e.getMessage(), search.getQuery()); } finally { Database.closeObjects(GenericSQLDataFilter.class, null, stmt); } }
From source file:com.redhat.rhn.common.conf.ConfigDefaults.java
/** * Return the kickstart mount point directory * Note the mount point is guaranteed to have a * '/' at the end of the string so you can use it * for appending sub directories.//from w ww . ja v a 2 s . com * @return the ks mount point directory. */ public String getKickstartMountPoint() { String mount = StringUtils .defaultIfEmpty(Config.get().getString(KICKSTART_MOUNT_POINT), Config.get().getString(MOUNT_POINT)) .trim(); if (!mount.endsWith("/")) { mount = mount + "/"; } return mount; }
From source file:com.redhat.rhn.common.conf.ConfigDefaults.java
/** * Returns the default kickstart package name * @return the default kickstart package name *//*from w w w. ja v a 2 s . c o m*/ public String getKickstartPackageName() { return StringUtils .defaultIfEmpty(Config.get().getString(KICKSTART_PACKAGE_NAME), DEFAULT_KICKSTART_PACKAGE_NAME) .trim(); }
From source file:com.iyonger.apm.web.configuration.Config.java
/** * Resolve nGrinder extended home path.//from www . j a va 2 s . c o m * * @return resolved home */ protected Home resolveExHome() { String exHomeFromEnv = System.getenv("NGRINDER_EX_HOME"); String exHomeFromProperty = System.getProperty("ngrinder.ex_home"); if (!StringUtils.equals(exHomeFromEnv, exHomeFromProperty)) { CoreLogger.LOGGER.warn("The path to ngrinder ex home is ambiguous:"); CoreLogger.LOGGER.warn(" System Environment: NGRINDER_EX_HOME=" + exHomeFromEnv); CoreLogger.LOGGER.warn(" Java System Property: ngrinder.ex_home=" + exHomeFromProperty); CoreLogger.LOGGER.warn(" '" + exHomeFromProperty + "' is accepted."); } String userHome = StringUtils.defaultIfEmpty(exHomeFromProperty, exHomeFromEnv); if (StringUtils.isEmpty(userHome)) { userHome = System.getProperty("user.home") + File.separator + NGRINDER_EX_FOLDER; } else if (StringUtils.startsWith(userHome, "~" + File.separator)) { userHome = System.getProperty("user.home") + File.separator + userHome.substring(2); } else if (StringUtils.startsWith(userHome, "." + File.separator)) { userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2); } userHome = FilenameUtils.normalize(userHome); File exHomeDirectory = new File(userHome); CoreLogger.LOGGER.info("nGrinder ex home directory:{}.", exHomeDirectory); try { //noinspection ResultOfMethodCallIgnored exHomeDirectory.mkdirs(); } catch (Exception e) { // If it's not possible.. do it... without real directory. noOp(); } return new Home(exHomeDirectory, false); }
From source file:com.yoncabt.ebr.ui.ReportWindow.java
private void fillTheGrid() throws SQLException, IOException { gridLayout.removeComponent(grid);/*from w w w. j a va2s . c om*/ ReportRequest request = new ReportRequest(); request.setUuid(reportIDGenerator.generate()); request.setLocale((String) reportLocale.getValue()); request.setDatasourceName(reportDefinition.getDataSource()); request.setExtension(((ReportOutputFormat) reportType.getValue()).name()); request.setAsync(false); request.setEmail(email.getValue()); String dataSourceName = StringUtils.defaultIfEmpty(reportDefinition.getDataSource(), "default"); for (ReportParam reportParam : reportDefinition.getReportParams()) { if (reportParam.isRaw()) { String value = (String) findFormField(reportParam.getName()).getValue(); value = StringEscapeUtils.escapeSql(value); Pattern pattern = Pattern.compile(":\\b" + reportParam.getName() + "\\b"); sql = pattern.matcher(sql).replaceAll(value); } else { Object value = findFormField(reportParam.getName()).getValue(); request.getReportParams().put(reportParam.getName(), value); } } request.setReportQuery(sql); request.setReport(reportName); try (EBRConnection con = dataSourceManager.get(dataSourceName, "EBR", "SQL", reportDefinition.getFile().getAbsolutePath());) { if (report instanceof JasperReport) { fillTheGridJRXML(request, con); } else if (report instanceof SQLReport) { fillTheGridSQL(request, con); } else { throw new IllegalArgumentException(String.valueOf(report)); } } }
From source file:com.manydesigns.portofino.actions.admin.database.TablesAction.java
@Button(key = "save", list = "table-edit", order = 1, type = Button.TYPE_PRIMARY) public Resolution saveTable() { com.manydesigns.portofino.actions.admin.tables.forms.TableForm tf = setupTableForm(Mode.EDIT); setupColumnsForm(Mode.EDIT);/*from w w w . j av a2s . co m*/ tableForm.readFromRequest(context.getRequest()); columnsTableForm.readFromRequest(context.getRequest()); if (validateTableForm() && columnsTableForm.validate()) { tableForm.writeToObject(tf); tf.copyTo(table); table.setEntityName(StringUtils.defaultIfEmpty(table.getEntityName(), null)); table.setJavaClass(StringUtils.defaultIfEmpty(table.getJavaClass(), null)); table.setShortName(StringUtils.defaultIfEmpty(table.getShortName(), null)); columnsTableForm.writeToObject(decoratedColumns); //Copy by name, not by index. Some columns may have been skipped. for (Column column : table.getColumns()) { for (ColumnForm columnForm : decoratedColumns) { if (columnForm.getColumnName().equals(column.getColumnName())) { columnForm.copyTo(column); } } } Collections.sort(table.getColumns(), new Comparator<Column>() { public int compare(Column o1, Column o2) { int i1 = sortedColumnNames.indexOf(o1.getColumnName()); int i2 = sortedColumnNames.indexOf(o2.getColumnName()); return Integer.valueOf(i1).compareTo(i2); } }); for (ForeignKey fk : table.getForeignKeys()) { fk.setOnePropertyName(fkOnePropertyNames.get(fk.getName())); fk.setManyPropertyName(fkManyPropertyNames.get(fk.getName())); } try { saveModel(); for (Table otherTable : table.getSchema().getTables()) { for (ForeignKey fk : otherTable.getForeignKeys()) { if (fk.getFromTable().equals(table) || (!fk.getFromTable().equals(table) && fk.getToTable().equals(table))) { for (Reference ref : fk.getReferences()) { Column fromColumn = ref.getActualFromColumn(); Column toColumn = ref.getActualToColumn(); if (fromColumn.getActualJavaType() != toColumn.getActualJavaType()) { SessionMessages.addWarningMessage(ElementsThreadLocals.getText( "detected.type.mismatch.between.column._.and.column._", fromColumn.getQualifiedName(), fromColumn.getActualJavaType().getName(), toColumn.getQualifiedName(), toColumn.getActualJavaType().getName(), fk.getName())); } } } } } SessionMessages.consumeWarningMessages(); //Clear skipped columns warnings //setupTableForm(Mode.EDIT); //Recalculate entity name //setupColumnsForm(Mode.EDIT); //Reflect the new order of the columns } catch (Exception e) { logger.error("Could not save model", e); SessionMessages.addErrorMessage(e.toString()); } return new RedirectResolution(TablesAction.class, "editTable") .addParameter("databaseName", databaseName).addParameter("schemaName", schemaName) .addParameter("tableName", tableName); } else { return new ForwardResolution("/m/admin/tables/edit-table.jsp"); } }
From source file:com.thinkbiganalytics.spark.datavalidator.StandardDataValidator.java
private String toSelectFields(FieldPolicy[] policies1) { List<String> fields = new ArrayList<>(); log.info("Building select statement for # of policies {}", policies1.length); for (int i = 0; i < policies1.length; i++) { if (policies1[i].getField() != null) { log.info("policy [{}] name {} feedName {}", i, policies1[i].getField(), policies1[i].getFeedField()); String feedField = StringUtils.defaultIfEmpty(policies1[i].getFeedField(), policies1[i].getField()); fields.add("`" + feedField + "` as `" + policies1[i].getField() + "`"); }/*ww w .j av a 2s . c o m*/ } fields.add("`processing_dttm`"); return StringUtils.join(fields.toArray(new String[0]), ","); }
From source file:jp.terasoluna.fw.web.taglib.DateFormatterTagBase.java
/** * ^O]Jn?\bh?B/* w w w.jav a 2 s . c o m*/ * * @return ???w?B? <code>SKIP_BODY</code> * @throws JspException JSPO */ @Override public int doStartTag() throws JspException { Object value = this.value; if (value == null) { // bean???Av?beanbNAbv // ???A^?[ if (ignore) { if (TagUtil.lookup(pageContext, name, scope) == null) { return SKIP_BODY; // ?o } } // v?v?peBlbNAbv value = TagUtil.lookup(pageContext, name, property, scope); if (value == null) { return SKIP_BODY; // ?o } } // v?peBlString^xDate Date date = null; if (value instanceof String) { // Eg String trimed = StringUtil.rtrim((String) value); // ttH?[}bg String dateFormat = StringUtils.defaultIfEmpty(getFormat(), getDefaultDateFormat()); // xDate^ SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); try { date = sdf.parse(trimed); } catch (ParseException e) { log.error("Date parsing error."); throw new JspTagException(e.getMessage()); } } else if (value instanceof Date) { date = (Date) value; } else { return SKIP_BODY; // ?o } // tH?[}bg String output = doFormat(date); if (id != null) { // idw?AXNveBO?p // y?[WXR?[vZbg?B pageContext.setAttribute(id, output); } else { // idw?Av?peBlC^vg // ?BK?tB^?B if (filter) { TagUtil.write(pageContext, TagUtil.filter(output)); } else { TagUtil.write(pageContext, output); } } return SKIP_BODY; }
From source file:com.gst.portfolio.group.domain.Group.java
public Map<String, Object> update(final JsonCommand command) { final Map<String, Object> actualChanges = new LinkedHashMap<>(9); if (command.isChangeInIntegerParameterNamed(GroupingTypesApiConstants.statusParamName, this.status)) { final Integer newValue = command .integerValueOfParameterNamed(GroupingTypesApiConstants.statusParamName); actualChanges.put(GroupingTypesApiConstants.statusParamName, GroupingTypeEnumerations.status(newValue)); this.status = GroupingTypeStatus.fromInt(newValue).getValue(); }/*ww w .j av a2 s. c o m*/ if (command.isChangeInStringParameterNamed(GroupingTypesApiConstants.externalIdParamName, this.externalId)) { final String newValue = command .stringValueOfParameterNamed(GroupingTypesApiConstants.externalIdParamName); actualChanges.put(GroupingTypesApiConstants.externalIdParamName, newValue); this.externalId = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInLongParameterNamed(GroupingTypesApiConstants.officeIdParamName, this.office.getId())) { final Long newValue = command.longValueOfParameterNamed(GroupingTypesApiConstants.officeIdParamName); actualChanges.put(GroupingTypesApiConstants.officeIdParamName, newValue); } if (command.isChangeInLongParameterNamed(GroupingTypesApiConstants.staffIdParamName, staffId())) { final Long newValue = command.longValueOfParameterNamed(GroupingTypesApiConstants.staffIdParamName); actualChanges.put(GroupingTypesApiConstants.staffIdParamName, newValue); } if (command.isChangeInStringParameterNamed(GroupingTypesApiConstants.nameParamName, this.name)) { final String newValue = command.stringValueOfParameterNamed(GroupingTypesApiConstants.nameParamName); actualChanges.put(GroupingTypesApiConstants.nameParamName, newValue); this.name = StringUtils.defaultIfEmpty(newValue, null); } final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); if (command.isChangeInLocalDateParameterNamed(GroupingTypesApiConstants.activationDateParamName, getActivationLocalDate())) { final String valueAsInput = command .stringValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); actualChanges.put(GroupingTypesApiConstants.activationDateParamName, valueAsInput); actualChanges.put(GroupingTypesApiConstants.dateFormatParamName, dateFormatAsInput); actualChanges.put(GroupingTypesApiConstants.localeParamName, localeAsInput); final LocalDate newValue = command .localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); this.activationDate = newValue.toDate(); } if (command.isChangeInStringParameterNamed(GroupingTypesApiConstants.accountNoParamName, this.accountNumber)) { final String newValue = command .stringValueOfParameterNamed(GroupingTypesApiConstants.accountNoParamName); actualChanges.put(GroupingTypesApiConstants.accountNoParamName, newValue); this.accountNumber = StringUtils.defaultIfEmpty(newValue, null); } return actualChanges; }