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

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

Introduction

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

Prototype

public static String stripToNull(String str) 

Source Link

Document

Strips whitespace from the start and end of a String returning null if the String is empty ("") after the strip.

This is similar to #trimToNull(String) but removes whitespace.

Usage

From source file:rapture.dp.invocable.ftp.steps.SendFileStep.java

@Override
public String invoke(CallingContext ctx) {
    decision = Kernel.getDecision();
    try {/*from www  .j a v a  2  s  .  c om*/
        decision.setContextLiteral(ctx, getWorkerURI(), "STEPNAME", getStepName());

        String configUri = decision.getContextValue(ctx, getWorkerURI(), "FTP_CONFIGURATION");
        if (configUri == null) {
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    "Problem in SendFileStep " + getStepName() + " - parameter FTP_CONFIGURATION is not set",
                    true);
            decision.setContextLiteral(ctx, getWorkerURI(), getStepName(), "FTP_CONFIGURATION not set");
            return getErrorTransition();
        }

        if (!Kernel.getDoc().docExists(ctx, configUri)) {
            decision.setContextLiteral(ctx, getWorkerURI(), getStepName(),
                    "Cannot load FTP_CONFIGURATION from " + configUri);
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    "Problem in " + getStepName() + ": Cannot load FTP_CONFIGURATION from " + configUri, true);
            return getErrorTransition();
        }

        String copy = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "COPY_FILES"));
        if (copy == null) {
            decision.setContextLiteral(ctx, getWorkerURI(), getStepName(),
                    "COPY_FILES context variable is not set");
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    getStepName() + ": No files to copy - COPY_FILES context variable is not set", false);
            return getNextTransition();
        }

        Map<String, Object> map = JacksonUtil.getMapFromJson(renderTemplate(ctx, copy));

        String retval = getNextTransition();
        int failCount = 0;
        Connection connection = new SFTPConnection(configUri).setContext(ctx);
        List<FTPRequest> requests = new ArrayList<>();
        for (Entry<String, Object> e : map.entrySet()) {
            String remote = e.getValue().toString();
            // If the target is a URI then just use the leaf name. Eg blob://foo/bar/baz -> baz
            if (remote.contains("://"))
                remote = new RaptureURI(remote, Scheme.DOCUMENT).getLeafName();
            FTPRequest request = new FTPRequest(Action.WRITE).setLocalName(e.getKey()).setRemoteName(remote);
            connection.doAction(request);
            if (!request.getStatus().equals(Status.SUCCESS)) {
                retval = getFailTransition();
                decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Unable to send " + e.getKey(), true);
                failCount++;
            }
            requests.add(request);
        }
        if (failCount > 0) {
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    "Unable to send " + failCount + " of " + map.size() + " files)", true);
        } else {
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), getStepName() + ": All files sent", false);
        }
        decision.setContextLiteral(ctx, getWorkerURI(), getStepName(),
                "Sent " + (map.size() - failCount) + " of " + map.size() + " files)");
        return retval;
    } catch (Exception e) {
        decision.setContextLiteral(ctx, getWorkerURI(), getStepName(),
                "Unable to send files : " + e.getLocalizedMessage());
        decision.setContextLiteral(ctx, getWorkerURI(), getErrName(), ExceptionToString.summary(e));
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": " + ExceptionToString.getRootCause(e).getLocalizedMessage(),
                true);
        return getErrorTransition();
    }
}

From source file:rapture.dp.invocable.notification.steps.NotificationStep.java

@Override
public String invoke(CallingContext ctx) {
    // Don't set STEPNAME here because we want the name of the preceding step
    // Can read config from a documemnt or pass as args
    AdminApi admin = Kernel.getAdmin();
    String types = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "NOTIFY_TYPE"));

    if (types == null) {
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": parameter NOTIFY_TYPE is not set", true);
        return getErrorTransition();
    }//from   www.j a  va2 s  .c o m
    StringBuffer error = new StringBuffer();
    String retval = getNextTransition();
    for (String type : types.split("[, ]+")) {
        try {
            if (type.equalsIgnoreCase("SLACK") && !sendSlack(ctx)) {
                decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Slack notification failed", true);
                retval = getErrorTransition();
            }
        } catch (Exception e) {
            Throwable cause = ExceptionToString.getRootCause(e);
            error.append("Cannot send slack notification : ").append(cause.getLocalizedMessage()).append("\n");
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    "Problem in " + getStepName() + ": slack notification failed", true);
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), ExceptionToString.summary(cause), true);
            retval = getErrorTransition();
        }

        try {
            if (type.equalsIgnoreCase("EMAIL") && !sendEmail(ctx)) {
                decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Email notification failed", true);
                retval = getErrorTransition();
            }
        } catch (Exception e) {
            Throwable cause = ExceptionToString.getRootCause(e);
            error.append("Cannot send email notification : ").append(cause.getLocalizedMessage()).append("\n");
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    "Problem in NotificationStep " + getStepName() + ": email notification failed", true);
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), ExceptionToString.summary(cause), true);
            log.error(ExceptionToString.format(ExceptionToString.getRootCause(e)));
            retval = getErrorTransition();
        }
    }

    String errMsg = error.toString();
    if (!StringUtils.isEmpty(errMsg)) {
        log.error(errMsg);
        decision.setContextLiteral(ctx, getWorkerURI(), getStepName(), "Notification failure");
        decision.setContextLiteral(ctx, getWorkerURI(), getErrName(), errMsg);
    }
    return retval;
}

From source file:rapture.dp.invocable.notification.steps.NotificationStep.java

private boolean sendSlack(CallingContext ctx) throws IOException {
    String message = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "MESSAGE_BODY"));
    // Legacy: use template if values are not set
    String templateName = StringUtils
            .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "MESSAGE_TEMPLATE"));
    String webhook = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "SLACK_WEBHOOK"));
    if (webhook == null) {
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": No webhook specified", true);
        return false;
    }/*from w w  w. j ava 2s .co m*/

    if (message == null) {
        if (templateName == null) {
            decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                    "Problem in " + getStepName() + ": No message specified", true);
            return false;
        }
        EmailTemplate template = Mailer.getEmailTemplate(ctx, templateName);
        message = template.getMsgBody();
    }
    URL url = new URL(webhook);
    Map<String, String> slackNotification = new HashMap<>();
    slackNotification.put("text", renderTemplate(ctx, message));
    int response = doPost(url, JacksonUtil.bytesJsonFromObject(slackNotification));
    if (response == 200) {
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                getStepName() + ": slack notification sent successfully", false);
        return true;
    } else {
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": slack notification failed with HTTP error code " + response,
                true);
        return false;
    }
}

From source file:rapture.dp.invocable.notification.steps.NotificationStep.java

private boolean sendEmail(CallingContext ctx) throws AddressException, MessagingException {
    String message = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "MESSAGE_BODY"));
    String subject = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "MESSAGE_SUBJECT"));
    String recipientList = StringUtils
            .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "EMAIL_RECIPIENTS"));
    // Legacy: use template if values are not set
    String templateName = StringUtils
            .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "MESSAGE_TEMPLATE"));

    if (templateName != null) {
        EmailTemplate template = Mailer.getEmailTemplate(ctx, templateName);
        if (template != null) {
            if (message == null)
                message = template.getMsgBody();
            if (subject == null)
                subject = template.getSubject();
            if (recipientList == null)
                recipientList = template.getEmailTo();
        }// w  ww.j a  v  a  2  s  . co m
    }

    if (message == null) {
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": No message specified", true);
        return false;
    }

    if (recipientList == null) {
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                "Problem in " + getStepName() + ": No recipient specified", true);
        return false;
    }

    try {
        Mailer.email(renderTemplate(ctx, recipientList).split("[, ]+"), renderTemplate(ctx, subject),
                renderTemplate(ctx, message));
        decision.writeWorkflowAuditEntry(ctx, getWorkerURI(),
                getStepName() + ": email notification sent successfully", false);
        return true;
    } catch (MessagingException e) {
        log.warn("Unable to send email", e);
        return false;
    }
}

From source file:ru.mystamps.web.service.SiteServiceImpl.java

@SuppressWarnings({ "PMD.UseObjectForClearerAPI", "checkstyle:parameternumber" })
protected void logEvent(String type, String page, String method, Integer userId, String ip, String referer,
        String agent, Date date) {

    Validate.isTrue(type != null, "Type of suspicious activity must be non null");
    Validate.isTrue(page != null, "Page must be non null");

    AddSuspiciousActivityDbDto activity = new AddSuspiciousActivityDbDto();

    activity.setType(type);//from   w ww . j a  v  a 2s  .com
    activity.setOccurredAt(date == null ? new Date() : date);
    activity.setPage(abbreviatePage(page));
    activity.setMethod(abbreviateMethod(method));
    activity.setUserId(userId);
    activity.setIp(StringUtils.defaultString(ip));
    activity.setRefererPage(StringUtils.stripToNull(abbreviateRefererPage(referer)));
    activity.setUserAgent(StringUtils.stripToNull(abbreviateUserAgent(agent)));

    suspiciousActivities.add(activity);
}

From source file:uk.gov.hscic.patient.details.search.LegacyPatientSearch.java

private BooleanBuilder generateAdvancedSearchPredicate(final PatientQueryParams params) {
    final QPatientEntity blueprint = QPatientEntity.patientEntity;
    final BooleanBuilder predicate = new BooleanBuilder();

    final String nhsNumber = params.getNhsNumber();

    if (nhsNumber != null) {
        predicate.and(blueprint.nhsNumber.eq(nhsNumber));
    } else {// w  ww . jav a2s .  c  o  m
        final String surname = StringUtils.stripToNull(params.getSurname());
        final String forename = StringUtils.stripToNull(params.getForename());
        final Date dateOfBirth = params.getDateOfBirth();
        final String gender = StringUtils.stripToNull(params.getGender());

        if (surname != null) {
            predicate.and(blueprint.lastName.like(surname));
        }
        if (forename != null) {
            predicate.and(blueprint.firstName.like(forename));
        }
        if (dateOfBirth != null) {
            final Date truncatedDateOfBirth = DateUtils.truncate(dateOfBirth, Calendar.DATE);

            predicate.and(blueprint.dateOfBirth.eq(truncatedDateOfBirth));
        }
        if (gender != null) {
            predicate.and(blueprint.gender.eq(gender));
        }
    }

    return predicate;
}