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

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

Introduction

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

Prototype

public static String defaultString(final String str, final String defaultStr) 

Source Link

Document

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

 StringUtils.defaultString(null, "NULL")  = "NULL" StringUtils.defaultString("", "NULL")    = "" StringUtils.defaultString("bat", "NULL") = "bat" 

Usage

From source file:com.xpn.xwiki.pdf.impl.FileSystemURLFactory.java

/**
 * Store the requested attachment on the filesystem and return a {@code file://} URL where FOP can access that file.
 *
 * @param wiki the name of the owner document's wiki
 * @param spaces a serialized space reference which can contain one or several spaces (e.g. "space1.space2"). If
 *        a space name contains a dot (".") it must be passed escaped as in "space1\.with\.dot.space2"
 * @param name the name of the owner document
 * @param filename the name of the attachment
 * @param revision an optional attachment version
 * @param context the current request context
 * @return a {@code file://} URL where the attachment has been stored
 * @throws Exception if the attachment can't be retrieved from the database and stored on the filesystem
 *//*from  www.jav  a 2s  .  c o  m*/
private URL getURL(String wiki, String spaces, String name, String filename, String revision,
        XWikiContext context) throws Exception {
    Map<String, File> usedFiles = getFileMapping(context);
    List<String> spaceNames = this.legacySpaceResolver.resolve(spaces);
    String key = getAttachmentKey(spaceNames, name, filename, revision);
    if (!usedFiles.containsKey(key)) {
        File file = getTemporaryFile(key, context);
        LOGGER.debug("Temporary PDF export file [{}]", file.toString());
        XWikiDocument doc = context.getWiki().getDocument(
                new DocumentReference(StringUtils.defaultString(wiki, context.getWikiId()), spaceNames, name),
                context);
        XWikiAttachment attachment = doc.getAttachment(filename);
        if (StringUtils.isNotEmpty(revision)) {
            attachment = attachment.getAttachmentRevision(revision, context);
        }
        FileOutputStream fos = new FileOutputStream(file);
        IOUtils.copy(attachment.getContentInputStream(context), fos);
        fos.close();
        usedFiles.put(key, file);
    }
    return usedFiles.get(key).toURI().toURL();
}

From source file:com.formkiq.core.service.entry.WorkflowEntryFlowEventProcessor.java

/**
 * Add Signature Metadata.//from ww w  . j av a 2  s.  c  om
 *
 * @param flow {@link WebFlow}
 * @param request {@link HttpServletRequest}
 */
public void eventIdsignaturemetadata(final WebFlow flow, final HttpServletRequest request) {

    FormJSON form = flow.getCurrentState().getData();

    Map<String, String[]> params = new HashMap<>(request.getParameterMap());
    params.put("inserteddate", new String[] { this.jsonService.dateToString(this.dateservice.now()) });
    params.put("ipaddress", new String[] { request.getRemoteAddr() });
    params.put("xforwardedfor",
            new String[] { StringUtils.defaultString(request.getHeader("X-FORWARDED-FOR"), "") });

    for (Map.Entry<String, String[]> e : params.entrySet()) {

        Optional<FormJSONField> field = findValueByKey(form, e.getKey());
        if (field.isPresent()) {

            if (isEmpty(field.get().getValue())) {
                field.get().setValue(Arrays.first(e.getValue()));
            }
        }
    }
}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientImpl.java

private Throwable mapToKnownException(CaravanHttpRequest request, Throwable ex) {
    if (ex instanceof RequestFailedRuntimeException || ex instanceof IllegalResponseRuntimeException) {
        return ex;
    }/*from www  .  j  ava2  s  .co m*/
    if ((ex instanceof HystrixRuntimeException || ex instanceof ClientException) && ex.getCause() != null) {
        return mapToKnownException(request, ex.getCause());
    }
    throw new RequestFailedRuntimeException(request,
            StringUtils.defaultString(ex.getMessage(), ex.getClass().getSimpleName()), ex);
}

From source file:alfio.manager.SpecialPriceManager.java

public boolean sendCodeToAssignee(List<SendCodeModification> input, String eventName, int categoryId,
        String username) {/*  w ww. j  av a  2 s  . c o  m*/
    final Event event = eventManager.getSingleEvent(eventName, username);
    final Organization organization = eventManager.loadOrganizer(event, username);
    Set<SendCodeModification> set = new LinkedHashSet<>(input);
    checkCodeAssignment(set, categoryId, event, username);
    Validate.isTrue(set.stream().allMatch(IS_CODE_PRESENT),
            "There are missing codes. Please check input file.");
    List<ContentLanguage> eventLanguages = i18nManager.getEventLanguages(event.getLocales());
    Validate.isTrue(!eventLanguages.isEmpty(),
            "No locales have been defined for the event. Please check the configuration");
    ContentLanguage defaultLocale = eventLanguages.contains(ContentLanguage.ENGLISH) ? ContentLanguage.ENGLISH
            : eventLanguages.get(0);
    set.forEach(m -> {
        Locale locale = Locale.forLanguageTag(StringUtils.defaultString(StringUtils.trimToNull(m.getLanguage()),
                defaultLocale.getLanguage()));
        Map<String, Object> model = TemplateResource.prepareModelForSendReservedCode(organization, event, m,
                eventManager.getEventUrl(event));
        notificationManager.sendSimpleEmail(event, m.getEmail(),
                messageSource.getMessage("email-code.subject", new Object[] { event.getDisplayName() }, locale),
                () -> templateManager.renderTemplate(event, TemplateResource.SEND_RESERVED_CODE, model,
                        locale));
        int marked = specialPriceRepository.markAsSent(ZonedDateTime.now(event.getZoneId()),
                m.getAssignee().trim(), m.getEmail().trim(), m.getCode().trim());
        Validate.isTrue(marked == 1, "Expected exactly one row updated, got " + marked);
    });
    return true;
}

From source file:architecture.user.spring.config.SecurityConfig.java

protected AuthenticationSuccessHandler authenticationSuccessHandler() {
    SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler = new SimpleUrlAuthenticationSuccessHandler() {
        @Override/*from   ww w . j  a va  2s . co m*/
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            OutputFormat output = getOutputFormat(request, response);
            if (output == OutputFormat.JSON) {
                // Token
                String referer = request.getHeader("Referer");
                Map model = new ModelMap();
                Map<String, String> item = new java.util.HashMap<String, String>();
                item.put("success", "true");
                if (StringUtils.isNotEmpty(referer))
                    item.put("referer", referer);
                /*
                 * model.put("item", item);
                 * request.setAttribute(WebApplicatioinConstants.
                 * MODEL_ATTRIBUTE, model); if(output == OutputFormat.JSON
                 * ){ JsonView view = new JsonView();
                 * view.setModelKey("item"); try { view.render(model,
                 * request, response); } catch (Exception e) { } return; }
                 */
            }
            super.onAuthenticationSuccess(request, response, authentication);
        }

        protected OutputFormat getOutputFormat(HttpServletRequest httpservletrequest,
                HttpServletResponse httpservletresponse) {
            String temp = httpservletrequest.getParameter("output");
            String formatString = StringUtils.defaultString(temp, "html");
            OutputFormat format = OutputFormat.stingToOutputFormat(formatString);
            return format;
        }
    };
    return authenticationSuccessHandler;
}

From source file:com.xpn.xwiki.internal.render.XWiki10OldRendering.java

private String localizePlainOrKey(String key, Object... parameters) {
    return StringUtils.defaultString(this.localization.getTranslationPlain(key, parameters), key);
}

From source file:ca.simplegames.micro.Micro.java

public RackResponse call(Context<String> input) {

    MicroContext context = new MicroContext<String>();

    //try {//from  w ww .j  a  v a2  s .c  om
    input.with(Globals.SITE, site);
    input.with(Rack.RACK_LOGGER, log);

    String pathInfo = input.get(Rack.PATH_INFO);
    context.with(Globals.RACK_INPUT, input).with(Globals.SITE, site).with(Rack.RACK_LOGGER, log)
            .with(Globals.LOG, log).with(Globals.REQUEST, context.getRequest())
            .with(Globals.MICRO_ENV, site.getMicroEnv())
            // .with(Globals.CONTEXT, context) <-- don't, please!
            .with(Globals.PARAMS, input.get(Rack.PARAMS)).with(Globals.PARAMS, ParamsFactory.capture(context)) //<- wrap them nicely
            .with(Globals.SITE, site).with(Globals.PATH_INFO, pathInfo).with(TOOLS, tools);

    input.with(Globals.CONTEXT, context); // mostly for helping the testing effort

    context.with(Globals.MICRO_TEMPLATE_ENGINES, new TemplateEngineWrapper(context));
    for (Repository repository : site.getRepositoryManager().getRepositories()) {
        context.with(repository.getName(), repository.getRepositoryWrapper(context));
    }

    RackResponse response = new RackResponse(RackResponseUtils.ReturnCode.OK).withContentType(null)
            .withContentLength(0); // a la Sinatra, they're doing it right

    context.setRackResponse(response);

    try {
        // inject the Helpers into the current context
        List<HelperWrapper> helpers = site.getHelperManager().getHelpers();
        if (!helpers.isEmpty()) {
            for (HelperWrapper helper : helpers) {
                if (helper != null) {
                    context.with(helper.getName(), helper.getInstance(context));
                }
            }
        }

        if (site.getFilterManager() != null) {
            callFilters(site.getFilterManager().getBeforeFilters(), context);
        }

        if (!context.isHalt()) {
            String path = input.get(JRack.PATH_INFO);
            if (StringUtils.isBlank(path)) {
                path = input.get(Rack.SCRIPT_NAME);
            }

            if (site.getRouteManager() != null) {
                site.getRouteManager().call(path, context);
            }

            // Routes or filters providing their own Views will most probably ask a flow interruption, hence the
            // next check for isHalt()
            if (!context.isHalt()) {
                path = (String) context.get(Globals.PATH);
                if (path == null) { // user not deciding the PATH
                    path = maybeAppendHtmlToPath(context);
                    context.with(Globals.PATH,
                            path.contains(DOUBLE_SLASH) ? path.replace(DOUBLE_SLASH, SLASH) : path);
                }

                final String pathBasedContentType = PathUtilities
                        .extractType((String) context.get(Globals.PATH));

                String templateName = StringUtils.defaultString(context.getTemplateName(),
                        RepositoryManager.DEFAULT_TEMPLATE_NAME);

                Repository defaultRepository = site.getRepositoryManager().getDefaultRepository();
                // verify if there is a default repository decided by 3rd party components; controllers, extensions, etc.
                if (context.getDefaultRepositoryName() != null) {
                    defaultRepository = site.getRepositoryManager()
                            .getRepository(context.getDefaultRepositoryName());
                }

                // calculate the Template name
                View view = (View) context.get(Globals.VIEW);
                if (view != null && StringUtils.isNotBlank(view.getTemplate())) {
                    templateName = view.getTemplate();
                } else {
                    view = defaultRepository.getView(path);
                    if (view != null && view.getTemplate() != null) {
                        templateName = view.getTemplate();
                    }
                }

                if (!site.isLegacy()) {
                    // Execute the View Filters and Controllers (if any), render it and save it as the context 'yield' var
                    context.put(Globals.YIELD, defaultRepository.getRepositoryWrapper(context).get(path));
                }

                // Render the Default Template. The template will pull out the View via the Globals.YIELD, and the result being
                // sent out as the Template body merged with the View's own content. The Controllers are executed *before*
                // rendering the View, any context artifacts being available to the Template as well.

                Repository templatesRepository = site.getRepositoryManager().getTemplatesRepository();
                if (context.getTemplatesRepositoryName() != null) {
                    templatesRepository = site.getRepositoryManager()
                            .getRepository(context.getTemplatesRepositoryName());
                }

                if (templatesRepository != null) {
                    String out = templatesRepository.getRepositoryWrapper(context)
                            .get(templateName + pathBasedContentType);

                    response.withContentLength(out.getBytes(Charset.forName(Globals.UTF8)).length)
                            .withBody(out);
                } else {
                    throw new FileNotFoundException(
                            String.format("templates repository: %s", context.getTemplatesRepositoryName()));
                }
            }

            if (!context.isHalt()) {
                if (site.getFilterManager() != null) {
                    callFilters(site.getFilterManager().getAfterFilters(), context);
                }
            }
        }

        return context.getRackResponse().withContentType(getContentType(context));

    } catch (ControllerNotFoundException e) {
        context.with(Globals.ERROR, e);
        return badJuju(context, HttpServletResponse.SC_NO_CONTENT, e);
    } catch (ControllerException e) {
        context.with(Globals.ERROR, e);
        return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } catch (FileNotFoundException e) {
        context.with(Globals.ERROR, e);
        return badJuju(context, HttpServletResponse.SC_NOT_FOUND, e);
    } catch (ViewException e) {
        context.with(Globals.ERROR, e);
        return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } catch (RedirectException re) {
        return context.getRackResponse();
    } catch (Exception e) { // must think more about this one :(
        context.with(Globals.ERROR, e);
        e.printStackTrace();
        return badJuju(context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    }
    // Experimental!!!!!!
    //        } finally {
    //            // this is an experimental trick that will save some processing time required by BSF to load
    //            // various engines.
    //            @SuppressWarnings("unchecked")
    //            CloseableThreadLocal<BSFManager> closeableBsfManager = (CloseableThreadLocal<BSFManager>)
    //                    context.get(Globals.CLOSEABLE_BSF_MANAGER);
    //            if(closeableBsfManager!=null){
    //                closeableBsfManager.close();
    //            }
    //    }
}

From source file:com.sonicle.webtop.calendar.PublicService.java

private String buildOrganizer(UserProfileId organizerPid) {
    return StringUtils.defaultString(WT.getUserData(organizerPid).getDisplayName(), organizerPid.toString());
}

From source file:ca.uhn.fhir.jaxrs.server.util.JaxRsRequest.java

@Override
protected byte[] getByteStreamRequestContents() {
    return StringUtils.defaultString(myResourceString, "")
            .getBytes(ResourceParameter.determineRequestCharset(this));
}

From source file:edu.toronto.cs.phenotips.measurements.internal.DefaultMeasurementsChartConfigurationsFactory.java

/**
 * Load the settings for one chart./*from w  w  w  .  ja v a2  s .com*/
 * 
 * @param prefix the prefix for the configuration keys, in the format
 *            {@code charts.<measurement type>.configurations.<chart identifier>.}
 * @param configuration the resource bundle of the configuration
 * @return the configured settings
 */
private SimpleMeasurementsChartConfiguration loadChart(String prefix, ResourceBundle configuration) {
    SimpleMeasurementsChartConfiguration result = new SimpleMeasurementsChartConfiguration(prefix);
    result.lowerAgeLimit = getIntSetting(prefix + "lowerAgeLimit", result.lowerAgeLimit, configuration);
    result.upperAgeLimit = getIntSetting(prefix + "upperAgeLimit", result.upperAgeLimit, configuration);
    result.ageTickStep = getIntSetting(prefix + "ageTickStep", result.ageTickStep, configuration);
    result.ageLabelStep = getIntSetting(prefix + "ageLabelStep", result.ageLabelStep, configuration);
    result.lowerValueLimit = getDoubleSetting(prefix + "lowerValueLimit", result.lowerValueLimit,
            configuration);
    result.upperValueLimit = getDoubleSetting(prefix + "upperValueLimit", result.upperValueLimit,
            configuration);
    result.valueTickStep = getPositiveDoubleSetting(prefix + "valueTickStep", result.valueTickStep,
            configuration);
    result.valueLabelStep = getPositiveDoubleSetting(prefix + "valueLabelStep", result.valueLabelStep,
            configuration);
    result.chartTitle = getStringSetting(prefix + "chartTitle", result.chartTitle, configuration);
    result.topLabel = getStringSetting(prefix + "topLabel", result.topLabel, configuration);
    result.bottomLabel = getStringSetting(prefix + "bottomLabel",
            StringUtils.defaultString(result.topLabel, "Age (years)"), configuration);
    result.leftLabel = getStringSetting(prefix + "leftLabel", result.leftLabel, configuration);
    result.rightLabel = getStringSetting(prefix + "rightLabel", result.rightLabel, configuration);
    return result;
}