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.googlecode.psiprobe.controllers.sessions.ListSessionsController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    boolean calcSize = ServletRequestUtils.getBooleanParameter(request, "size", false)
            && SecurityUtils.hasAttributeValueRole(getServletContext(), request);

    SessionSearchInfo searchInfo = new SessionSearchInfo();
    searchInfo.setSearchAction(StringUtils.trimToNull(
            ServletRequestUtils.getStringParameter(request, "searchAction", SessionSearchInfo.ACTION_NONE)));
    HttpSession sess = request.getSession();

    if (searchInfo.isApply()) {
        searchInfo.setSessionId(//ww w  .  ja  v  a2 s . c  o m
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchSessionId")));
        searchInfo.setLastIP(
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchLastIP")));

        searchInfo.setAgeFrom(
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchAgeFrom")));
        searchInfo.setAgeTo(
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchAgeTo")));
        searchInfo.setIdleTimeFrom(
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchIdleTimeFrom")));
        searchInfo.setIdleTimeTo(
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchIdleTimeTo")));
        searchInfo.setAttrName(
                StringUtils.trimToNull(ServletRequestUtils.getStringParameter(request, "searchAttrName")));
        if (sess != null) {
            sess.setAttribute(SessionSearchInfo.SESS_ATTR_NAME, searchInfo);
        }
    } else if (sess != null) {
        if (searchInfo.isClear()) {
            sess.removeAttribute(SessionSearchInfo.SESS_ATTR_NAME);
        } else {
            SessionSearchInfo ss = (SessionSearchInfo) sess.getAttribute(SessionSearchInfo.SESS_ATTR_NAME);
            if (ss != null) {
                searchInfo = ss;
            }
        }
    }

    // context is not specified we'll retrieve all sessions of the container

    List ctxs;
    if (context == null) {
        ctxs = getContainerWrapper().getTomcatContainer().findContexts();
    } else {
        ctxs = new ArrayList();
        ctxs.add(context);
    }

    List sessionList = new ArrayList();
    for (Iterator it = ctxs.iterator(); it.hasNext();) {
        Context ctx = (Context) it.next();
        if (ctx != null && ctx.getManager() != null && (!searchInfo.isApply() || searchInfo.isUseSearch())) {
            Session[] sessions = ctx.getManager().findSessions();
            for (int i = 0; i < sessions.length; i++) {
                Session session = sessions[i];
                ApplicationSession appSession = ApplicationUtils.getApplicationSession(session, calcSize,
                        searchInfo.isUseAttr());
                if (appSession != null && matchSession(appSession, searchInfo)) {
                    if (ctx.getName() != null) {
                        appSession.setApplicationName(ctx.getName().length() > 0 ? ctx.getName() : "/");
                    }
                    sessionList.add(appSession);
                }
            }
        }
    }

    if (sessionList.isEmpty() && searchInfo.isApply()) {
        synchronized (sess) {
            populateSearchMessages(searchInfo);
        }
    }

    ModelAndView modelAndView = new ModelAndView(getViewName(), "sessions", sessionList);
    modelAndView.addObject("searchInfo", searchInfo);

    return modelAndView;
}

From source file:com.seyren.core.service.notification.TwilioNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String twilioUrl = StringUtils.trimToNull(seyrenConfig.getTwilioUrl());

    if (twilioUrl == null) {
        LOGGER.warn("Twilio URL needs to be set before sending notifications to Twilio");
        return;/*from  w  w  w.j  a va  2  s  .  c om*/
    }

    String body;
    if (check.getState() == AlertType.ERROR) {
        body = "ERROR Check " + check.getName() + " has exceeded its threshold.";
    } else if (check.getState() == AlertType.OK) {
        body = "OK Check " + check.getName() + " has been resolved.";
    } else if (check.getState() == AlertType.WARN) {
        body = "WARN Check " + check.getName() + " has exceeded its threshold.";
    } else {
        LOGGER.warn("Did not send notification to Twilio for check in state: {}", check.getState());
        body = null;
    }

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("To", subscription.getTarget()));
    params.add(new BasicNameValuePair("From", seyrenConfig.getTwilioPhoneNumber()));
    params.add(new BasicNameValuePair("Body", body));

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();

    HttpPost post = new HttpPost(twilioUrl + "/" + seyrenConfig.getTwilioAccountSid() + "/Messages");
    try {
        String credentials = seyrenConfig.getTwilioAccountSid() + ":" + seyrenConfig.getTwilioAuthToken();
        post.setHeader(new BasicHeader("Authorization",
                "Basic " + Base64.encodeBase64String(credentials.getBytes("UTF-8"))));

        HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() / 100 != 2)
            throw new IOException("API request failed: " + response.getStatusLine());
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Twilio at " + twilioUrl + " failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:ips1ap101.lib.core.app.ConsultaBusqueda.java

/**
 * @return the select statement/*from ww  w  . java2 s  .c  o  m*/
 */
public String getQuerySql() {
    InterpreteSql interpreteSql = TLC.getInterpreteSql();
    String querySql = StringUtils.trimToNull(select);
    if (querySql != null) {
        String criteria = getCriteriosConjugados();
        if (criteria != null && !criteria.isEmpty()) {
            querySql += " WHERE (" + criteria + ") ";
        }
        querySql = interpreteSql.getComandoSelect(querySql);
    }
    return querySql;
}

From source file:com.bluexml.xforms.servlets.DeleteServlet.java

/**
 * Delete.//w  ww .j av  a  2  s . c o m
 * 
 * @param req
 *            the req
 * @throws ServletException
 *             the servlet exception
 */
protected void delete(HttpServletRequest req) throws ServletException {
    AlfrescoController controller = AlfrescoController.getInstance();
    try {
        String dataId = StringUtils.trimToNull(req.getParameter(DATA_ID));
        dataId = controller.patchDataId(dataId);
        String userName = req.getParameter(MsgId.PARAM_USER_NAME.getText());
        AlfrescoTransaction transaction = createTransaction(controller, userName);
        controller.delete(transaction, dataId);
        transaction.executeBatch();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.bluexml.xforms.actions.GetAction.java

@Override
public Node resolve() throws ServletException {
    Page currentPage = navigationPath.peekCurrentPage();
    String formName = currentPage.getFormName();
    String dataId = currentPage.getDataId();
    FormTypeEnum formType = currentPage.getFormType();
    Document node = currentPage.getNode();

    boolean formIsReadOnly = !StringUtils.equals(currentPage.getDataType(), currentPage.getFormName());
    if (StringUtils.trimToNull(dataId) != null || node == null) {
        if (formType == FormTypeEnum.FORM) {
            boolean massTagging = currentPage.isMassTagging(); // #1241
            String massIds = currentPage.getMassIds();

            GetInstanceFormBean bean = new GetInstanceFormBean(formName, dataId, formIsReadOnly, massTagging,
                    massIds);// w w w.ja v a 2 s . c  om
            node = controller.getInstanceForm(transaction, bean);
        } else if (formType == FormTypeEnum.CLASS) {
            node = controller.getInstanceClass(transaction, formName, dataId, formIsReadOnly, false);
        } else if (formType == FormTypeEnum.WKFLW) {
            node = getInstanceWorkflow(currentPage, formName);
        } else if ((formType == FormTypeEnum.LIST) || (formType == FormTypeEnum.SELECTOR)) {
            return getInstanceListOrSelector(formName, formType);
        } else if (formType == FormTypeEnum.SEARCH) {
            node = controller.getInstanceSearch(formName);
        }
    }

    return node;
}

From source file:com.seyren.core.service.notification.HttpNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String httpUrl = StringUtils.trimToNull(subscription.getTarget());

    if (httpUrl == null) {
        LOGGER.warn("URL needs to be set before sending notifications to HTTP");
        return;/*from ww  w.  ja va 2 s  .co  m*/
    }
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("preview", getPreviewImage(check));

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost post;

    if (StringUtils.isNotBlank(seyrenConfig.getHttpNotificationUrl())) {
        post = new HttpPost(seyrenConfig.getHttpNotificationUrl());
    } else {
        post = new HttpPost(subscription.getTarget());
    }

    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to HTTP", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.bluexml.xforms.generator.forms.modelelement.ModelElementEnumeration.java

@Override
public Element getModelElement() {
    Element enumsInstance = XFormsGenerator.createElement("instance", XFormsGenerator.NAMESPACE_XFORMS);
    // String dataSourceURI = MsgId.INT_URI_SCHEME_READER + "enum/" + getParameters();
    String dataSourceURI = MsgId.INT_URI_SCHEME_READER + "enum?" + buildEnumActionUriFragment(selectBean);

    if (StringUtils.trimToNull(selectBean.getDataSourceUri()) != null) { // #1660
        dataSourceURI = selectBean.getDataSourceUri();
    }/*from  ww w.j  av a  2 s.co m*/

    enumsInstance.setAttribute("src", dataSourceURI);
    enumsInstance.setAttribute("id", enumInstanceName);
    return enumsInstance;
}

From source file:com.bluexml.side.form.workflow.utils.WorkflowInitialization.java

/**
 * Launch initialization from a Workflow Form Collection
 * /*ww w .java2 s  .com*/
 * @param fc
 * @param domain
 * @return
 */
public static Command initialize(WorkflowFormCollection fc, EditingDomain domain) {
    CompoundCommand cmd = null;
    Process p = fc.getLinked_process();
    if (p != null) {
        // fix update fc.name
        if (StringUtils.trimToNull(fc.getName()) == null) {
            fc.setName(p.getName());
        }

        boolean doWork = true;
        if (fc.getForms().size() > 0) {
            doWork = UIUtils.showConfirmation("Workflow already set",
                    "This Workflow Form Collection has already been set. Do you want to overwrite it?");
        }

        if (doWork) {
            cmd = new CompoundCommand();
            // Delete all childs:
            if (fc.getForms().size() > 0) {
                cmd.append(RemoveCommand.create(domain, fc.getForms()));
            }
            // Get All Tasks
            List<State> l = new ArrayList<State>();
            l.add(p.getStartstate());
            l.addAll(p.getTasknode());

            // List of Form
            List<FormWorkflow> lf = new ArrayList<FormWorkflow>();

            // For each task we create a form
            for (State s : l) {
                FormWorkflow fw = createTaskForForm(s);

                lf.add(fw);
            }
            cmd.append(AddCommand.create(domain, fc, FormPackage.eINSTANCE.getFormCollection_Forms(), lf));
        }
    } else {
        UIUtils.showError("No Process defined",
                "No Process has been defined. \n" + "Choose one and run Initialize again.");
    }
    return cmd;
}

From source file:com.enonic.cms.business.SitePropertiesServiceImpl.java

public String getProperty(String key, SiteKey siteKey) {
    Properties props = doGetSiteProperties(siteKey);
    if (props == null) {
        throw new IllegalArgumentException("No properties for site " + siteKey);
    }//from  w w  w. j  a  v  a 2 s  .  c  om

    return StringUtils.trimToNull(props.getProperty(key));
}

From source file:cn.vlabs.duckling.vwb.service.init.SQLReader.java

public String next() throws WrongSQL {
    if (!isClosed()) {
        StringBuffer buffer = new StringBuffer();

        String line = null;//w  w w  .  j  ava2s . com
        try {
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (isDelimiter(line)) {
                    changeDelimiter(line);
                } else if (isComment(line)) {
                    //FIXME Do not support multiline comment, Just throw off now.
                } else {
                    if (line.endsWith(delimeter)) {
                        line = line.substring(0, line.length() - delimeter.length());
                        buffer.append(line + "\n");
                        return StringUtils.trimToNull(buffer.toString());
                    } else
                        buffer.append(line + "\n");
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            log.debug("", e);
            close();
        }
        if (line == null) {
            close();
        }
        return StringUtils.trimToNull(buffer.toString());
    }
    return null;
}