Example usage for org.apache.commons.lang3 StringUtils trim

List of usage examples for org.apache.commons.lang3 StringUtils trim

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils trim.

Prototype

public static String trim(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String, handling null by returning null .

The String is trimmed using String#trim() .

Usage

From source file:lolth.autohome.buy.AutohomeBuyInfoListTaskFetch.java

@Override
protected void parsePage(Document doc, FetchTask task) throws Exception {
    Elements lis = doc.select("li.price-item");

    for (Element li : lis) {
        AutohomeBuyInfoBean bean = new AutohomeBuyInfoBean();
        bean.setUrl(task.getUrl());/*from w  w w .j a  v  a  2 s.  co m*/
        bean.setForumId(task.getExtra());

        // post id
        Elements id = li.select("div.price-share a.share");
        if (!id.isEmpty()) {
            String idStr = id.first().attr("data-target");
            idStr = StringUtils.substringAfterLast(idStr, "_");
            if (StringUtils.isBlank(idStr)) {
                continue;
            }

            bean.setId(idStr);
        }

        // 
        Elements user = li.select("div.user-name a");
        if (!user.isEmpty()) {
            String userUrl = user.first().absUrl("href");
            String userId = StringUtils.substringAfterLast(userUrl, "/");
            String userName = user.first().text();

            bean.setUserId(userId);
            bean.setUserUrl(userUrl);
            bean.setUserName(userName);
        }

        // ?
        Elements postTime = li.select("div.user-name span");
        if (!postTime.isEmpty()) {
            bean.setPostTime(StringUtils.trim(StringUtils.substringBefore(postTime.first().text(), "?")));
        }

        Elements dataLis = li.select("div.price-item-bd li");
        for (Element dataLi : dataLis) {
            String data = dataLi.text();

            if (StringUtils.startsWith(data, "")) {
                bean.setCar(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }

            if (StringUtils.startsWith(data, "")) {
                bean.setPrice(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }

            if (StringUtils.startsWith(data, "")) {
                bean.setGuidePrice(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }

            if (StringUtils.startsWith(data, "?")) {
                bean.setTotalPrice(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }

            if (StringUtils.startsWith(data, "")) {
                bean.setPurchaseTax(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }

            if (StringUtils.startsWith(data, "?")) {
                bean.setCommercialInsurance(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }

            if (StringUtils.startsWith(data, "")) {
                bean.setVehicleUseTax(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }
            if (StringUtils.startsWith(data, "")) {
                bean.setCompulsoryInsurance(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }
            if (StringUtils.startsWith(data, "")) {
                bean.setLicenseFee(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }
            if (StringUtils.startsWith(data, "?")) {
                bean.setPromotion(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }
            if (StringUtils.startsWith(data, "")) {
                bean.setBuyTime(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }
            if (StringUtils.startsWith(data, "")) {
                String area = StringUtils.trim(StringUtils.substringAfter(data, ""));
                String[] pAndC = StringUtils.splitByWholeSeparator(area, ",", 2);

                if (pAndC.length == 1) {
                    bean.setBuyProvince(pAndC[0]);
                    bean.setBuyCity(pAndC[0]);
                }

                if (pAndC.length == 2) {
                    bean.setBuyProvince(pAndC[0]);
                    bean.setBuyCity(pAndC[1]);
                }

            }
            if (StringUtils.startsWith(data, "")) {
                Elements level = dataLi.select("span.level");
                // 
                if (!level.isEmpty()) {
                    bean.setSellerComment(level.first().text());
                }

                // ?
                Elements seller = dataLi.select("a.title");
                if (!seller.isEmpty()) {
                    String sellerUrl = seller.first().absUrl("href");
                    String sellerName = seller.first().text();
                    String sellerId = StringUtils.substringAfterLast(sellerUrl, "/");

                    bean.setSellerId(sellerId);
                    bean.setSellerName(sellerName);
                    bean.setSellerUrl(sellerUrl);
                }

                // ?
                Elements sellerPhone = dataLi.select("em.phone-num");
                if (!sellerPhone.isEmpty()) {
                    bean.setSellerPhone(sellerPhone.first().text());
                }

                // ?
                // Elements sellerAddress = dataLi.select("em.phone-num");

            }
            if (StringUtils.startsWith(data, "?")) {
                bean.setBuyFeeling(StringUtils.trim(StringUtils.substringAfter(data, "")));
            }
        }

        log.debug("Bean : {}", bean);

        bean.persistOnNotExist();
    }
}

From source file:de.micromata.genome.gwiki.jetty.CmdLineInput.java

public static String getInput(String prompt, String defaultValue, boolean allowEmpty) {
    do {//from  w  w  w .  j a v a  2 s . co m
        if (defaultValue == null) {
            message(prompt + ": ");
        } else {
            message(prompt + "[" + defaultValue + "]: ");
        }
        String inp = readLine();
        inp = StringUtils.trim(inp);
        if (defaultValue != null) {
            if (inp.length() == 0) {
                return defaultValue;
            }
        }
        if (allowEmpty == true || inp.length() > 0) {
            return inp;
        }
    } while (true);
}

From source file:com.qcadoo.model.beans.qcadooPlugin.QcadooPluginPlugin.java

public void setState(final String state) {
    this.state = StringUtils.trim(StringUtils.upperCase(state, Locale.ENGLISH));
}

From source file:de.micromata.genome.tpsb.httpmockup.testbuilder.HttpParser.java

private void checkUrlPost() {
    String ct = getHeader("Content-Type");
    if (ct == null) {
        return;/*from  ww w . jav a2  s. c o m*/
    }
    if (ct.contains("application/x-www-form-urlencoded") == false) {
        return;
    }
    String trimmedbody = StringUtils.trim(body);
    if (trimmedbody.isEmpty() == true) {
        return;
    }
    if (StringUtils.isEmpty(queryString) == false) {
        queryString += "&" + trimmedbody;
    } else {
        queryString = trimmedbody;
    }
}

From source file:de.micromata.genome.gwiki.page.impl.wiki.macros.GWikiHtmlTagMacro.java

public static void ensureHtmlAttrRight(MacroAttributes attrs, GWikiContext ctx)
        throws AuthorizationFailedException {
    if (ctx.isAllowTo(GWikiAuthorizationRights.GWIKI_EDITHTML.name()) == true) {
        return;//from   w w  w .j  a  va2 s .  com
    }
    if (restrictedTags.contains(attrs.getCmd()) == true) {
        throw new AuthorizationFailedException("Usage of tag " + attrs.getCmd() + " is not allowed");
    }
    Map<String, String> args = attrs.getArgs().getMap();
    for (Map.Entry<String, String> me : args.entrySet()) {
        String k = me.getKey().toLowerCase();
        if (k.startsWith("on") == true) {
            throw new AuthorizationFailedException("Java Script methods in Macros are not allowed");
        }
        if (k.equals("href") == true || k.equals("src") == true) {
            String v = StringUtils.trim(me.getValue().toLowerCase());
            if (v.startsWith("javascript:") == true) {
                throw new AuthorizationFailedException("Java Script methods in Macros are not allowed");
            }
        }
    }
}

From source file:net.siegmar.japtproxy.fetcher.FetcherHttp.java

/**
 * {@inheritDoc}/*from   ww  w.  j  a v  a 2s .  c  om*/
 */
@Override
public FetchedResourceHttp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final HttpGet httpGet = new HttpGet(targetResource.toExternalForm());

    httpGet.addHeader(HttpHeaderConstants.USER_AGENT,
            StringUtils.trim(StringUtils.defaultString(originalUserAgent) + " " + Util.USER_AGENT));

    if (lastModified != 0) {
        final String lastModifiedSince = Util.getRfc822DateFromTimestamp(lastModified);
        LOG.debug("Setting If-Modified-Since: {}", lastModifiedSince);
        httpGet.setHeader(HttpHeaderConstants.IF_MODIFIED_SINCE, lastModifiedSince);
    }

    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);

        if (LOG.isDebugEnabled()) {
            logResponseHeader(httpResponse.getAllHeaders());
        }

        final int retCode = httpResponse.getStatusLine().getStatusCode();
        if (retCode == HttpServletResponse.SC_NOT_FOUND) {
            httpGet.releaseConnection();
            throw new ResourceUnavailableException("Resource '" + targetResource + " not found");
        }

        if (retCode != HttpServletResponse.SC_OK && retCode != HttpServletResponse.SC_NOT_MODIFIED) {
            throw new IOException("Invalid status code returned: " + httpResponse.getStatusLine());
        }

        final FetchedResourceHttp fetchedResourceHttp = new FetchedResourceHttp(httpResponse);
        fetchedResourceHttp.setModified(lastModified == 0 || retCode != HttpServletResponse.SC_NOT_MODIFIED);

        if (LOG.isDebugEnabled()) {
            final long fetchedTimestamp = fetchedResourceHttp.getLastModified();
            if (fetchedTimestamp != 0) {
                LOG.debug("Response status code: {}, Last modified: {}", retCode,
                        Util.getSimpleDateFromTimestamp(fetchedTimestamp));
            } else {
                LOG.debug("Response status code: {}", retCode);
            }
        }

        return fetchedResourceHttp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceHttp
        if (httpResponse != null) {
            httpResponse.close();
        }

        throw e;
    }
}

From source file:de.micromata.tpsb.doc.renderer.RendererClassUtils.java

private static void addRenderprojectsCps(List<String> cps) {
    String tpsbcp = LocalSettings.get().get("genome.tpsb.renderprojectscp");
    if (StringUtils.isBlank(tpsbcp) == true) {
        return;/*  www. j av a 2 s  . c  om*/
    }
    String[] pathes = StringUtils.split(tpsbcp, ',');
    for (String path : pathes) {
        String spath = StringUtils.trim(path);
        File dir = new File(spath);
        File td = new File(dir, "target/test-classes");
        if (td.exists() == true) {
            cps.add(td.getAbsolutePath());
        }
        td = new File(dir, "target/classes");
        if (td.exists() == true) {
            cps.add(td.getAbsolutePath());
        }
    }

}

From source file:com.thinkbiganalytics.policy.validation.NotNullValidator.java

@Override
public boolean validate(Object value) {

    if (value == null) {
        return false;
    }// w w w.  ja  v a2 s .co  m
    if (!allowEmptyString && value instanceof String) {
        String svalue = (trimString ? StringUtils.trim((String) value) : (String) value);
        return (!StringUtils.isEmpty(svalue));
    }
    return true;
}

From source file:at.beris.virtualfile.shell.Shell.java

public void run() {
    System.out.println("VirtualFile Shell");
    String line;//ww  w . ja  v a 2s  .  c o m
    Pair<Command, List<String>> cmd = null;

    do {
        try {
            System.out.print("> ");
            line = StringUtils.trim(scanner.next());
            cmd = parseCommandLine(line);
            if (commandArgumentsValid(cmd))
                processCommand(cmd);
        } catch (IOException e) {
            logException(e);
            System.out.println("Error: " + e.getMessage());
        }

    } while (cmd != null && cmd.getLeft() != Command.QUIT);
}

From source file:io.apiman.gateway.vertx.api.AuthenticatingRouteMatcher.java

private boolean basicAuth(HttpServerRequest request, String encodedAuth) {
    byte[] authBytes = Base64.decodeBase64(encodedAuth);
    String decodedString = new String(authBytes);
    String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); //$NON-NLS-1$

    if (splitAuth.length != 2)
        return false;

    if (fileBasicAuthData.containsKey(splitAuth[0])) {
        String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0])));

        MessageDigest digest;//ww  w. j av  a2 s.  c  o m
        try {
            digest = MessageDigest.getInstance("SHA-256"); //$NON-NLS-1$
            digest.update(splitAuth[1].getBytes());

            String receivedHash = new String(digest.digest());

            if (storedHash.equals(receivedHash)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e.getCause());
        }
    }

    request.response().headers().add("WWW-Authenticate", "Basic realm=\"" + config.getRealm() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    return false;
}