Example usage for java.util StringTokenizer nextToken

List of usage examples for java.util StringTokenizer nextToken

Introduction

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

Prototype

public String nextToken() 

Source Link

Document

Returns the next token from this string tokenizer.

Usage

From source file:de.mpg.imeji.presentation.util.Scripts.java

public static String login(String frameworkUrl, String userName, String password) throws Exception {
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");

    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");

    String host = hostPort.nextToken();
    int port = Integer.parseInt(hostPort.nextToken());

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userName);
    login.addParameter("j_password", password);

    client.executeMethod(login);/* w  w  w .  j av  a  2s. c  o m*/
    //System.out.println("Login form post: " + login.getStatusLine().toString());

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod("/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    //System.out.println("Login second post: " + postMethod.getStatusLine().toString());

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
            //System.out.println("location: "+location);
            //System.out.println("handle: "+userHandle);
        }
    }

    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:org.springframework.core.util.StringUtils.java

/**
 * Tokenize the given String into a String array via a StringTokenizer.
 * <p>The given delimiters string is supposed to consist of any number of
 * delimiter characters. Each of those characters can be used to separate
 * tokens. A delimiter is always a single character; for multi-character
 * delimiters, consider using <code>delimitedListToStringArray</code>
 *
 * @param str               the String to tokenize
 * @param delimiters        the delimiter characters, assembled as String
 *                          (each of those characters is individually considered as delimiter)
 * @param trimTokens        trim the tokens via String's <code>trim</code>
 * @param ignoreEmptyTokens omit empty tokens from the result array
 *                          (only applies to tokens that are empty after trimming; StringTokenizer
 *                          will not consider subsequent delimiters as token in the first place).
 * @return an array of the tokens (<code>null</code> if the input String
 *         was <code>null</code>)
 * @see java.util.StringTokenizer/*from ww w  .  j  a v a  2s  .  c  o  m*/
 * @see String#trim()
 */
public static String[] tokenizeToStringArray(final String str, final String delimiters,
        final boolean trimTokens, final boolean ignoreEmptyTokens) {

    if (str == null) {
        return null;
    }
    StringTokenizer st = new StringTokenizer(str, delimiters);
    List<String> tokens = new ArrayList<String>();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (trimTokens) {
            token = token.trim();
        }
        if (!ignoreEmptyTokens || token.length() > 0) {
            tokens.add(token);
        }
    }
    return toStringArray(tokens);
}

From source file:com.handpay.ibenefit.framework.util.WebUtils.java

public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response,
        String etag) {// w  ww .ja  v  a 2 s.  c  o  m
    String headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {
        boolean conditionSatisfied = false;
        if (!"*".equals(headerValue)) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(etag)) {
                    conditionSatisfied = true;
                }
            }
        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", etag);
            return false;
        }
    }
    return true;
}

From source file:Main.java

/**
 * //  ww  w  . j a va 2 s. com
 * @param value
 * @return double[][]
 */
public static double[][] to2dDoubleArray(final String value) {
    final String strippedValue = value.replace(ARRAY_OPEN_TAG, EMPTY_STRING).replace(ARRAY_CLOSE_TAG,
            EMPTY_STRING);
    final StringTokenizer tokenizer = new StringTokenizer(strippedValue, ARRAY_SEPARATOR);
    final double[][] array = new double[tokenizer.countTokens()][];
    int i = 0;

    while (tokenizer.hasMoreTokens()) {
        array[i++] = toDoubleArray(tokenizer.nextToken());
    }

    return array;
}

From source file:com.redhat.lightblue.util.Error.java

public static Error fromJson(JsonNode node) {
    if (node instanceof ObjectNode) {
        String e = null;//from   ww  w .  j  a  v  a2  s  .c  om
        String m = null;

        JsonNode x;

        x = ((ObjectNode) node).get("errorCode");
        if (x != null) {
            e = x.asText();
        }
        x = ((ObjectNode) node).get("msg");
        if (x != null) {
            m = x.asText();
        }

        Error ret = new Error(e, m);

        x = ((ObjectNode) node).get("context");
        if (x != null) {
            StringTokenizer tok = new StringTokenizer(x.asText(), "/");
            while (tok.hasMoreTokens()) {
                ret.pushContext(tok.nextToken());
            }
        }

        return ret;
    }
    return null;
}

From source file:LauncherBootstrap.java

/**
 * Convert a ":" separated list of URL file fragments into an array of URL
 * objects. Note that any all URL file fragments must conform to the format
 * required by the "file" parameter in the
 * {@link URL(String, String, String)} constructor.
 *
 * @param fileList the ":" delimited list of URL file fragments to be
 *  converted//from  w  w w .j  a va 2s. com
 * @return an array of URL objects
 * @throws MalformedURLException if the fileList parameter contains any
 *  malformed URLs
 */
private static URL[] fileListToURLs(String fileList) throws MalformedURLException {

    if (fileList == null || "".equals(fileList))
        return new URL[0];

    // Parse the path string
    ArrayList list = new ArrayList();
    StringTokenizer tokenizer = new StringTokenizer(fileList, ":");
    URL bootstrapURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.class.getName() + ".class");
    while (tokenizer.hasMoreTokens())
        list.add(new URL(bootstrapURL, tokenizer.nextToken()));

    return (URL[]) list.toArray(new URL[list.size()]);

}

From source file:axiom.util.MimePart.java

/**
 *  Get a sub-header from a header, e.g. the charset from
 *  <code>Content-Type: text/plain; charset="UTF-8"</code>
 *//* www  . ja va 2  s  .  c  o m*/
public static String getSubHeader(String header, String subHeaderName) {
    if (header == null) {
        return null;
    }

    StringTokenizer headerTokenizer = new StringTokenizer(header, ";");

    while (headerTokenizer.hasMoreTokens()) {
        String token = headerTokenizer.nextToken().trim();
        int i = token.indexOf("=");

        if (i > 0) {
            String hname = token.substring(0, i).trim();

            if (hname.equalsIgnoreCase(subHeaderName)) {
                String value = token.substring(i + 1);
                return value.replace('"', ' ').trim();
            }
        }
    }

    return null;
}

From source file:de.perdian.commons.servlet.ServletUtils.java

/**
 * Extracts the locales supported by the client that sent a given request.
 * According to RFC 2161 the result list will be sorted according to any
 * specified preferenc value (see the RFC for details)
 *
 * @param servletRequest/* ww  w .  j av a2  s . co m*/
 *     the request from which to extract the information
 * @param defaultLocales
 *     the locales to be returned if no locales could be extracted from the
 *     request
 * @return
 *     a {@code List} containing the accepted {@code java.util.Locale}
 *     objects. If no locales are found in the request, then the method will
 *     return the default locale list or an empty list if no default locales
 *     have been passed - never {@code null}
 */
public static List<Locale> extractAcceptedLocales(HttpServletRequest servletRequest,
        List<Locale> defaultLocales) {

    Map<Float, List<Locale>> localeValuesByPriority = new TreeMap<>((o1, o2) -> -1 * Float.compare(o1, o2));
    String headerValue = servletRequest.getHeader("accept-language");
    if (headerValue != null) {
        StringTokenizer headerTokenizer = new StringTokenizer(headerValue, ",");
        while (headerTokenizer.hasMoreElements()) {
            String header = headerTokenizer.nextToken().trim();
            int semicolonSeparator = header.indexOf(";");
            String localeValue = semicolonSeparator > 0 ? header.substring(0, semicolonSeparator) : header;
            Locale locale = LocaleUtils.toLocale(localeValue);
            if (locale != null) {
                Float qValue = Float.valueOf(1f);
                String qParameter = ";q=";
                int qParameterIndex = header.indexOf(qParameter);
                if (qParameterIndex > 0) {
                    try {
                        String qParameterValue = header.substring(qParameterIndex + qParameter.length());
                        qValue = Float.valueOf(qParameterValue);

                    } catch (Exception e) {
                        // Ignore here and use the default
                    }
                }
                List<Locale> targetList = localeValuesByPriority.get(qValue);
                if (targetList == null) {
                    targetList = new ArrayList<>();
                    localeValuesByPriority.put(qValue, targetList);
                }
                targetList.add(locale);
            }
        }
    }

    List<Locale> localeValues = new ArrayList<>();
    for (Map.Entry<Float, List<Locale>> localeValueEntry : localeValuesByPriority.entrySet()) {
        for (Locale locale : localeValueEntry.getValue()) {
            localeValues.add(locale);
        }
    }
    if (localeValues.isEmpty() && defaultLocales != null) {
        localeValues.addAll(defaultLocales);
    }
    return Collections.unmodifiableList(localeValues);

}

From source file:com.funambol.server.db.DataSourceContextHelper.java

/**
 * Create all intermediate subcontexts./*from www . j  a  va2 s . c  om*/
 */
private static void createSubcontexts(javax.naming.Context ctx, String name) throws NamingException {
    javax.naming.Context currentContext = ctx;
    StringTokenizer tokenizer = new StringTokenizer(name, "/");
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if ((!token.equals("")) && (tokenizer.hasMoreTokens())) {
            try {
                currentContext = currentContext.createSubcontext(token);
            } catch (NamingException e) {
                // Silent catch. Probably an object is already bound in
                // the context.
                currentContext = (javax.naming.Context) currentContext.lookup(token);
            }
        }
    }
}

From source file:org.jberet.support.io.MappingJsonFactoryObjectFactory.java

static void configureDeserializationProblemHandlers(final ObjectMapper objectMapper,
        final String deserializationProblemHandlers, final ClassLoader classLoader) throws Exception {
    final StringTokenizer st = new StringTokenizer(deserializationProblemHandlers, ", ");
    while (st.hasMoreTokens()) {
        final Class<?> c = classLoader.loadClass(st.nextToken());
        objectMapper.addHandler((DeserializationProblemHandler) c.newInstance());
    }//from  w  ww.  j  av a 2 s  .com
}