Example usage for java.util Iterator toString

List of usage examples for java.util Iterator toString

Introduction

In this page you can find the example usage for java.util Iterator toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:ch.entwine.weblounge.common.url.UrlUtils.java

/**
 * Sorts the given urls by path./* w  ww  . ja v a 2s.  c  o m*/
 * 
 * @param urls
 *          the urls to sort
 * @return the sorted urls
 */
public static String[] sort(String[] urls) {
    TreeSet<String> set = new TreeSet<String>();
    for (int i = 0; i < urls.length; i++)
        set.add(urls[i]);
    String[] result = new String[urls.length];
    Iterator<String> i = set.iterator();
    int index = 0;
    while (i.hasNext()) {
        result[index++] = i.toString();
    }
    return result;
}

From source file:controllers.user.UserGroupsApp.java

/**
 * ?//w  w w .j  a  v a 2 s  .  c om
 * @throws IOException 
 */
@BodyParser.Of(BodyParser.Json.class)
@Transactional
public static Result createMultiCommunicate() throws IOException {
    JsonNode json = request().body().asJson();
    Iterator<JsonNode> userIds = json.findPath("userIds").iterator();
    List<Long> userIdList = new ArrayList<Long>();
    if (!userIds.hasNext()) {
        return ok("{\"status\":\"0\",\"error\":\"userIds??\"}");
    }
    while (userIds.hasNext()) {
        Long userId = userIds.next().asLong();
        userIdList.add(userId);
    }
    Logger.info("userIds --------> " + userIds.toString());

    User me = User.getFromSession(session());
    ObjectNodeResult result = null;
    result = ChatService.createMultiCommunicateGroup(me, userIdList);
    return ok(result.getObjectNode());
}

From source file:net.csthings.cassinate.CassinateHelper.java

public void dropAllTables(String keyspaceName) {
    Iterator<TableMetadata> tables = cluster.getMetadata().getKeyspace(keyspaceName).getTables().iterator();
    LOG.debug("Truncating tables: {}", tables.toString());
    tables.forEachRemaining(//from  w  ww.j  a v  a2  s  .  co  m
            t -> session.executeAsync(String.format("DROP TABLE %s.%s ;", keyspaceName, t.getName())));
}

From source file:org.apache.hadoop.hbase.regionserver.DataBlockEncodingTool.java

/**
 * Verify if all data block encoders are working properly.
 *
 * @param scanner Of file which was compressed.
 * @param kvLimit Maximal count of KeyValue which will be processed.
 * @return true if all data block encoders compressed/decompressed correctly.
 * @throws IOException thrown if scanner is invalid
 *//*ww w  .j a  v a2  s.com*/
public boolean verifyCodecs(final KeyValueScanner scanner, final int kvLimit) throws IOException {
    KeyValue currentKv;

    scanner.seek(KeyValue.LOWESTKEY);
    List<Iterator<Cell>> codecIterators = new ArrayList<Iterator<Cell>>();
    for (EncodedDataBlock codec : codecs) {
        codecIterators.add(codec.getIterator(HFileBlock.headerSize(useHBaseChecksum)));
    }

    int j = 0;
    while ((currentKv = KeyValueUtil.ensureKeyValue(scanner.next())) != null && j < kvLimit) {
        // Iterates through key/value pairs
        ++j;
        for (Iterator<Cell> it : codecIterators) {
            Cell c = it.next();
            KeyValue codecKv = KeyValueUtil.ensureKeyValue(c);
            if (codecKv == null || 0 != Bytes.compareTo(codecKv.getBuffer(), codecKv.getOffset(),
                    codecKv.getLength(), currentKv.getBuffer(), currentKv.getOffset(), currentKv.getLength())) {
                if (codecKv == null) {
                    LOG.error("There is a bug in codec " + it + " it returned null KeyValue,");
                } else {
                    int prefix = 0;
                    int limitLength = 2 * Bytes.SIZEOF_INT
                            + Math.min(codecKv.getLength(), currentKv.getLength());
                    while (prefix < limitLength && codecKv.getBuffer()[prefix
                            + codecKv.getOffset()] == currentKv.getBuffer()[prefix + currentKv.getOffset()]) {
                        prefix++;
                    }

                    LOG.error("There is bug in codec " + it.toString() + "\n on element " + j
                            + "\n codecKv.getKeyLength() " + codecKv.getKeyLength()
                            + "\n codecKv.getValueLength() " + codecKv.getValueLength()
                            + "\n codecKv.getLength() " + codecKv.getLength() + "\n currentKv.getKeyLength() "
                            + currentKv.getKeyLength() + "\n currentKv.getValueLength() "
                            + currentKv.getValueLength() + "\n codecKv.getLength() " + currentKv.getLength()
                            + "\n currentKV rowLength " + currentKv.getRowLength() + " familyName "
                            + currentKv.getFamilyLength() + " qualifier " + currentKv.getQualifierLength()
                            + "\n prefix " + prefix + "\n codecKv   '"
                            + Bytes.toStringBinary(codecKv.getBuffer(), codecKv.getOffset(), prefix)
                            + "' diff '"
                            + Bytes.toStringBinary(codecKv.getBuffer(), codecKv.getOffset() + prefix,
                                    codecKv.getLength() - prefix)
                            + "'" + "\n currentKv '"
                            + Bytes.toStringBinary(currentKv.getBuffer(), currentKv.getOffset(), prefix)
                            + "' diff '" + Bytes.toStringBinary(currentKv.getBuffer(),
                                    currentKv.getOffset() + prefix, currentKv.getLength() - prefix)
                            + "'");
                }
                return false;
            }
        }
    }

    LOG.info("Verification was successful!");

    return true;
}

From source file:org.jahia.services.workflow.WorkflowService.java

public List<JahiaPrincipal> getAssignedRole(WorkflowDefinition definition, String activityName,
        String processId, JCRSessionWrapper session) throws RepositoryException {
    List<JahiaPrincipal> principals = Collections.emptyList();
    Map<String, String> perms = workflowRegistrationByDefinition.get(definition.getKey()).getPermissions();
    String permPath = perms != null ? perms.get(activityName) : null;
    if (permPath == null) {
        return principals;
    }//ww w .  j  a v  a 2 s .c o m

    Workflow w = getWorkflow(definition.getProvider(), processId, null);
    JCRNodeWrapper node = session.getNodeByIdentifier((String) w.getVariables().get("nodeId"));
    if (permPath.indexOf("$") > -1) {
        if (w != null) {
            for (Map.Entry<String, Object> entry : w.getVariables().entrySet()) {
                Object value = entry.getValue();
                if (value instanceof List) {
                    List<?> list = (List<?>) entry.getValue();
                    StringBuilder sb = new StringBuilder();
                    Iterator<?> iterator = list.iterator();
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if (o instanceof WorkflowVariable) {
                            sb.append(((WorkflowVariable) o).getValue());
                        }
                        if (iterator.hasNext()) {
                            sb.append(",");
                        }
                    }
                    permPath = permPath.replace("$" + entry.getKey(), iterator.toString());
                } else if (value instanceof WorkflowVariable) {
                    permPath = permPath.replace("$" + entry.getKey(), ((WorkflowVariable) value).getValue());
                }
            }
        }
    }
    try {
        if (!permPath.contains("/")) {
            Query q = session.getWorkspace().getQueryManager().createQuery(
                    "select * from [jnt:permission] where name()='" + JCRContentUtils.sqlEncode(permPath) + "'",
                    Query.JCR_SQL2);
            NodeIterator ni = q.execute().getNodes();
            if (ni.hasNext()) {
                permPath = StringUtils.substringAfter(ni.nextNode().getPath(), "/permissions");

            } else {
                return principals;
            }
        }

        Set<String> roles = new HashSet<String>();
        Set<String> extPerms = new HashSet<String>();

        while (!StringUtils.isEmpty(permPath)) {
            String permissionName = permPath.contains("/") ? StringUtils.substringAfterLast(permPath, "/")
                    : permPath;
            NodeIterator ni = session.getWorkspace().getQueryManager()
                    .createQuery("select * from [jnt:role] where [j:permissionNames] = '"
                            + JCRContentUtils.sqlEncode(permissionName) + "'", Query.JCR_SQL2)
                    .execute().getNodes();
            while (ni.hasNext()) {
                JCRNodeWrapper roleNode = (JCRNodeWrapper) ni.next();
                roles.add(roleNode.getName());
            }
            ni = session.getWorkspace().getQueryManager()
                    .createQuery("select * from [jnt:externalPermissions] where [j:permissionNames] = '"
                            + JCRContentUtils.sqlEncode(permissionName) + "'", Query.JCR_SQL2)
                    .execute().getNodes();
            while (ni.hasNext()) {
                JCRNodeWrapper roleNode = (JCRNodeWrapper) ni.next();
                extPerms.add(roleNode.getParent().getName() + "/" + roleNode.getName());
            }
            permPath = permPath.contains("/") ? StringUtils.substringBeforeLast(permPath, "/") : "";
        }

        Map<String, List<String[]>> m = node.getAclEntries();
        principals = new LinkedList<JahiaPrincipal>();
        JahiaUserManagerService userService = ServicesRegistry.getInstance().getJahiaUserManagerService();
        JahiaGroupManagerService groupService = ServicesRegistry.getInstance().getJahiaGroupManagerService();

        JCRSiteNode site = null;

        for (Map.Entry<String, List<String[]>> entry : m.entrySet()) {
            for (String[] strings : entry.getValue()) {
                if (strings[1].equals("GRANT") && roles.contains(strings[2])
                        || strings[1].equals("EXTERNAL") && extPerms.contains(strings[2])) {
                    String principal = entry.getKey();
                    final String principalName = principal.substring(2);
                    if (site == null) {
                        site = node.getResolveSite();
                    }
                    if (principal.charAt(0) == 'u') {
                        JCRUserNode userNode = userService.lookupUser(principalName,
                                strings[0].startsWith("/sites/") ? site.getSiteKey() : null);
                        if (userNode != null) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("user " + userNode.getUserKey() + " is granted");
                            }
                            JahiaUser jahiaUser = userNode.getJahiaUser();
                            principals.add(jahiaUser);
                        }
                    } else if (principal.charAt(0) == 'g') {
                        JCRGroupNode group = groupService.lookupGroup(site.getSiteKey(), principalName);
                        if (group == null) {
                            group = groupService.lookupGroup(null, principalName);
                        }
                        if (group != null) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("group " + group.getGroupKey() + " is granted");
                            }
                            principals.add(group.getJahiaGroup());
                        }
                    }
                }
            }
        }
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    } catch (BeansException e) {
        logger.error(e.getMessage(), e);
    }
    return principals;
}

From source file:org.javafunk.funk.iterators.ComprehensionIteratorTest.java

@Test
@SuppressWarnings("unchecked")
public void shouldIncludeTheIteratorFunctionInTheToStringRepresentation() throws Exception {
    // Given//from  w w  w.  j a v a 2 s. co m
    UnaryFunction<Integer, Integer> mapper = UnaryFunctions.identity();
    Iterator<Integer> input = (Iterator<Integer>) mock(Iterator.class);
    Predicate<Integer> predicate = Predicates.alwaysTrue();

    when(input.toString()).thenReturn("the-iterator");

    ComprehensionIterator<Integer, Integer> iterator = new ComprehensionIterator<Integer, Integer>(mapper,
            input, listWith(predicate));

    // When
    String toString = iterator.toString();

    // Then
    assertThat(toString, containsString("the-iterator"));
}

From source file:org.opencms.db.CmsSecurityManager.java

/**
 * Writes a new URL name mapping for a given resource.<p>
 * /*from  w  w w.jav  a2 s .co  m*/
 * The first name from the given sequence which is not already mapped to another resource will be used for 
 * the URL name mapping.<p>
 * 
 * @param context the request context 
 * @param nameSeq the sequence of URL name candidates  
 * @param structureId the structure id which should be mapped to the name
 * @param locale the locale for the mapping 
 *  
 * @return the name which was actually mapped to the structure id
 *  
 * @throws CmsException if something goes wrong 
 */
public String writeUrlNameMapping(CmsRequestContext context, Iterator<String> nameSeq, CmsUUID structureId,
        String locale) throws CmsException {

    CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
    try {
        return m_driverManager.writeUrlNameMapping(dbc, nameSeq, structureId, locale);
    } catch (Exception e) {
        CmsMessageContainer message = Messages.get().container(Messages.ERR_ADD_URLNAME_MAPPING_2,
                nameSeq.toString(), structureId.toString());
        dbc.report(null, message, e);
        return null;
    } finally {
        dbc.clear();
    }
}