Example usage for java.util StringTokenizer StringTokenizer

List of usage examples for java.util StringTokenizer StringTokenizer

Introduction

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

Prototype

public StringTokenizer(String str, String delim) 

Source Link

Document

Constructs a string tokenizer for the specified string.

Usage

From source file:com.bst.tags.JavascriptHref.java

/**
 * Construct a new Href parsing a URL. Parameters are stripped from the base url and saved in the parameters map.
 * @param baseUrl String//from  w  w  w.j a  v a 2 s  .  co  m
 */
public JavascriptHref(String baseUrl) {
    super(baseUrl);

    this.parameters = new HashMap();

    String noAnchorUrl;
    int anchorposition = baseUrl.indexOf('#');

    // extract anchor from url
    if (anchorposition != -1) {
        noAnchorUrl = baseUrl.substring(0, anchorposition);
        this.anchor = baseUrl.substring(anchorposition + 1);
    } else {
        noAnchorUrl = baseUrl;
    }

    if (noAnchorUrl.indexOf('?') == -1) {
        // simple url, no parameters
        this.url = noAnchorUrl;
        return;
    }

    // the Url already has parameters, put them in the parameter Map
    StringTokenizer tokenizer = new StringTokenizer(noAnchorUrl, "?"); //$NON-NLS-1$

    if (baseUrl.startsWith("?")) //$NON-NLS-1$
    {
        // support fake URI's which are just parameters to use with the current uri
        url = TagConstants.EMPTY_STRING;
    } else {
        // base url (before "?")
        url = tokenizer.nextToken();
    }

    if (!tokenizer.hasMoreTokens()) {
        return;
    }

    // process parameters
    StringTokenizer paramTokenizer = new StringTokenizer(tokenizer.nextToken(), "&"); //$NON-NLS-1$

    // split parameters (key=value)
    while (paramTokenizer.hasMoreTokens()) {
        // split key and value ...
        String[] keyValue = StringUtils.split(paramTokenizer.nextToken(), '=');

        // encode name/value to prevent css
        String escapedKey = StringEscapeUtils.escapeHtml(keyValue[0]);
        String escapedValue = keyValue.length > 1 ? StringEscapeUtils.escapeHtml(keyValue[1])
                : TagConstants.EMPTY_STRING;

        if (!this.parameters.containsKey(escapedKey)) {
            // ... and add it to the map
            this.parameters.put(escapedKey, escapedValue);
        } else {
            // additional value for an existing parameter
            Object previousValue = this.parameters.get(escapedKey);
            if (previousValue != null && previousValue.getClass().isArray()) {
                Object[] previousArray = (Object[]) previousValue;
                Object[] newArray = new Object[previousArray.length + 1];

                int j;

                for (j = 0; j < previousArray.length; j++) {
                    newArray[j] = previousArray[j];
                }

                newArray[j] = escapedValue;
                this.parameters.put(escapedKey, newArray);
            } else {
                this.parameters.put(escapedKey, new Object[] { previousValue, escapedValue });
            }
        }
    }
}

From source file:com.adito.properties.attributes.AttributeValueItem.java

/**
 * Constructor./*  ww  w  . j  av  a 2s .  c  o m*/
 * 
 * @param definition definition
 * @param request request
 * @param value initial value
 * @param subCategory 
 */
public AttributeValueItem(AttributeDefinition definition, HttpServletRequest request, String value,
        String subCategory) {
    super(definition, request, subCategory);

    this.value = getDefinition().parseValue(value);

    // Process the type meta for any type specific parameters
    if (definition.getType() == PropertyDefinition.TYPE_TEXT_AREA) {
        this.value = value;
        StringTokenizer t = new StringTokenizer(
                definition.getTypeMeta().equals("") ? "25x5" : definition.getTypeMeta(), "x");
        try {
            columns = Integer.parseInt(t.nextToken());
            rows = Integer.parseInt(t.nextToken());
        } catch (Exception e) {
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_LIST) {
        List<Pair> listItemsList = new ArrayList<Pair>();
        if (!definition.getTypeMeta().startsWith("!")) {
            for (Iterator i = ((List) definition.getTypeMetaObject()).iterator(); i.hasNext();) {
                TypeMetaListItem item = (TypeMetaListItem) i.next();
                ServletContext context = CoreServlet.getServlet().getServletContext();
                ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig(request, context);
                String mrKey = (item.getMessageResourcesKey() == null ? "properties"
                        : item.getMessageResourcesKey()) + moduleConfig.getPrefix();
                MessageResources res = (MessageResources) context.getAttribute(mrKey);
                String k = definition.getName() + ".value." + item.getValue();
                String v = "";
                if (res != null) {
                    v = res.getMessage((Locale) request.getSession().getAttribute(Globals.LOCALE_KEY), k);
                    if (v == null) {
                        v = item.getValue();
                    }
                }
                Pair pair = new Pair(item.getValue(), v);
                if (item.getValue().equals(value)) {
                    this.value = pair.getValue();
                }
                listItemsList.add(pair);
            }
        } else {
            String className = definition.getTypeMeta().substring(1);
            try {
                Class clazz = Class.forName(className);
                Object obj = clazz.newInstance();
                if (obj instanceof PairListDataSource)
                    listItemsList.addAll(((PairListDataSource) obj).getValues(request));
                else
                    throw new Exception("Not a PairListDataSource.");
            } catch (Exception e) {
                log.error("Failed to create list data source.", e);
            }
            this.value = value;
        }
        listItems = new Pair[listItemsList.size()];
        listItemsList.toArray(listItems);
    } else if (definition.getType() == PropertyDefinition.TYPE_STRING) {
        columns = 25;
        if (!definition.getTypeMeta().equals("")) {
            try {
                columns = Integer.parseInt(definition.getTypeMeta());
            } catch (NumberFormatException nfe) {
            }
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_INTEGER) {
        columns = 8;
        if (!definition.getTypeMeta().equals("")) {
            try {
                columns = Integer.parseInt(definition.getTypeMeta());
            } catch (NumberFormatException e) {
            }
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_PASSWORD) {
        columns = 25;
        if (!definition.getTypeMeta().equals("")) {
            try {
                columns = Integer.parseInt(definition.getTypeMeta());
            } catch (NumberFormatException nfe) {
            }
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_TIME_IN_MS) {
        try {
            int val = Integer.parseInt(value);
            if (definition.getTypeMeta().equalsIgnoreCase("s")) {
                this.value = String.valueOf(val / 1000);
            } else if (definition.getTypeMeta().equalsIgnoreCase("m")) {
                this.value = String.valueOf(val / 1000 / 60);
            } else if (definition.getTypeMeta().equalsIgnoreCase("h")) {
                this.value = String.valueOf(val / 1000 / 60 / 60);
            } else if (definition.getTypeMeta().equalsIgnoreCase("d")) {
                this.value = String.valueOf(val / 1000 / 60 / 60 / 24);
            } else {
                this.value = String.valueOf(val);
            }
        } catch (Exception e) {
        }
    }
}

From source file:es.tid.cosmos.platform.injection.server.FrontendPassword.java

@Override
public boolean authenticate(String username, String password, ServerSession session) {
    LOG.debug(String.format("received %s as username, %d chars as password", username, password.length()));
    boolean ans = false;
    ResultSet resultSet = null;//from   w w w . j  ava2  s  .  c  om
    PreparedStatement preparedStatement = null;
    Connection connection = null;

    try {
        connection = this.connect(this.frontendDbUrl, this.dbName, this.dbUserName, this.dbPassword);
        String sql = "SELECT password FROM auth_user WHERE username = ?";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        resultSet = preparedStatement.executeQuery();
        String algorithm = "";
        String hash = "";
        String salt = "";

        while (resultSet.next()) {
            StringTokenizer algorithmSaltHash = new StringTokenizer(resultSet.getString(1), DJANGO_SEPARATOR);
            algorithm = algorithmSaltHash.nextToken();
            salt = algorithmSaltHash.nextToken();
            hash = algorithmSaltHash.nextToken();
        } // while

        if (algorithm.equals("sha1")) {
            ans = hash.equals(DigestUtils.shaHex(salt + password));
        } else if (algorithm.equals("md5")) {
            ans = hash.equals(DigestUtils.md5Hex(salt + password));
        } else {
            LOG.warn("Unknown algorithm found in DB: " + algorithm);
        } // if else if
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
        return false;
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                LOG.error("could not close a result set", e);
            } // try catch
        } // if

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                LOG.error("could not close a database statement", e);
            } // try catch
        } // if

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.error("could not close a database connection", e);
            } // try catch
        } // if
    } // try catch finally

    return ans;
}

From source file:com.ai.smart.common.helper.util.RequestUtils.java

public static Map<String, String[]> parseQueryString(String s) {
    String valArray[] = null;/*from   w  w w  . j  a v a  2  s .  c  o m*/
    if (s == null) {
        throw new IllegalArgumentException();
    }
    Map<String, String[]> ht = new HashMap<String, String[]>();
    StringTokenizer st = new StringTokenizer(s, "&");
    while (st.hasMoreTokens()) {
        String pair = (String) st.nextToken();
        int pos = pair.indexOf('=');
        if (pos == -1) {
            continue;
        }
        String key = pair.substring(0, pos);
        String val = pair.substring(pos + 1, pair.length());
        if (ht.containsKey(key)) {
            String oldVals[] = (String[]) ht.get(key);
            valArray = new String[oldVals.length + 1];
            for (int i = 0; i < oldVals.length; i++) {
                valArray[i] = oldVals[i];
            }
            valArray[oldVals.length] = val;
        } else {
            valArray = new String[1];
            valArray[0] = val;
        }
        ht.put(key, valArray);
    }
    return ht;
}

From source file:com.blocks.framework.utils.date.StringUtil.java

/**
  * ?,,?????, ??, ?JAVA?????.// w w w  .j a va  2s.  c  o  m
  * 
  * @param columnName
  *            String ???
  * 
  * @return String ???
  * 
  */
 public static String getStandardStr(String columnName) {
     columnName = columnName.toLowerCase();
     StringBuffer sb = new StringBuffer();
     StringTokenizer token = new StringTokenizer(columnName, "_");
     int itoken = token.countTokens();
     for (int i = 0; i < itoken; i++) {
         if (i == 0) {
             sb.append(token.nextToken());
         } else {
             String temp = token.nextToken();
             sb.append(temp.substring(0, 1).toUpperCase());
             sb.append(temp.substring(1));
         }
     }
     return sb.toString();
 }

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.DataAccessMatrixQueriesMockImpl.java

public List<DataSet> getDataSetsForDiseaseType(String diseaseType) throws DAMQueriesException {
    List<DataSet> ret = new ArrayList<DataSet>();
    BufferedReader reader = null;
    try {//from  w w  w  .java 2 s.  c o  m
        reader = new BufferedReader(new FileReader(dataFileName));
        String record = reader.readLine();
        while (record != null) {
            StringTokenizer st = new StringTokenizer(record, "\t");
            String platformType = readNext(st);
            String center = readNext(st);
            String level = readNext(st);
            String batch = readNext(st);
            String sample = readNext(st);
            String availability = readNext(st);
            String sProtected = readNext(st);
            String barcode = readNext(st);
            String platform = readNext(st);
            //todo: add some error checking for bad file format
            DataSet dataSet = new DataSet();
            dataSet.setPlatformTypeId(platformType);
            dataSet.setCenterId(center);
            dataSet.setLevel(level);
            dataSet.setBatch(batch);
            dataSet.setSample(sample);
            dataSet.setAvailability(availability);
            if ("Y".equals(sProtected)) {
                dataSet.setProtected(true);
            }
            // dataSet.setBarcode(barcode);
            dataSet.setPlatformId(platform);
            ret.add(dataSet);
            record = reader.readLine();
        }
    } catch (IOException e) {
        //ret = null;
        throw new DAMQueriesException(e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
        }
    }
    return ret;
}

From source file:ve.gob.mercal.app.controllers.suscriptorController.java

@RequestMapping(value = { "/Suscriptor" }, method = { RequestMethod.GET })
public ModelAndView getTienda() {
    ModelAndView model = new ModelAndView();
    String s = "NULL";
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in username
    try {/*from w  w w.ja  v a 2 s . c  o m*/
        s = wsQuery.getConsulta("SELECT t.tienda FROM public.susc_tiendas as st"
                + ", public.tiendas as t, public.usuarios as u WHERE st.activo=TRUE and "
                + "t.id_tienda=st.id_tienda and st.id_usuario=u.id_usuario and " + "u.usuario='" + name + "';");
    } catch (ExcepcionServicio e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JsonParser parser = new JsonParser();
    JsonElement elementObject;
    s = s.substring(1, s.length() - 1);
    StringTokenizer st = new StringTokenizer(s, ",");
    while (st.hasMoreTokens()) {
        s = st.nextToken();
        elementObject = parser.parse(s);
        if (existeCampo.existeCampo(s, "tienda")) {
            this.tienda = elementObject.getAsJsonObject().get("tienda").getAsString();
        }
        listString.add("<option value=\"" + this.tienda + "\" type=\"submit\">" + this.tienda + "</option>");
    }
    model.addObject("tienda", listString);
    model.setViewName("Suscriptor");
    return model;
}

From source file:com.glaf.oa.purchase.web.springmvc.PurchaseitemController.java

@ResponseBody
@RequestMapping("/delete")
public ModelAndView delete(HttpServletRequest request, ModelMap modelMap) {
    String purchaseitemids = request.getParameter("purchaseitemIds");
    String purchaseid = request.getParameter("purchaseId");
    try {//from w  w  w  .  j a v  a 2 s  . c  o  m
        if (StringUtils.isNotEmpty(purchaseitemids)) {
            StringTokenizer token = new StringTokenizer(purchaseitemids, ",");
            while (token.hasMoreTokens()) {
                String x = token.nextToken();
                if (StringUtils.isNotEmpty(x)) {
                    purchaseitemService.deleteById(Long.parseLong(x), Long.parseLong(purchaseid));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex.getMessage());
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", "");
        return mav;
    }
    return this.list(request, modelMap);
}

From source file:com.kyne.webby.rtk.web.Connection.java

@Override
public void run() {
    InputStream in = null;/*from   ww  w  . j  a v a 2  s.  com*/
    try {
        in = this.clientSocket.getInputStream();
        String url = null;
        String params = null;

        final StringBuffer buff = new StringBuffer();
        final int b = in.read();
        if (b < 0) {
            return;
        }
        buff.appendCodePoint(b);
        while (0 != in.available()) {
            buff.appendCodePoint(in.read());
        }
        final String httpContent = buff.toString();
        final StringTokenizer tokenizer = new StringTokenizer(httpContent, "\n");
        final String firstLine = tokenizer.nextToken();
        final String[] splittedFirstLine = firstLine.split(" ");
        if (splittedFirstLine.length > 1) {
            final String requestUrl = (firstLine.split(" "))[1]; //GET /url?params HTTP/1.X   or   //POST /url HTTP/1.X
            final Matcher result = this.urlRegex.matcher(requestUrl);
            if (result.find()) {
                url = result.group(1);
                params = result.group(2);
            } else {
                LogHelper.warn("Invalid URL format : " + requestUrl);
            }
            if (httpContent.startsWith("POST")) {
                String lastLine = null;
                while (tokenizer.hasMoreTokens()) {
                    lastLine = tokenizer.nextToken();
                }
                params = "?" + lastLine;
            }
        } else {
            LogHelper.warn("Empty Request with HttpContent = " + httpContent);
        }

        final boolean isAllowedRessource;
        if (url == null) {
            LogHelper.warn("Null url " + url);
            isAllowedRessource = false;
        } else {
            isAllowedRessource = this.isRestrictedUrl(url) || this.isContextualCallUrl(url)
                    || this.webServer.isAllowedRessource(url) || this.isPredefinedUrl(url);
        }
        if (isAllowedRessource) {
            if (url != null && params != null) {
                this.handleRequest(url, params, this.clientSocket);
            }
        } else {
            this.handleRequest("/404", params, clientSocket); //Forward to 404
        }
    } catch (final SocketException e) {
        /* Pics or it didn't happen ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                /**/ }
        }
    }
}

From source file:it.unibas.spicy.persistence.xml.operators.TransformFilePaths.java

private List<String> getPathSteps(String filePath) {
    List<String> result = new ArrayList<String>();
    String separators = "/\\";
    StringTokenizer tokenizer = new StringTokenizer(filePath, separators);
    while (tokenizer.hasMoreTokens()) {
        result.add(0, tokenizer.nextToken());
    }//  ww w  . ja  va2s.co  m
    return result;
}