Example usage for org.apache.commons.lang ObjectUtils defaultIfNull

List of usage examples for org.apache.commons.lang ObjectUtils defaultIfNull

Introduction

In this page you can find the example usage for org.apache.commons.lang ObjectUtils defaultIfNull.

Prototype

public static <T> T defaultIfNull(T object, T defaultValue) 

Source Link

Document

Returns a default value if the object passed is null.

 ObjectUtils.defaultIfNull(null, null)      = null ObjectUtils.defaultIfNull(null, "")        = "" ObjectUtils.defaultIfNull(null, "zz")      = "zz" ObjectUtils.defaultIfNull("abc", *)        = "abc" ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE 

Usage

From source file:org.mifos.accounts.savings.persistence.SavingsDaoHibernate.java

@SuppressWarnings("unchecked")
private List<CollectionSheetCustomerSavingDto> nullSafeSavingsHierarchy(
        final List<CollectionSheetCustomerSavingDto> mandatorySavingsOnRootCustomer,
        final List<CollectionSheetCustomerSavingDto> mandatorySavingsOnRestOfHierarchy) {

    List<CollectionSheetCustomerSavingDto> nullSafeSavings = (List<CollectionSheetCustomerSavingDto>) ObjectUtils
            .defaultIfNull(mandatorySavingsOnRootCustomer, new ArrayList<CollectionSheetCustomerSavingDto>());

    List<CollectionSheetCustomerSavingDto> nullSafeRest = (List<CollectionSheetCustomerSavingDto>) ObjectUtils
            .defaultIfNull(mandatorySavingsOnRestOfHierarchy,
                    new ArrayList<CollectionSheetCustomerSavingDto>());

    nullSafeSavings.addAll(nullSafeRest);
    return nullSafeSavings;
}

From source file:org.mifos.application.servicefacade.CollectionSheetServiceImpl.java

@SuppressWarnings("unchecked")
private CollectionSheetCustomerDto createNullSafeCollectionSheetCustomer(
        final CollectionSheetCustomerDto collectionSheetCustomer,
        final List<CollectionSheetCustomerLoanDto> associatedLoanRepayments,
        final Map<Integer, List<CollectionSheetLoanFeeDto>> outstandingFeesOnLoanRepayments,
        final List<CollectionSheetCustomerLoanDto> allLoanDisbursements,
        final List<CollectionSheetCustomerSavingDto> associatedSavingAccount,
        final List<CollectionSheetCustomerSavingDto> associatedIndividualSavingsAccounts,
        final CollectionSheetCustomerAccountDto customerAccount) {

    final List<CollectionSheetCustomerSavingDto> savingAccounts = (List<CollectionSheetCustomerSavingDto>) ObjectUtils
            .defaultIfNull(associatedSavingAccount, new ArrayList<CollectionSheetCustomerSavingDto>());

    final List<CollectionSheetCustomerSavingDto> individualSavingAccounts = (List<CollectionSheetCustomerSavingDto>) ObjectUtils
            .defaultIfNull(associatedIndividualSavingsAccounts,
                    new ArrayList<CollectionSheetCustomerSavingDto>());

    if (outstandingFeesOnLoanRepayments == null) {

        List<CollectionSheetCustomerLoanDto> loanRepaymentsAndDisbursements = new ArrayList<CollectionSheetCustomerLoanDto>();

        if (associatedLoanRepayments != null) {
            loanRepaymentsAndDisbursements.addAll(associatedLoanRepayments);
        }/*ww  w .  j  av a  2  s .co  m*/

        if (allLoanDisbursements != null) {
            loanRepaymentsAndDisbursements.addAll(allLoanDisbursements);
        }

        return new CollectionSheetCustomerDto(collectionSheetCustomer, loanRepaymentsAndDisbursements,
                savingAccounts, individualSavingAccounts, customerAccount);
    }

    final List<CollectionSheetCustomerLoanDto> loanRepaymentsAndDisbursementsWithFees = new ArrayList<CollectionSheetCustomerLoanDto>();

    if (associatedLoanRepayments != null) {
        for (CollectionSheetCustomerLoanDto collectionSheetCustomerLoan : associatedLoanRepayments) {
            final List<CollectionSheetLoanFeeDto> loanFeesAgainstAccountOfCustomer = outstandingFeesOnLoanRepayments
                    .get(collectionSheetCustomerLoan.getAccountId());

            loanRepaymentsAndDisbursementsWithFees.add(populateCollectionSheetCustomerLoan(
                    collectionSheetCustomerLoan, loanFeesAgainstAccountOfCustomer));
        }
    }

    if (allLoanDisbursements != null) {
        loanRepaymentsAndDisbursementsWithFees.addAll(allLoanDisbursements);
    }

    return new CollectionSheetCustomerDto(collectionSheetCustomer, loanRepaymentsAndDisbursementsWithFees,
            savingAccounts, individualSavingAccounts, customerAccount);
}

From source file:org.ngrinder.operation.cotroller.ScriptConsoleController.java

/**
 * Run the given script. The run result is stored in "result" of the given model.
 *
 * @param script script// w ww .  ja  v  a  2s .  c om
 * @param model  model
 * @return operation/script_console
 */
@RequestMapping("")
public String run(@RequestParam(value = "script", defaultValue = "") String script, Model model) {
    if (StringUtils.isNotBlank(script)) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy");
        engine.put("applicationContext", this.applicationContext);
        engine.put("agentManager", this.agentManager);
        engine.put("agentManagerService", this.agentManagerService);
        engine.put("regionService", this.regionService);
        engine.put("consoleManager", this.consoleManager);
        engine.put("userService", this.userService);
        engine.put("perfTestService", this.perfTestService);
        engine.put("tagService", this.tagService);
        engine.put("fileEntryService", this.fileEntryService);
        engine.put("config", getConfig());
        engine.put("pluginManager", this.pluginManager);
        engine.put("cacheManager", this.cacheManager);
        engine.put("user", getCurrentUser());
        final StringWriter out = new StringWriter();
        PrintWriter writer = new PrintWriter(out);
        engine.getContext().setWriter(writer);
        engine.getContext().setErrorWriter(writer);
        try {
            Object result = engine.eval(script);
            result = out.toString() + "\n" + ObjectUtils.defaultIfNull(result, "");
            model.addAttribute("result", result);
        } catch (ScriptException e) {
            model.addAttribute("result", out.toString() + "\n" + e.getMessage());
        }
    }
    model.addAttribute("script", script);
    return "operation/script_console";
}

From source file:org.openengsb.itests.util.AbstractExamTestHelper.java

public static Option[] baseConfiguration() throws Exception {
    String loglevel = LOG_LEVEL;/*  w  ww.  jav  a  2  s  .  c  om*/
    String debugPort = Integer.toString(DEBUG_PORT);
    boolean hold = true;
    boolean debug = false;
    InputStream paxLocalStream = ClassLoader.getSystemResourceAsStream("itests.local.properties");
    if (paxLocalStream != null) {
        Properties properties = new Properties();
        properties.load(paxLocalStream);
        loglevel = (String) ObjectUtils.defaultIfNull(properties.getProperty("loglevel"), loglevel);
        debugPort = (String) ObjectUtils.defaultIfNull(properties.getProperty("debugport"), debugPort);
        debug = ObjectUtils.equals(Boolean.TRUE.toString(), properties.getProperty("debug"));
        hold = ObjectUtils.equals(Boolean.TRUE.toString(), properties.getProperty("hold"));
    }
    Properties portNames = new Properties();
    InputStream portsPropertiesFile = ClassLoader.getSystemResourceAsStream("ports.properties");
    if (portsPropertiesFile == null) {
        throw new IllegalStateException("ports-configuration not found");
    }
    portNames.load(portsPropertiesFile);
    LOGGER.warn("running itests with the following port-config");
    LOGGER.warn(portNames.toString());
    LogLevel realLogLevel = transformLogLevel(loglevel);
    Option[] mainOptions = new Option[] { new VMOption("-Xmx2048m"), new VMOption("-XX:MaxPermSize=256m"),
            karafDistributionConfiguration().frameworkUrl(maven().groupId("org.openengsb.framework")
                    .artifactId("openengsb-framework").type("zip").versionAsInProject()),
            logLevel(realLogLevel),
            editConfigurationFilePut(WebCfg.HTTP_PORT, (String) portNames.get("jetty.http.port")),
            editConfigurationFilePut(ManagementCfg.RMI_SERVER_PORT, (String) portNames.get("rmi.server.port")),
            editConfigurationFilePut(ManagementCfg.RMI_REGISTRY_PORT,
                    (String) portNames.get("rmi.registry.port")),
            editConfigurationFilePut(
                    new ConfigurationPointer("etc/org.openengsb.infrastructure.jms.cfg", "openwire"),
                    (String) portNames.get("jms.openwire.port")),
            editConfigurationFilePut(
                    new ConfigurationPointer("etc/org.openengsb.infrastructure.jms.cfg", "stomp"),
                    (String) portNames.get("jms.stomp.port")),
            mavenBundle(maven().groupId("org.openengsb.wrapped").artifactId("net.sourceforge.htmlunit-all")
                    .versionAsInProject()) };
    if (debug) {
        return combine(mainOptions, debugConfiguration(debugPort, hold));
    }
    return mainOptions;
}

From source file:org.openengsb.openticket.integrationtest.util.AbstractExamTestHelper.java

@Configuration
public static Option[] configuration() throws Exception {
    Option[] baseOptions = Helper.getDefaultOptions();
    /*/*ww  w  . j  a  va  2s  .c o m*/
     * do not change the values for loglevel or debug here, but refer the comment at the top of the class for
     * further instructions
     */
    String loglevel = "WARN";
    boolean debug = false;
    InputStream paxLocalStream = ClassLoader.getSystemResourceAsStream("itests.local.properties");
    if (paxLocalStream != null) {
        Properties properties = new Properties();
        properties.load(paxLocalStream);
        loglevel = (String) ObjectUtils.defaultIfNull(properties.getProperty("loglevel"), loglevel);
        debug = ObjectUtils.equals(Boolean.TRUE.toString(), properties.getProperty("debug"));
    }

    if (debug) {
        baseOptions = combine(baseOptions, Helper.activateDebugging(Integer.toString(DEBUG_PORT)));
    }
    String targetpath = new File("target").getAbsolutePath();
    FileUtils.deleteDirectory(new File(targetpath, "karaf.data"));
    return combine(baseOptions, Helper.loadKarafStandardFeatures("config", "management"),
            Helper.setLogLevel(loglevel),
            mavenBundle(maven().groupId("org.apache.aries").artifactId("org.apache.aries.util")
                    .versionAsInProject()),
            mavenBundle(maven().groupId("org.apache.aries.proxy").artifactId("org.apache.aries.proxy")
                    .versionAsInProject()),
            mavenBundle(maven().groupId("org.apache.aries.blueprint").artifactId("org.apache.aries.blueprint")
                    .versionAsInProject()),
            scanFeatures(
                    maven().groupId("org.openengsb.openticket").artifactId("openticket").type("xml")
                            .classifier("features").versionAsInProject(),
                    "openengsb-connector-memoryauditing", "openengsb-ui-admin", "openticket-core"),
            workingDirectory(getWorkingDirectory()),
            vmOption("-Dorg.osgi.framework.system.packages.extra=com.sun.org.apache.xerces.internal.dom,"
                    + "com.sun.org.apache.xerces.internal.jaxp,org.apache.karaf.branding,sun.reflect"),
            vmOption("-Dorg.osgi.service.http.port=" + WEBUI_PORT),
            vmOption("-DrmiRegistryPort=" + RMI_REGISTRY_PORT), vmOption("-DrmiServerPort=" + RMI_SERVER_PORT),
            waitForFrameworkStartup(), vmOption("-Dkaraf.data=" + targetpath + "/karaf.data"),
            vmOption("-Dkaraf.home=" + targetpath + "/karaf.home"),
            vmOption("-Dkaraf.base=" + targetpath + "/karaf.base"),
            mavenBundle(maven().groupId("org.openengsb.wrapped").artifactId("net.sourceforge.htmlunit-all")
                    .versionAsInProject()),
            felix());
}

From source file:org.openhab.binding.ebus.internal.parser.EBusTelegramParser.java

/**
 * Evaluates the compiled script of a entry.
 * @param entry The configuration entry to evaluate
 * @param scopeValues All known values for script scope
 * @return The computed value/* w  w  w . j av a  2s  . c o  m*/
 * @throws ScriptException
 */
private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> scopeValues)
        throws ScriptException {

    Object value = null;

    // executes compiled script
    if (entry.getValue().containsKey("cscript")) {
        CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript");

        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(scopeValues);
        value = cscript.eval(bindings);
    }

    // try to convert the returned value to BigDecimal
    value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value);

    // round to two digits, maybe not optimal for any result
    if (value instanceof BigDecimal) {
        ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    return value;
}

From source file:org.openhab.binding.ebus.parser.EBusTelegramParser.java

/**
 * @param entry/*  w  w  w.j av  a2 s  . com*/
 * @param bindings2
 * @return
 * @throws ScriptException
 */
private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> bindings2)
        throws ScriptException {
    Object value = null;
    if (entry.getValue().containsKey("cscript")) {
        CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript");

        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(bindings2);
        value = cscript.eval(bindings);
    }

    value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value);

    // round to two digits, maybe not optimal for any result
    if (value instanceof BigDecimal) {
        ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    return value;
}

From source file:org.openhab.binding.neato.internal.handler.NeatoHandler.java

private void publishChannels() {
    logger.debug("Updating Channels");

    NeatoState neatoState = mrRobot.getState();
    if (neatoState == null) {
        return;/*from w ww .j a v  a  2s.  c o m*/
    }

    updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, neatoState.getMeta().getFirmware());
    updateProperty(Thing.PROPERTY_MODEL_ID, neatoState.getMeta().getModelName());

    updateState(CHANNEL_STATE, new StringType(neatoState.getRobotState().name()));
    updateState(CHANNEL_ERROR, new StringType((String) ObjectUtils.defaultIfNull(neatoState.getError(), "")));
    updateState(CHANNEL_ACTION, new StringType(neatoState.getRobotAction().name()));

    Details details = neatoState.getDetails();
    if (details != null) {
        updateState(CHANNEL_BATTERY, new DecimalType(details.getCharge()));
        updateState(CHANNEL_DOCKHASBEENSEEN, details.getDockHasBeenSeen() ? OnOffType.ON : OnOffType.OFF);
        updateState(CHANNEL_ISCHARGING, details.getIsCharging() ? OnOffType.ON : OnOffType.OFF);
        updateState(CHANNEL_ISSCHEDULED, details.getIsScheduleEnabled() ? OnOffType.ON : OnOffType.OFF);
        updateState(CHANNEL_ISDOCKED, details.getIsDocked() ? OnOffType.ON : OnOffType.OFF);
    }

    Cleaning cleaning = neatoState.getCleaning();
    if (cleaning != null) {
        updateState(CHANNEL_CLEANINGCATEGORY, new StringType(cleaning.getCategory().name()));
        updateState(CHANNEL_CLEANINGMODE, new StringType(cleaning.getMode().name()));
        updateState(CHANNEL_CLEANINGMODIFIER, new StringType(cleaning.getModifier().name()));
        updateState(CHANNEL_CLEANINGSPOTWIDTH, new DecimalType(cleaning.getSpotWidth()));
        updateState(CHANNEL_CLEANINGSPOTHEIGHT, new DecimalType(cleaning.getSpotHeight()));
    }
}

From source file:org.pentaho.di.flume.PentahoKettleSink.java

@Override
public void configure(Context context) {
    this.sinkTransPath = context.getString(SINK_TRANS_PATH);
    Preconditions.checkNotNull(this.sinkTransPath, "Please configure the sinkTransPath variable.");

    this.sinkInjectorName = context.getString(SINK_INJECTOR_NAME);
    Preconditions.checkNotNull(this.sinkInjectorName, "Please configure the sinkInjectorName variable.");

    this.sinkExecutionType = TransExecutionType.getExecutionType(context.getString(SINK_EXECUTION_TYPE));

    this.sinkLogLevel = (String) ObjectUtils.defaultIfNull(context.getString(SINK_LOG_LEVEL),
            DEFAULT_SINK_LOG_LEVEL);/*w w  w.j a  v  a2s  . c  o m*/
}

From source file:org.pentaho.di.flume.PentahoKettleSource.java

@Override
public void configure(Context context) {
    this.sourceTransPath = context.getString(SOURCE_TRANS_PATH);
    Preconditions.checkNotNull(this.sourceTransPath, "Please configure the sourceTransPath variable.");

    this.sourceOutputName = context.getString(SOURCE_OUTPUT_NAME);
    Preconditions.checkNotNull(this.sourceOutputName, "Please configure the sourceOutputName variable.");

    this.sourceExecutionType = TransExecutionType.getExecutionType(context.getString(SOURCE_EXECUTION_TYPE));

    this.sourceLogLevel = (String) ObjectUtils.defaultIfNull(context.getString(SOURCE_LOG_LEVEL),
            DEFAULT_SOURCE_LOG_LEVEL);//from w  ww .  j  a v a2s  .  c om
}