List of usage examples for org.apache.commons.lang3 StringUtils containsWhitespace
public static boolean containsWhitespace(final CharSequence seq)
From source file:com.erudika.para.persistence.CassandraUtils.java
/** * Creates a table in Cassandra.// w w w .j a v a 2 s . c om * @param appid name of the {@link com.erudika.para.core.App} * @return true if created */ public static boolean createTable(String appid) { if (StringUtils.isBlank(appid) || StringUtils.containsWhitespace(appid) || existsTable(appid)) { return false; } try { String table = getTableNameForAppid(appid); getClient().execute("CREATE KEYSPACE IF NOT EXISTS " + DBNAME + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': " + REPLICATION + "};"); getClient().execute("USE " + DBNAME + ";"); getClient().execute("CREATE TABLE IF NOT EXISTS " + table + " (id text PRIMARY KEY, json text);"); } catch (Exception e) { logger.error(null, e); return false; } return true; }
From source file:com.erudika.para.persistence.AWSDynamoUtils.java
/** * Creates a table in AWS DynamoDB.// www.j a v a 2s.c o m * @param appid name of the {@link com.erudika.para.core.App} * @param readCapacity read capacity * @param writeCapacity write capacity * @return true if created */ public static boolean createTable(String appid, long readCapacity, long writeCapacity) { if (StringUtils.isBlank(appid) || StringUtils.containsWhitespace(appid) || existsTable(appid)) { return false; } try { getClient().createTable(new CreateTableRequest().withTableName(getTableNameForAppid(appid)) .withKeySchema(new KeySchemaElement(Config._KEY, KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName(Config._KEY) .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput(new ProvisionedThroughput(readCapacity, writeCapacity))); } catch (Exception e) { logger.error(null, e); return false; } return true; }
From source file:blue.orchestra.editor.blueSynthBuilder.BSBCompletionProvider.java
@Override public CompletionTask createTask(int queryType, JTextComponent component) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE || bsbInterface == null) { return null; }//www.j a va 2 s.c o m return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { String filter = null; int startOffset = caretOffset - 1; try { final StyledDocument bDoc = (StyledDocument) document; final int lineStartOffset = getRowFirstNonWhite(bDoc, caretOffset); final char[] line = bDoc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray(); final int whiteOffset = indexOfWhite(line); filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1); if (whiteOffset > 0) { startOffset = lineStartOffset + whiteOffset + 1; } else { startOffset = lineStartOffset; } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } if (filter != null && !filter.equals("")) { int index = filter.indexOf("<"); if (index >= 0) { filter = filter.substring(index + 1); Iterator<BSBObject> bsbObjects = bsbInterface.iterator(); while (bsbObjects.hasNext()) { BSBObject bsbObj = bsbObjects.next(); String[] keys = bsbObj.getReplacementKeys(); if (keys == null) { continue; } for (String key : keys) { if (StringUtils.containsWhitespace(key)) { continue; } if (filter.isEmpty() || key.startsWith(filter)) { completionResultSet.addItem(new BSBCompletionItem(bsbObj, key)); } } } } } completionResultSet.finish(); } }, component); }
From source file:com.erudika.para.persistence.AWSDynamoUtils.java
/** * Updates the table settings (read and write capacities) * @param appid name of the {@link com.erudika.para.core.App} * @param readCapacity read capacity//from www.ja v a2 s . c o m * @param writeCapacity write capacity * @return true if updated */ public static boolean updateTable(String appid, long readCapacity, long writeCapacity) { if (StringUtils.isBlank(appid) || StringUtils.containsWhitespace(appid)) { return false; } try { Map<String, Object> dbStats = getTableStatus(appid); long currentReadCapacity = (Long) dbStats.get("readCapacityUnits"); long currentWriteCapacity = (Long) dbStats.get("writeCapacityUnits"); // AWS throws an exception if the new read/write capacity values are the same as the current ones if (!dbStats.isEmpty() && readCapacity != currentReadCapacity && writeCapacity != currentWriteCapacity) { getClient().updateTable(new UpdateTableRequest().withTableName(getTableNameForAppid(appid)) .withProvisionedThroughput(new ProvisionedThroughput(readCapacity, writeCapacity))); } } catch (Exception e) { logger.error(null, e); return false; } return true; }
From source file:de.ks.idnadrev.information.chart.ChartDataEditor.java
private TextField createCategoryEditor(ChartRow chartRow, int rowNum) { TextField categoryEditor = new TextField(); categoryEditor.textProperty().bindBidirectional(chartRow.getCategory()); categoryEditor.focusedProperty().addListener(getEditorFocusListener(rowNum, categoryEditor)); categoryEditor.textProperty().addListener((p, o, n) -> { categoryEditor.setUserData(true); });/*from w w w .j av a 2 s. co m*/ BiFunction<Integer, Integer, TextField> nextCategoryField = (row, column) -> { if (categoryEditors.size() > row) { return categoryEditors.get(row); } else { return null; } }; BiConsumer<Integer, Integer> clipBoardHandler = (row, col) -> { String string = Clipboard.getSystemClipboard().getString(); if (StringUtils.containsWhitespace(string)) { List<String> datas = Arrays.asList(StringUtils.split(string, "\n")); int missingRows = (row + datas.size()) - rows.size(); if (missingRows > 0) { for (int i = 0; i < missingRows; i++) { rows.add(new ChartRow()); } } for (int i = row; i < row + datas.size(); i++) { ChartRow currentChartRow = rows.get(i); String data = datas.get(i - row); currentChartRow.setCategory(data); } } }; categoryEditor.setOnKeyReleased(getInputKeyHandler(rowNum, -1, nextCategoryField, clipBoardHandler)); validationRegistry.registerValidator(categoryEditor, (control, value) -> { if (value != null) { Set<String> values = categoryEditors.stream()// .filter(e -> e != categoryEditor)// .map(e -> e.textProperty().getValueSafe())// .filter(v -> !v.isEmpty())// .collect(Collectors.toSet()); if (values.contains(value)) { ValidationMessage message = new ValidationMessage("validation.noDuplicates", control, value); return ValidationResult.fromMessages(message); } } return null; }); categoryEditors.add(categoryEditor); return categoryEditor; }
From source file:com.beans.CustomerAdminMBean.java
public String addAction2() throws ProcessingException { if (StringUtils.containsWhitespace(userName)) { FacesMessage msg = new FacesMessage("Username contains white spaces"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; }/*w w w .j a va 2 s. c o m*/ if (customerrepo.findByUsername(userName) != null) { FacesMessage msg = new FacesMessage("Username already exists"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } else if (userName != null && userName.length() > 11) { FacesMessage msg = new FacesMessage("Username Length is greater than eleven"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } else if (customerrepo.findByEmail(email) != null) { FacesMessage msg = new FacesMessage("Email already exists"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } if (customerrepo.findByPhone(phone) != null) { FacesMessage msg = new FacesMessage("Phone already exists"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } else { RequestContext context = RequestContext.getCurrentInstance(); Customer cust = new Customer(); cust.setUsername(userName); cust.setStatus(CustomerStatus.INACTIVE.ordinal()); cust.setReward(0d); // customer.setReseller(); cust.setPhone(phone); try { cust.setPassword(Util.hash(passwd)); } catch (ProcessingException ex) { Logger.getLogger(CustomerAdminMBean.class.getName()).log(Level.SEVERE, null, ex); } cust.setLastName(lname); cust.setFirstName(fname); cust.setEmail(email); cust.setBalance(customerrepo.getProperty("SignUpBonus")); String code = Util.generateCode(); cust.setActivationCode(code); cust.setAccountType(accountType); cust.setAddress(address); cust.setRate(customerrepo.getProperty("FlatRate")); cust.setRegDate(new Date()); String messsg = ""; try { customerrepo.create(cust); } catch (Exception ex) { messsg = ex.getMessage(); } //SENDING EMAIL SendEmail sendObject = new SendEmail(); Email mail = new Email(); mail.setEmailAddress(email); mail.setMessage("Dear " + fname + ", SMS Solutions welcomes you. " + "Your sms account has been successfully created. " + "Your Username is " + userName + " and your password is " + passwd + " ." + " Your number verification code has been sent to your phone. \n" + "Kindly click on the link below to verify your number and activate your account:\n" + "http://smssolutions.com.ng:8180/BulkSMS/verifycode\n" + "Thank you for your patronage."); mail.setSubject("SMS Account Created"); sendObject.sendSimpleMail(mail); //END OF EMAIL String SMSMESSAGE = "Your SMS account has been created successfully." + " Username = " + userName + " and" + " password = " + passwd + " . Your verification code is " + code + "." + " Kindly confirm your phone to log in"; smsrepo.sendSMS(ResponseCode.HEADER, SMSMESSAGE, null, phone, new Date()); messsg = "Account Created successfully"; FacesMessage msg = new FacesMessage(messsg); FacesContext.getCurrentInstance().addMessage(null, msg); context.addCallbackParam("loggedIn", true); email = ""; phone = ""; lname = ""; fname = ""; status = 0; return null; } }
From source file:com.beans.CustomerMBean.java
public String addAction2() throws ProcessingException { if (StringUtils.containsWhitespace(userName)) { FacesMessage msg = new FacesMessage("Username contains white spaces"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; }//from w ww . j a v a 2 s .c om if (customerrepo.findByUsername(userName) != null) { FacesMessage msg = new FacesMessage("Username already exists"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } else if (userName != null && userName.length() > 11) { FacesMessage msg = new FacesMessage("Username Length is greater than eleven"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } else if (email != null && !email.contains("@") || customerrepo.findByEmail(email) != null) { FacesMessage msg = new FacesMessage("Email already exists or invalid"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } if (customerrepo.findByPhone(phone) != null) { FacesMessage msg = new FacesMessage("Phone number already exists"); FacesContext.getCurrentInstance().addMessage(null, msg); return null; } else { RequestContext context = RequestContext.getCurrentInstance(); Customer cust = new Customer(); cust.setUsername(userName); cust.setStatus(CustomerStatus.INACTIVE.ordinal()); cust.setReward(0d); // customer.setReseller(); cust.setPhone(phone); try { cust.setPassword(Util.hash(passwd)); } catch (ProcessingException ex) { Logger.getLogger(CustomerMBean.class.getName()).log(Level.SEVERE, null, ex); } cust.setLastName(lname); cust.setFirstName(fname); cust.setEmail(email); cust.setBalance(customerrepo.getProperty("SignUpBonus")); String code = Util.generateCode(); cust.setActivationCode(code); cust.setAccountType(accountType); cust.setRegDate(new Date()); cust.setRate(customerrepo.getProperty("FlatRate")); cust.setAddress(address); String messsg = ""; String accountRole = "Customer"; if (accountType == 1) { accountRole = "Reseller"; } try { customerrepo.create(cust); } catch (Exception ex) { messsg = ex.getMessage(); } //SENDING EMAIL SendEmail sendObject = new SendEmail(); Email mail = new Email(); mail.setEmailAddress(email); mail.setMessage("Dear " + fname + ", SMS Solutions welcomes you. " + "Your " + accountRole + " account has been successfully created. " + "Your Username is " + userName + " and your password is " + passwd + " ." + " Your number verification code has been sent to your phone. \n" + "Kindly click on the link below to verify your number and activate your account:\n" + "http://smssolutions.com.ng:8180/BulkSMS/verifycode\n" + "Thank you for your patronage."); mail.setSubject("SMS Account Created"); sendObject.sendSimpleMail(mail); //END OF EMAIL String SMSMESSAGE = "Your " + accountRole + " account has been created successfully." + " Username = " + userName + " and" + " password = " + passwd + " . Your verification code is " + code + "." + " Kindly confirm your phone to log in"; smsrepo.sendSMS(ResponseCode.HEADER, SMSMESSAGE, null, phone, new Date()); messsg = "Account Created successfully"; FacesMessage msg = new FacesMessage(messsg); FacesContext.getCurrentInstance().addMessage(null, msg); context.addCallbackParam("loggedIn", true); email = ""; phone = ""; lname = ""; fname = ""; status = 0; return null; } }
From source file:com.erudika.para.search.ElasticSearchUtils.java
/** * Creates a new search index.//from ww w .j a va 2s. c om * @param appid the index name (alias) * @param shards number of shards * @param replicas number of replicas * @return true if created */ public static boolean createIndex(String appid, int shards, int replicas) { if (StringUtils.isBlank(appid) || StringUtils.containsWhitespace(appid) || existsIndex(appid)) { return false; } try { NodeBuilder nb = NodeBuilder.nodeBuilder(); nb.settings().put("number_of_shards", Integer.toString(shards)); nb.settings().put("number_of_replicas", Integer.toString(replicas)); nb.settings().put("auto_expand_replicas", "0-1"); nb.settings().put("analysis.analyzer.default.type", "standard"); nb.settings().putArray("analysis.analyzer.default.stopwords", "arabic", "armenian", "basque", "brazilian", "bulgarian", "catalan", "czech", "danish", "dutch", "english", "finnish", "french", "galician", "german", "greek", "hindi", "hungarian", "indonesian", "italian", "norwegian", "persian", "portuguese", "romanian", "russian", "spanish", "swedish", "turkish"); String name = appid + "1"; CreateIndexRequestBuilder create = getClient().admin().indices().prepareCreate(name) .setSettings(nb.settings().build()); // default system mapping (all the rest are dynamic) create.addMapping("_default_", getDefaultMapping()); create.execute().actionGet(); addIndexAlias(name, appid); } catch (Exception e) { logger.warn(null, e); return false; } return true; }
From source file:eu.ggnet.dwoss.customer.eao.CustomerEao.java
/** * This Method search for a Customer by his Id or, Company or Firstname or Lastname. * First it searchs for the CustomerId via sql. Second an index search using the fields company, firsname, lastname is executed. * The combiened result is returned./*from w w w . java 2s . c om*/ * <p/> * @param search the search parameter * @return the result of the search */ public List<Customer> find(String search) { if (StringUtils.isBlank(search)) return new ArrayList<>(); search = search.trim(); List<Customer> result = new ArrayList<>(); try { Long kid = Long.valueOf(search); Customer find = em.find(Customer.class, kid); if (find != null) result.add(find); } catch (NumberFormatException numberFormatException) { // If not a number, ignore. } FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get(); Query query; if (StringUtils.containsWhitespace(search)) { // Multiple Words TermContext keyword = qb.keyword(); TermMatchingContext onField = null; for (String string : searchFields) { if (onField == null) onField = keyword.onField(string); else onField = onField.andField(string); } query = onField.matching(search.toLowerCase()).createQuery(); } else { // One Word, wildcards are possibel WildcardContext keyword = qb.keyword().wildcard(); TermMatchingContext onField = null; for (String string : searchFields) { if (onField == null) onField = keyword.onField(string); else onField = onField.andField(string); } query = onField.matching(search.toLowerCase()).createQuery(); } result.addAll(ftem.createFullTextQuery(query, Customer.class).getResultList()); return result; }
From source file:com.github.rvesse.airline.model.MetadataLoader.java
public static <C> GlobalMetadata<C> loadGlobal(Class<?> cliClass) { Annotation annotation = cliClass.getAnnotation(com.github.rvesse.airline.annotations.Cli.class); if (annotation == null) throw new IllegalArgumentException( String.format("Class %s does not have the @Cli annotation", cliClass)); com.github.rvesse.airline.annotations.Cli cliConfig = (com.github.rvesse.airline.annotations.Cli) annotation; // Prepare commands CommandMetadata defaultCommand = null; if (!cliConfig.defaultCommand().equals(com.github.rvesse.airline.annotations.Cli.NO_DEFAULT.class)) { defaultCommand = loadCommand(cliConfig.defaultCommand()); }/* w w w . j a v a 2 s . c o m*/ List<CommandMetadata> defaultGroupCommands = new ArrayList<CommandMetadata>(); for (Class<?> cls : cliConfig.commands()) { defaultGroupCommands.add(loadCommand(cls)); } // Prepare parser configuration ParserMetadata<C> parserConfig = cliConfig.parserConfiguration() != null ? MetadataLoader.<C>loadParser(cliConfig.parserConfiguration()) : MetadataLoader.<C>loadParser(cliClass); // Prepare restrictions // We find restrictions in the following order: // 1 - Those declared via annotations // 2 - Those declared via the restrictions field of the @Cli annotation // 3 - Standard restrictions if the includeDefaultRestrctions field of // the @Cli annotation is true List<GlobalRestriction> restrictions = new ArrayList<GlobalRestriction>(); for (Class<? extends Annotation> annotationClass : RestrictionRegistry .getGlobalRestrictionAnnotationClasses()) { annotation = cliClass.getAnnotation(annotationClass); if (annotation == null) continue; GlobalRestriction restriction = RestrictionRegistry.getGlobalRestriction(annotationClass, annotation); if (restriction != null) restrictions.add(restriction); } for (Class<? extends GlobalRestriction> cls : cliConfig.restrictions()) { restrictions.add(ParserUtil.createInstance(cls)); } if (cliConfig.includeDefaultRestrictions()) { restrictions.addAll(AirlineUtils.arrayToList(GlobalRestriction.DEFAULTS)); } // Prepare groups // We sort sub-groups by name length then lexically // This means that when we build the groups hierarchy we'll ensure we // build the parent groups first wherever possible Map<String, CommandGroupMetadata> subGroups = new TreeMap<String, CommandGroupMetadata>( new StringHierarchyComparator()); List<CommandGroupMetadata> groups = new ArrayList<CommandGroupMetadata>(); for (Group groupAnno : cliConfig.groups()) { String groupName = groupAnno.name(); String subGroupPath = null; if (StringUtils.containsWhitespace(groupName)) { // Normalize the path subGroupPath = StringUtils.join(StringUtils.split(groupAnno.name()), ' '); } // Maybe a top level group we've already seen CommandGroupMetadata group = CollectionUtils.find(groups, new GroupFinder(groupName)); if (group == null) { // Maybe a sub-group we've already seen group = subGroups.get(subGroupPath); } List<CommandMetadata> groupCommands = new ArrayList<CommandMetadata>(); for (Class<?> cls : groupAnno.commands()) { groupCommands.add(loadCommand(cls)); } if (group == null) { // Newly discovered group //@formatter:off group = loadCommandGroup(subGroupPath != null ? subGroupPath : groupName, groupAnno.description(), groupAnno.hidden(), Collections.<CommandGroupMetadata>emptyList(), !groupAnno.defaultCommand().equals(Group.NO_DEFAULT.class) ? loadCommand(groupAnno.defaultCommand()) : null, groupCommands); //@formatter:on if (subGroupPath == null) { groups.add(group); } else { // Remember sub-groups for later subGroups.put(subGroupPath, group); } } else { for (CommandMetadata cmd : groupCommands) { group.addCommand(cmd); } } } // Build sub-group hierarchy buildGroupsHierarchy(groups, subGroups); // Find all commands List<CommandMetadata> allCommands = new ArrayList<CommandMetadata>(); allCommands.addAll(defaultGroupCommands); if (defaultCommand != null && !defaultGroupCommands.contains(defaultCommand)) { allCommands.add(defaultCommand); } for (CommandGroupMetadata group : groups) { allCommands.addAll(group.getCommands()); if (group.getDefaultCommand() != null) { allCommands.add(group.getDefaultCommand()); } Queue<CommandGroupMetadata> subGroupsQueue = new LinkedList<CommandGroupMetadata>(); subGroupsQueue.addAll(group.getSubGroups()); while (subGroupsQueue.size() > 0) { CommandGroupMetadata subGroup = subGroupsQueue.poll(); allCommands.addAll(subGroup.getCommands()); if (subGroup.getDefaultCommand() != null) allCommands.add(subGroup.getDefaultCommand()); subGroupsQueue.addAll(subGroup.getSubGroups()); } } // Post-process to find possible further group assignments loadCommandsIntoGroupsByAnnotation(allCommands, groups, defaultGroupCommands); return loadGlobal(cliConfig.name(), cliConfig.description(), defaultCommand, defaultGroupCommands, groups, restrictions, parserConfig); }