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

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

Introduction

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

Prototype

public static String trimToEmpty(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null .

Usage

From source file:com.mgmtp.jfunk.core.util.CsvDataProcessor.java

/**
 * Processes the specified CSV file. For every line but the header line (which is required), the
 * specified command is executed.//from ww  w .jav  a2 s  .co  m
 * 
 * @param reader
 *            the reader for loading the CSV data
 * @param delimiter
 *            the column separator
 * @param quoteChar
 *            the quote character ('\0' for no quoting)
 * @param command
 *            the command (i. e. a Groovy closure if used in a Groovy script) to be executed for
 *            every processed line
 */
public void processFile(final Reader reader, final String delimiter, final char quoteChar,
        final Runnable command) {
    try {
        List<String> inputLines = CharStreams.readLines(reader);

        StrTokenizer st = StrTokenizer.getCSVInstance();
        st.setDelimiterString(delimiter);
        if (quoteChar != '\0') {
            st.setQuoteChar(quoteChar);
        } else {
            st.setQuoteMatcher(StrMatcher.noneMatcher());
        }

        // extract header
        String headerLine = inputLines.remove(0);
        List<Column> columns = initColumns(st, headerLine);
        for (String line : inputLines) {
            st.reset(line);
            String[] colArray = st.getTokenArray();
            int len = colArray.length;
            checkState(len == columns.size(),
                    "Mismatch between number of header columns and number of line columns.");

            DataSource dataSource = dataSourceProvider.get();
            Configuration config = configProvider.get();
            for (int i = 0; i < len; ++i) {
                String value = StringUtils.trimToEmpty(colArray[i]);

                String dataSetKey = columns.get(i).dataSetKey;
                String key = columns.get(i).key;
                if (dataSetKey != null) {
                    if ("<auto>".equals(value)) {
                        dataSource.resetFixedValue(dataSetKey, key);
                    } else {
                        log.debug("Setting data set entry for " + this + " to value=" + value);
                        dataSource.setFixedValue(dataSetKey, key, value);
                    }
                } else {
                    log.debug("Setting property for " + this + " to value=" + value);
                    config.put(key, value);
                }
            }

            command.run();
        }
    } catch (IOException ex) {
        throw new JFunkException("Error processing CSV data", ex);
    }
}

From source file:de.jfachwert.post.Adresse.java

private static String[] split(String adresse) {
    String[] lines = StringUtils.trimToEmpty(adresse).split("[,\\n$]");
    if (lines.length != 2) {
        throw new LocalizedIllegalArgumentException(adresse, "address");
    }/*  w  w w  .j av  a 2 s.  c o m*/
    List<String> splitted = new ArrayList<>();
    if (hasPLZ(lines[0])) {
        splitted.add(lines[0].trim());
        splitted.addAll(toStrasseHausnummer(lines[1]));
    } else {
        splitted.add(lines[1].trim());
        splitted.addAll(toStrasseHausnummer(lines[0]));
    }
    return splitted.toArray(new String[3]);
}

From source file:com.nesscomputing.syslog4j.impl.log4j.Syslog4jAppenderSkeleton.java

protected void _initialize() {
    String initializedProtocol = initialize();

    if (initializedProtocol != null && this.protocol == null) {
        this.protocol = initializedProtocol;
    }//from  w w  w.j ava2  s  .c  o m

    if (this.protocol != null) {
        try {
            this.syslog = Syslog.getInstance(this.protocol);
            if (this.host != null) {
                this.syslog.getConfig().setHost(this.host);
            }
            if (this.facility != null) {
                this.syslog.getConfig().setFacility(this.facility);
            }
            if (this.port != null) {
                try {
                    int i = Integer.parseInt(this.port);
                    this.syslog.getConfig().setPort(i);

                } catch (NumberFormatException nfe) {
                    LogLog.error(nfe.toString());
                }
            }
            if (this.charSet != null) {
                this.syslog.getConfig().setCharSet(this.charSet);
            }
            if (this.ident != null) {
                this.syslog.getConfig().setIdent(this.ident);
            }
            if (this.localName != null) {
                this.syslog.getConfig().setLocalName(this.localName);
            }

            this.syslog.getConfig()
                    .setTruncateMessage(isTrueOrOn(StringUtils.trimToEmpty(this.truncateMessage)));

            try {
                int i = Integer.parseInt(StringUtils.trimToEmpty(this.maxMessageLength));
                this.syslog.getConfig().setMaxMessageLength(i);

            } catch (NumberFormatException nfe) {
                LogLog.error(nfe.toString());
            }

            if (this.useStructuredData != null) {
                this.syslog.getConfig().setUseStructuredData(isTrueOrOn(this.useStructuredData));
            }
            if (this.syslog.getConfig() instanceof AbstractSyslogConfigIF) {
                AbstractSyslogConfigIF abstractSyslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();

                abstractSyslogConfig.setThreaded(isTrueOrOn(StringUtils.trimToEmpty(this.threaded)));

                try {
                    long l = Long.parseLong(StringUtils.trimToEmpty(this.threadLoopInterval));
                    abstractSyslogConfig.setThreadLoopInterval(l);
                } catch (NumberFormatException nfe) {
                    LogLog.error(nfe.toString());
                }

                if (this.splitMessageBeginText != null) {
                    abstractSyslogConfig.setSplitMessageBeginText(
                            SyslogUtility.getBytes(abstractSyslogConfig, this.splitMessageBeginText));
                }

                if (this.splitMessageEndText != null) {
                    abstractSyslogConfig.setSplitMessageEndText(
                            SyslogUtility.getBytes(abstractSyslogConfig, this.splitMessageEndText));
                }

                try {
                    int i = Integer.parseInt(StringUtils.trimToEmpty(this.maxShutdownWait));
                    abstractSyslogConfig.setMaxShutdownWait(i);

                } catch (NumberFormatException nfe) {
                    LogLog.error(nfe.toString());
                }

                try {
                    int i = Integer.parseInt(StringUtils.trimToEmpty(this.writeRetries));
                    abstractSyslogConfig.setWriteRetries(i);

                } catch (NumberFormatException nfe) {
                    LogLog.error(nfe.toString());
                }
            }

            this.initialized = true;

        } catch (SyslogRuntimeException sre) {
            LogLog.error(sre.toString());
        }
    }
}

From source file:com.github.binlee1990.spider.movie.spider.MovieCrawler.java

@Override
public void visit(Page page) {
    int docid = page.getWebURL().getDocid();
    String url = page.getWebURL().getURL();

    logger.info(url);/*w ww. j a v a 2s  .c  o m*/
    if (!url.startsWith("http://dianying.fm/movie/")) {
        return;
    }

    if (page.getParseData() instanceof HtmlParseData) {
        HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
        String html = htmlParseData.getHtml();

        Document doc = Jsoup.parse(html);

        if (null != doc) {
            Elements filmTitleElements = doc.select(".fm-title");
            if (CollectionUtils.isNotEmpty(filmTitleElements)) {
                String filmTitle = StringUtils.trimToEmpty(filmTitleElements.select("a[name]").text());
                if (StringUtils.isNotBlank(filmTitle)) {
                    // film
                    Film film = createOrQueryFilm(url, doc, filmTitle);
                    logger.info("Add Film: " + filmTitle);

                    if (null != film) {
                        // film_actor
                        addFilmActorList(doc, film);

                        // film_album
                        addFilmAlbumList(doc, film);

                        // film_review
                        addFilmReview(doc, film);

                        // film_genre
                        addFilmGenreList(filmTitleElements, film);

                        // film_region
                        addFilmRegionList(doc, film);
                    }
                }
            }
        }
    }
}

From source file:com.nesscomputing.migratory.migration.sql.SqlScript.java

/**
 * Turns these lines in a series of statements.
 */// w w  w  . j a  v a2s  . co  m
List<SqlStatement> linesToStatements(List<String> lines) {
    final List<SqlStatement> statements = Lists.newArrayList();
    final StringBuilder statementSql = new StringBuilder();
    int count = 0;

    String delimiter = DEFAULT_STATEMENT_DELIMITER;

    for (final String line : lines) {
        if (StringUtils.isBlank(line)) {
            continue;
        }

        if (statementSql.length() > 0) {
            statementSql.append(" ");
        }
        statementSql.append(line);

        final String oldDelimiter = delimiter;
        delimiter = changeDelimiterIfNecessary(statementSql.toString(), line, delimiter);
        if (!StringUtils.equals(delimiter, oldDelimiter) && isDelimiterChangeExplicit()) {
            statementSql.setLength(0);
            continue; // for
        }

        if (StringUtils.endsWith(line, delimiter)) {
            // Trim off the delimiter at the end.
            statementSql.setLength(statementSql.length() - delimiter.length());
            statements.add(new SqlStatement(count++, StringUtils.trimToEmpty(statementSql.toString())));
            LOG.debug("Found statement: %s", statementSql);

            if (!isDelimiterChangeExplicit()) {
                delimiter = DEFAULT_STATEMENT_DELIMITER;
            }
            statementSql.setLength(0);
        }
    }

    // Catch any statements not followed by delimiter.
    if (statementSql.length() > 0) {
        statements.add(new SqlStatement(count++, StringUtils.trimToEmpty(statementSql.toString())));
    }

    return statements;
}

From source file:com.nesscomputing.httpclient.response.ContentResponseHandler.java

/**
 * Processes the client response.//from w  w  w.  j ava  2  s  .co  m
 */
@Override
public T handle(final HttpClientResponse response) throws IOException {
    if (allowRedirect && response.isRedirected()) {
        LOG.debug("Redirecting based on '%d' response code", response.getStatusCode());
        throw new RedirectedException(response);
    } else {
        // Find the response stream - the error stream may be valid in cases
        // where the input stream is not.
        InputStream is = null;
        try {
            is = response.getResponseBodyAsStream();
        } catch (IOException e) {
            LOG.warnDebug(e, "Could not locate response body stream");
            // normal for 401, 403 and 404 responses, for example...
        }

        if (is == null) {
            // Fall back to zero length response.
            is = new NullInputStream(0);
        }

        try {
            final Long contentLength = response.getContentLength();

            if (maxBodyLength > 0) {
                if (contentLength != null && contentLength > maxBodyLength) {
                    throw new SizeExceededException("Content-Length: " + contentLength);
                }

                LOG.debug("Limiting stream length to '%d'", maxBodyLength);
                is = new SizeLimitingInputStream(is, maxBodyLength);
            }

            final String encoding = StringUtils.trimToEmpty(response.getHeader("Content-Encoding"));

            if (StringUtils.equalsIgnoreCase(encoding, "lz4")) {
                LOG.debug("Found LZ4 stream");
                is = new LZ4BlockInputStream(is);
            } else if (StringUtils.equalsIgnoreCase(encoding, "gzip")
                    || StringUtils.equalsIgnoreCase(encoding, "x-gzip")) {
                LOG.debug("Found GZIP stream");
                is = new GZIPInputStream(is);
            } else if (StringUtils.equalsIgnoreCase(encoding, "deflate")) {
                LOG.debug("Found deflate stream");
                final Inflater inflater = new Inflater(true);
                is = new InflaterInputStream(is, inflater);
            }

            return contentConverter.convert(response, is);
        } catch (IOException ioe) {
            return contentConverter.handleError(response, ioe);
        }
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.admin.source.Addshortcode.java

/**
 * Set the class variables that represent form parameters.
 *
 * @param request// w  w  w  .j a v  a2 s  .co m
 */
private void setClassParameters(HttpServletRequest request) {
    codenumber = StringUtils.trimToEmpty(request.getParameter("shortcode"));
    networkuuid = StringUtils.trimToEmpty(request.getParameter("network"));
    accountuuid = StringUtils.trimToEmpty(request.getParameter("account"));

}

From source file:com.omertron.themoviedbapi.model.Person.java

public void setJob(String job) {
    this.job = StringUtils.trimToEmpty(job);
}

From source file:com.jeans.iservlet.service.rest.impl.SoftwareRestServiceImpl.java

@Override
@Transactional/*from   w  w  w .  ja v a  2 s.c o  m*/
public SoftwareResource create(SoftwareResource resource) {
    if (resource.getId() < 0) {
        resource.setId(0);
        return resource;
    } else {
        Software sw = new Software();
        // 1. company?
        Company company = compDao.getById(Company.class, resource.getCompanyId());
        if (null == company) {
            return null;
        }
        sw.setCompany(company);
        sw.setType(AssetConstants.SOFTWARE_ASSET);
        // 2. catalog?
        byte catalog = resource.getCatalog();
        if ((catalog < AssetConstants.OPERATING_SYSTEM_SOFTWARE
                || catalog > AssetConstants.APPLICATION_SOFTWARE) && catalog != AssetConstants.OTHER_SOFTWARE) {
            return null;
        }
        sw.setCatalog(catalog);
        // 3. name?
        if (StringUtils.isBlank(resource.getName())) {
            return null;
        }
        sw.setName(StringUtils.left(StringUtils.trimToEmpty(resource.getName()), 32));
        sw.setVendor(StringUtils.left(StringUtils.trimToEmpty(resource.getVendor()), 32));
        sw.setModelOrVersion(StringUtils.left(StringUtils.trimToEmpty(resource.getModelOrVersion()), 64));
        sw.setAssetUsage(StringUtils.left(StringUtils.trimToEmpty(resource.getAssetUsage()), 255));
        sw.setPurchaseTime(resource.getPurchaseTime());
        // 4. quantity?0
        if (resource.getQuantity() <= 0) {
            return null;
        }
        sw.setQuantity(resource.getQuantity());
        // 5. cost?
        if (resource.getCost().doubleValue() < 0) {
            return null;
        }
        sw.setCost(resource.getCost());
        // 6. state?IN_USEIDLE
        byte state = resource.getState();
        if (state != AssetConstants.IN_USE && state != AssetConstants.IDLE) {
            return null;
        }
        sw.setState(state);
        sw.setComment(StringUtils.left(StringUtils.trimToEmpty(resource.getComment()), 255));
        // 7. softwareType?
        byte softwareType = resource.getSoftwareType();
        if (softwareType < AssetConstants.COMMERCIAL_SOFTWARE
                || softwareType > AssetConstants.OTHER_TYPE_SOFTWARE) {
            return null;
        }
        sw.setSoftwareType(softwareType);
        sw.setLicense(StringUtils.left(StringUtils.trimToEmpty(resource.getLicense()), 64));
        sw.setExpiredTime(resource.getExpiredTime());
        swDao.save(sw);

        return ResourceFactory.createResource(Software.class, SoftwareResource.class, sw);
    }
}

From source file:de.jfachwert.post.Postfach.java

private static String[] split(String postfach) {
    String[] lines = StringUtils.trimToEmpty(postfach).split("[,\\n$]");
    String[] splitted = { "", lines[0] };
    if (lines.length == 2) {
        splitted = lines;//from w  ww .  java  2 s.co m
    } else if (lines.length > 2) {
        throw new InvalidValueException(postfach, "post_office_box");
    }
    return splitted;
}