List of usage examples for org.apache.commons.lang StringUtils defaultString
public static String defaultString(String str, String defaultStr)
Returns either the passed in String, or if the String is null
, the value of defaultStr
.
From source file:net.navasoft.madcoin.backend.services.rest.impl.SessionService.java
/** * Login./*from w ww . jav a2 s.co m*/ * * @param loginRequested * the login requested * @return the user info success response vo * @since 31/08/2014, 07:37:51 PM */ public SuccessResponseVO login(SuccessRequestVO loginRequested) { SessionSuccessResponseVO response; try { loginRequested.processValues(this); requestingUser = String.valueOf(loginRequested.extractValue("requestingUser"));// (String) // loginRequested.getAttribute("Username"); passwordProvided = BCrypt.hashpw(String.valueOf(loginRequested.extractValue("passwordProvided")), BCrypt.gensalt(14));// (String) // loginRequested.getAttribute("Password"); type = (UserTypes) loginRequested.extractValue("type"); model = String.valueOf(loginRequested.extractValue("model")); operativeSystem = String.valueOf(loginRequested.extractValue("operativeSystem")); serial = String.valueOf(loginRequested.extractValue("serial")); version = String.valueOf(loginRequested.extractValue("version")); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(requestingUser, passwordProvided); Authentication auth; String generatedToken; switch (type) { case END_USER_TYPE: response = new UserInfoSuccessResponseVO(); auth = authenticationManager.authenticate(token); // SecurityContextHolder.getContext().setAuthentication(auth); generatedToken = tokenGenerator.getToken(requestingUser, passwordProvided); response.setToken(generatedToken.replace("+", "%2B").replace("/", "%2F")); requestAddress = String.valueOf(loginRequested.extractValue("requestAddress")); EndUsersPK key = new EndUsersPK(); key.setAppUsername(auth.getName()); EndUsers user = accessor.getByLogicalId(key); user.setLastLoggedIp(requestAddress); user.setLastLogged(Calendar.getInstance().getTime()); try { user = accessor.edit(user); } catch (NonexistentEntityException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } response.setFullName(user.getUserNames() + " " + user.getLastName()); response.setEmail(user.getEmail()); ((UserInfoSuccessResponseVO) response).setLastSuccessLoggedOn(user.getLastLogged()); ((UserInfoSuccessResponseVO) response).setLastSuccessLoggedIP(user.getLastLoggedIp()); ((UserInfoSuccessResponseVO) response).setLastSuccessLoggedWay(AllowedChannels .valueOf(StringUtils.defaultString(user.getLastLoggedWay(), AllowedChannels.NONE.name()))); response.setLastPasswordReset(user.getLastPasswordReset()); response.setCreatedSince(user.getCreatedSince()); response.setUserType(user.getIdUserType().getEndUserType()); response.setUserTypeDescription(user.getIdUserType().getEndUserDescription()); ((UserInfoSuccessResponseVO) response).setMobile(user.getMobile()); ((UserInfoSuccessResponseVO) response).setBirthAge(user.getBirthAge()); return response; case SERVICE_PROVIDER_TYPE: response = new ProviderInfoSuccessResponseVO(); auth = authenticationProvider.authenticate(token); generatedToken = tokenGenerator.getToken(requestingUser, passwordProvided); response.setToken(generatedToken.replace("+", "%2B").replace("/", "%2F")); requestAddress = String.valueOf(loginRequested.extractValue("requestAddress")); ServiceProvidersPK keyProv = new ServiceProvidersPK(); keyProv.setAppUsername(auth.getName()); ServiceProviders userProv = accessorProvider.getByLogicalId(keyProv); // accessorProv.update(user); response.setFullName(userProv.getName() + " " + userProv.getLastName()); response.setEmail(userProv.getEmail()); response.setCreatedSince(userProv.getAuthorizedOn()); response.setUserType(userProv.getProviderRole().getProviderType()); response.setUserTypeDescription(userProv.getProviderRole().getProviderType()); return response; } response = null; } catch (BadCredentialsException unmatched) { System.out.println("unmatched"); throw ControllerExceptionFactory.createException(unmatched.getClass().getCanonicalName(), 3, loginRequested.getErrorProcessingValues()); } catch (UsernameNotFoundException notfound) { System.out.println("notfound"); throw ControllerExceptionFactory.createException(notfound.getClass().getCanonicalName(), 3, loginRequested.getErrorProcessingValues()); } catch (DisabledException unable) { System.out.println("unable"); throw ControllerExceptionFactory.createException(unable.getClass().getCanonicalName(), 3, loginRequested.getErrorProcessingValues()); } return response; }
From source file:gtu._work.ui.JUnitMakerUI.java
/** * validate/* w w w. j a v a2 s . c o m*/ * * @param evt */ private void jButton3ActionPerformed(ActionEvent evt) { try { Validate.notEmpty(jTextField2.getText(), "Package is empty"); Validate.notEmpty(jTextField1.getText(), "Class is empty"); String clz = jTextField1.getText(); String api = jTextArea1.getText(); String fieldName = StringUtils.defaultString(jTextField3.getText(), "test"); String pkg = jTextField2.getText(); String writeToDir = jTextField4.getText(); Map<String, String> apiMap = ApiMatcher.newInstance().loadString(api).execute().getApiMap(); junitMaker = JUnitMaker.newInstance(Class.forName(clz), pkg)// .setFieldName(fieldName)// .setPrefix("\\t")// .apiMap(apiMap)// .setIgnore(true)// .allowPackage(false)// .allowPrivate(false)// .allowProtected(false)// .allowOther(false)// ; if (StringUtils.isNotBlank(writeToDir)) { junitMaker.setWriteTo(new File(writeToDir)); } else { jTextField4.setText(junitMaker.getWriteTo().getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(e.getMessage(), "error"); } }
From source file:com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator.java
@Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("2.2.0") @NonNull//w w w . j av a 2 s . co m public String getCheckoutCredentialsId() { for (SCMTrait<?> t : traits) { if (t instanceof SSHCheckoutTrait) { return StringUtils.defaultString(((SSHCheckoutTrait) t).getCredentialsId(), BitbucketSCMSource.DescriptorImpl.ANONYMOUS); } } return BitbucketSCMSource.DescriptorImpl.SAME; }
From source file:info.magnolia.cms.taglibs.util.SimpleNavigationTag.java
/** * Checks if the page has a visible children. Pages with the <code>hide in nav</code> attribute set to * <code>true</code> are ignored. * @param page root page// w w w.ja v a 2 s . c o m * @return <code>true</code> if the given page has at least one visible child. */ private boolean hasVisibleChildren(Content page) { Iterator it = page.getChildren().iterator(); if (it.hasNext() && expandAll.equalsIgnoreCase(EXPAND_ALL)) { return true; } while (it.hasNext()) { Content ch = (Content) it.next(); if (!ch.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)) .getBoolean()) { return true; } } return false; }
From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.ExcelImportUtilities.java
/** * Creates a set of ResponsibilityAV objects from the attrValue for the given responsibility attribute type. * @param at The attribute to which the user name should be linked. * @param attrValue Cell value holder which contains the relevant responsibility value(s)/ user name(s). User names are split at semicolons * @param valueOverride an override value for the actual cell content. If this String is non-null/empty and non-whitespace, it will be used in the ResponsibilityAV, regardless of the cell content in attrValue! * @return A set of responsibility attribute value objects containing the value(s) from attrValue or valueOverride, or <code>null</code> if no user name could be identified *///ww w. j av a 2 s . c om private static Set<ResponsibilityAV> getResponsibilityAV(ResponsibilityAT at, CellValueHolder attrValue, String valueOverride) { final Set<ResponsibilityAV> respAVs = Sets.newHashSet(); final String cell = StringUtils.defaultString(valueOverride, attrValue.getAttributeValue()); Collection<ResponsibilityAV> valuesR = at.getAttributeValues(); String[] names = getSplittedArray(cell, ExcelSheet.IN_LINE_SEPARATOR.trim()); if (!at.isMultiassignmenttype() && names.length > 1) { String pattern = "Cell [{0}] Import of value for Attribute Type {1} ignored. The attribute allows only single value assignments, but several attribute values are given."; String problemMsg = MessageFormat.format(pattern, getCellRef(attrValue.getOriginCell()), at.getName()); getProcessingLog().warn(problemMsg); attrValue.addProblem(ProblemMarker.WARNING, problemMsg); throw new IllegalArgumentException(problemMsg); } for (String name : names) { ResponsibilityAV responsibilityValue = findResponsibilityAVfromCollection(valuesR, name); if (responsibilityValue != null) { respAVs.add(responsibilityValue); } else if (name.length() > 0) { String problemMsg = "Cell [" + getCellRef(attrValue.getOriginCell()) + "] Value " + name + " for responsibility attribute type " + at.getName() + " is not defined as possible enumeration value; ignored"; getProcessingLog().warn(problemMsg); attrValue.addProblem(ProblemMarker.WARNING, problemMsg); throw new IllegalArgumentException(problemMsg); } } return respAVs; }
From source file:com.redhat.rhn.domain.user.UserFactory.java
/** * Insert a new user. Invalid to call this when updating a user * TODO: mmccune fill out the other fields in the user object. * @param usr The object we are commiting. * @param addr The address to add to the User * @param orgId Org this new user is a member of * @return User The freshly commited user. *//* w ww . j a va 2s. co m*/ protected User addNewUser(User usr, Address addr, Long orgId) { LOG.debug("Starting addNewUser"); if (addr != null) { usr.setAddress1(addr.getAddress1()); usr.setAddress2(addr.getAddress2()); usr.setCity(addr.getCity()); usr.setCountry(addr.getCountry()); usr.setFax(addr.getFax()); usr.setIsPoBox(addr.getIsPoBox()); usr.setPhone(addr.getPhone()); usr.setState(addr.getState()); usr.setZip(addr.getZip()); } // save the user CallableMode m = ModeFactory.getCallableMode("User_queries", "create_new_user"); Map<String, Object> inParams = new HashMap<String, Object>(); Map<String, Integer> outParams = new HashMap<String, Integer>(); // Can't add the orgId to the object until the User has been // successfully added to the DB. Doing so will mean that if // there are problems, the user won't be rolled back properly. inParams.put("orgId", orgId); inParams.put("login", usr.getLogin()); inParams.put("password", usr.getPassword()); inParams.put("contactId", null); inParams.put("prefix", StringUtils.defaultString(usr.getPrefix(), " ")); inParams.put("fname", StringUtils.defaultString(usr.getFirstNames(), null)); inParams.put("lname", StringUtils.defaultString(usr.getLastName(), null)); inParams.put("genqual", null); inParams.put("parentCompany", StringUtils.defaultIfEmpty(usr.getCompany(), null)); inParams.put("company", StringUtils.defaultIfEmpty(usr.getCompany(), null)); inParams.put("title", StringUtils.defaultIfEmpty(usr.getTitle(), null)); inParams.put("phone", StringUtils.defaultIfEmpty(usr.getPhone(), null)); inParams.put("fax", StringUtils.defaultIfEmpty(usr.getFax(), null)); inParams.put("email", StringUtils.defaultIfEmpty(usr.getEmail(), null)); inParams.put("pin", new Integer(0)); inParams.put("fnameOl", " "); inParams.put("lnameOl", " "); inParams.put("addr1", StringUtils.defaultIfEmpty(usr.getAddress1(), null)); inParams.put("addr2", StringUtils.defaultIfEmpty(usr.getAddress2(), null)); inParams.put("addr3", " "); inParams.put("city", StringUtils.defaultIfEmpty(usr.getCity(), null)); inParams.put("state", StringUtils.defaultIfEmpty(usr.getState(), null)); inParams.put("zip", StringUtils.defaultIfEmpty(usr.getZip(), null)); inParams.put("country", StringUtils.defaultIfEmpty(usr.getCountry(), null)); inParams.put("altFnames", null); inParams.put("altLnames", null); inParams.put("contCall", "N"); inParams.put("contMail", "N"); inParams.put("contFax", "N"); inParams.put("contEmail", "N"); outParams.put("userId", new Integer(Types.NUMERIC)); Map<String, Object> result = m.execute(inParams, outParams); Org org = OrgFactory.lookupById(orgId); if (org != null) { usr.setOrg(org); } long userId = ((Long) result.get("userId")).longValue(); // We need to lookup the User to make sure that the Address in the // User object has an Id and that the User has an org_id. User retval = lookupById(new Long(userId)); saveObject(retval); return retval; }
From source file:com.flexive.faces.FxJsfUtils.java
public static long getLongParameter(String name, long defaultValue) { return Long.valueOf(StringUtils.defaultString(getParameter(name), String.valueOf(defaultValue))); }
From source file:com.flexive.faces.FxJsfUtils.java
public static int getIntParameter(String name, int defaultValue) { return Integer.valueOf(StringUtils.defaultString(getParameter(name), String.valueOf(defaultValue))); }
From source file:dk.dma.msinm.legacy.msi.service.LegacyMsiImportService.java
/** * Import the legacy MSI with the given ID's * @param ids the ID's of the MSI to import * @param conn the DB connection/*from ww w. j a v a 2 s. c o m*/ * @return the result */ private Date importMsi(List<Integer> ids, Connection conn, List<LegacyMessage> result) { log.debug("Start importing at most " + LIMIT + " legacy MSI warnings from local DB"); long t0 = System.currentTimeMillis(); Date lastUpdate = null; Statement stmt = null; try { stmt = conn.createStatement(); String sql = legacyMsiDataSql.replace(":ids", StringUtils.join(ids, ",")); log.debug("Executing SQL\n" + sql); ResultSet rs = stmt.executeQuery(sql); Integer skipId = null; LegacyMessage legacyMessage = null; while (rs.next()) { Integer id = getInt(rs, "id"); Integer messageId = getInt(rs, "messageId"); Boolean statusDraft = getBoolean(rs, "statusDraft"); String navtexNo = getString(rs, "navtexNo"); String descriptionEn = getString(rs, "description_en"); String descriptionDa = getString(rs, "description_da"); String title = getString(rs, "title"); Date validFrom = getDate(rs, "validFrom"); Date validTo = getDate(rs, "validTo"); Date created = getDate(rs, "created"); Date updated = getDate(rs, "updated"); Date deleted = getDate(rs, "deleted"); Integer version = getInt(rs, "version"); String priority = getString(rs, "priority"); String messageType = getString(rs, "messageType"); String category1En = getString(rs, "category1_en"); String category1Da = getString(rs, "category1_da"); String category2En = getString(rs, "category2_en"); String category2Da = getString(rs, "category2_da"); String area1En = getString(rs, "area1_en"); String area1Da = getString(rs, "area1_da"); String area2En = getString(rs, "area2_en"); String area2Da = getString(rs, "area2_da"); String area3En = getString(rs, "area3_en"); String area3Da = getString(rs, "area3_da"); String locationType = getString(rs, "locationType"); Integer pointIndex = getInt(rs, "pointIndex"); Double pointLatitude = getDouble(rs, "pointLatitude"); Double pointLongitude = getDouble(rs, "pointLongitude"); Integer pointRadius = getInt(rs, "pointRadius"); // Update the lastUpdate if (lastUpdate == null || lastUpdate.before(updated)) { lastUpdate = updated; } if (skipId != null && skipId.intValue() == id.intValue()) { continue; } if (legacyMessage != null && !legacyMessage.getLegacyId().equals(id)) { legacyMessageService.saveLegacyMessage(legacyMessage); legacyMessage = null; } // Handle first record of a new message if (legacyMessage == null) { // Initialize the legacy message to update. // If null is returned, the message should be skipped. legacyMessage = legacyMessageService.initLegacyMessage(id, messageId, version); if (legacyMessage == null) { // Skip the import skipId = id; continue; } result.add(legacyMessage); Message message = legacyMessage.getMessage(); // Update legacy message legacyMessage.setLegacyId(id); legacyMessage.setLegacyMessageId(messageId); legacyMessage.setNavtexNo(navtexNo); legacyMessage.setVersion(version); legacyMessage.setUpdated(updated); // Create the message series identifier SeriesIdentifier identifier = new SeriesIdentifier(); identifier.setMainType(SeriesIdType.MSI); message.setSeriesIdentifier(identifier); if (StringUtils.isNotBlank(navtexNo) && navtexNo.split("-").length == 3) { // Extract the series identifier from the navtext number String[] parts = navtexNo.split("-"); identifier.setAuthority(parts[0]); identifier.setNumber(Integer.valueOf(parts[1])); identifier.setYear(2000 + Integer.valueOf(parts[2])); } else { // Some legacy MSI do not have a navtex number. // Give them a number > 1000, since these are unused Calendar cal = Calendar.getInstance(); cal.setTime(validFrom); int year = cal.get(Calendar.YEAR); if (!statusDraft) { Sequence sequence = new DefaultSequence( "LEGACY_MESSAGE_SERIES_ID_MSI_" + app.getOrganization() + "_" + year, 1000); identifier.setNumber((int) sequences.getNextValue(sequence)); } identifier.setAuthority(app.getOrganization()); identifier.setYear(year); } // Message data message.setCreated(created); message.setUpdated(updated); if ("Navtex".equals(messageType) || "Navwarning".equals(messageType)) { message.setType(Type.SUBAREA_WARNING); } else { message.setType(Type.COASTAL_WARNING); } Date now = new Date(); Status status = Status.PUBLISHED; if (deleted != null && statusDraft) { status = Status.DELETED; } else if (deleted != null && validTo != null && deleted.after(validTo)) { status = Status.EXPIRED; } else if (deleted != null) { status = Status.CANCELLED; } else if (statusDraft) { status = Status.DRAFT; } else if (validTo != null && now.after(validTo)) { status = Status.EXPIRED; } message.setStatus(status); message.setValidFrom(validFrom); message.setValidTo((validTo != null) ? validTo : deleted); try { message.setPriority(Priority.valueOf(priority)); } catch (Exception ex) { message.setPriority(Priority.NONE); } // Message Desc if (StringUtils.isNotBlank(title) || StringUtils.isNotBlank(descriptionEn) || StringUtils.isNotBlank(area3En)) { MessageDesc descEn = message.checkCreateDesc("en"); descEn.setTitle(StringUtils.defaultString(title, descriptionEn)); descEn.setDescription(TextUtils.txt2html(descriptionEn)); descEn.setVicinity(area3En); } if (StringUtils.isNotBlank(title) || StringUtils.isNotBlank(descriptionDa) || StringUtils.isNotBlank(area3Da)) { MessageDesc descDa = message.checkCreateDesc("da"); descDa.setTitle(StringUtils.defaultString(title, descriptionDa)); descDa.setDescription(TextUtils.txt2html(descriptionDa)); descDa.setVicinity(area3Da); } // Areas Area area = createAreaTemplate(area1En, area1Da, null); // Annoyingly, legacy data has Danmark as a sub-area of Danmark if (!StringUtils.equals(area1En, area2En) || !StringUtils.equals(area1Da, area2Da)) { area = createAreaTemplate(area2En, area2Da, area); } message.setArea(area); // Categories message.getCategories().clear(); // Because of changes to the category structure, categories are no longer imported /** Category category = createCategoryTemplate(category1En, category1Da, null); category = createCategoryTemplate(category2En, category2Da, category); if (category != null) { message.getCategories().add(category); } **/ // Locations message.getLocations().clear(); if (pointLatitude != null) { Location.LocationType type; switch (locationType) { case "Point": type = Location.LocationType.POINT; break; case "Polygon": type = Location.LocationType.POLYGON; break; case "Points": type = Location.LocationType.POLYLINE; break; case "Polyline": type = Location.LocationType.POLYLINE; break; default: type = Location.LocationType.POLYLINE; } Location loc1 = new Location(type); if (pointRadius != null) { loc1.setRadius(pointRadius); } message.getLocations().add(loc1); } } if (pointLatitude != null) { Location loc1 = legacyMessage.getMessage().getLocations().get(0); // If the type of the location is POINT, there must only be one point per location if (loc1.getType() == Location.LocationType.POINT && loc1.getPoints().size() > 0) { loc1 = new Location(Location.LocationType.POINT); legacyMessage.getMessage().getLocations().add(loc1); } loc1.addPoint(new Point(loc1, pointLatitude, pointLongitude, pointIndex)); } } if (legacyMessage != null) { legacyMessageService.saveLegacyMessage(legacyMessage); } if (result.size() > 0) { log.info(String.format("Import of %d legacy messages completed in %d ms", result.size(), System.currentTimeMillis() - t0)); } rs.close(); stmt.close(); conn.close(); } catch (Exception ex) { log.error("Failed fetching legacy MSI messages from database ", ex); } finally { try { stmt.close(); } catch (Exception ex) { } try { conn.close(); } catch (Exception ex) { } } return lastUpdate; }
From source file:com.flexive.faces.FxJsfUtils.java
public static boolean getBooleanParameter(String name, boolean defaultValue) { return Boolean.valueOf(StringUtils.defaultString(getParameter(name), String.valueOf(defaultValue))); }