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:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString/* w  w w. j  a v  a  2 s. co m*/
 * @param q
 */
public static void setQueryParameters(String queryString, String parameterString, Query q) {
    Map<String, String> paramsMap = new HashMap<String, String>();

    StringTokenizer st = new StringTokenizer(parameterString, "&");
    while (st.hasMoreTokens()) {
        String element = st.nextToken();
        paramsMap.put(element.substring(0, element.indexOf("=")),
                element.substring(element.indexOf("=") + 1, element.length()));
    }
    KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
    Set<Parameter<?>> parameters = kq.getParameters();
    for (String paramName : paramsMap.keySet()) {
        String value = paramsMap.get(paramName);
        if (paramName.equalsIgnoreCase("firstResult")) {
            q.setFirstResult(Integer.parseInt(value));
        } else if (paramName.equalsIgnoreCase("maxResult")) {
            q.setMaxResults(Integer.parseInt(value));
        } else if (StringUtils.isNumeric(paramName)) {
            for (Parameter param : parameters) {
                if (param.getPosition() == Integer.parseInt(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(Integer.parseInt(paramName), paramValue);
                    break;
                }
            }
        } else {
            for (Parameter param : parameters) {
                if (param.getName().equals(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(paramName, paramValue);

                    break;
                }
            }

        }
    }
}

From source file:ch.entwine.weblounge.common.impl.content.image.ImageMetadataUtils.java

/**
 * This utility method extracts image metadata stored in EXIF and IPTC tags
 * and returns the extracted information in a {@link ImageMetadata}.
 * //from   w w  w  .ja v a 2 s. c  o  m
 * @param img
 *          image input stream
 * @return extracted meta information
 */
public static ImageMetadata extractMetadata(BufferedInputStream img) {
    Metadata meta;
    try {
        meta = ImageMetadataReader.readMetadata(img);
    } catch (ImageProcessingException e) {
        if ("File is not the correct format".equals(e.getMessage()))
            return null;
        logger.warn("Failed to extract image metadata from image: {}", e.getMessage());
        return null;
    }

    if (meta == null) {
        logger.debug("Extracted metadata is null");
        return null;
    } else {

        ImageMetadata imgmeta = new ImageMetadata();

        // Extract IPTC information
        Directory iptc = meta.getDirectory(IptcDirectory.class);
        if (iptc.containsTag(IptcDirectory.TAG_HEADLINE))
            imgmeta.setCaption(iptc.getString(IptcDirectory.TAG_HEADLINE));
        if (iptc.containsTag(IptcDirectory.TAG_CAPTION))
            imgmeta.setLegend(iptc.getString(IptcDirectory.TAG_CAPTION));
        if (iptc.containsTag(IptcDirectory.TAG_BY_LINE))
            imgmeta.setPhotographer(iptc.getString(IptcDirectory.TAG_BY_LINE));
        if (iptc.containsTag(IptcDirectory.TAG_COPYRIGHT_NOTICE))
            imgmeta.setCopyright(iptc.getString(IptcDirectory.TAG_COPYRIGHT_NOTICE));
        if (iptc.containsTag(IptcDirectory.TAG_CITY))
            imgmeta.setLocation(iptc.getString(IptcDirectory.TAG_CITY));
        if (iptc.containsTag(IptcDirectory.TAG_KEYWORDS)) {
            StringTokenizer st = new StringTokenizer(iptc.getString(IptcDirectory.TAG_KEYWORDS), ",;");
            while (st.hasMoreTokens()) {
                imgmeta.addKeyword(st.nextToken());
            }
        }

        // Extract EXIF information
        Directory exif = meta.getDirectory(ExifDirectory.class);
        if (exif.containsTag(ExifDirectory.TAG_DATETIME)) {
            try {
                imgmeta.setDateTaken(exif.getDate(ExifDirectory.TAG_DATETIME));
            } catch (MetadataException e) {
            }
        }
        if (exif.containsTag(ExifDirectory.TAG_ISO_EQUIVALENT)) {
            try {
                imgmeta.setFilmspeed(exif.getInt(ExifDirectory.TAG_ISO_EQUIVALENT));
            } catch (MetadataException e) {
            }
        }
        if (exif.containsTag(ExifDirectory.TAG_FNUMBER)) {
            try {
                imgmeta.setFNumber(exif.getFloat(ExifDirectory.TAG_FNUMBER));
            } catch (MetadataException e) {
            }
        }
        if (exif.containsTag(ExifDirectory.TAG_FOCAL_LENGTH)) {
            try {
                imgmeta.setFocalWidth(exif.getInt(ExifDirectory.TAG_FOCAL_LENGTH));
            } catch (MetadataException e) {
            }
        }
        if (exif.containsTag(ExifDirectory.TAG_EXPOSURE_TIME)) {
            try {
                imgmeta.setExposureTime(exif.getFloat(ExifDirectory.TAG_EXPOSURE_TIME));
            } catch (MetadataException e) {
            }
        }
        if (StringUtils.isBlank(imgmeta.getCopyright()) && exif.containsTag(ExifDirectory.TAG_COPYRIGHT))
            imgmeta.setCopyright(exif.getString(ExifDirectory.TAG_COPYRIGHT));

        // Extract GPS information
        try {
            Directory gps = meta.getDirectory(GpsDirectory.class);
            if (gps.containsTag(GpsDirectory.TAG_GPS_LATITUDE)) {
                Rational[] lat = gps.getRationalArray(GpsDirectory.TAG_GPS_LATITUDE);
                String latRef = gps.getString(GpsDirectory.TAG_GPS_LATITUDE_REF);
                double latitude = parseHMS(lat);
                if (latitude != 0) {
                    if (StringUtils.isNotBlank(latRef) && "S".equalsIgnoreCase(latRef) && latitude > 0)
                        latitude *= -1;
                }
                imgmeta.setGpsLat(latitude);
            }
            if (gps.containsTag(GpsDirectory.TAG_GPS_LONGITUDE)) {
                Rational[] lng = gps.getRationalArray(GpsDirectory.TAG_GPS_LONGITUDE);
                String lngRef = gps.getString(GpsDirectory.TAG_GPS_LONGITUDE_REF);
                double longitude = parseHMS(lng);
                if (longitude != 0) {
                    if (StringUtils.isNotBlank(lngRef) && "W".equalsIgnoreCase(lngRef) && longitude > 0)
                        longitude *= -1;
                }
                imgmeta.setGpsLong(longitude);
            }
        } catch (MetadataException e) {
            logger.info("Error while extracting GPS information out of an image.");
            imgmeta.setGpsLat(0);
            imgmeta.setGpsLong(0);
        }

        return imgmeta;
    }
}

From source file:com.intel.chimera.cipher.Openssl.java

private static Transform tokenizeTransformation(String transformation) throws NoSuchAlgorithmException {
    if (transformation == null) {
        throw new NoSuchAlgorithmException("No transformation given.");
    }/*  ww w  .  ja  va 2 s .  c o  m*/

    /*
     * Array containing the components of a Cipher transformation:
     *
     * index 0: algorithm (e.g., AES)
     * index 1: mode (e.g., CTR)
     * index 2: padding (e.g., NoPadding)
     */
    String[] parts = new String[3];
    int count = 0;
    StringTokenizer parser = new StringTokenizer(transformation, "/");
    while (parser.hasMoreTokens() && count < 3) {
        parts[count++] = parser.nextToken().trim();
    }
    if (count != 3 || parser.hasMoreTokens()) {
        throw new NoSuchAlgorithmException("Invalid transformation format: " + transformation);
    }
    return new Transform(parts[0], parts[1], parts[2]);
}

From source file:org.yamj.core.service.metadata.online.ImdbSearchEngine.java

private static String getImdbIdFromURL(String url, String objectType) {
    if (StringUtils.isBlank(url)) {
        return null;
    }//from   w w  w. ja  va 2 s . c o m

    String imdbId = StringUtils.EMPTY;
    int beginIndex = url.indexOf(objectType.equals(OBJECT_MOVIE) ? "/title/tt" : "/name/nm");
    if (beginIndex > -1) {
        int index;
        if (objectType.equals(OBJECT_MOVIE)) {
            index = beginIndex + 7;
        } else {
            index = beginIndex + 6;
        }
        StringTokenizer st = new StringTokenizer(url.substring(index), HTML_SLASH_QUOTE);
        imdbId = st.nextToken();
    }

    if (imdbId.startsWith(objectType.equals(OBJECT_MOVIE) ? "tt" : "nm")) {
        LOG.debug("Found IMDb ID '{}'", imdbId);
        return imdbId;
    }
    return null;
}

From source file:com.glaf.mail.util.MailUtils.java

public static String getMailText(int type, String text) {
    String mailText = "";
    if (text == null || text.trim().equalsIgnoreCase("null")) {
        return mailText;
    }//  ww  w  .  ja  v  a2  s.c o m
    String newline = System.getProperty("line.separator");
    StringBuffer buffer = new StringBuffer();
    buffer.append(newline);
    buffer.append(newline);
    if (type == 1) {
        buffer.append(newline);
        buffer.append(newline);
        buffer.append("=================== ??====================");
        buffer.append(newline);
    }
    if (type == 2) {
        buffer.append(newline);
        buffer.append("********************??**********************");
    }

    StringTokenizer token = new StringTokenizer(text, "\r\n");
    while (token.hasMoreTokens()) {
        String temp = token.nextToken();
        buffer.append(newline);
        buffer.append(">").append(temp);
    }
    buffer.append(newline);
    buffer.append(newline);
    buffer.append("= = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
    buffer.append(newline);
    return buffer.toString();
}

From source file:de.elbe5.base.util.StringUtil.java

public static String toHtmlText(String src) {
    if (src == null) {
        return "";
    }//from  www .j  a v a 2  s .  co m
    if (src.indexOf('\n') == -1)
        return StringEscapeUtils.escapeHtml4(src);

    StringTokenizer stk = new StringTokenizer(src, "\n", true);
    if (stk.countTokens() == 0)
        return "";
    StringBuilder sb = new StringBuilder();
    String token;
    while (stk.hasMoreTokens()) {
        token = stk.nextToken();
        if (token.equals("\n"))
            sb.append("\n<br/>\n");
        else
            sb.append(StringEscapeUtils.escapeHtml4(token));
    }
    return sb.toString();
}

From source file:Utils.java

/**
 * Wrap multi-line strings (and get the individual lines).
 * /*  w w w.ja  v a2 s.co  m*/
 * @param original
 *          the original string to wrap
 * @param width
 *          the maximum width of lines
 * @param breakIterator
 *          breaks original to chars, words, sentences, depending on what
 *          instance you provide.
 * @param removeNewLines
 *          if <code>true</code>, any newlines in the original string are
 *          ignored
 * @return the lines after wrapping
 */
public static String[] wrapStringToArray(String original, int width, BreakIterator breakIterator,
        boolean removeNewLines) {
    if (original.length() == 0) {
        return new String[] { original };
    }

    String[] workingSet;

    // substitute original newlines with spaces,
    // remove newlines from head and tail
    if (removeNewLines) {
        original = trimString(original);
        original = original.replace('\n', ' ');
        workingSet = new String[] { original };
    } else {
        StringTokenizer tokens = new StringTokenizer(original, "\n"); // NOI18N
        int len = tokens.countTokens();
        workingSet = new String[len];

        for (int i = 0; i < len; i++) {
            workingSet[i] = tokens.nextToken();
        }
    }

    if (width < 1) {
        width = 1;
    }

    if (original.length() <= width) {
        return workingSet;
    }

    widthcheck: {
        boolean ok = true;

        for (int i = 0; i < workingSet.length; i++) {
            ok = ok && (workingSet[i].length() < width);

            if (!ok) {
                break widthcheck;
            }
        }

        return workingSet;
    }

    java.util.ArrayList<String> lines = new java.util.ArrayList<String>();

    int lineStart = 0; // the position of start of currently processed line in
                       // the original string

    for (int i = 0; i < workingSet.length; i++) {
        if (workingSet[i].length() < width) {
            lines.add(workingSet[i]);
        } else {
            breakIterator.setText(workingSet[i]);

            int nextStart = breakIterator.next();
            int prevStart = 0;

            do {
                while (((nextStart - lineStart) < width) && (nextStart != BreakIterator.DONE)) {
                    prevStart = nextStart;
                    nextStart = breakIterator.next();
                }

                if (nextStart == BreakIterator.DONE) {
                    nextStart = prevStart = workingSet[i].length();
                }

                if (prevStart == 0) {
                    prevStart = nextStart;
                }

                lines.add(workingSet[i].substring(lineStart, prevStart));

                lineStart = prevStart;
                prevStart = 0;
            } while (lineStart < workingSet[i].length());

            lineStart = 0;
        }
    }

    String[] s = new String[lines.size()];

    return (String[]) lines.toArray(s);
}

From source file:com.thoughtworks.go.util.FileUtil.java

public static File normalize(final String path) {
    Stack s = new Stack();
    String[] dissect = dissect(path);
    s.push(dissect[0]);//from   www. ja va 2  s  .  com

    StringTokenizer tok = new StringTokenizer(dissect[1], File.separator);
    while (tok.hasMoreTokens()) {
        String thisToken = tok.nextToken();
        if (".".equals(thisToken)) {
            continue;
        }
        if ("..".equals(thisToken)) {
            if (s.size() < 2) {
                // Cannot resolve it, so skip it.
                return new File(path);
            }
            s.pop();
        } else { // plain component
            s.push(thisToken);
        }
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.size(); i++) {
        if (i > 1) {
            // not before the filesystem root and not after it, since root
            // already contains one
            sb.append(File.separatorChar);
        }
        sb.append(s.elementAt(i));
    }
    return new File(sb.toString());
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.penntree.PennTreeUtils.java

public static PennTreeNode parsePennTree(String aTree) {
    StringTokenizer st = new StringTokenizer(aTree, "() ", true);

    PennTreeNode root = null;/*from  w  w  w . j a va2 s . com*/
    Stack<PennTreeNode> stack = new Stack<PennTreeNode>();
    boolean seenLabel = false;

    while (st.hasMoreTokens()) {
        String t = st.nextToken().trim();
        if (t.length() == 0) {
            // Skip
        } else if ("(".equals(t)) {
            PennTreeNode n = new PennTreeNode();
            stack.push(n);
            if (root == null) {
                root = n;
            }
            seenLabel = false;
        } else if (")".equals(t)) {
            PennTreeNode n = stack.pop();
            if (!stack.isEmpty()) {
                PennTreeNode p = stack.peek();
                p.addChild(n);
            }
        } else if (seenLabel) {
            // If the node has two labels, its a leaf, add a new terminal node then.
            PennTreeNode p = stack.peek();
            PennTreeNode n = new PennTreeNode();
            n.setLabel(t);
            p.addChild(n);
        } else {
            PennTreeNode n = stack.peek();
            n.setLabel(t);
            seenLabel = true;
        }
    }

    return root;
}

From source file:elaborate.util.StringUtil.java

/**
 * change ULRs in <code>textWithURLs</code> to links
 * /*from   w  w  w.j ava 2s .  c  o  m*/
 * @param textWithURLs
 *          text with URLs
 * @return text with links
 */
public static String activateURLs(String textWithURLs) {
    StringTokenizer tokenizer = new StringTokenizer(textWithURLs, "<> ", true);
    StringBuilder replaced = new StringBuilder(textWithURLs.length());
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        // Log.info("token={}", token);
        try {
            URL url = new URL(token);
            // If possible then replace with anchor...
            String linktext = token;
            String file = url.getFile();
            if (StringUtils.isNotBlank(file)) {
                linktext = file;
            }
            String protocol = url.getProtocol();
            if (hostProtocols.contains(protocol)) {
                linktext = url.getHost() + linktext;
            }
            replaced.append("<a target=\"_blank\" href=\"" + url + "\">" + linktext + "</a>");
        } catch (MalformedURLException e) {
            replaced.append(token);
        }
    }

    return replaced.toString();
}