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

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

Introduction

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

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is whitespace, empty ("") or null, the value of defaultStr.

Usage

From source file:org.niord.web.MessageMailRestService.java

/**
 * Generates and sends an e-mail for the message search result.
 *///  www. jav  a  2s.c o m
@GET
@Path("/send")
@Produces("text/plain")
@GZIP
@NoCache
@RolesAllowed(Roles.EDITOR)
public String sendMessageMail(@Context HttpServletRequest request) throws Exception {

    long t0 = System.currentTimeMillis();

    String[] mailAddresses = request.getParameterValues("mailTo");
    String mailSubject = request.getParameter("mailSubject");
    String mailMessage = request.getParameter("mailMessage");
    if (mailAddresses == null || mailAddresses.length == 0) {
        throw new WebApplicationException(400);
    }
    mailSubject = StringUtils.defaultIfBlank(mailSubject, "No subject");
    mailMessage = StringEscapeUtils.escapeHtml(StringUtils.defaultIfBlank(mailMessage, "")).replace("\n",
            "<br>");

    try {
        // Perform a search for at most 1000 messages
        MessageSearchParams params = MessageSearchParams.instantiate(domainService.currentDomain(), request);
        params.maxSize(1000).page(0);
        PagedSearchResultVo<MessageVo> result = messageSearchRestService.searchMessages(params);

        // Send the e-mails
        StringBuilder str = new StringBuilder();
        for (String mailTo : mailAddresses) {

            MailRecipient recipient = new MailRecipient(RecipientType.TO, new InternetAddress(mailTo));

            MessageMailTemplate mailTemplate = new MessageMailTemplate().subject(mailSubject)
                    .mailMessage(mailMessage).messages(result.getData())
                    .recipients(Collections.singletonList(recipient)).language(params.getLanguage())
                    .templatePath("/templates/messages/message-mail.ftl");

            messageMailService.sendMessageMail(mailTemplate);

            String msg = "Message mail scheduled to " + mailTo + " in " + (System.currentTimeMillis() - t0)
                    + " ms";
            log.info(msg);
            str.append(msg).append("\n");

        }
        return str.toString();

    } catch (Exception e) {
        log.error("Error sending e-mail for messages", e);
        throw e;
    }
}

From source file:org.niord.web.PublicationRestService.java

/**
 * Generates a publication report based on the PDF print parameters passed along
 *
 *
 * @param request the servlet request//from   w  w w .  j  a  va2 s.  c o  m
 * @return the updated publication descriptor
 */
@POST
@Path("/generate-publication-report/{folder:.+}")
@Consumes("application/json;charset=UTF-8")
@Produces("application/json;charset=UTF-8")
@RolesAllowed(Roles.ADMIN)
public PublicationDescVo generatePublicationReport(@PathParam("folder") String path, PublicationDescVo desc,
        @Context HttpServletRequest request) throws Exception {

    URL url = new URL(app.getBaseUri() + "/rest/message-reports/report.pdf?" + request.getQueryString()
            + "&ticket=" + ticketService.createTicket());

    // Validate that the path is a temporary repository folder path
    java.nio.file.Path folder = checkCreateTempRepoPath(path);

    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        httpConn.disconnect();
        log.error("Error creating publication report " + request.getQueryString());
        throw new WebApplicationException("Error creating publication report: " + request.getQueryString(),
                500);
    }

    // If the file name has not been specified in the descriptor, extract it from the
    // "Content-Disposition" header of the report connection
    String fileName = desc.getFileName();
    if (StringUtils.isBlank(fileName)) {
        String disposition = httpConn.getHeaderField("Content-Disposition");
        if (StringUtils.isNotBlank(disposition)) {
            Matcher regexMatcher = FILE_NAME_HEADER_PATTERN.matcher(disposition);
            if (regexMatcher.find()) {
                fileName = regexMatcher.group();
            }
        }
    }
    fileName = StringUtils.defaultIfBlank(fileName, "publication.pdf");

    File destFile = folder.resolve(fileName).toFile();
    try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
            InputStream is = httpConn.getInputStream()) {
        IOUtils.copy(is, out);
    } catch (IOException ex) {
        log.error("Error generating publication report " + destFile, ex);
        throw new WebApplicationException("Error generating publication report: " + destFile, 500);
    }
    httpConn.disconnect();

    desc.setFileName(fileName);
    desc.setLink(repositoryService.getRepoUri(destFile.toPath()));

    log.info("Generated publication report at destination " + destFile);

    return desc;
}

From source file:org.niord.web.PublicationRestService.java

/**
 * Uploads a publication file//  ww w  .  j  av a  2s .  c o m
 *
 * @param request the servlet request
 * @return the updated publication descriptor
 */
@POST
@Path("/upload-publication-file/{folder:.+}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
@RolesAllowed(Roles.ADMIN)
public PublicationDescVo uploadPublicationFile(@PathParam("folder") String path,
        @Context HttpServletRequest request) throws Exception {

    List<FileItem> items = repositoryService.parseFileUploadRequest(request);

    // Get hold of the first uploaded publication file
    FileItem fileItem = items.stream().filter(item -> !item.isFormField()).findFirst()
            .orElseThrow(() -> new WebApplicationException("No uploaded publication file", 400));

    // Check for the associated publication desc record
    PublicationDescVo desc = items.stream()
            .filter(item -> item.isFormField() && "data".equals(item.getFieldName())).map(item -> {
                try {
                    return new ObjectMapper().readValue(item.getString("UTF-8"), PublicationDescVo.class);
                } catch (Exception ignored) {
                }
                return null;
            }).filter(Objects::nonNull).findFirst()
            .orElseThrow(() -> new WebApplicationException("No publication descriptor found", 400));

    // Validate that the path is a temporary repository folder path
    java.nio.file.Path folder = checkCreateTempRepoPath(path);

    String fileName = StringUtils.defaultIfBlank(desc.getFileName(),
            Paths.get(fileItem.getName()).getFileName().toString()); // NB: IE includes the path in item.getName()!

    File destFile = folder.resolve(fileName).toFile();
    try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) {
        IOUtils.copy(fileItem.getInputStream(), out);
    } catch (IOException ex) {
        log.error("Error creating publication file " + destFile, ex);
        throw new WebApplicationException("Error creating destination file: " + destFile, 500);
    }

    desc.setFileName(fileName);
    desc.setLink(repositoryService.getRepoUri(destFile.toPath()));

    log.info("Copied publication file " + fileItem.getName() + " to destination " + destFile);

    return desc;
}

From source file:org.nuxeo.aws.elastictranscoder.connverters.AWSElasticTranscoderConverter.java

@Override
public void init(ConverterDescriptor descriptor) {

    Map<String, String> params = descriptor.getParameters();
    inputBucket = StringUtils.defaultIfBlank(params.get("inputBucket"),
            AWSElasticTranscoderConstants.getDefaultBucketInput());

    outputBucket = StringUtils.defaultIfBlank(params.get("outputBucket"),
            AWSElasticTranscoderConstants.getDefaultBucketOutput());

    pipelineId = StringUtils.defaultIfBlank(params.get("pipelineId"),
            AWSElasticTranscoderConstants.getDefaultPipelineId());

    presetId = StringUtils.defaultIfBlank(params.get("presetId"),
            AWSElasticTranscoderConstants.getDefaultPresetId());

    sqsQueueUrl = StringUtils.defaultIfBlank(params.get("sqsQueueUrl"),
            AWSElasticTranscoderConstants.getDefaultSqsQueueUrl());

    String str = params.get("deleteInputfileWhenDone");
    if (StringUtils.isBlank(str)) {
        deleteInputFileWhenDone = AWSElasticTranscoderConstants.getDefaultDeleteInputFileWhenDone();
    } else {//from www  .  java  2 s .  c o m
        deleteInputFileWhenDone = str.toLowerCase().equals("true");
    }

    str = params.get("deleteOutputFileWhenDone");
    if (StringUtils.isBlank(str)) {
        deleteOutputFileWhenDone = AWSElasticTranscoderConstants.getDefaultDeleteOutputFileWhenDone();
    } else {
        deleteOutputFileWhenDone = str.toLowerCase().equals("true");
    }

    outputFileSuffix = params.get("outputFileSuffix");

}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

protected void initializeOptions(String options) {
    for (String option : options.split(",")) {
        String[] split = option.split("=", 2);
        if (split.length != 2) {
            throw new NuxeoException("Unrecognized option: " + option);
        }//from www  .  j a  v a2 s.  c o m
        String value = StringUtils.defaultIfBlank(split[1], null);
        switch (split[0]) {
        case PARAM_PASSWORD:
            password = value;
            break;
        case PARAM_KEY_STORE_TYPE:
            keyStoreType = value;
            break;
        case PARAM_KEY_STORE_FILE:
            keyStoreFile = value;
            break;
        case PARAM_KEY_STORE_PASSWORD:
            keyStorePassword = value;
            break;
        case PARAM_KEY_ALIAS:
            keyAlias = value;
            break;
        case PARAM_KEY_PASSWORD:
            keyPassword = value;
            break;
        default:
            throw new NuxeoException("Unrecognized option: " + option);
        }
    }
    usePBKDF2 = password != null;
    if (usePBKDF2) {
        if (keyStoreType != null) {
            throw new NuxeoException("Cannot use " + PARAM_KEY_STORE_TYPE + " with " + PARAM_PASSWORD);
        }
        if (keyStoreFile != null) {
            throw new NuxeoException("Cannot use " + PARAM_KEY_STORE_FILE + " with " + PARAM_PASSWORD);
        }
        if (keyStorePassword != null) {
            throw new NuxeoException("Cannot use " + PARAM_KEY_STORE_PASSWORD + " with " + PARAM_PASSWORD);
        }
        if (keyAlias != null) {
            throw new NuxeoException("Cannot use " + PARAM_KEY_ALIAS + " with " + PARAM_PASSWORD);
        }
        if (keyPassword != null) {
            throw new NuxeoException("Cannot use " + PARAM_KEY_PASSWORD + " with " + PARAM_PASSWORD);
        }
    } else {
        if (keyStoreType == null) {
            throw new NuxeoException("Missing " + PARAM_KEY_STORE_TYPE);
        }
        // keystore file is optional
        if (keyStoreFile == null && keyStorePassword != null) {
            throw new NuxeoException("Missing " + PARAM_KEY_STORE_PASSWORD);
        }
        if (keyAlias == null) {
            throw new NuxeoException("Missing " + PARAM_KEY_ALIAS);
        }
        if (keyPassword == null) {
            keyPassword = keyStorePassword;
        }
    }
}

From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java

@Override
public void downloadBlob(HttpServletRequest request, HttpServletResponse response, DocumentModel doc,
        String xpath, Blob blob, String filename, String reason, Map<String, Serializable> extendedInfos,
        Boolean inline, Consumer<ByteRange> blobTransferer) throws IOException {
    Objects.requireNonNull(blob);
    // check blob permissions
    if (!checkPermission(doc, xpath, blob, reason, extendedInfos)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission denied");
        return;//from   www  .j  a  v  a 2  s. c o m
    }

    // check Blob Manager download link
    URI uri = redirectResolver.getURI(blob, UsageHint.DOWNLOAD, request);
    if (uri != null) {
        try {
            Map<String, Serializable> ei = new HashMap<>();
            if (extendedInfos != null) {
                ei.putAll(extendedInfos);
            }
            ei.put("redirect", uri.toString());
            logDownload(doc, xpath, filename, reason, ei);
            response.sendRedirect(uri.toString());
        } catch (IOException ioe) {
            DownloadHelper.handleClientDisconnect(ioe);
        }
        return;
    }

    try {
        String digest = blob.getDigest();
        if (digest == null) {
            digest = DigestUtils.md5Hex(blob.getStream());
        }
        String etag = '"' + digest + '"'; // with quotes per RFC7232 2.3
        response.setHeader("ETag", etag); // re-send even on SC_NOT_MODIFIED
        addCacheControlHeaders(request, response);

        String ifNoneMatch = request.getHeader("If-None-Match");
        if (ifNoneMatch != null) {
            boolean match = false;
            if (ifNoneMatch.equals("*")) {
                match = true;
            } else {
                for (String previousEtag : StringUtils.split(ifNoneMatch, ", ")) {
                    if (previousEtag.equals(etag)) {
                        match = true;
                        break;
                    }
                }
            }
            if (match) {
                String method = request.getMethod();
                if (method.equals("GET") || method.equals("HEAD")) {
                    response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                } else {
                    // per RFC7232 3.2
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                }
                return;
            }
        }

        // regular processing

        if (StringUtils.isBlank(filename)) {
            filename = StringUtils.defaultIfBlank(blob.getFilename(), "file");
        }
        String contentDisposition = DownloadHelper.getRFC2231ContentDisposition(request, filename, inline);
        response.setHeader("Content-Disposition", contentDisposition);
        response.setContentType(blob.getMimeType());
        if (blob.getEncoding() != null) {
            response.setCharacterEncoding(blob.getEncoding());
        }

        long length = blob.getLength();
        response.setHeader("Accept-Ranges", "bytes");
        String range = request.getHeader("Range");
        ByteRange byteRange;
        if (StringUtils.isBlank(range)) {
            byteRange = null;
        } else {
            byteRange = DownloadHelper.parseRange(range, length);
            if (byteRange == null) {
                log.error("Invalid byte range received: " + range);
            } else {
                response.setHeader("Content-Range",
                        "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + length);
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            }
        }
        long contentLength = byteRange == null ? length : byteRange.getLength();
        if (contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }

        logDownload(doc, xpath, filename, reason, extendedInfos);

        // execute the final download
        blobTransferer.accept(byteRange);
    } catch (UncheckedIOException e) {
        DownloadHelper.handleClientDisconnect(e.getCause());
    } catch (IOException ioe) {
        DownloadHelper.handleClientDisconnect(ioe);
    }
}

From source file:org.nuxeo.ecm.core.redis.RedisPoolDescriptor.java

@XNode("password")
public void setPassword(String value) {
    password = StringUtils.defaultIfBlank(value, null);
}

From source file:org.nuxeo.ecm.core.redis.RedisServerDescriptor.java

@Override
public RedisExecutor newExecutor() {
    if (hosts.length == 0) {
        throw new RuntimeException("Missing Redis host");
    }/*from w w  w .ja v a  2s . c  om*/
    if (hosts.length > 1) {
        throw new RuntimeException("Only one host supported");
    }
    RedisHostDescriptor host = selectHost();
    return new RedisPoolExecutor(new JedisPool(new JedisPoolConfig(), host.name, host.port, timeout,
            StringUtils.defaultIfBlank(password, null), database));

}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicRepository.java

public static ContentSource newMarkLogicContentSource(MarkLogicRepositoryDescriptor descriptor) {
    String host = descriptor.host;
    Integer port = descriptor.port;
    if (StringUtils.isBlank(host) || port == null) {
        throw new NuxeoException("Missing <host> or <port> in MarkLogic repository descriptor");
    }//from w ww  .j a  v  a2s.  c  om
    String dbname = StringUtils.defaultIfBlank(descriptor.dbname, DB_DEFAULT);
    String user = descriptor.user;
    String password = descriptor.password;
    // handle SSL
    SecurityOptions securityOptions = descriptor.sslEnabled ? newTrustOptions() : null;
    return ContentSourceFactory.newContentSource(host, port.intValue(), user, password, dbname,
            securityOptions);
}

From source file:org.nuxeo.ecm.platform.routing.core.impl.GraphNodeImpl.java

@Override
public String getSubRouteModelId() throws DocumentRouteException {
    String subRouteModelExpr = (String) getProperty(PROP_SUB_ROUTE_MODEL_EXPR);
    if (StringUtils.isBlank(subRouteModelExpr)) {
        return null;
    }//from   ww  w  . ja v a2s.com
    OperationContext context = getExecutionContext(getSession());
    String res = valueOrExpression(String.class, subRouteModelExpr, context, "Sub-workflow id expression");
    return StringUtils.defaultIfBlank(res, null);
}