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:gov.nih.nci.caarray.plugins.affymetrix.AffymetrixTsvFileReader.java
/** * Read the next data line from the file. If the headers haven't been loaded yet, they will be before the * next data line is read./* w w w . j ava2 s .co m*/ * @return the next data record * @throws IOException on error reading from the file */ public Record readNextDataLine() throws IOException { if (columnHeaders.isEmpty()) { loadHeaders(); } String trimmedLine; do { currentLine = fileReader.readLine(); trimmedLine = StringUtils.trim(currentLine); } while ("".equals(currentLine) || StringUtils.indexOf(trimmedLine, FILE_HEADER_MARKER) > -1 || StringUtils.indexOf(trimmedLine, COMMENT_MARKER) > -1); return parseDataLine(); }
From source file:de.iteratec.iteraplan.presentation.UserContextInitializationServiceImpl.java
/** * Stores the user's login name and the user's roles to the session. The stored information is * used in {@link de.iteratec.iteraplan.presentation.dialogs.Start.InitCommand} to create the * {@link UserContext} object.//from w w w .j a v a2 s. c om * * Retrieves all information about the logged-in user from the iteraplan database, creates the * {@link UserContext} filled with the respective values of the logged-in user and stores the * context in the global memory. Also checks, if the user's password has expired. If the user * context already exists, nothing is done. * * @return An error message key or null if everything was successful. */ private String createAndStoreUserContext(HttpServletRequest req, Authentication authentication) { HttpSession session = req.getSession(); String userLogin = StringUtils.trim(authentication.getName()); session.setAttribute(LOGGED_IN_USER_LOGIN, userLogin); // Make sure that the MASTER data source is used upon login. The user's context stored in the // thread local of the UserContext is not null, if the user has already logged into iteraplan // previously and the server has not been restarted since. Note that though the session has // been invalidated on logout (see Spring Security configuration), but the UserContext is still // there. // Thus the reference to the data source that the user connects to must be explicitly set to // the MASTER data source. Otherwise the data source stored in the context is used, but the // according database does usually not contain all the data necessary for a successful login // (e.g. the role for the demo access to iteraplan). if (UserContext.getCurrentUserContext() != null) { LOGGER.info("Point the user to the MASTER data source."); UserContext.getCurrentUserContext().setDataSource(Constants.MASTER_DATA_SOURCE); } final Set<String> userRoles = getUserRoles(authentication); session.setAttribute(LOGGED_IN_USER_ROLES, userRoles); User user = userService.getUserByLoginIfExists(userLogin); final Set<Role> roles = loadRoles(userRoles); Locale locale = RequestContextUtils.getLocale(req); // Create and store user context. UserContext userContext = new UserContext(userLogin, roles, locale, user); UserContext.setCurrentUserContext(userContext); session.setAttribute(SessionConstants.USER_CONTEXT, userContext); LOGGER.debug("User context created and stored in user's session."); LOGIN_LOGGER.info(userContext.toCSVString()); if (user == null) { user = userService.createUser(userLogin); // Create and store user context. // the new user can only be created after the user context is set (above) // as the update of an entity triggers the LastModificationInterceptor, which // expects an already set user context userContext = new UserContext(userLogin, roles, locale, user); UserContext.detachCurrentUserContext(); UserContext.setCurrentUserContext(userContext); session.setAttribute(SessionConstants.USER_CONTEXT, userContext); } readLdapData(authentication.getPrincipal(), user); if (roles != null && !roles.isEmpty() && !(roles.containsAll(user.getRoles()) && user.getRoles().containsAll(roles))) { user.clearRoles(); for (Role role : roles) { user.addRoleTwoWay(role); } userService.saveOrUpdate(user); } final String errorMessageKey = createDataSource(userContext); if (errorMessageKey != null) { return errorMessageKey; } LOGGER.info("User has logged in."); // notify ElasticeamService (bean), that the metamodel and model for the 'new' datasource needs to be loaded elasticService.initOrReload(); //Create elasticMiContext ElasticMiContext elasticMiContext = elasticMiContextAndStakeholderManagerInitializationService .initializeMiContextAndStakeholderManager(userLogin, userContext.getDataSource()); session.setAttribute(SessionConstants.ELASTIC_MI_CONTEXT, elasticMiContext); return null; }
From source file:com.adobe.acs.commons.errorpagehandler.cache.impl.ErrorPageCacheImpl.java
@Override public final String getCacheData(final String errorPage) { final CacheEntry cacheEntry = this.cache.get(StringUtils.trim(errorPage)); if (cacheEntry == null) { return ""; }// w w w . j ava 2s .c o m return cacheEntry.getData(); }
From source file:info.magnolia.cms.beans.config.PropertiesInitializer.java
public void loadPropertiesFiles(String propertiesLocationString, String rootPath) { String[] propertiesLocation = StringUtils.split(propertiesLocationString, ','); boolean found = false; // attempt to load each properties file at the given locations in reverse order: first files in the list // override the later ones for (int j = propertiesLocation.length - 1; j >= 0; j--) { String location = StringUtils.trim(propertiesLocation[j]); if (loadPropertiesFile(rootPath, location)) { found = true;//from ww w . j a v a 2 s. co m } } if (!found) { final String msg = MessageFormat.format( "No configuration found using location list {0}. Base path is [{1}]", //$NON-NLS-1$ ArrayUtils.toString(propertiesLocation), rootPath); log.error(msg); throw new ConfigurationException(msg); } }
From source file:com.intuit.tank.harness.APITestHarness.java
private void initializeFromArgs(String[] args) { String controllerBase = null; for (int iter = 0; iter < args.length; ++iter) { String argument = args[iter]; LOG.info("checking arg " + argument); String[] values = argument.split("="); if (values[0].equalsIgnoreCase("-tp")) { testPlans = values[1];//from w w w . j a v a2s. com if (!AgentUtil.validateTestPlans(testPlans)) { return; } continue; } else if (values[0].equalsIgnoreCase("-ramp")) { agentRunData.setRampTime(Long.parseLong(values[1]) * 60000); continue; } else if (values[0].equalsIgnoreCase("-client")) { tankHttpClientClass = StringUtils.trim(values[1]); continue; } else if (values[0].equalsIgnoreCase("-d")) { Logger.getLogger("com.intuit.tank.http").setLevel(Level.DEBUG); Logger.getLogger("com.intuit.tank").setLevel(Level.DEBUG); DEBUG = true; agentRunData.setActiveProfile(LoggingProfile.VERBOSE); setFlowControllerTemplate(new DebugFlowController()); continue; } else if (values[0].equalsIgnoreCase("-local")) { isLocal = true; continue; } else if (values[0].equalsIgnoreCase("-instanceId")) { instanceId = values[1]; continue; } else if (values[0].equalsIgnoreCase("-logging")) { agentRunData.setActiveProfile(LoggingProfile.fromString(values[1])); continue; } else if (values[0].equalsIgnoreCase("-users")) { agentRunData.setNumUsers(Integer.parseInt(values[1])); continue; } else if (values[0].equalsIgnoreCase("-capacity")) { capacity = Integer.parseInt(values[1]); continue; } else if (values[0].equalsIgnoreCase("-start")) { agentRunData.setNumStartUsers(Integer.parseInt(values[1])); continue; } else if (values[0].equalsIgnoreCase("-jobId")) { agentRunData.setJobId(values[1]); continue; } else if (values[0].equalsIgnoreCase("-stopBehavior")) { agentRunData.setStopBehavior(StopBehavior.fromString(values[1])); continue; } else if (values[0].equalsIgnoreCase("-http")) { controllerBase = (values.length > 1 ? values[1] : null); continue; } else if (values[0].equalsIgnoreCase("-time")) { agentRunData.setSimulationTime(Integer.parseInt(values[1]) * 60000); continue; } } if (instanceId == null) { try { instanceId = AmazonUtil.getInstanceId(); if (instanceId == null) { instanceId = getLocalInstanceId(); } } catch (Exception e) { instanceId = getLocalInstanceId(); } } if (agentRunData.getActiveProfile() == null && !isLocal) { agentRunData.setActiveProfile(AmazonUtil.getLoggingProfile()); } agentRunData.setMachineName(instanceId); agentRunData.setInstanceId(instanceId); if (controllerBase != null) { resultsReporter = ReportingFactory.getResultsReporter(); startHttp(controllerBase); } else { resultsReporter = new DummyResultsReporter(); TestPlanSingleton plans = TestPlanSingleton.getInstance(); if (null == testPlanXmls) { plans.setTestPlans(testPlans); } else { plans.setTestPlans(testPlanXmls); } runConcurrentTestPlans(); } }
From source file:mitm.common.security.smime.SMIMEEnvelopedInspectorImplTest.java
@Test public void testOutlook2010MissingSubjKeyIdWorkAround() throws Exception { MimeMessage message = loadMessage("outlook2010_cert_missing_subjkeyid.eml"); KeyStoreKeyProvider keyStoreKeyProvider = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/outlook2010_cert_missing_subjkeyid.p12"), ""), "");//ww w .j av a 2 s . co m keyStoreKeyProvider.setUseOL2010Workaround(true); SMIMEEnvelopedInspector inspector = new SMIMEEnvelopedInspectorImpl(message, keyStoreKeyProvider, securityFactory.getNonSensitiveProvider(), securityFactory.getSensitiveProvider()); MimeMessage decrypted = inspector.getContentAsMimeMessage(); File file = new File(tempDir, "test-testOutlook2010MissingSubjKeyId-decrypted.eml"); MailUtils.writeMessage(decrypted, file); assertNotNull(decrypted); assertTrue(decrypted.isMimeType("text/plain")); assertNull(decrypted.getSubject()); assertEquals("Created with Outlook 2010 Beta (14.0.4536.1000)", StringUtils.trim((String) decrypted.getContent())); }
From source file:com.doculibre.constellio.wicket.panels.admin.featuredLink.AddEditFeaturedLinkPanel.java
public AddEditFeaturedLinkPanel(String id, FeaturedLink featuredLink) { super(id, false); this.featuredLinkModel = new ReloadableEntityModel<FeaturedLink>(featuredLink); Form form = getForm();/*from w w w . j a va2s.c om*/ form.setModel(new CompoundPropertyModel(featuredLinkModel)); IModel localesModel = new LoadableDetachableModel() { @Override protected Object load() { AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); return collection.getLocales(); } }; MultiLocaleComponentHolder titleHolder = new MultiLocaleComponentHolder("linkTitle", "title", featuredLinkModel, localesModel) { @Override protected void onPopulateItem(ListItem item, IModel componentModel, Locale locale) { TextField titleLocaleField = new RequiredTextField("titleLocale", componentModel); titleLocaleField.add(new StringValidator.MaximumLengthValidator(50)); item.add(titleLocaleField); item.add(new LocaleNameLabel("localeName", locale, true) { @Override public boolean isVisible() { AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); return collection.getLocales().size() > 1; } }); } }; form.add(titleHolder); MultiLocaleComponentHolder descriptionHolder = new MultiLocaleComponentHolder("description", featuredLinkModel, localesModel) { @Override protected void onPopulateItem(ListItem item, IModel componentModel, Locale locale) { TextArea descriptionLocaleField = new TextArea("descriptionLocale", componentModel); // descriptionLocaleField.add(new StringValidator.MaximumLengthValidator(50)); item.add(descriptionLocaleField); TinyMCESettings tinyMCESettings = new TinyMCESettings(TinyMCESettings.Theme.advanced); tinyMCESettings.setToolbarLocation(TinyMCESettings.Location.top); descriptionLocaleField.add(new TinyMceBehavior(tinyMCESettings)); item.add(new LocaleNameLabel("localeName", locale, true) { @Override public boolean isVisible() { AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); return collection.getLocales().size() > 1; } }); } }; form.add(descriptionHolder); IModel keywordsModel = new Model() { @Override public Object getObject() { FeaturedLink featuredLink = featuredLinkModel.getObject(); StringBuffer keywordsSB = new StringBuffer(); for (Iterator<String> it = featuredLink.getKeywords().iterator(); it.hasNext();) { String keyword = it.next(); keywordsSB.append(keyword); if (it.hasNext()) { keywordsSB.append("\n"); } } return keywordsSB.toString(); } @Override public void setObject(Serializable object) { String keywordsText = (String) object; FeaturedLink featuredLink = featuredLinkModel.getObject(); featuredLink.getKeywords().clear(); if (keywordsText != null) { AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); StringTokenizer st = new StringTokenizer(keywordsText, "\n"); while (st.hasMoreTokens()) { String keyword = StringUtils.trim(st.nextToken()); String keywordAnalyzed = AnalyzerUtils.analyze(keyword, collection); featuredLink.getKeywords().add(keyword); featuredLink.getKeywordsAnalyzed().add(keywordAnalyzed); } } } }; form.add(new TextArea("keywords", keywordsModel)); }
From source file:au.edu.anu.portal.portlets.rss.SimpleRSSPortlet.java
/** * Process any portlet actions. /*from ww w .j a v a 2s. co m*/ */ public void processAction(ActionRequest request, ActionResponse response) throws PortletModeException { log.debug("Simple RSS processAction()"); //this handles both EDIT and CONFIG modes in exactly the same way. //if we need to split, check PortletMode. boolean success = true; //get prefs and submitted values PortletPreferences prefs = request.getPreferences(); String portletTitle = StringEscapeUtils.escapeHtml(StringUtils.trim(request.getParameter("portletTitle"))); String maxItems = StringUtils.trim(request.getParameter("maxItems")); String feedUrl = StringUtils.trim(request.getParameter("feedUrl")); //portlet title could be blank, set to default if (StringUtils.isBlank(portletTitle)) { portletTitle = Constants.PORTLET_TITLE_DEFAULT; } boolean feedUrlIsLocked = isPrefLocked(request, PREF_FEED_URL); boolean portletTitleIsLocked = isPrefLocked(request, PREF_PORTLET_TITLE); //check not readonly try { //only do this if we know its not locked, ie this is not a preconfigured portlet if (!portletTitleIsLocked) { prefs.setValue(PREF_PORTLET_TITLE, portletTitle); } //only do this if we know its not locked, ie this is not a preconfigured portlet if (!feedUrlIsLocked) { prefs.setValue(PREF_FEED_URL, feedUrl); } prefs.setValue(PREF_MAX_ITEMS, maxItems); } catch (ReadOnlyException e) { success = false; response.setRenderParameter("errorMessage", Messages.getString("error.form.readonly.error")); log.error(e.getMessage()); } //validate and save if (success) { try { prefs.store(); response.setPortletMode(PortletMode.VIEW); } catch (ValidatorException e) { //PORT-672 present entered data on the form again response.setRenderParameter("errorMessage", e.getMessage()); response.setRenderParameter("portletTitle", portletTitle); response.setRenderParameter("maxItems", maxItems); //this will be null if locked so don't set it, we dont need it if (!feedUrlIsLocked) { response.setRenderParameter("feedUrl", feedUrl); } log.error(e.getMessage()); } catch (IOException e) { response.setRenderParameter("errorMessage", Messages.getString("error.form.save.error")); log.error(e.getMessage()); } catch (PortletModeException e) { log.error(e.getMessage(), e); } } }
From source file:com.redhat.winddrop.mdb.WindupExecutionQueueMDB.java
/** * Configures and executes Windup.//from w ww. j a va 2 s .co m * * @param packageSignature * @param windupInputFile * @param windupOutputDirectory * @throws IOException */ protected void executeWindup(String packageSignature, File windupInputFile, File windupOutputDirectory) throws IOException { // Map the environment settings from the input arguments. WindupEnvironment settings = new WindupEnvironment(); settings.setPackageSignature(packageSignature); // settings.setExcludeSignature("excludePkgs"); // settings.setTargetPlatform("targetPlatform"); settings.setFetchRemote("false"); boolean isSource = false; if (BooleanUtils.toBoolean("source")) { isSource = true; } settings.setSource(isSource); boolean captureLog = false; if (BooleanUtils.toBoolean("captureLog")) { captureLog = true; } String logLevel = StringUtils.trim("logLevel"); settings.setCaptureLog(captureLog); settings.setLogLevel(logLevel); LOG.info("captureLog " + captureLog); LOG.info("logLevel " + logLevel); LOG.info("isSource " + isSource); // Run Windup new ReportEngine(settings).process(windupInputFile, windupOutputDirectory); }
From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java
public String getCollectionValues(JsonSimple emailConfig, JsonSimple tfPackage, String varField) { String formattedCollectionValues = ""; JSONArray subKeys = emailConfig.getArray("collections", varField, "subKeys"); String tfPackageField = emailConfig.getString("", "collections", varField, "payloadKey"); if (StringUtils.isNotBlank(tfPackageField) && subKeys instanceof JSONArray) { List<JsonObject> jsonList = new StorageDataUtil().getJavaList(tfPackage, tfPackageField); log.debug("Collating collection values for email template..."); JSONArray fieldSeparators = emailConfig.getArray("collections", varField, "fieldSeparators"); String recordSeparator = emailConfig.getString(IOUtils.LINE_SEPARATOR, "collections", varField, "recordSeparator"); String nextDelimiter = " "; for (JsonObject collectionRow : jsonList) { if (fieldSeparators instanceof JSONArray && fieldSeparators.size() > 0) { // if no more delimiters, continue to use the last one specified Object nextFieldSeparator = fieldSeparators.remove(0); if (nextFieldSeparator instanceof String) { nextDelimiter = (String) nextFieldSeparator; } else { log.warn("Unable to retrieve String value from fieldSeparator: " + fieldSeparators.toString()); }// w ww. ja v a2s. com } List<String> collectionValuesList = new ArrayList<String>(); for (Object requiredKey : subKeys) { Object rawKeyValue = collectionRow.get(requiredKey); if (rawKeyValue instanceof String) { String keyValue = StringUtils.trim((String) rawKeyValue); if (StringUtils.isNotBlank(keyValue)) { collectionValuesList.add(keyValue); } else if (!isVariableNameHiddenIfEmpty) { collectionValuesList.add("$" + requiredKey); } else { log.info("blank variable name will be hidden: " + keyValue); } } else { log.warn("No string value returned from: " + requiredKey); } } formattedCollectionValues += StringUtils.join(collectionValuesList, nextDelimiter) + recordSeparator; } formattedCollectionValues = StringUtils.chomp(formattedCollectionValues, recordSeparator); log.debug("email formatted collection values: " + formattedCollectionValues); } return formattedCollectionValues; }