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

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

Introduction

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

Prototype

public static String defaultIfEmpty(String str, String defaultStr) 

Source Link

Document

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

Usage

From source file:org.jahia.bin.Render.java

private void doAction(HttpServletRequest req, HttpServletResponse resp, URLResolver urlResolver,
        RenderContext renderContext, Resource resource, Action action, Map<String, List<String>> parameters)
        throws Exception {
    final String requestWith = req.getHeader("x-requested-with");
    boolean isAjaxRequest = req.getHeader("accept") != null
            && req.getHeader("accept").contains("application/json") && requestWith != null
            && requestWith.equals("XMLHttpRequest");

    final Action originalAction = action;

    int tokenResult = TokenChecker.NO_TOKEN;
    if (!isWebflowRequest(req)) {
        tokenResult = TokenChecker.checkToken(req, resp, parameters);
    }//  w w w .j a  va2  s.  c  om

    switch (tokenResult) {
    case TokenChecker.NO_TOKEN:
        break;
    case TokenChecker.INVALID_TOKEN:
        throw new AccessDeniedException("Invalid token.");
    case TokenChecker.INVALID_CAPTCHA:
        Map<String, String[]> formDatas = new HashMap<String, String[]>();
        Set<Map.Entry<String, List<String>>> set = parameters.entrySet();
        for (Map.Entry<String, List<String>> params : set) {
            formDatas.put(params.getKey(), params.getValue().toArray(new String[params.getValue().size()]));
        }
        String errorMessage = Messages.getInternal("failure.captcha", urlResolver.getLocale(),
                "Your captcha is invalid");
        if (!isAjaxRequest) {
            req.getSession().setAttribute("formDatas", formDatas);
            req.getSession().setAttribute("formError", errorMessage);
            performRedirect(renderContext.getMainResource().getNode().getPath(), urlResolver.getPath(), req,
                    resp, parameters, true);
        } else {
            resp.setContentType("application/json; charset=UTF-8");
            Map<String, String> res = new HashMap<String, String>();
            res.put("status", errorMessage);
            new JSONObject(res).write(resp.getWriter());
        }
        return;
    case TokenChecker.INVALID_HIDDEN_FIELDS:
        throw new AccessDeniedException();
    case TokenChecker.VALID_TOKEN:
        action = new SystemAction() {
            @Override
            public ActionResult doExecuteAsSystem(HttpServletRequest req, RenderContext renderContext,
                    JCRSessionWrapper systemSession, Resource resource, Map<String, List<String>> parameters,
                    URLResolver urlResolver) throws Exception {
                return originalAction.doExecute(req, renderContext, resource, systemSession, parameters,
                        urlResolver);
            }
        };
    }

    if (!(action instanceof SystemAction)) {
        if (action.getRequiredWorkspace() != null
                && !action.getRequiredWorkspace().equals(urlResolver.getWorkspace())) {
            throw new PathNotFoundException("Action is not supported for this workspace");
        }
        if (action.isRequireAuthenticatedUser() && !renderContext.isLoggedIn()) {
            throw new AccessDeniedException("Action '" + action.getName() + "' requires an authenticated user");
        }
        if (!action.isPermitted(urlResolver.getNode())) {
            throw new AccessDeniedException("Action '" + action.getName() + "' requires '"
                    + action.getRequiredPermission() + "' permission.");
        }
    } else if (originalAction instanceof LicensedAction) {
        LicensedAction licensedAction = (LicensedAction) originalAction;
        if (!licensedAction.isAllowedByLicense()) {
            logger.error(
                    "Action '{}' requires a licene feature '{}'"
                            + " which is not allowed by the current license terms",
                    originalAction.getName(), licensedAction.getLicenseFeature());
            throw new AccessDeniedException("Action '" + action.getName() + "' requires a licene feature '"
                    + licensedAction.getLicenseFeature()
                    + "' which is not allowed by the current license terms");
        }
    }

    JCRSessionWrapper session = null;
    if (resource != null) {
        session = resource.getNode().getSession();
    } else {
        session = JCRSessionFactory.getInstance().getCurrentUserSession(urlResolver.getWorkspace(),
                urlResolver.getLocale());
    }
    ActionResult result;
    try {
        result = action.doExecute(req, renderContext, resource, session, parameters, urlResolver);
    } catch (Exception e) {
        logger.error("An error occurs when executing action {}", action.getName(), e);
        throw e;
    }
    if (result != null) {
        boolean returnJSON = "json".equals(
                parameters.get(RETURN_CONTENTTYPE) != null ? parameters.get(RETURN_CONTENTTYPE).get(0) : "")
                || req.getHeader("accept") != null && req.getHeader("accept").contains("application/json");
        if (result.getResultCode() < 300 || returnJSON) {
            resp.setStatus(result.getResultCode());
            addCookie(req, resp);
            if (result.getJson() != null && returnJSON) {
                try {
                    String contentType = parameters.get(RETURN_CONTENTTYPE_OVERRIDE) != null
                            ? StringUtils.defaultIfEmpty(parameters.get(RETURN_CONTENTTYPE_OVERRIDE).get(0),
                                    null)
                            : null;
                    if (contentType == null) {
                        contentType = "application/json; charset=UTF-8";
                    } else if (!contentType.toLowerCase().contains("charset")) {
                        // append the charset
                        contentType += "; charset=UTF-8";
                    }
                    resp.setContentType(contentType);
                    result.getJson().write(resp.getWriter());
                } catch (JSONException e) {
                    logger.error(e.getMessage(), e);
                }
            } else {
                if (!result.isAbsoluteUrl()) {
                    performRedirect(result.getUrl(), urlResolver.getPath(), req, resp, parameters, false);
                } else {
                    resp.sendRedirect(resp.encodeRedirectURL(result.getUrl()));
                }
            }
        } else {
            resp.sendError(result.getResultCode());
        }
    }
}

From source file:org.jahia.bin.WelcomeServlet.java

protected String resolveLanguage(HttpServletRequest request, final JCRSiteNode site, JCRUserNode user,
        boolean userRedirect) throws JahiaException {
    List<Locale> siteLanguages = null;
    if (!userRedirect && site != null && !JahiaSitesService.SYSTEM_SITE_KEY.equals(site.getSiteKey())) {
        try {/*from w  w  w.jav a2s  . c o  m*/
            siteLanguages = site.getActiveLiveLanguagesAsLocales();
        } catch (Exception t) {
            logger.debug("Exception while getting language settings as locales", t);
            siteLanguages = Collections.emptyList();
        }
    }

    // first we will check the preferred user locale (if it is among the
    Locale preferredLocale = UserPreferencesHelper.getPreferredLocale(user);
    if (preferredLocale != null && isLocaleSupported(site, siteLanguages, preferredLocale)) {
        return preferredLocale.toString();
    }

    // retrieve the browser locales, but if Accept-Language header is missing we won't fallback to the default system locale
    for (Enumeration<?> requestLocales = Util.getRequestLocales(request); requestLocales.hasMoreElements();) {
        final Locale curLocale = (Locale) requestLocales.nextElement();
        if (curLocale != null) {
            // check that the site contains the language and the home page exists in live for that language
            if (isLocaleSupported(site, siteLanguages, curLocale)) {
                return curLocale.toString();
            }
            if (!StringUtils.isEmpty(curLocale.getCountry())) {
                // check the same but for language only
                final Locale langOnlyLocale = LanguageCodeConverters
                        .languageCodeToLocale(curLocale.getLanguage());
                if (isLocaleSupported(site, siteLanguages, langOnlyLocale)) {
                    return langOnlyLocale.toString();
                }
            }
        }
    }

    String lang = site.getDefaultLanguage();
    if (lang != null) {
        // use site's default language
        return lang;
    }

    // nothing matches -> fallback to default
    return StringUtils.defaultIfEmpty(SettingsBean.getInstance().getDefaultLanguageCode(), DEFAULT_LOCALE);
}

From source file:org.jahia.bundles.extender.jahiamodules.JspServletWrapper.java

private String getJspFilePath(final ServletRequest req) {
    String jspPath = jspFile;/*  ww w  . j a v  a 2  s.  c  o m*/
    if (jspPath == null && jspFilePrefix != null && req instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        String servletPath = StringUtils.defaultIfEmpty(
                (String) httpRequest.getAttribute("javax.servlet.include.servlet_path"),
                httpRequest.getServletPath());
        String pathInfo = StringUtils.defaultIfEmpty(
                (String) httpRequest.getAttribute("javax.servlet.include.path_info"),
                httpRequest.getPathInfo());
        if (pathInfo != null && servletPath != null && "/modules".equals(servletPath)
                && pathInfo.startsWith(jspFilePrefix) && pathInfo.length() > jspFilePrefix.length()) {
            jspPath = pathInfo.substring(jspFilePrefix.length());
        }
    }
    return jspPath;
}

From source file:org.jahia.dm.DocumentOperationJob.java

@Override
public void executeJahiaJob(final JobExecutionContext jobExecutionContext) throws Exception {
    JobDataMap data = jobExecutionContext.getJobDetail().getJobDataMap();
    final String uuid = (String) data.get(JOB_UUID);
    final String workspace = StringUtils.defaultIfEmpty((String) data.get(JOB_WORKSPACE),
            Constants.EDIT_WORKSPACE);//  w w w . j  av a 2 s  .com
    JCRTemplate.getInstance().doExecuteWithSystemSession(null, workspace, new JCRCallback<Boolean>() {
        public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException {

            JCRNodeWrapper node = null;
            try {
                node = session.getNodeByIdentifier(uuid);
                doOperation(node, jobExecutionContext);
            } catch (ItemNotFoundException e) {
                logger.warn(
                        "Unable to find node with ID {} in {} workspace. Skip executing a document operation.",
                        uuid, workspace);
            } catch (Exception e) {
                logger.error("Error executing operation on the document node "
                        + (node != null ? node.getPath() : uuid), e);
            }

            return Boolean.TRUE;
        }
    });
}

From source file:org.jahia.modules.dm.thumbnails.video.impl.VideoThumbnailServiceImpl.java

public boolean generateThumbnail(File videoFile, File outputFile, int offsetSeconds, String size)
        throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("FFmpeg service is not enabled." + " Skip converting file {}", videoFile);

        return false;
    }/*from  ww  w.  j a  va  2  s  . co  m*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(videoFile, outputFile, String.valueOf(offsetSeconds),
            StringUtils.defaultIfEmpty(size, "320x240"));

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting thumbnail generation command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (exitValue > 0 && err.getLength() > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && err.getLength() > 0) {
            logger.debug(err.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Generating thumbnail {} from {} done (exit code: {}) in {} ms",
                new Object[] { outputFile, videoFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.modules.docrules.DocumentRuleJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    JobDataMap data = jobExecutionContext.getJobDetail().getJobDataMap();
    final String ruleBeanId = (String) data.get(JOB_RULE_BEAN_ID);
    final String uuid = (String) data.get(JOB_UUID);
    String workspace = StringUtils.defaultIfEmpty((String) data.get(JOB_WORKSPACE), Constants.EDIT_WORKSPACE);
    JCRTemplate.getInstance().doExecuteWithSystemSession(null, workspace, new JCRCallback<Boolean>() {
        public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException {

            JCRNodeWrapper node = session.getNodeByIdentifier(uuid);
            try {
                executeRule(node, ruleBeanId);
                session.save();/*from   w  w  w . j a v  a2 s.com*/
            } catch (Exception e) {
                logger.error("Error executing rule " + ruleBeanId + " on the document node " + node.getPath(),
                        e);
            }

            return Boolean.TRUE;
        }
    });
}

From source file:org.jahia.modules.gateway.admin.forms.MailStartPointFormHandlerImpl.java

public static String buildUri(Map<String, String> parameters) {
    String protocol = StringUtils.defaultIfEmpty(parameters.get("protocol"), "imap");
    String host = StringUtils.defaultIfEmpty(parameters.get("host"), "imap.gmail.com");
    if ("imap.gmail.com".equals(host)) {
        protocol = "imaps";
    }//from w w w. j av  a 2s.  c  om
    String port = StringUtils.defaultIfEmpty(parameters.get("port"), "");
    if (port.length() > 0) {
        port = ":" + port;
    }
    String username = StringUtils.defaultString(parameters.get("username"));
    String delay = StringUtils.defaultIfEmpty(parameters.get("delay"), "60000");
    String delete = StringUtils.defaultString(parameters.get("delete"), "false");

    return StringUtils.replaceEachRepeatedly(URI_TEMPLATE,
            new String[] { "${protocol}", "${host}", "${port}", "${username}", "${delay}", "${delete}" },
            new String[] { protocol, host, port, username, delay, delete });
}

From source file:org.jahia.modules.gateway.JSONToJCRDeserializer.java

@Handler
public void handleExchange(final Exchange exchange) {
    if (exchange != null && exchange.getIn() != null && exchange.getIn().getBody().toString().startsWith("{")) {
        try {/*from ww  w .  ja v a2s  .  co m*/
            String body = exchange.getIn().getBody().toString();
            final JSONObject jsonObject = new JSONObject(body);

            final String nodetype = jsonObject.getString("nodetype");
            assert nodetype != null;

            // Check that nodetype exists
            final ExtendedNodeType extendedNodeType = NodeTypeRegistry.getInstance().getNodeType(nodetype);
            assert extendedNodeType != null;
            final String name = jsonObject.getString("name");
            assert name != null;

            String username = null;
            if (jsonObject.has("username")) {
                username = jsonObject.getString("username");
            }
            String locale = jsonObject.getString("locale");
            assert locale != null;
            String workspace = jsonObject.getString("workspace");
            assert workspace != null;
            final String path = jsonObject.getString("path");
            assert path != null;
            if (!extendedNodeType.isNodeType("nt:file")) {
                final JSONObject properties = jsonObject.getJSONObject("properties");
                assert properties != null;
                jcrTemplate.doExecuteWithSystemSession(username, workspace,
                        org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(locale),
                        new JCRCallback<Object>() {
                            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                                logger.debug("Getting parent node with path : " + path);
                                boolean saveFileUnderNode = false;
                                try {
                                    if (jsonObject.has("saveFileUnderNewlyCreatedNode")) {
                                        saveFileUnderNode = jsonObject
                                                .getBoolean("saveFileUnderNewlyCreatedNode");
                                    }
                                } catch (JSONException e) {
                                    logger.error(e.getMessage(), e);
                                }
                                Object header = exchange.getIn().getHeader(Constants.UPDATE_ONLY);
                                if (header == null || !(Boolean) header) {
                                    createNewNode(session, path, name, nodetype, properties, extendedNodeType,
                                            jsonObject, saveFileUnderNode);
                                } else {
                                    updateExistingNode(session, path, name, properties, extendedNodeType,
                                            jsonObject, nodetype, saveFileUnderNode);
                                }
                                session.save();
                                return null;
                            }
                        });
            } else if (jsonObject.has("files")) {
                jcrTemplate.doExecuteWithSystemSession(username, workspace,
                        org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(locale),
                        new JCRCallback<Object>() {
                            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Getting parent node with path : " + path);
                                }
                                try {
                                    JCRNodeWrapper node = session.getNode(path);
                                    boolean doUpdate = jsonObject.has("updateifexists")
                                            && Boolean.valueOf(jsonObject.getString("updateifexists"));
                                    JSONArray files = jsonObject.getJSONArray("files");
                                    for (int i = 0; i < files.length(); i++) {
                                        File file = null;
                                        String contentType = null;
                                        String nodeName = null;

                                        Object fileItem = files.get(i);
                                        if (fileItem instanceof JSONObject) {
                                            JSONObject fileDescriptor = (JSONObject) fileItem;
                                            file = new File(fileDescriptor.getString("file"));
                                            nodeName = StringUtils.defaultIfEmpty(fileDescriptor.has("name")
                                                    ? fileDescriptor.getString("name")
                                                    : null, file.getName());
                                            contentType = fileDescriptor.has("contentType")
                                                    ? fileDescriptor.getString("contentType")
                                                    : null;
                                        } else {
                                            file = new File(files.getString(i));
                                            nodeName = file.getName();
                                        }
                                        if (contentType == null) {
                                            contentType = JCRContentUtils.getMimeType(nodeName);
                                        }

                                        if (file == null || nodeName == null || contentType == null) {
                                            continue;
                                        }

                                        InputStream is = null;
                                        try {
                                            is = FileUtils.openInputStream(file);
                                            final JCRNodeWrapper newNode = node.uploadFile(doUpdate ? nodeName
                                                    : JCRContentUtils.findAvailableNodeName(node, nodeName), is,
                                                    contentType);
                                            if (jsonObject.has("tags")) {
                                                String siteKey = newNode.getResolveSite().getSiteKey();
                                                taggingService.tag(newNode.getPath(),
                                                        jsonObject.getString("tags"), siteKey, true, session);
                                            }
                                        } catch (IOException e) {
                                            logger.error(e.getMessage(), e);
                                        } finally {
                                            IOUtils.closeQuietly(is);
                                            FileUtils.deleteQuietly(file);
                                        }
                                    }
                                    session.save();
                                } catch (JSONException e) {
                                    logger.error(e.getMessage(), e);
                                }
                                return null;
                            }
                        });
            }
        } catch (JSONException e) {
            logger.error(e.getMessage(), e);
        } catch (NoSuchNodeTypeException e) {
            logger.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.jahia.modules.gateway.mail.MailToJSONImpl.java

protected void parseMailMessage(Part part, MailContent content) throws IOException, MessagingException {
    Object mailContent = part.getContent();
    if (mailContent instanceof MimeMultipart) {
        MimeMultipart mailMessageContent = (MimeMultipart) mailContent;
        // We have some attachments
        for (int i = 0; i < mailMessageContent.getCount(); i++) {
            BodyPart bodyPart = mailMessageContent.getBodyPart(i);
            parseMailMessage(bodyPart, content);
        }//from  w ww.  j  a v a2 s  .  c o  m
    } else if (mailContent instanceof String && part.getDisposition() == null) {
        boolean isHtml = false;
        if (content.getBody() == null || ((isHtml = part.isMimeType("text/html")) && !content.isHtml())) {
            if (isHtml) {
                content.setBodyHtml((String) mailContent);
            } else {
                content.setBody((String) mailContent);
            }
        }
    } else if (mailContent instanceof InputStream || mailContent instanceof String) {
        File tempFile = File.createTempFile("mail2json-", null);
        try {
            FileUtils.copyInputStreamToFile(
                    mailContent instanceof InputStream ? (InputStream) mailContent : part.getInputStream(),
                    tempFile);
            content.getFiles()
                    .add(new FileItem(StringUtils.defaultIfEmpty(part.getFileName(), "unknown"), tempFile));
        } catch (IOException e) {
            FileUtils.deleteQuietly(tempFile);
            throw e;
        }
    }
    assert content.getBody() != null;
}

From source file:org.jahia.modules.irclogs.IRCJobRunner.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap data = jobExecutionContext.getJobDetail().getJobDataMap();
    final String workspace = StringUtils.defaultIfEmpty(data.getString("workspace"), Constants.LIVE_WORKSPACE);

    JCRTemplate.getInstance().doExecuteWithSystemSession(null, workspace, new JCRCallback<Integer[]>() {
        @SuppressWarnings("unchecked")
        public Integer[] doInJCR(JCRSessionWrapper session) throws RepositoryException {

            Query q = session.getWorkspace().getQueryManager()
                    .createQuery("select * from [rvnt:displayIRCLogs]", Query.JCR_SQL2);
            NodeIterator ni = q.execute().getNodes();
            while (ni.hasNext()) {
                JCRNodeWrapper next = (JCRNodeWrapper) ni.next();
                String channel = next.getProperty("channel").getString();
                // String directory = next.getProperty("directory").getString();

                ChatlogChannel clc = ChatLogCache.getInstance().getChannel(channel);
                if (clc != null) {
                    clc.runJob();//  w w w  .j  a v a  2s.  com
                } else {
                    // We could create a new channel here... TODO??
                }
            }
            return null;
        }
    });

    logger.info("Finnished");
}