Example usage for org.apache.commons.lang StringUtils trimToNull

List of usage examples for org.apache.commons.lang StringUtils trimToNull

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils trimToNull.

Prototype

public static String trimToNull(String str) 

Source Link

Document

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

Usage

From source file:com.hmsinc.epicenter.webapp.remoting.GeographyService.java

/**
 * @return//w  w  w .j  ava 2 s . co  m
 *
@Secured("ROLE_USER")
@Transactional(readOnly = true)
@RemoteMethod
public Collection<GeographyDTO> autocompleteGeography() {
   return autocompleteGeography(null, "ALL");
}
*/

@Transactional(readOnly = true)
@RemoteMethod
private List<? extends Geography> getGeographiesInState(final State state, final String text) {
    Validate.notNull(state);
    String query = StringUtils.trimToNull(text);
    final Class<? extends Geography> geographyType;
    if (StringUtils.isNumeric(query)) {
        geographyType = Zipcode.class;
    } else {
        geographyType = County.class;
        query = stripCountyFromQuery(query);
    }
    List<? extends Geography> ret = geographyRepository.getGeographiesInState(state, query, geographyType,
            false);
    if (ret.size() == 0) {
        ret = geographyRepository.getGeographiesInState(state, query, geographyType, true);
    }
    return ret;
}

From source file:mp.platform.cyclone.webservices.CyclosWebServicesClientFactory.java

/**
 * Sets the service client username/*from   www  .j a  v  a  2s.co m*/
 */
public void setUsername(final String username) {
    this.username = StringUtils.trimToNull(username);
    invalidateCache();
}

From source file:mitm.common.dlp.impl.MimeMessageTextExtractorImpl.java

public void setSkipHeaders(Collection<String> headersToSkip) {
    if (headersToSkip == null) {
        return;/*from  w ww  .j a v  a2  s.co m*/
    }

    skipHeaders = Collections.synchronizedSet(new HashSet<String>());

    for (String header : headersToSkip) {
        header = StringUtils.trimToNull(header);

        if (header == null) {
            continue;
        }

        skipHeaders.add(header.toLowerCase());
    }

    logger.info("Skip headers: " + StringUtils.join(skipHeaders, ","));
}

From source file:com.opengamma.bloombergexample.loader.ExampleEquityPortfolioLoader.java

protected Collection<ExternalId> readEquityTickers() {
    Collection<ExternalId> result = new ArrayList<ExternalId>();
    InputStream inputStream = ExampleEquityPortfolioLoader.class.getResourceAsStream("example-equity.csv");
    try {/*  ww  w  .j a v a2  s.  c  o m*/
        if (inputStream != null) {
            List<String> equityTickers = IOUtils.readLines(inputStream);
            for (String idStr : equityTickers) {
                idStr = StringUtils.trimToNull(idStr);
                if (idStr != null && !idStr.startsWith("#")) {
                    result.add(ExternalSchemes.bloombergTickerSecurityId(idStr));
                }
            }
        } else {
            throw new OpenGammaRuntimeException("File '" + EXAMPLE_EQUITY_FILE + "' could not be found");
        }
    } catch (IOException ex) {
        throw new OpenGammaRuntimeException(
                "An error occurred while reading file '" + EXAMPLE_EQUITY_FILE + "'");
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Parsed ").append(result.size()).append(" equities:\n");
    for (ExternalId equityId : result) {
        sb.append("\t").append(equityId.getValue()).append("\n");
    }
    s_logger.info(sb.toString());
    return result;
}

From source file:com.opengamma.web.historicaltimeseries.WebAllHistoricalTimeSeriesResource.java

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)/*from   w ww .jav a  2s.  com*/
public Response postJSON(@FormParam("dataProvider") String dataProvider,
        @FormParam("dataField") String dataField, @FormParam("start") String start,
        @FormParam("end") String end, @FormParam("idscheme") String idScheme,
        @FormParam("idvalue") String idValue) {

    idScheme = StringUtils.trimToNull(idScheme);
    idValue = StringUtils.trimToNull(idValue);
    dataField = StringUtils.trimToNull(dataField);
    start = StringUtils.trimToNull(start);
    end = StringUtils.trimToNull(end);
    dataProvider = StringUtils.trimToNull(dataProvider);

    LocalDate startDate = null;
    boolean validStartDate = true;
    if (start != null) {
        try {
            startDate = LocalDate.parse(start);
            validStartDate = true;
        } catch (DateTimeException e) {
            validStartDate = false;
        }
    }
    LocalDate endDate = null;
    boolean validEndDate = true;
    if (end != null) {
        try {
            endDate = LocalDate.parse(end);
            validEndDate = true;
        } catch (DateTimeException e) {
            validEndDate = false;
        }
    }

    if (dataField == null || idValue == null || !validStartDate || !validEndDate) {
        return Response.status(Status.BAD_REQUEST).build();
    }

    ExternalScheme scheme = ExternalScheme.of(idScheme);
    Set<ExternalId> identifiers = buildSecurityRequest(scheme, idValue);
    Map<ExternalId, UniqueId> added = addTimeSeries(dataProvider, dataField, identifiers, startDate, endDate);

    FlexiBean out = createPostJSONOutput(added, identifiers, scheme, dataProvider, dataField, startDate,
            endDate);
    Response response = Response.ok(getFreemarker().build(JSON_DIR + "timeseries-added.ftl", out)).build();
    return response;
}

From source file:com.hmsinc.epicenter.webapp.remoting.AdminService.java

/**
 * @param obj/*from   w  w w.j a v  a  2s . c  o m*/
 * @return
 */
@Secured("ROLE_ADMIN")
@Transactional
@RemoteMethod
public EpiCenterUser saveUser(EpiCenterUser obj, Long orgId, String password, boolean isOrgAdmin)
        throws PermissionException {

    Validate.notNull(obj);
    Validate.notNull(orgId);
    final Organization org = permissionRepository.load(orgId, Organization.class);
    Validate.notNull(org, "Invalid organization: " + orgId);
    Validate.isTrue(org.isEnabled(), "Organization is disabled.");

    EpiCenterUser user = null;

    final EpiCenterRole orgAdminRole = permissionRepository.getRole("ROLE_ORG_ADMIN");

    if (obj.getId() == null) {
        Validate.notEmpty(password, "No password given");
        user = obj;
        user.setPassword(password);
        permissionRepository.addUser(user);

        org.getUsers().add(user);

        if (isOrgAdmin) {
            user.getRoles().add(orgAdminRole);
        }

        permissionRepository.save(org);
        logger.info("Created user: {}", user);

    } else {

        obj.setPassword(null);
        user = merge(obj, EpiCenterUser.class);
        if (!user.getOrganizations().contains(org)) {
            user.getOrganizations().add(org);
            org.getUsers().add(user);
            permissionRepository.save(org);
        }

        if (isOrgAdmin) {
            if (!user.getRoles().contains(orgAdminRole)) {
                user.getRoles().add(orgAdminRole);
            }
        } else {
            if (user.getRoles().contains(orgAdminRole)) {
                user.getRoles().remove(orgAdminRole);
            }
        }
        permissionRepository.save(user);
        audit("Updated user: " + user.toString());

        final String pw = StringUtils.trimToNull(password);

        if (pw != null) {
            permissionRepository.changePassword(user, pw);
            logger.info("Changed user password: {}", user);
        }
    }

    return user;
}

From source file:ch.entwine.weblounge.security.sql.endpoint.SQLDirectoryProviderEndpoint.java

@PUT
@Path("/account/{id}")
public Response updateAccount(@PathParam("id") String login, @FormParam("password") String password,
        @FormParam("firstname") String firstname, @FormParam("lastname") String lastname,
        @FormParam("initials") String initials, @FormParam("email") String email,
        @FormParam("language") String language, @FormParam("challenge") String challenge,
        @FormParam("response") String response, @Context HttpServletRequest request) {

    // Make sure that the user owns the roles required for this operation
    User user = securityService.getUser();
    if (!SecurityUtils.userHasRole(user, SystemRole.SITEADMIN) && !user.getLogin().equals(login))
        return Response.status(Status.FORBIDDEN).build();

    JpaAccount account = null;/*from  ww w . j  a  v a 2 s  .  c o m*/
    Site site = getSite(request);
    try {
        account = directory.getAccount(site, login);
        if (account == null)
            return Response.status(Status.NOT_FOUND).build();

        // Hash the password
        if (StringUtils.isNotBlank(password)) {
            logger.debug("Hashing password for user '{}@{}' using md5", login, site.getIdentifier());
            String digestPassword = PasswordEncoder.encode(StringUtils.trim(password));
            account.setPassword(digestPassword);
        }

        account.setFirstname(StringUtils.trimToNull(firstname));
        account.setLastname(StringUtils.trimToNull(lastname));
        account.setInitials(StringUtils.trimToNull(initials));
        account.setEmail(StringUtils.trimToNull(email));

        // The language
        if (StringUtils.isNotBlank(language)) {
            try {
                account.setLanguage(LanguageUtils.getLanguage(language));
            } catch (UnknownLanguageException e) {
                return Response.status(Status.BAD_REQUEST).build();
            }
        } else {
            account.setLanguage(null);
        }

        // Hash the response
        if (StringUtils.isNotBlank(response)) {
            logger.debug("Hashing response for user '{}@{}' using md5", login, site.getIdentifier());
            String digestResponse = PasswordEncoder.encode(StringUtils.trim(response));
            account.setResponse(digestResponse);
        }

        directory.updateAccount(account);
        return Response.ok().build();
    } catch (Throwable t) {
        return Response.serverError().build();
    }
}

From source file:mitm.common.postfix.PostfixLogParser.java

public List<String> getRawLogItems(Reader log, final int startIndex, final int maxItems) throws IOException {
    if (startIndex < 0) {
        throw new IllegalArgumentException("startIndex must be >= 0");
    }//from  ww w .java  2s  . c o m

    if (maxItems <= 0) {
        throw new IllegalArgumentException("maxItems must be > 0");
    }

    List<String> logLines = new LinkedList<String>();

    LineNumberReader lineReader = new LineNumberReader(log);

    int index = 0;

    String line;

    while ((line = lineReader.readLine()) != null) {
        line = StringUtils.trimToNull(line);

        if (line == null) {
            continue;
        }

        if (searchPattern == null) {
            if (index >= startIndex) {
                logLines.add(line);
            }

            index++;
        } else {
            /*
             * Search pattern is given. We *must* always check if there is a match
             * before doing anything else
             */
            Matcher matcher = searchPattern.matcher(line);

            if (matcher.find()) {
                if (index >= startIndex) {
                    logLines.add(line);
                }

                index++;
            }
        }

        if (logLines.size() > maxItems) {
            break;
        }
    }

    return logLines;
}

From source file:com.bluexml.xforms.controller.navigation.NavigationManager.java

/**
 * Send XForms to Chiba filter.<br>
 * Inserts session id into form.<br>
 * No data manipulation has to be made here.
 * //from w  w  w. j a  va 2s  . co m
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void sendXForms(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession(true);
    String sessionId = session.getId();

    controller = getController();

    String testStr = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_SERVE_TEST_PAGE.getText()));
    boolean serveTestPage = StringUtils.equals(testStr, "true");
    String pageId = StringUtils.trimToNull(req.getParameter(PAGE_ID));

    // called from a direct link? set our info (pageId, stackId)
    if (pageId == null) {
        // check for a possible initialisation call
        boolean isInit = StringUtils.equals(req.getParameter(MsgId.PARAM_INIT_CALL.getText()), "true");
        if (isInit) {
            ServletOutputStream stream = resp.getOutputStream();
            String result = (loadConfiguration(req, true) == -1) ? "success" : "failure";
            stream.write(result.getBytes());
            stream.close();
            return;
        }
        pageId = NavigationSessionListener.getPageId(sessionId);
        NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);

        // check whether reloading of the mapping.xml file was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_MAPPING_FILE.getText()), "true")) {
            controller.performDynamicReload();
        }
        // check whether reloading of properties/configuration files was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_PROPERTIES.getText()), "true")) {
            int resLoad = loadConfiguration(req, false);
            if (logger.isDebugEnabled()) {
                if (resLoad == -1) {
                    logger.debug("Reloaded properties: OK.");
                } else {
                    String reason = "";
                    switch (resLoad) {
                    case 0:
                        reason = "an exception occured";
                        break;
                    case 1:
                        reason = "properties files";
                        break;
                    case 2:
                        reason = "redirection file";
                        break;
                    }
                    logger.debug("Failed in loading the configuration. Reason: " + reason);
                }
            }
        }
        // set specific CSS if given
        this.setCssUrl(req);
        // initial status message. CAUTION: may be overridden later in case of errors.
        String statusMsg = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_STATUS_MSG.getText()));
        if (statusMsg != null) {
            navigationPath.setStatusMsg(statusMsg);
        }
        // deal with standalone mode
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "true")) {
            controller.setStandaloneMode(true);
        }
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "false")) {
            controller.setStandaloneMode(false);
        }

        PageInfoBean pageInfo = collectPageInfo(req);
        // save session and URL we were called with (useful when a host is multi-domain'ed)
        String curServletURL = this.registerSessionURL(req, sessionId);
        // remember where we are
        navigationPath.setCurrentPage(pageInfo);
        String location = curServletURL + "?pageId=" + pageId + "&stackId=" + navigationPath.getSize();
        // propagate queryString
        location += "&" + req.getQueryString();
        if (serveTestPage == false) {
            // redirect the web client, providing ids we need
            resp.sendRedirect(resp.encodeRedirectURL(location));
            return;
        }
    }
    // the ids are available
    NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);
    if (navigationPath.isEmpty()) {
        // the servlet is called directly with ids we did not register
        throw new ServletException(MsgPool.getMsg(MsgId.MSG_SESSION_TIMED_OUT));
    }
    Page currentPage = navigationPath.peekCurrentPage();
    // set the warning if page was called with an object it can't display
    if (currentPage.isWrongCallType()) {
        navigationPath.setStatusMsg("WARNING: the data Id provided is not appropriate for this form.");
    }

    // get the form template as a string
    String statusDisplayedMsg = navigationPath.getStatusDisplayedMsg();
    Document doc = loadXFormsDocument(req, sessionId, pageId, statusDisplayedMsg, currentPage);

    req.setAttribute(WebFactory.XFORMS_NODE, doc);
    resp.getOutputStream().close();
}

From source file:ips1ap101.web.fragments.FragmentoFiltro1.java

public String getValorTextoFiltro1() {
    return StringUtils.trimToNull(getRecursoDataProvider().getCodigoFuncionSelect());
}