List of usage examples for org.apache.commons.lang StringUtils trim
public static String trim(String str)
Removes control characters (char <= 32) from both ends of this String, handling null
by returning null
.
From source file:com.adobe.acs.commons.contentfinder.querybuilder.impl.viewhandler.GQLToQueryBuilderConverter.java
/** * Helper method for adding comma delimited values into a Query Builder predicate * * @param map// ww w . j ava 2 s. co m * @param predicate * @param values * @param group * @param or * @return */ public static Map<String, String> putAll(Map<String, String> map, String predicate, String[] values, int group, boolean or) { final String groupId = String.valueOf(group) + SUFFIX_GROUP; int count = 1; for (final String value : values) { final String predicateId = count + "_" + predicate; map.put(groupId + "." + predicateId, StringUtils.trim(value)); count++; } map.put(groupId + SUFFIX_P_OR, String.valueOf(or)); return map; }
From source file:ch.entwine.weblounge.security.sql.endpoint.SQLDirectoryProviderEndpoint.java
@PUT @Path("/account/{id}") public Response updateAccount(@PathParam("id") String login, @FormParam("password") String password, @FormParam("firstname") String firstname, @FormParam("lastname") String lastname, @FormParam("initials") String initials, @FormParam("email") String email, @FormParam("language") String language, @FormParam("challenge") String challenge, @FormParam("response") String response, @Context HttpServletRequest request) { // Make sure that the user owns the roles required for this operation User user = securityService.getUser(); if (!SecurityUtils.userHasRole(user, SystemRole.SITEADMIN) && !user.getLogin().equals(login)) return Response.status(Status.FORBIDDEN).build(); JpaAccount account = null;// ww w .j a v a2 s . co m Site site = getSite(request); try { account = directory.getAccount(site, login); if (account == null) return Response.status(Status.NOT_FOUND).build(); // Hash the password if (StringUtils.isNotBlank(password)) { logger.debug("Hashing password for user '{}@{}' using md5", login, site.getIdentifier()); String digestPassword = PasswordEncoder.encode(StringUtils.trim(password)); account.setPassword(digestPassword); } account.setFirstname(StringUtils.trimToNull(firstname)); account.setLastname(StringUtils.trimToNull(lastname)); account.setInitials(StringUtils.trimToNull(initials)); account.setEmail(StringUtils.trimToNull(email)); // The language if (StringUtils.isNotBlank(language)) { try { account.setLanguage(LanguageUtils.getLanguage(language)); } catch (UnknownLanguageException e) { return Response.status(Status.BAD_REQUEST).build(); } } else { account.setLanguage(null); } // Hash the response if (StringUtils.isNotBlank(response)) { logger.debug("Hashing response for user '{}@{}' using md5", login, site.getIdentifier()); String digestResponse = PasswordEncoder.encode(StringUtils.trim(response)); account.setResponse(digestResponse); } directory.updateAccount(account); return Response.ok().build(); } catch (Throwable t) { return Response.serverError().build(); } }
From source file:hydrograph.ui.expression.editor.composites.CategoriesDialogSourceComposite.java
private void createDelButton(Composite headerComposite) { deleteButton = new Button(headerComposite, SWT.NONE); deleteButton.setBounds(0, 0, 75, 25); deleteButton.setToolTipText(Messages.EXTERNAL_JAR_DIALOG_DELETE_BUTTON_TOOLTIP); try {/*from w w w. j a v a2 s .com*/ deleteButton.setImage(ImagePathConstant.DELETE_BUTTON.getImageFromRegistry()); } catch (Exception exception) { LOGGER.error("Exception occurred while attaching image to button", exception); deleteButton.setText("Delete"); } deleteButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (comboJarList.getSelectionIndex() > -1) { String jarName = comboJarList.getItem(comboJarList.getSelectionIndex()); if (userIsSure(jarName)) { try { removeJarFromBuildPath(jarName); comboJarList.remove(jarName); sourcePackageList.removeAll(); refresh(jarName); enableOrDisableAddLabelsOnComboSelection(); } catch (CoreException e1) { LOGGER.error( "Exception occurred while removing jar file" + jarName + "from build Path"); } } } } private boolean userIsSure(String jarName) { MessageBox messageBox = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); messageBox.setMessage("Do you really want to remove " + jarName + " file?\nCannot be undone."); messageBox.setText("Remove Resource"); int response = messageBox.open(); if (response == SWT.YES) return true; return false; } private void refresh(String jarName) { boolean isAnyItemRemovedFromTargetList = false; String[] items = targetComposite.getTargetList().getItems(); targetComposite.getTargetList().removeAll(); for (String item : items) { String jarFileName = StringUtils.trim(StringUtils.substringAfter(item, Constants.DASH)); if (!StringUtils.equalsIgnoreCase(jarFileName, jarName)) { targetComposite.getTargetList().add(item); } else isAnyItemRemovedFromTargetList = true; } if (isAnyItemRemovedFromTargetList) { addCategoreisDialog.createPropertyFileForSavingData(); } } private void removeJarFromBuildPath(String jarName) throws CoreException { LOGGER.debug("Removing jar file" + jarName + "from build Path"); IJavaProject javaProject = JavaCore .create(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()); IFile jarFile = javaProject.getProject().getFolder(PathConstant.PROJECT_LIB_FOLDER) .getFile(jarName); IClasspathEntry[] oldClasspathEntry = javaProject.getRawClasspath(); IClasspathEntry[] newClasspathEntry = new IClasspathEntry[oldClasspathEntry.length - 1]; if (jarFile.exists()) { int index = 0; for (IClasspathEntry classpathEntry : oldClasspathEntry) { if (classpathEntry.getPath().equals(jarFile.getFullPath())) { continue; } newClasspathEntry[index] = classpathEntry; index++; } javaProject.setRawClasspath(newClasspathEntry, new NullProgressMonitor()); jarFile.delete(true, new NullProgressMonitor()); } javaProject.close(); } @Override public void widgetDefaultSelected(SelectionEvent e) {/* Do-Nothing */ } }); }
From source file:com.qcadoo.view.internal.components.grid.GridComponentFilterUtils.java
private static String getFieldNameFromExpression(final String expression) { String pattern = "#(\\w+)(\\['(\\w+)'\\])?([[?]?.get\\('\\w+'\\)]*)"; Matcher matcher = Pattern.compile(pattern).matcher(StringUtils.trim(expression)); if (matcher.matches()) { final StringBuilder fieldNameBuilder = new StringBuilder(matcher.group(1)); if (StringUtils.isNotBlank(matcher.group(3))) { fieldNameBuilder.append("."); fieldNameBuilder.append(matcher.group(3)); }//www.java 2 s .c o m if (StringUtils.isNotBlank(matcher.group(4))) { final String[] searchList = new String[] { "get('", "?.get('", "')" }; final String[] replacementList = new String[] { "", ".", "" }; fieldNameBuilder.append(StringUtils.replaceEach(matcher.group(4), searchList, replacementList)); } return fieldNameBuilder.toString(); } return null; }
From source file:com.bstek.dorado.core.pkgs.PackageManager.java
private static void doBuildPackageInfos() throws Exception { Map<String, PackageInfo> packageMap = new HashMap<String, PackageInfo>(); Enumeration<URL> defaultContextFileResources = org.springframework.util.ClassUtils.getDefaultClassLoader() .getResources(PACKAGE_PROPERTIES_LOCATION); while (defaultContextFileResources.hasMoreElements()) { URL url = defaultContextFileResources.nextElement(); InputStream in = null;/*from w ww . ja v a2 s . c o m*/ try { URLConnection con = url.openConnection(); con.setUseCaches(false); in = con.getInputStream(); Properties properties = new Properties(); properties.load(in); String packageName = properties.getProperty("name"); if (StringUtils.isEmpty(packageName)) { throw new IllegalArgumentException("Package name undefined."); } PackageInfo packageInfo = new PackageInfo(packageName); packageInfo.setAddonVersion(properties.getProperty("addonVersion")); packageInfo.setVersion(properties.getProperty("version")); String dependsText = properties.getProperty("depends"); if (StringUtils.isNotBlank(dependsText)) { List<Dependence> dependences = new ArrayList<Dependence>(); for (String depends : StringUtils.split(dependsText, "; ")) { if (StringUtils.isNotEmpty(depends)) { Dependence dependence = parseDependence(depends); dependences.add(dependence); } } if (!dependences.isEmpty()) { packageInfo.setDepends(dependences.toArray(new Dependence[0])); } } String license = StringUtils.trim(properties.getProperty("license")); if (StringUtils.isNotEmpty(license)) { if (INHERITED.equals(license)) { packageInfo.setLicense(LICENSE_INHERITED); } else { String[] licenses = StringUtils.split(license); licenses = StringUtils.stripAll(licenses); packageInfo.setLicense(licenses); } } packageInfo.setLoadUnlicensed(BooleanUtils.toBoolean(properties.getProperty("loadUnlicensed"))); packageInfo.setClassifier(properties.getProperty("classifier")); packageInfo.setHomePage(properties.getProperty("homePage")); packageInfo.setDescription(properties.getProperty("description")); packageInfo.setPropertiesLocations(properties.getProperty("propertiesConfigLocations")); packageInfo.setContextLocations(properties.getProperty("contextConfigLocations")); packageInfo.setComponentLocations(properties.getProperty("componentConfigLocations")); packageInfo.setServletContextLocations(properties.getProperty("servletContextConfigLocations")); String configurerClass = properties.getProperty("configurer"); if (StringUtils.isNotBlank(configurerClass)) { Class<?> type = ClassUtils.forName(configurerClass); packageInfo.setConfigurer((PackageConfigurer) type.newInstance()); } String listenerClass = properties.getProperty("listener"); if (StringUtils.isNotBlank(listenerClass)) { Class<?> type = ClassUtils.forName(listenerClass); packageInfo.setListener((PackageListener) type.newInstance()); } String servletContextListenerClass = properties.getProperty("servletContextListener"); if (StringUtils.isNotBlank(servletContextListenerClass)) { Class<?> type = ClassUtils.forName(servletContextListenerClass); packageInfo.setServletContextListener((ServletContextListener) type.newInstance()); } if (packageMap.containsKey(packageName)) { PackageInfo conflictPackageInfo = packageMap.get(packageName); StringBuffer conflictInfo = new StringBuffer(20); conflictInfo.append('[').append(conflictPackageInfo.getName()).append(" - ") .append(conflictPackageInfo.getVersion()).append(']'); conflictInfo.append(" and "); conflictInfo.append('[').append(packageInfo.getName()).append(" - ") .append(packageInfo.getVersion()).append(']'); Exception e = new IllegalArgumentException("More than one package \"" + packageName + "\" found. They are " + conflictInfo.toString()); logger.warn(e, e); } packageMap.put(packageName, packageInfo); } catch (Exception e) { throw new IllegalArgumentException("Error occured during parsing \"" + url.getPath() + "\".", e); } finally { if (in != null) { in.close(); } } } List<PackageInfo> calculatedPackages = new ArrayList<PackageInfo>(); for (PackageInfo packageInfo : packageMap.values()) { calculateDepends(packageInfo, calculatedPackages, packageMap); } packageInfosMap.clear(); for (PackageInfo packageInfo : calculatedPackages) { packageInfosMap.put(packageInfo.getName(), packageInfo); } }
From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java
/** * Check if the user email is valid./*from w w w.jav a 2s . com*/ * Only emails that match the accepted domains are validated * @param userEmail The email to check * @return true if the email is valid */ protected boolean isUserValid(String userEmail) { logger.warn("isUserValid " + userEmail); if (!EmailValidator.getInstance().isValid(userEmail)) { return false; } String[] emailParts = StringUtils.split(userEmail, '@'); if (emailParts.length != 2 || StringUtils.isBlank(emailParts[0]) || StringUtils.isBlank(emailParts[1])) { return false; } String domains = getConfigurationValue(USER_DOMAIN); if (StringUtils.isBlank(domains)) { return true; } for (String validDomain : StringUtils.split(domains, ',')) { if (StringUtils.isBlank(validDomain)) { continue; } if (StringUtils.trim(validDomain).equalsIgnoreCase(emailParts[1])) { return true; } } return false; }
From source file:hydrograph.ui.propertywindow.widgets.customwidgets.AbstractWidget.java
public void showHideErrorSymbol(List<AbstractWidget> widgetList) { boolean isErrorPresent = false; for (AbstractWidget abstractWidget : widgetList) { if (StringUtils.equals(abstractWidget.getProperty().getPropertyGroup(), property.getPropertyGroup()) && !(abstractWidget.isWidgetValid())) { isErrorPresent = true;// www .j a va2 s. co m break; } } if (isErrorPresent) { for (CTabItem item : getTabFolder().getItems()) { if (StringUtils.equalsIgnoreCase(StringUtils.trim(item.getText()), property.getPropertyGroup())) { item.setImage(ImagePathConstant.COMPONENT_ERROR_ICON.getImageFromRegistry()); } } } else { for (CTabItem item : getTabFolder().getItems()) { if (StringUtils.equalsIgnoreCase(StringUtils.trim(item.getText()), property.getPropertyGroup())) { item.setImage(null); } } } }
From source file:eionet.cr.web.action.TypeSearchActionBean.java
@Override public Resolution search() throws DAOException { logger.trace("************** START SEARCH REQUEST ***********"); if (!StringUtils.isBlank(type)) { long startTime = System.currentTimeMillis(); restoreStateFromSession();/*from ww w.j a v a 2 s . c o m*/ logger.trace("after restoreStateFromSession " + Util.durationSince(startTime)); startTime = System.currentTimeMillis(); LastAction lastAction = getLastAction(); if (resultList == null || !(lastAction != null && lastAction.equals(LastAction.ADD_FILTER))) { Map<String, String> criteria = new HashMap<String, String>(); criteria.put(Predicates.RDF_TYPE, type); if (selectedFilters != null && !selectedFilters.isEmpty()) { for (Entry<String, String> entry : selectedFilters.entrySet()) { if (!StringUtils.isBlank(entry.getValue())) { criteria.put(entry.getKey(), StringUtils.trim(entry.getValue().trim())); } } } SearchResultDTO<SubjectDTO> searchResult = DAOFactory.get().getDao(SearchDAO.class) .searchByTypeAndFilters(criteria, false, PagingRequest.create(getPageN()), new SortingRequest(getSortP(), SortOrder.parse(getSortO())), selectedColumns); resultList = searchResult.getItems(); matchCount = searchResult.getMatchCount(); queryString = searchResult.getQuery(); int exactRowCountLimit = DAOFactory.get().getDao(SearchDAO.class).getExactRowCountLimit(); exactCount = exactRowCountLimit <= 0 || matchCount <= exactRowCountLimit; } // cache result list. getSession().setAttribute(RESULT_LIST_CACHED, resultList); getSession().setAttribute(LAST_ACTION, LastAction.SEARCH); getSession().setAttribute(MATCH_COUNT, matchCount); getSession().setAttribute(EXACT_COUNT, exactCount); } setExportColumns(getSelectedColumnsFromCache()); return new ForwardResolution(TYPE_SEARCH_PATH); }
From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * Handles the creation of a page based on an e-mail body of type * <code>text/plain</code>./*ww w . j a v a2 s . c o m*/ * * @param content * the message body * @param page * the page * @param language * the content language * @return the page */ private Page handleTextPlain(String content, Page page, Language language) { for (String paragraph : content.split("\r\n")) { if (StringUtils.isBlank(paragraph)) continue; PageletImpl p = new PageletImpl("text", "paragraph"); p.setContent("text", StringUtils.trim(paragraph), language); page.addPagelet(p, page.getStage().getIdentifier()); } return page; }
From source file:io.ecarf.core.utils.LogParser.java
/** * - Processing file: /tmp/wordnet_links.nt.gz.kryo.gz, dictionary items: 49382611, memory usage: 14.336268931627274GB, timer: 290.0 ms * /tmp/wikipedia_links_en.nt.gz.kryo.gz, dictionary items: 44, memory usage: 0.013648882508277893GB, timer: 2.636 s * START: Downloading file: interlanguage_links_chapters_en.nt.gz.kryo.gz, memory usage: 0.0GB * @param line//w w w .j a v a2 s . c o m * @param after * @return */ private double[] extractAndGetMemoryDictionaryItems(String line) { double memory = 0; double items = 0; String memoryStr = null; if (line.contains(TIMER_PREFIX)) { memoryStr = StringUtils.substringBetween(line, MEM_USE, TIMER_PREFIX); if (line.contains(DIC_ITEMS)) { String itemsStr = StringUtils.trim(StringUtils.substringBetween(line, DIC_ITEMS, MEM_USE)); items = Double.parseDouble(itemsStr); } } else { memoryStr = StringUtils.substringAfter(line, MEM_USE); } if (memoryStr != null) { memoryStr = StringUtils.remove(memoryStr, "GB"); memoryStr = StringUtils.strip(memoryStr); } memory = Double.parseDouble(memoryStr); double[] values = new double[] { memory, items }; return values; }