Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

In this page you can find the example usage for java.util StringTokenizer hasMoreElements.

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:com.likemag.cordova.inappbrowsercustom.InAppBrowser.java

/**
 * Put the list of features into a hash map
 * /* ww w.  java 2s .  c  o  m*/
 * @param optString
 * @return
 */
private HashMap<String, Boolean> parseFeature(String optString) {
    if (optString.equals(NULL)) {
        return null;
    } else {
        HashMap<String, Boolean> map = new HashMap<String, Boolean>();
        StringTokenizer features = new StringTokenizer(optString, ",");
        StringTokenizer option;

        while (features.hasMoreElements()) {
            option = new StringTokenizer(features.nextToken(), "=");
            if (option.hasMoreElements()) {
                String key = option.nextToken();
                Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
                map.put(key, value);
            }
        }
        return map;
    }
}

From source file:org.bibalex.gallery.model.BAGImage.java

public BAGImage(BAGGalleryAbstract gallery, BAGAlbum album, String name, long viewPaneWidth,
        long viewPaneHeight) throws BAGException {
    super();/*from   w  ww .j  av a2s  . c  o m*/
    this.gallery = gallery;
    this.album = album;
    this.name = name;
    HttpGet djatokaReq = null;
    try {

        this.highResUrlStr = this.gallery.getImageDirectAccUrlStr(album.getName(), name, EnumResolutions.high);

        // this.highResUrlEncoded = this.highResUrlStr.replaceAll(" ", "%20");
        // new URLCodec("US-ASCII").encode(this.highResUrlStr);

        this.thumbLocalUrl = this.gallery.getThumbLocalUrl(this.album.getName(), this.name);

        Integer tempFullWidth = null;
        Integer tempFullHeight = null;
        Integer tempZoomLevels = null;

        // Execute HTTP request
        this.httpclient = new DefaultHttpClient();

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("url_ver", "Z39.88-2004"));
        qparams.add(new BasicNameValuePair("rft_id", this.highResUrlStr)); // "http://memory.loc.gov/gmd/gmd433/g4330/g4330/np000066.jp2"));
        qparams.add(new BasicNameValuePair("svc_id", "info:lanl-repo/svc/getMetadata"));

        URI serverUri = new URI(gallery.getDjatokaServerUrlStr());

        URI reqUri = URIUtils.createURI(serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(),
                serverUri.getPath(), URLEncodedUtils.format(qparams, "US-ASCII"), null);

        djatokaReq = new HttpGet(reqUri);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting metadata of image via URL: " + djatokaReq.getURI());
        }

        HttpResponse response = this.httpclient.execute(djatokaReq);

        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            throw new BAGException("Connection error: " + response.getStatusLine().toString());
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response from URL: " + djatokaReq.getURI() + " => " + response.getStatusLine());
        }

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if ((entity != null)) {

            entity = new BufferedHttpEntity(entity);

            if ("application/json".equalsIgnoreCase(entity.getContentType().getValue())) {
                // Since the djatoka returned JSON is not properly escaped and I cannot find
                // any library that escapes JSON while parsing it I had to do this:
                String jsonString = EntityUtils.toString(entity);

                // remove the braces:
                jsonString = jsonString.substring(1);
                jsonString = jsonString.substring(0, jsonString.length() - 1);

                StringTokenizer pairTokens = new StringTokenizer(jsonString, ",", false);
                while (pairTokens.hasMoreElements()) {
                    String pair = pairTokens.nextToken().trim();

                    int colonIx = pair.indexOf(':');
                    String memberName = pair.substring(0, colonIx);
                    memberName = memberName.substring(1);
                    memberName = memberName.substring(0, memberName.length() - 1);

                    String memberValue = pair.substring(colonIx + 1).trim();
                    memberValue = memberValue.substring(memberValue.indexOf('"') + 1);
                    memberValue = memberValue.substring(0, memberValue.lastIndexOf('"'));

                    if ("width".equals(memberName)) {
                        tempFullWidth = Integer.valueOf(memberValue);
                    } else if ("height".equals(memberName)) {
                        tempFullHeight = Integer.valueOf(memberValue);
                    } else if ("levels".equals(memberName)) {
                        // FIXME replace "dwtLevels" by "levels" according to
                        // http://sourceforge.net/apps/mediawiki/djatoka/index.php?title=Djatoka_Level_Logic
                        // "dwtLevels" are the native JP2 DWT levels
                        tempZoomLevels = Integer.valueOf(memberValue);
                    }
                }

            }
        }

        if ((tempFullWidth == null) || (tempFullHeight == null) || (tempZoomLevels == null)) {
            throw new BAGException("Cannot retrieve metadata!");
        } else {
            this.fullWidth = tempFullWidth;
            this.fullHeight = tempFullHeight;
            this.zoomLevels = tempZoomLevels;
        }

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        djatokaReq.abort();
        throw ex;

    } catch (URISyntaxException e) {
        throw new BAGException(e);
        // } catch (EncoderException e) {
        // throw new BAGException(e);
    } finally {
        // connection kept alive and closed in finalize
    }

    this.djatokaParams = new ArrayList<NameValuePair>();
    this.djatokaParams.add(new BasicNameValuePair("url_ver", "Z39.88-2004"));
    this.djatokaParams.add(new BasicNameValuePair("rft_id", this.highResUrlStr)); // "http://memory.loc.gov/gmd/gmd433/g4330/g4330/np000066.jp2"));
    this.djatokaParams.add(new BasicNameValuePair("svc_id", "info:lanl-repo/svc/getRegion"));
    this.djatokaParams.add(new BasicNameValuePair("svc_val_fmt", "info:ofi/fmt:kev:mtx:jpeg2000"));
    this.djatokaParams.add(new BasicNameValuePair("svc.format", "image/jpeg"));

    this.zoomedX = 0;
    this.zoomedY = 0;
    this.zoomedWidth = this.fullWidth;
    this.zoomedHeight = this.fullHeight;
    this.zoomedRotate = 0;

    this.viewPaneHeight = viewPaneHeight;
    this.viewPaneWidth = viewPaneWidth;
    this.calculateDjatokaLevel();
    this.updateZoomedBytes();

    String lowResCache = URLPathStrUtils.appendParts(this.gallery.cacheLocalPath, "low");
    File tempJpg = new File(URLPathStrUtils.appendParts(lowResCache, name + ".jpg"));
    try {

        if (!tempJpg.exists()) {
            synchronized (BAGImage.class) {
                new File(lowResCache).mkdirs();
                tempJpg.createNewFile();
                FileOutputStream tempJpgOs = new FileOutputStream(tempJpg);
                ByteArrayInputStream temlJpgIS = new ByteArrayInputStream(this.zoomedBytes);
                try {
                    byte buffer[] = new byte[10240];
                    int bytesRead = 0;
                    do {
                        bytesRead = temlJpgIS.read(buffer);
                        if (bytesRead > 0) {
                            tempJpgOs.write(buffer, 0, bytesRead);
                        } else {
                            break;
                        }
                    } while (true);

                } finally {
                    tempJpgOs.flush();
                    tempJpgOs.close();

                }
            }
        }

    } catch (IOException e) {
        LOG.error("Couldn't create local cached version of low resolution version of: " + name);
        tempJpg = null;
    }
    if (tempJpg != null) {
        String ctxRootURL = new File(this.gallery.contextRootPath).toURI().toString();
        this.lowResLocalUrl = tempJpg.toURI().toString().substring(ctxRootURL.length());

    } else {
        this.lowResLocalUrl = this.thumbLocalUrl;
    }

}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 * This method overwrites the method in LDAPUserStoreManager. This implements the functionality
 * of updating user's profile information in LDAP user store.
 *
 * @param userName/*ww w. ja  v  a  2s .c  o m*/
 * @param claims
 * @param profileName
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public void doSetUserClaimValues(String userName, Map<String, String> claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    boolean cnModified = false;
    String cnValue = null;

    try {

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        returnedUserEntry = returnedResultList.next().getName();

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    if (profileName == null) {
        profileName = UserCoreConstants.DEFAULT_PROFILE;
    }

    if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) {
        claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);

        String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1
                ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0]
                : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME);
        for (Map.Entry<String, String> claimEntry : claims.entrySet()) {
            String claimURI = claimEntry.getKey();
            // if there is no attribute for profile configuration in LDAP,
            // skip updating it.
            if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                continue;
            }
            // get the claimMapping related to this claimURI
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            //remove user DN from cache if changing username attribute
            if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) {
                userCache.remove(userName);
            }
            // if mapped attribute is CN, then skip treating as a modified
            // attribute -
            // it should be an object rename
            if ("CN".toLowerCase().equals(attributeName.toLowerCase())) {
                cnModified = true;
                cnValue = claimEntry.getValue();
                continue;
            }
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            /* if updated attribute value is null, remove its values. */
            if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                currentUpdatedAttribute.clear();
            } else {
                if (claimEntry.getValue() != null) {
                    String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                    if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                        userAttributeSeparator = claimSeparator;
                    }
                    if (claimEntry.getValue().contains(userAttributeSeparator)) {
                        StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator);
                        while (st.hasMoreElements()) {
                            String newVal = st.nextElement().toString();
                            if (newVal != null && newVal.trim().length() > 0) {
                                currentUpdatedAttribute.add(newVal.trim());
                            }
                        }
                    } else {
                        currentUpdatedAttribute.add(claimEntry.getValue());
                    }
                } else {
                    currentUpdatedAttribute.add(claimEntry.getValue());
                }
            }
            updatedAttributes.put(currentUpdatedAttribute);
        }
        // update the attributes in the relevant entry of the directory
        // store

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

        if (cnModified && cnValue != null) {
            subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue));
        }

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMessage = "Error in obtaining claim mapping for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv1Reader.java

/**
 * Iterate through all lines and get available annotations<br>
 * First column is sentence number and a blank new line marks end of a sentence<br>
 * The Second column is the token <br>
 * The third column is the lemma annotation <br>
 * The fourth column is the POS annotation <br>
 * The fifth column is used for Named Entity annotations (Multiple annotations separeted by |
 * character) <br>/*from   ww  w  .j  ava 2  s . c om*/
 * The sixth column is the origin token number of dependency parsing <br>
 * The seventh column is the function/type of the dependency parsing <br>
 * eighth and ninth columns are undefined currently
 */
private void setAnnotations(InputStream aIs, String aEncoding, StringBuilder text, Map<Integer, String> tokens,
        Map<Integer, String> pos, Map<Integer, String> lemma, Map<Integer, String> namedEntity,
        Map<Integer, String> dependencyFunction, Map<Integer, Integer> dependencyDependent,
        List<Integer> firstTokenInSentence) throws IOException {
    int tokenNumber = 0;
    boolean first = true;
    int base = 0;

    LineIterator lineIterator = IOUtils.lineIterator(aIs, aEncoding);
    boolean textFound = false;
    StringBuffer tmpText = new StringBuffer();
    while (lineIterator.hasNext()) {
        String line = lineIterator.next().trim();
        if (line.startsWith("#text=")) {
            text.append(line.substring(6) + "\n");
            textFound = true;
            continue;
        }
        if (line.startsWith("#")) {
            continue;// it is a comment line
        }
        int count = StringUtils.countMatches(line, "\t");
        if (line.isEmpty()) {
            continue;
        }
        if (count != 9) {// not a proper TSV file
            getUimaContext().getLogger().log(Level.INFO, "This is not a valid TSV File");
            throw new IOException(fileName + " This is not a valid TSV File");
        }
        StringTokenizer lineTk = new StringTokenizer(line, "\t");

        if (first) {
            tokenNumber = Integer.parseInt(line.substring(0, line.indexOf("\t")));
            firstTokenInSentence.add(tokenNumber);
            first = false;
        } else {
            int lineNumber = Integer.parseInt(line.substring(0, line.indexOf("\t")));
            if (lineNumber == 1) {
                base = tokenNumber;
                firstTokenInSentence.add(base);
            }
            tokenNumber = base + Integer.parseInt(line.substring(0, line.indexOf("\t")));
        }

        while (lineTk.hasMoreElements()) {
            lineTk.nextToken();
            String token = lineTk.nextToken();

            // for backward compatibility
            tmpText.append(token + " ");

            tokens.put(tokenNumber, token);
            lemma.put(tokenNumber, lineTk.nextToken());
            pos.put(tokenNumber, lineTk.nextToken());
            String ne = lineTk.nextToken();
            lineTk.nextToken();// make it compatible with prev WebAnno TSV reader
            namedEntity.put(tokenNumber, (ne.equals("_") || ne.equals("-")) ? "O" : ne);
            String dependentValue = lineTk.nextToken();
            if (NumberUtils.isDigits(dependentValue)) {
                int dependent = Integer.parseInt(dependentValue);
                dependencyDependent.put(tokenNumber, dependent == 0 ? 0 : base + dependent);
                dependencyFunction.put(tokenNumber, lineTk.nextToken());
            } else {
                lineTk.nextToken();
            }
            lineTk.nextToken();
            lineTk.nextToken();
        }
    }
    if (!textFound) {
        text.append(tmpText);
    }
}

From source file:com.jamiealtizer.cordova.inappbrowser.InAppBrowser.java

/**
 * Put the list of features into a hash map
 *
 * @param optString/*w  w  w. j a va  2 s .  c o  m*/
 * @return
 */
private HashMap<String, Boolean> parseFeature(String optString) {
    if (optString.equals(NULL)) {
        return null;
    } else {
        HashMap<String, Boolean> map = new HashMap<String, Boolean>();
        StringTokenizer features = new StringTokenizer(optString, ",");
        StringTokenizer option;
        while (features.hasMoreElements()) {
            option = new StringTokenizer(features.nextToken(), "=");
            if (option.hasMoreElements()) {
                String key = option.nextToken();
                Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
                map.put(key, value);
            }
        }
        return map;
    }
}

From source file:org.apache.tez.dag.app.web.AMWebController.java

/**
 * Parse a params list in the format: CtrGroup/CtrName1,CtrName2;CtrGroup2;
 * @return nested structure of counter groups and names. Null if nothing specified.
 *///from www. j ava  2  s . c  o m
Map<String, Set<String>> getCounterListFromRequest() {
    final String counterStr = $(WebUIService.COUNTERS).trim();
    if (counterStr == null || counterStr.isEmpty()) {
        return null;
    }

    String delimiter = ";";
    String groupDelimiter = "/";
    String counterDelimiter = ",";

    StringTokenizer tokenizer = new StringTokenizer(counterStr, delimiter);

    Map<String, Set<String>> counterList = new TreeMap<String, Set<String>>();
    while (tokenizer.hasMoreElements()) {
        String token = tokenizer.nextToken().trim();
        int pos = token.indexOf(groupDelimiter);
        if (pos == -1) {
            counterList.put(token, Collections.<String>emptySet());
            continue;
        }
        String counterGroup = token.substring(0, pos);
        Set<String> counters = Collections.<String>emptySet();
        if (pos < token.length() - 1) {
            String counterNames = token.substring(pos + 1, token.length());
            counters = Sets.newHashSet(
                    Splitter.on(counterDelimiter).omitEmptyStrings().trimResults().split(counterNames));
        }
        counterList.put(counterGroup, counters);
    }
    return counterList;
}

From source file:com.irets.datadownloader.SearchPropertyServlet.java

public String getServer(HttpServletRequest req) {
    String server = null;// ww  w  .  j  a  va  2 s  .c  o  m
    String uri = req.getRequestURI();

    if (uri.indexOf("/") > -1) {
        StringTokenizer sToken = new StringTokenizer(uri, "/");
        if (sToken.hasMoreElements()) {
            server = (String) (sToken.nextElement());
            if (server.equals("imls"))
                return null;
        }
    }
    System.out.println("server from uri is " + server);
    return server;

}

From source file:org.fcrepo.server.access.DefaultAccess.java

private String[] getAdminEmails() {
    String emailsCSV = convertToCSV(getServer().getParameter("adminEmailList"));
    Vector<Object> emails = new Vector<Object>();
    StringTokenizer st = new StringTokenizer(emailsCSV, ",");
    while (st.hasMoreElements()) {
        emails.add(st.nextElement());// ww w .  j  a v a 2 s .com
    }
    return emails.toArray(EMPTY_STRING_ARRAY);
}

From source file:org.fcrepo.server.access.DefaultAccess.java

private String[] getRetainPIDs() {
    String retainPIDsCSV = convertToCSV(
            getServer().getModule("org.fcrepo.server.storage.DOManager").getParameter("retainPIDs"));
    Vector<Object> retainPIDs = new Vector<Object>();
    StringTokenizer st = new StringTokenizer(retainPIDsCSV, ",");
    while (st.hasMoreElements()) {
        retainPIDs.add(st.nextElement());
    }//  w  ww . jav  a 2s. c o m
    return retainPIDs.toArray(EMPTY_STRING_ARRAY);
}

From source file:it.unimi.di.big.mg4j.document.DocumentCollectionTest.java

/** Checks that the tokenizer and the word reader return exactly the same sequence of words. 
 * /*from   w  w  w .  jav  a2 s.  com*/
 * @param wordReader the word reader.
 * @param tok the tokenizer.
 * @throws IOException
 */
private void checkSameWords(WordReader wordReader, StringTokenizer tok) throws IOException {
    MutableString word = new MutableString();
    MutableString nonWord = new MutableString();
    boolean aWordInDocum, aWordInDocument;
    boolean firstTime = true;
    for (;;) {
        aWordInDocum = wordReader.next(word, nonWord);
        if (firstTime) {
            firstTime = false;
            if (word.equals(""))
                continue;
        }
        assertFalse(aWordInDocum && word.equals(""));
        aWordInDocument = tok.hasMoreElements();
        assertTrue(aWordInDocum == aWordInDocument);
        if (!aWordInDocum)
            break;
        assertEquals(tok.nextElement(), word.toString());
    }
}