List of usage examples for java.util Set toArray
<T> T[] toArray(T[] a);
From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppTestAccountUser.java
@Test public void testCRUDAccountUser() throws NoSuchAlgorithmException, InvalidKeySpecException { logger.info("testCRUDAccountUser: Sequence start"); logger.info("testCRUDAccountUser: Create"); Integer userId = null;//from w w w .j a v a 2 s .c o m Integer accountId = null; User userResult = null; Account accountResult = null; AccountUser accountUserResult; AccountUser accountUser = null; try { // // Create a user // String userName = "Desperate Dan"; String userEmail = "ddan@beano.com"; String userPassword = "1403772743"; Date createDate = getDateWithoutMillis(); String msg = "What time is it?"; // User user = new SimpleUser(); user.setUserName(userName); user.setUserEmail(userEmail); // user.setPasswordSalt(PasswordAuthentication.generateSalt()); // user.setUserPassword(PasswordAuthentication.getEncryptedPassword(userPassword, user.getPasswordSalt())); user.setPasswordSalt(salt); user.setUserPassword(encoder.encode(userPassword).getBytes()); // user.setActive(ACTIVE); user.setEnabled(true); user.setCreateDate(createDate); // // Persist it and test // userResult = instance.createUser(user); assertThat(userResult, is(notNullValue())); assertThat(userResult.getId(), is(notNullValue())); userId = userResult.getId(); // New, so should not have any accounts assertThat(userResult.getAccounts(), is(nullValue())); // // Create an Account // String resourceName = "1403696013.db"; // Account account = new SimpleAccount(); account.setResourceName(resourceName); // account.setActive(ACTIVE); user.setEnabled(true); account.setCreateDate(createDate); account.setApplicationId(APPLICATION1); // accountResult = instance.createAccount(account); // assertThat(accountResult, is(notNullValue())); assertThat(accountResult.getId(), is(notNullValue())); accountId = accountResult.getId(); // // Create the Account User // accountUser = new SimpleAccountUser(); accountUser.setAccountId(accountId); accountUser.setUserId(userId); // accountUser.setActive(ACTIVE); accountUser.setEnabled(true); accountUser.setCreateDate(createDate); accountUser.setLastAccessDate(createDate); accountUser.setAccessLevelId(OWNER); accountUser.setAccountMessage(msg); // accountUserResult = instance.createAccountUser(accountUser); assertThat(accountUserResult, is(notNullValue())); // // // logger.info("testCRUDAccountUser: Read"); accountUserResult = instance.getAccountUser(accountUser); assertEquals(userId, accountUserResult.getUserId()); assertEquals(accountId, accountUserResult.getAccountId()); // assertEquals(ACTIVE, accountUserResult.getActive()); assertEquals(true, accountUserResult.isEnabled()); assertEquals(createDate, accountUserResult.getCreateDate()); assertEquals(createDate, accountUserResult.getLastAccessDate()); assertEquals(OWNER, accountUserResult.getAccessLevelId()); assertEquals(msg, accountUserResult.getAccountMessage()); // // Re-read the user, it should now have an account // userResult = instance.getUser(user.getId()); assertThat(userResult, is(notNullValue())); Set<? extends Account> accounts = userResult.getAccounts(); assertThat(accounts, is(notNullValue())); assertFalse(accounts.isEmpty()); assertEquals(1, accounts.size()); Account linkedAccount = accounts.toArray(new Account[0])[0]; assertThat(linkedAccount, is(notNullValue())); assertEquals(linkedAccount.getId(), accountId); // // Perform updates // msg = "It's cow pie time!"; createDate = getDateWithoutMillis(); accountUser.setLastAccessDate(createDate); // accountUser.setActive(INACTIVE); accountUser.setEnabled(false); accountUser.setAccessLevelId(GUEST); accountUser.setAccountMessage(msg); // logger.info("testCRUDAccountUser: Update"); accountUserResult = instance.updateAccountUser(accountUser); assertEquals(userId, accountUserResult.getUserId()); assertEquals(accountId, accountUserResult.getAccountId()); // assertEquals(INACTIVE, accountUserResult.getActive()); assertEquals(false, accountUserResult.isEnabled()); assertEquals(createDate, accountUserResult.getLastAccessDate()); assertEquals(GUEST, accountUserResult.getAccessLevelId()); assertEquals(msg, accountUserResult.getAccountMessage()); } finally { // // Delete User and test // logger.info("testCRUDAccountUser: Delete"); instance.deleteUser(userResult); userResult = instance.getUser(userId); assertThat(userResult, is(nullValue())); // // Account User should be gone // accountUserResult = instance.getAccountUser(accountUser); assertThat(accountUserResult, is(nullValue())); // // Delete Account and test // instance.deleteAccount(accountResult); accountResult = instance.getAccount(accountId); assertThat(accountResult, is(nullValue())); } }
From source file:com.hmsinc.epicenter.classifier.lm.AbstractLMClassifier.java
@Override @SuppressWarnings("unchecked") protected synchronized void doInit(ClassifierConfig config) throws Exception { Validate.notNull(config.getTrainingSet(), "Training set was null!"); Validate.notNull(config.getTrainingSet().getCategories(), "No categories are defined."); // Extract categories final Set<String> categories = new HashSet<String>(); for (Category category : config.getTrainingSet().getCategories()) { categories.add(category.getName()); if (category.isIgnore() != null && category.isIgnore()) { ignoredCategories.add(category.getName()); }//from w ww . j a va 2 s .c o m } final NaiveBayesClassifier nbc = new NaiveBayesClassifier(categories.toArray(new String[categories.size()]), new IndoEuropeanTokenizerFactory(), (config.getNgramSize() == null ? DEFAULT_NGRAM_SIZE : config.getNgramSize())); // Train the classifier for (Category category : config.getTrainingSet().getCategories()) { logger.debug("Training category: {}", category.getName()); for (Entry entry : category.getEntries()) { if (entry.getValue() == null) { logger.warn("Null value in training set!"); } else if (entry.getType() == null || entry.getType().equals(EntryType.WORD)) { nbc.train(category.getName(), entry.getValue()); } } } logger.debug("Compiling the classifier.."); classifier = (LMClassifier) AbstractExternalizable.compile(nbc); }
From source file:org.tonguetied.usermanagement.User.java
/** * Convenience method to remove a {@link UserRight} from this User. If the * UserRight does not exist then no action is taken. * //from www.j a va 2 s .com * @param userRight the authorized permission to remove * @throws IllegalArgumentException if the <tt>userRight</tt> is * <tt>null</tt> or the <tt>permission</tt> is <tt>null</tt> */ public void removeUserRight(UserRight userRight) { if (userRight == null || userRight.getPermission() == null) { throw new IllegalArgumentException("userRight cannot be null"); } this.userRights.remove(userRight); final GrantedAuthority authority = new GrantedAuthorityImpl(userRight.getPermission().name()); Set<GrantedAuthority> authorities = getAuthoritiesAsSet(); authorities.remove(authority); this.setAuthorities(authorities.toArray(new GrantedAuthority[authorities.size()])); }
From source file:com.uberspot.storageutils.StorageUtils.java
protected String stringSetToJsonString(Set<String> set) { JSONObject json = new JSONObject(); try {//from w w w .j a v a2 s. com json.put("size", set.size()); String[] setString = set.toArray(new String[set.size()]); for (int i = 0; i < setString.length; i++) { json.put(Integer.toString(i), setString[i]); } } catch (JSONException e) { e.printStackTrace(); } return json.toString(); }
From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java
/** * List directory contents for a resource folder. Not recursive. This is * basically a brute-force implementation. Works for regular files and also * JARs./*from www . j av a 2 s . co m*/ * * @author Greg Briggs * @param path Should end with "/", but not start with one. * @return Just the name of each member item, not the full paths. * @throws URISyntaxException * @throws IOException */ public static String[] getResourceListing(String path) throws URISyntaxException, IOException { URL dirURL = Utils.class.getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ return new File(dirURL.toURI()).list(); } if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ String me = Utils.class.getName().replace(".", "/") + ".class"; dirURL = Utils.class.getClassLoader().getResource(me); } if (dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ String parent = (new File(dirURL.toURI()).getParent()); return new File(parent + "/../../../../../../resources/" + path).list(); } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar Set<String> result = new HashSet<>(); //avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { //filter according to the path String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = entry.substring(0, checkSubdir); } result.add(entry); } } return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:com.bluecloud.ioc.parse.KernelXMLParser.java
/** * <h3>XML?</h3> ?XML???Shcema?XMLXML * //from ww w .j av a 2 s .c om * @param xmlPath * XML?URL * @throws KernelXMLParserException */ private void load(URL[] xmlPath) throws KernelXMLParserException { Set<URL> urls = new LinkedHashSet<URL>(); for (URL url : xmlPath) { try { InputStream is = url.openStream(); validator.validate(new StreamSource(is)); urls.add(url); is.close(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(url.toString() + "?"); } } } this.validatedXML = urls.toArray(new URL[urls.size()]); }
From source file:org.waarp.gateway.kernel.rest.RestMethodHandler.java
/** * Will assign the intersection of both set of Methods * //w w w .ja v a2 s. c om * @param selectedMethods * the selected Methods among available * @param validMethod * the validMethod for this handler */ protected void setIntersectionMethods(METHOD[] selectedMethods, METHOD... validMethod) { Set<METHOD> set = new HashSet<METHOD>(); for (METHOD method : validMethod) { set.add(method); } Set<METHOD> set2 = new HashSet<METHOD>(); for (METHOD method : selectedMethods) { set2.add(method); } set.retainAll(set2); METHOD[] methodsToSet = set.toArray(new METHOD[0]); setMethods(methodsToSet); }
From source file:net.duckling.ddl.service.devent.listener.AbstractEventListener.java
protected void appendRecommendNotice(DEvent e) { String[] recipients = getDirectRecipients(e); appendNoticeList(e, recipients, NoticeRule.REASON_RECOMMEND); noticeService.increaseNoticeCount(recipients, e.getEventBody().getTid(), NoticeRule.PERSON_NOTICE, e.getEventBody().getId());//from www . j a v a2s . co m Set<String> email = new HashSet<String>(); if (recipients != null) { for (String r : recipients) { SimpleUser user = aoneUserService.getSimpleUserByUid(r); if (user != null) { email.add(user.getEmail()); } } } String[] emails = email.toArray(new String[email.size()]); aoneMailService.sendEmail(e, emails); }
From source file:com.orangeleap.common.security.OrangeLeapLdapAuthoritiesPopulator.java
/** * Obtains the authorities for the user who's directory entry is represented by * the supplied LdapUserDetails object./*from ww w. j ava2s . co m*/ * * @param user the user who's authorities are required * @return the set of roles granted to the user. */ public final GrantedAuthority[] getGrantedAuthorities(DirContextOperations user, String username) { String userDn = user.getNameInNamespace(); if (logger.isDebugEnabled()) { logger.debug("Getting authorities for user " + userDn); } Set roles = getGroupMembershipRoles(userDn, username); Set extraRoles = getAdditionalRoles(user, username); if (extraRoles != null) { roles.addAll(extraRoles); } if (defaultRole != null) { roles.add(defaultRole); } return (GrantedAuthority[]) roles.toArray(new GrantedAuthority[roles.size()]); }
From source file:de.berlios.gpon.wui.actions.data.ItemSearchAction.java
private void addAssociatedProperties(List idMapped, HashMap associatedPropertyMap) { // build up a pathDigest -> ipd-List mapping final Hashtable pathAndProperties = new Hashtable(); CollectionUtils.forAllDo(associatedPropertyMap.keySet(), new Closure() { // foreach key in associatedPropertyMap do: public void execute(Object o) { String key = (String) o; String[] keySplit = ItemSearchForm.splitAssociatedPropertyKey(key); String pathDigest = keySplit[0]; String ipdId = keySplit[1]; if (!pathAndProperties.containsKey(pathDigest)) { pathAndProperties.put(pathDigest, new ArrayList()); }/*from w w w .j av a2 s. c o m*/ ((List) pathAndProperties.get(pathDigest)).add(new Long(ipdId)); } }); final String[] digests = (String[]) Collections.list(pathAndProperties.keys()).toArray(new String[0]); final PathResolver pathResolver = (PathResolver) getObjectForBeanId("pathResolver"); CollectionUtils.forAllDo(idMapped, new Closure() { public void execute(Object o) { ItemMap im = (ItemMap) o; // foreach digest for (int digIdx = 0; digIdx < digests.length; digIdx++) { String digest = digests[digIdx]; Set items = pathResolver.getItemsForPath(im.getItem().getId(), digest); if (items != null && items.size() > 0) { if (items.size() > 1) { throw new RuntimeException("more than one associated item found"); } // get one & only item Item item = ((Item[]) items.toArray(new Item[0]))[0]; Long[] ipds = (Long[]) ((List) pathAndProperties.get(digest)).toArray(new Long[0]); ItemMappedById associatedImbi = new ItemMappedById(item); for (int ipdIdx = 0; ipdIdx < ipds.length; ipdIdx++) { Value value = associatedImbi.getValueObject(ipds[ipdIdx] + ""); if (value != null) { im.addAdditionalAttribute(digest + "|" + ipds[ipdIdx], value); } } } } } }); }