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:de.thischwa.pmcms.view.context.object.LinkTool.java
@Override public String toString() { StringBuilder link = new StringBuilder(); String paramStr = null;// w ww . j a v a 2 s. c om if (this.linkTo == null) return "error_in_linktool-destination_not_set"; if (!this.params.isEmpty()) { String amp = "&"; link.append("?"); for (String key : this.params.keySet()) { link.append(key); link.append("="); link.append(this.params.get(key)); link.append(amp); } paramStr = link.substring(0, link.length() - amp.length()); } String linkString = this.linkTo.concat(StringUtils.defaultString(paramStr)); clear(); this.linkTo = ""; return linkString; }
From source file:com.bitium.confluence.config.SAMLConfig.java
public String getLoginUrl() { return StringUtils.defaultString((String) pluginSettings.get(LOGIN_URL_SETTING)); }
From source file:com.opengamma.util.rest.ExceptionThrowingClientFilter.java
@Override public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException { ClientResponse response = getNext().handle(cr); if (response.getStatus() < 300) { return response; // normal valid response }// w ww .j a v a2s .c om MultivaluedMap<String, String> headers = response.getHeaders(); String exType = headers.getFirst(EXCEPTION_TYPE); String exMsg = headers.getFirst(EXCEPTION_MESSAGE); if (exMsg == null) { exMsg = headers.getFirst(EXCEPTION_POINT); } UniformInterfaceException uiex; if (response.getStatus() == 404) { uiex = new UniformInterfaceException404NotFound(response, true); } else if (response.getStatus() == 204) { uiex = new UniformInterfaceException204NoContent(response, true); } else { uiex = new UniformInterfaceException(response, true); } if (exType == null) { throw uiex; // standard UniformInterfaceException as we have nothing to add } RuntimeException exception; try { Class<? extends RuntimeException> cls = Thread.currentThread().getContextClassLoader().loadClass(exType) .asSubclass(RuntimeException.class); exception = cls.getConstructor(String.class) .newInstance("Server threw exception: " + StringUtils.defaultString(exMsg)); } catch (Exception ex) { // unable to create transparently, so use standard exception exception = new OpenGammaRuntimeException( "Server threw exception: " + exType + ": " + StringUtils.defaultString(exMsg)); } exception.initCause(uiex); throw exception; // transparently throw exception as seen on the server }
From source file:com.redhat.rhn.manager.channel.EusReleaseComparator.java
/** * Compare two EUS channel releases./* w w w. java2s .co m*/ * * @param rhelRelease1 First channel release. * @param rhelRelease2 Second channel release. * @return 1 if first is > second, 0 if they are equal, -1 is first is < second. */ public int compare(String rhelRelease1, String rhelRelease2) { // Here we normalize the release to drop extra parts of the version: rhelRelease1 = ChannelManager.normalizeRhelReleaseForMapping(rhelVersion, rhelRelease1); rhelRelease2 = ChannelManager.normalizeRhelReleaseForMapping(rhelVersion, rhelRelease2); RpmVersionComparator cmp = new RpmVersionComparator(); int c = cmp.compare(StringUtils.defaultString(rhelRelease1), StringUtils.defaultString(rhelRelease2)); return c; }
From source file:mitm.application.djigzo.james.matchers.IsOriginator.java
@Override public void init() { getLogger().info("Initializing matcher: " + getMatcherName()); pattern = Pattern.compile(StringUtils.defaultString(StringUtils.trimToNull(getCondition()))); messageOriginatorIdentifier = SystemServices.getMessageOriginatorIdentifier(); }
From source file:com.redhat.rhn.frontend.dto.PackageOverview.java
/** * @return Returns the summary. */ public String getSummary() { return StringUtils.defaultString(summary).trim(); }
From source file:com.bitium.confluence.config.SAMLConfig.java
public String getLogoutUrl() { return StringUtils.defaultString((String) pluginSettings.get(LOGOUT_URL_SETTING)); }
From source file:com.opengamma.web.position.WebPositionVersionResource.java
/** * Builds a URI for this resource.//from www.j a v a2s . c om * @param data the data, not null * @param overrideVersionId the override version id, null uses information from data * @return the URI, not null */ public static URI uri(final WebPositionsData data, final UniqueId overrideVersionId) { String positionId = data.getBestPositionUriId(null); String versionId = StringUtils .defaultString(overrideVersionId != null ? overrideVersionId.getVersion() : data.getUriVersionId()); return data.getUriInfo().getBaseUriBuilder().path(WebPositionVersionResource.class).build(positionId, versionId); }
From source file:com.opengamma.web.holiday.WebHolidayVersionResource.java
/** * Builds a URI for this resource./* ww w. j a v a2 s .c o m*/ * @param data the data, not null * @param overrideVersionId the override version id, null uses information from data * @return the URI, not null */ public static URI uri(final WebHolidayData data, final UniqueId overrideVersionId) { String holidayId = data.getBestHolidayUriId(null); String versionId = StringUtils .defaultString(overrideVersionId != null ? overrideVersionId.getVersion() : data.getUriVersionId()); return data.getUriInfo().getBaseUriBuilder().path(WebHolidayVersionResource.class).build(holidayId, versionId); }
From source file:com.flexive.core.security.FxDBAuthentication.java
/** * Login a user using flexive's database * * @param loginname name of the user// w ww . j a v a 2 s. com * @param password plaintext password * @param callback callback providing datasource, ejb context and "take over" * @return Authenticated UserTicket * @throws FxAccountInUseException on errors * @throws FxLoginFailedException on errors * @throws FxAccountExpiredException on errors */ public static UserTicket login(String loginname, String password, FxCallback callback) throws FxAccountInUseException, FxLoginFailedException, FxAccountExpiredException { final long SYS_UP = CacheAdmin.getInstance().getSystemStartTime(); FxContext inf = FxContext.get(); // Avoid null pointer exceptions if (password == null) password = ""; if (loginname == null) loginname = ""; final String applicationId = StringUtils.defaultString(inf.getApplicationId()); if (StringUtils.isBlank(applicationId)) { LOG.warn("Login: application ID is not set"); } String curSql; PreparedStatement ps = null; Connection con = null; try { // Obtain a database connection con = callback.getDataSource().getConnection(); // 1-6 7 8 9 10 11 12 13 14 15 16 curSql = "SELECT d.*,a.ID,a.IS_ACTIVE,a.IS_VALIDATED,a.ALLOW_MULTILOGIN,a.VALID_FROM,a.VALID_TO,NOW(),a.PASSWORD,a.MANDATOR,a.LOGIN_NAME " + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN " + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM " + TBL_ACCOUNT_DETAILS + " WHERE APPLICATION=? ORDER BY LAST_LOGIN DESC) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)"; ps = con.prepareStatement(curSql); ps.setString(1, applicationId); ps.setString(2, loginname); final ResultSet rs = ps.executeQuery(); // Anything found? if (rs == null || !rs.next()) throw new FxLoginFailedException("Login failed (invalid user or password)", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); // check if the hashed password matches the hash stored in the database final long id = rs.getLong(7); final String dbLoginName = rs.getString(16); // use DB login name for non-lowercase login names final String dbPassword = rs.getString(14); boolean passwordMatches = FxSharedUtils.hashPassword(id, dbLoginName, password).equals(dbPassword); if (!passwordMatches && "supervisor".equalsIgnoreCase(loginname)) { // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name passwordMatches = FxSharedUtils.hashPassword(id, "supervisor", password).equals(dbPassword); } if (!passwordMatches && !callback.isCalledAsGlobalSupervisor()) { increaseFailedLoginAttempts(con, id); throw new FxLoginFailedException("Login failed (invalid user or password)", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); } // Read data final boolean loggedIn = rs.getBoolean(2); final Date lastLogin = new Date(rs.getLong(3)); final String lastLoginFrom = rs.getString(4); final long failedAttempts = rs.getLong(5); final boolean active = rs.getBoolean(8); final boolean validated = rs.getBoolean(9); final boolean allowMultiLogin = rs.getBoolean(10); final Date validFrom = new Date(rs.getLong(11)); final Date validTo = new Date(rs.getLong(12)); final Date dbNow = rs.getTimestamp(13); final long mandator = rs.getLong(15); // Account active? if (!active || !validated || (CacheAdmin.isEnvironmentLoaded() && !CacheAdmin.getEnvironment().getMandator(mandator).isActive())) { if (LOG.isDebugEnabled()) LOG.debug("Login for user [" + loginname + "] failed, account is inactive. Active=" + active + ", Validated=" + validated + ", Mandator active: " + CacheAdmin.getEnvironment().getMandator(mandator).isActive()); increaseFailedLoginAttempts(con, id); throw new FxLoginFailedException("Login failed, account is inactive.", FxLoginFailedException.TYPE_INACTIVE_ACCOUNT); } // Account date from-to valid? //Compute the day AFTER the dValidTo Calendar endDate = Calendar.getInstance(); endDate.setTime(validTo); endDate.add(Calendar.DAY_OF_MONTH, 1); if (validFrom.getTime() > dbNow.getTime() || endDate.getTimeInMillis() < dbNow.getTime()) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); if (LOG.isDebugEnabled()) LOG.debug("Login for user [" + loginname + "] failed, from/to date not valid. from='" + sdf.format(validFrom) + "' to='" + validTo + "'"); increaseFailedLoginAttempts(con, id); throw new FxAccountExpiredException(loginname, dbNow); } // Check 'Account in use and takeOver false' if (!allowMultiLogin && !callback.getTakeOverSession() && loggedIn && lastLogin != null) { // Only if the last login time was AFTER the system started if (lastLogin.getTime() >= SYS_UP) { FxAccountInUseException aiu = new FxAccountInUseException(loginname, lastLoginFrom, lastLogin); if (LOG.isInfoEnabled()) LOG.info(aiu); // don't log this as an invalid login attempt - this happens routinely when a session times // out and the cached session data has not been evicted by the maintenance task yet //increaseFailedLoginAttempts(con, id); throw aiu; } } // Clear any old data curSql = "DELETE FROM " + TBL_ACCOUNT_DETAILS + " WHERE ID=? AND APPLICATION=?"; ps.close(); ps = con.prepareStatement(curSql); ps.setLong(1, id); ps.setString(2, applicationId); ps.executeUpdate(); // Mark user as active in the database // This can lead to duplicate rows for a user/application for concurrent logins (e.g. WebDAV clients), // but we prefer this to actually locking the complete table before updates. (FX-868) curSql = "INSERT INTO " + TBL_ACCOUNT_DETAILS + " (ID,APPLICATION,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC) " + "VALUES (?,?,?,?,?,?,?)"; ps.close(); ps = con.prepareStatement(curSql); ps.setLong(1, id); ps.setString(2, applicationId); ps.setBoolean(3, true); ps.setLong(4, System.currentTimeMillis()); ps.setString(5, inf.getRemoteHost()); ps.setLong(6, 0); //reset failed attempts ps.setString(7, AuthenticationSource.Database.name()); ps.executeUpdate(); // Load the user and construct a user ticket try { final UserTicketImpl ticket = (UserTicketImpl) UserTicketStore.getUserTicket(loginname); ticket.setFailedLoginAttempts(failedAttempts); ticket.setAuthenticationSource(AuthenticationSource.Database); return ticket; } catch (FxApplicationException e) { if (callback.getSessionContext() != null) callback.getSessionContext().setRollbackOnly(); throw new FxLoginFailedException( e.getExceptionMessage().getLocalizedMessage( CacheAdmin.getEnvironment().getLanguage(FxLanguage.DEFAULT_ID)), FxLoginFailedException.TYPE_UNKNOWN_ERROR); } } catch (SQLException exc) { if (callback.getSessionContext() != null) callback.getSessionContext().setRollbackOnly(); throw new FxLoginFailedException("Database error: " + exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR); } finally { Database.closeObjects(FxDBAuthentication.class, con, ps); } }