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.bluexml.side.clazz.edit.ui.actions.initializer.creator.ClassModelCreator.java

@Override
protected void headLessInitialize() throws Exception {
    // create packages      
    com.bluexml.side.common.Package parent = (Model) newRootObject;
    if (StringUtils.trimToNull(packages) != null) {
        String[] split = packages.split("/");
        for (String string : split) {
            ClassPackage createClassPackage = ClazzFactory.eINSTANCE.createClassPackage();
            createClassPackage.setName(string);
            parent.getPackageSet().add(createClassPackage);
            parent = createClassPackage;
        }/*from www.j a  va 2 s.  c  o m*/
    }

    rootDiagram = parent;
}

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

/**
 * Update./*w w  w  .  j  a v a2  s  .c o  m*/
 * 
 * @param req
 *            the req
 * @throws ServletException
 *             the servlet exception
 */
protected void update(HttpServletRequest req) throws ServletException {
    AlfrescoController controller = AlfrescoController.getInstance();
    try {
        Node node = getDocumentReq(req);
        String skipIdStr = StringUtils.trimToNull(req.getParameter(ID_AS_SERVLET));
        boolean idAsServlet = !StringUtils.equals(skipIdStr, "false");

        String userName = req.getParameter(MsgId.PARAM_USER_NAME.getText());
        AlfrescoTransaction transaction = createTransaction(controller, userName);
        controller.persistClass(transaction, node, idAsServlet, null);
        transaction.executeBatch();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.ActionsHolderLoader.java

protected void loadShortcut(Action instance, Element element) {
    String shortcut = StringUtils.trimToNull(element.attributeValue("shortcut"));
    if (StringUtils.isNotEmpty(shortcut)) {
        instance.setShortcut(loadShortcut(shortcut));
    }/*from  w w w.j ava2s  . co  m*/
}

From source file:com.jive.myco.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 www. jav  a 2s  .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().build();

    HttpPost 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.seyren.core.service.notification.BigPandaNotificationService.java

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

    String bigPandaAppKey = StringUtils.trimToNull(subscription.getTarget());
    if (bigPandaAppKey == null) {
        LOGGER.warn(//from  ww  w .ja v a2 s.c  o m
                "BigPanda Integration App Key in Subscription Target needs to be set before sending notifications to BigPanda");
        return;
    }

    for (Alert alert : alerts) {

        String level = alert.getToType().toString();
        String bigPandaStatus;
        if (level == "ERROR") {
            bigPandaStatus = "critical";
        } else if (level == "WARN") {
            bigPandaStatus = "warning";
        } else if (level == "OK") {
            bigPandaStatus = "ok";
        } else {
            LOGGER.warn("Unknown level {} specified in alert. Can't send to BigPanda.", level);
            return;
        }

        String checkUrl = seyrenConfig.getBaseUrl() + "/#/checks/" + check.getId();
        Long tstamp = alert.getTimestamp().getMillis() / 1000;

        Map<String, Object> body = new HashMap<String, Object>();
        body.put("app_key", bigPandaAppKey);
        body.put("status", bigPandaStatus);
        body.put("service", check.getName());
        body.put("check", alert.getTarget());
        body.put("description", check.getDescription());
        body.put("timestamp", tstamp);
        body.put("seyrenCheckUrl", checkUrl);
        body.put("currentValue", alert.getValue());
        body.put("thresholdWarning", alert.getWarn());
        body.put("thresholdCritical", alert.getError());
        body.put("previewGraph", getPreviewImageUrl(check));

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

        if (StringUtils.isNotBlank(seyrenConfig.getBigPandaNotificationUrl())) {
            post = new HttpPost(seyrenConfig.getBigPandaNotificationUrl());
        } else {
            LOGGER.warn(
                    "BigPanda API URL in Seyren Config needs to be set before sending notifications to BigPanda");
            return;
        }

        String authBearer;
        if (StringUtils.isNotBlank(seyrenConfig.getBigPandaAuthBearer())) {
            authBearer = seyrenConfig.getBigPandaAuthBearer();
        } else {
            LOGGER.warn(
                    "BigPanda Auth Bearer in Seyren Config needs to be set before sending notifications to BigPanda");
            return;
        }

        try {
            post.addHeader("Authorization", "Bearer " + authBearer);
            HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            LOGGER.info("Sending alert to BigPanda (AppKey: {}, Check: {}, Target: {}, Status: {})",
                    bigPandaAppKey, check.getName(), alert.getTarget(), bigPandaStatus);
            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.egt.core.util.JS.java

public static String getConfirmDialogJavaScript(String confirmMessage, boolean blur) {
    VelocityContext context = new VelocityContext();
    context.put("confirmMessage", StringUtils.trimToNull(confirmMessage));
    context.put("blur", blur ? "blur" : null);
    return merge("js-confirm-discard", context);
}

From source file:com.bluexml.side.build.tools.reader.FeatureReader.java

public Feature read(File project) throws Exception {
    logger.debug("Read Feature :" + project);
    // get properties

    File featureXMLFile = new File(project, "feature.xml");

    Feature feature = new Feature();

    Document doc = new SAXBuilder().build(featureXMLFile);
    Element root = doc.getRootElement();

    String id = root.getAttributeValue("id");
    feature.setId(id);//from  ww  w.  j  a va 2s .c  o  m

    String version = root.getAttributeValue("version");
    feature.setVersion(version);

    String provider_name = root.getAttributeValue("provider-name");
    if (StringUtils.trimToNull(provider_name) == null
            || !provider_name.equals(DependencyTree.getSampleFeature().getAttributeValue("provider-name"))) {
        this.registries.getAnomaly().addFeatureBadProvider(id);
    }

    String description = root.getChildText("description");
    if (StringUtils.trimToNull(description) == null || description.startsWith("[")) {
        this.registries.getAnomaly().addFeatureNoDescription(id);
    }
    String copyright = root.getChildText("copyright");
    if (StringUtils.trimToNull(copyright) == null || copyright.equals("[Enter Copyright Description here.]")) {
        this.registries.getAnomaly().addFeatureNoCopyright(id);
    }
    String license = root.getChildText("license");
    if (StringUtils.trimToNull(license) == null || license.equals("[Enter License Description here.]")) {
        this.registries.getAnomaly().addFeatureNoLicence(id);
    }

    if (readPlugins) {
        /**
         * read plugins in this feature
         */
        List<?> listPlugins = root.getChildren("plugin");

        for (Object object : listPlugins) {
            Element current = (Element) object;
            String pluginId = current.getAttributeValue("id");
            String pluginVersion = current.getAttributeValue("version");
            Plugin p;
            boolean side = true;

            if (registries.pluginsRegister.containsKey(pluginId)) {
                logger.debug("get plugin from regitry :" + pluginId);
                // search if this plugin have been previously read (from another feature)
                p = registries.pluginsRegister.get(pluginId);
            } else {
                File pluginFolder = registries.getProjectFolder(pluginId, id);
                if (pluginFolder != null) {
                    logger.debug("Read plugin from file " + pluginId);
                    PluginReader pr = new PluginReader(registries, props);
                    p = pr.read(pluginFolder);
                } else {
                    side = false;
                    logger.warn(id + " : plugin project not found, create plugin object with reference");
                    p = new Plugin();
                    p.setId(pluginId);
                    p.setVersion(pluginVersion);
                }
                logger.debug("Reccord Plugin :" + p.getId());
                registries.pluginsRegister.put(pluginId, p);
            }
            if (side || addAll) {
                logger.debug("add :" + feature + " ->" + p);
                Utils.add(registries.tree, feature, p);
                feature.getPlugins().add(p);
            }
        }

    }

    if (readIncludedFeatures) {
        List<?> listIncludedFeatures = root.getChildren("includes");

        for (Object object : listIncludedFeatures) {
            Element currentNode = (Element) object;
            String inculdedFeatureId = currentNode.getAttributeValue("id");
            boolean side = true;
            Feature f = registries.featuresRegister.get(inculdedFeatureId);

            if (f == null) {
                File featureFolder = registries.getProjectFolder(inculdedFeatureId, id);
                if (featureFolder != null) {
                    f = read(featureFolder);
                } else {
                    // not found in repository, not SIDE
                    side = false;
                    f = new Feature();
                    f.setId(inculdedFeatureId);
                    f.setVersion(currentNode.getAttributeValue("version"));

                }
            }
            if (side || addAll) {
                registries.featuresRegister.put(inculdedFeatureId, f);
                Utils.add(registries.tree, feature, f);
                feature.getIncludedFeatures().add(f);
            }
        }
    }

    return feature;
}

From source file:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);//from  w  ww.  ja  v  a 2  s.  com
    } else if (pathInfo == null || pathInfo.length() == 1) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } else {
        String referenceId = pathInfo.substring(1);
        boolean pending = Boolean.parseBoolean(request.getParameter("pending"));
        serialize(referenceId, pending, response);
    }
}

From source file:com.hmsinc.epicenter.surveillance.notification.EventNotifierUtils.java

public static String makeAgeGroupAndGenderString(final Anomaly anomaly) {

    // Just do this in Java because it's too goofy in Velocity
    final String genders = StringUtils.trimToNull(makeAttributeString(
            anomaly.getSet().getAttribute(com.hmsinc.epicenter.model.attribute.Gender.class)));
    final String ageGroups = StringUtils.trimToNull(makeAttributeString(
            anomaly.getSet().getAttribute(com.hmsinc.epicenter.model.attribute.AgeGroup.class)));

    final StringBuilder sb = new StringBuilder();
    if (genders != null || ageGroups != null) {
        if (ageGroups != null) {
            sb.append("grouped by age as ").append(ageGroups);
        }/*from   w ww. ja v  a 2s. c  o m*/
        if (genders != null) {
            if (sb.length() > 0) {
                sb.append("; and ");
            }
            sb.append("grouped by gender as ").append(genders);
        }
        sb.append(") ");
        sb.insert(0, "(for patients ");
    }

    return sb.toString();
}

From source file:ch.entwine.weblounge.common.impl.util.doc.EndpointDocumentationGenerator.java

/**
 * Handles the replacement of the variable strings within textual templates
 * and also allows the setting of variables for the control of logical
 * branching within the text template as well<br/>
 * Uses and expects freemarker (http://freemarker.org/) style templates (that
 * is using ${name} as the marker for a replacement)<br/>
 * NOTE: These should be compatible with Velocity
 * (http://velocity.apache.org/) templates if you use the formal notation
 * (formal: ${variable}, shorthand: $variable)
 * //from   ww w. j a  va 2 s. com
 * @param templateName
 *          this is the key to cache the template under
 * @param textTemplate
 *          a freemarker/velocity style text template, cannot be null or empty
 *          string
 * @param data
 *          a set of replacement values which are in the map like so:<br/>
 *          key => value (String => Object)<br/>
 *          "username" => "aaronz"<br/>
 * @return the processed template
 */
private static String processTextTemplate(String templateName, String textTemplate, Map<String, Object> data) {

    if (freemarkerConfig == null)
        throw new IllegalStateException("FreemarkerConfig is not initialized");
    if (StringUtils.trimToNull(templateName) == null)
        throw new IllegalArgumentException("The templateName cannot be null or empty string, "
                + "please specify a key name to use when processing this template (can be anything moderately unique)");
    if (data == null || data.size() == 0)
        return textTemplate;
    if (StringUtils.trimToNull(textTemplate) == null)
        throw new IllegalArgumentException("The textTemplate cannot be null or empty string, "
                + "please pass in at least something in the template or do not call this method");

    // get the template
    Template template = null;
    try {
        template = new Template(templateName, new StringReader(textTemplate), freemarkerConfig);
    } catch (ParseException e) {
        String msg = "Failure while parsing the Doc template (" + templateName + "), template is invalid: " + e
                + " :: template=" + textTemplate;
        logger.error(msg);
        throw new RuntimeException(msg, e);
    } catch (IOException e) {
        throw new RuntimeException("Failure while creating freemarker template", e);
    }

    // process the template
    String result = null;
    try {
        Writer output = new StringWriter();
        template.process(data, output);
        result = output.toString();
        logger.debug("Generated complete document ({} chars) from template ({})", result.length(),
                templateName);
    } catch (TemplateException e) {
        result = "Failed while processing the template (" + templateName + "): " + e.getMessage() + "\n";
        result += "Template: " + textTemplate + "\n";
        result += "Data: " + data;
        logger.error("Failed while processing the Doc template ({}): {}", templateName, e);
    } catch (IOException e) {
        throw new RuntimeException("Failure while sending freemarker output to stream", e);
    }

    return result;
}