Java Code Examples for org.apache.commons.lang3.ObjectUtils#firstNonNull()

The following examples show how to use org.apache.commons.lang3.ObjectUtils#firstNonNull() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InstallationDescription.java    From ES-Fastloader with Apache License 2.0 6 votes vote down vote up
InstallationDescription(
        InstallationSource installationSource,
        File downloadDirectory,
        File installationDirectory,
        boolean cleanInstallationDirectoryOnStop,
        List<Plugin> plugins,
        int downloaderConnectionTimeoutInMs,
        int downloaderReadTimeoutInMs, Proxy downloadProxy) {
    this.installationSource = installationSource;
    this.plugins = plugins;
    this.cleanInstallationDirectoryOnStop = cleanInstallationDirectoryOnStop;
    this.installationDirectory = ObjectUtils.firstNonNull(installationDirectory, DEFAULT_INSTALL_DIR);
    this.downloadDirectory = ObjectUtils.firstNonNull(downloadDirectory, DEFAULT_DOWNLOAD_DIR);
    this.downloaderConnectionTimeoutInMs = downloaderConnectionTimeoutInMs;
    this.downloaderReadTimeoutInMs = downloaderReadTimeoutInMs;
    this.downloadProxy = downloadProxy;
}
 
Example 2
Source File: GdxCvarManager.java    From riiablo with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T load(Cvar<T> cvar) {
  String alias = cvar.getAlias();
  StringSerializer<T> serializer = ObjectUtils.firstNonNull(cvar.getSerializer(), getSerializer(cvar));
  if (serializer == null) {
    try {
      throw new CvarManagerException("%s cannot be loaded (no deserializer found for %s)", alias, cvar.getType().getName());
    } finally {
      return cvar.getDefault();
    }
  }

  String serialization = PREFERENCES.getString(alias, null);
  if (serialization == null) return cvar.getDefault();

  T deserialization = serializer.deserialize(serialization);
  if (Gdx.app.getLogLevel() >= Application.LOG_DEBUG) {
    Gdx.app.debug(TAG, String.format("%s loaded as \"%s\" [%s] (raw: \"%s\")",
        alias, deserialization, deserialization.getClass().getName(), serialization));
  }

  return deserialization;
}
 
Example 3
Source File: InstallationDescription.java    From embedded-elasticsearch with Apache License 2.0 6 votes vote down vote up
InstallationDescription(
        InstallationSource installationSource,
        File downloadDirectory,
        File installationDirectory,
        boolean cleanInstallationDirectoryOnStop,
        List<Plugin> plugins,
        int downloaderConnectionTimeoutInMs,
        int downloaderReadTimeoutInMs, Proxy downloadProxy) {
    this.installationSource = installationSource;
    this.plugins = plugins;
    this.cleanInstallationDirectoryOnStop = cleanInstallationDirectoryOnStop;
    this.installationDirectory = ObjectUtils.firstNonNull(installationDirectory, DEFAULT_INSTALL_DIR);
    this.downloadDirectory = ObjectUtils.firstNonNull(downloadDirectory, DEFAULT_DOWNLOAD_DIR);
    this.downloaderConnectionTimeoutInMs = downloaderConnectionTimeoutInMs;
    this.downloaderReadTimeoutInMs = downloaderReadTimeoutInMs;
    this.downloadProxy = downloadProxy;
}
 
Example 4
Source File: DefaultOrganisationUnitService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
@Transactional( readOnly = true )
public List<OrganisationUnitLevel> getFilledOrganisationUnitLevels()
{
    Map<Integer, OrganisationUnitLevel> levelMap = getOrganisationUnitLevelMap();

    List<OrganisationUnitLevel> levels = new ArrayList<>();

    int levelNo = getNumberOfOrganisationalLevels();

    for ( int i = 0; i < levelNo; i++ )
    {
        int level = i + 1;

        OrganisationUnitLevel filledLevel = ObjectUtils.firstNonNull( levelMap.get( level ),
            new OrganisationUnitLevel( level, LEVEL_PREFIX + level ) );

        levels.add( filledLevel );
    }

    return levels;
}
 
Example 5
Source File: LeaseItemImport.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Programmatic
public LeaseItem importItem(boolean updateExisting) {
    final Lease lease = fetchLease(leaseReference);
    final Charge charge = fetchCharge(chargeReference);
    final LeaseItemType itemType = fetchLeaseItemType(itemTypeName);

    // for deposit items the start date defaults to the start date of the lease
    LocalDate startDateOrDefault;
    if (itemType == LeaseItemType.DEPOSIT) {
        startDateOrDefault = ObjectUtils.firstNonNull(startDate, lease.getStartDate());
    } else {
        startDateOrDefault = startDate;
    }
    LeaseItem item = lease.findItem(itemType, startDateOrDefault, sequence);
    if (item == null) {
        item = lease.newItem(itemType, LeaseAgreementRoleTypeEnum.LANDLORD, charge, InvoicingFrequency.valueOf(invoicingFrequency), PaymentMethod.valueOf(paymentMethod), startDateOrDefault);
        item.setSequence(sequence);
    }
    if (updateExisting) {
        item.setEpochDate(epochDate);
        item.setNextDueDate(nextDueDate);
        item.setStatus(LeaseItemStatus.valueOfElse(status, LeaseItemStatus.ACTIVE));
    }
    return item;
}
 
Example 6
Source File: GdxCvarManager.java    From riiablo with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void save(Cvar<T> cvar) {
  String alias = cvar.getAlias();
  if (Gdx.app.getLogLevel() >= Application.LOG_DEBUG && !isManaging(cvar)) {
    throw new CvarManagerException("%s must be managed by this CvarManager", alias);
  }

  StringSerializer<T> serializer = ObjectUtils.firstNonNull(cvar.getSerializer(), getSerializer(cvar));
  if (serializer == null) {
    throw new CvarManagerException("%s cannot be saved (no serializer found for %s)", alias, cvar.getType().getName());
  }

  T value = cvar.get();
  String serialization = serializer.serialize(value);
  PREFERENCES.putString(alias, serialization);
  PREFERENCES.flush();
  if (Gdx.app.getLogLevel() >= Application.LOG_DEBUG) {
    Gdx.app.debug(TAG, String.format("%s saved as \"%s\" (raw: \"%s\")", alias, value, serialization));
  }
}
 
Example 7
Source File: Plan.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
/**
 * Chains the underlying functions, applying "Combiner" if set.
 *
 * @param runningValue
 * @return
 * @throws SQLException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws InstantiationException
 */
@Override
public Object invoke(Object runningValue)
    throws SQLException,
    IllegalAccessException,
    InvocationTargetException,
    InstantiationException {

    boolean isFirst = true;
    Object glue = null;
    for (Function fn : functions) {
        log.debug("Invoking function: {}", fn.getFunction());
        Object returnValue = fn.invoke(runningValue);
        if (combiner != null && !isFirst) {
            final Object gl = glue;
            log.debug(
                "Combining with: {}, using glue: \"{}\"",
                () -> combiner.getFunctionName(),
                () -> StringEscapeUtils.escapeJava(Objects.toString(gl))
            );
            if (gl != null) {
                runningValue = invokeCombiner(runningValue, gl);
            }
            returnValue = invokeCombiner(runningValue, returnValue);
        }
        glue = ObjectUtils.firstNonNull(
            fn.getCombinerGlueObject(),
            combinerGlueObject
        );
        runningValue = returnValue;
        isFirst = false;
    }
    return runningValue;
}
 
Example 8
Source File: ProgressMessageService.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
protected ProgressMessageDto merge(ProgressMessageDto existingProgressMessage, ProgressMessageDto newProgressMessage) {
    super.merge(existingProgressMessage, newProgressMessage);
    String processId = ObjectUtils.firstNonNull(newProgressMessage.getProcessId(), existingProgressMessage.getProcessId());
    String taskId = ObjectUtils.firstNonNull(newProgressMessage.getTaskId(), existingProgressMessage.getTaskId());
    String type = ObjectUtils.firstNonNull(newProgressMessage.getType(), existingProgressMessage.getType());
    String text = ObjectUtils.firstNonNull(newProgressMessage.getText(), existingProgressMessage.getText());
    Date timestamp = ObjectUtils.firstNonNull(newProgressMessage.getTimestamp(), existingProgressMessage.getTimestamp());
    return getProgressMessageDto(newProgressMessage.getPrimaryKey(), processId, taskId, type, text, timestamp);
}
 
Example 9
Source File: CacheService.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates {@link CacheBid} from given {@link com.iab.openrtb.response.Bid} and determined cache ttl.
 */
private CacheBid toCacheBid(com.iab.openrtb.response.Bid bid, Map<String, Integer> impIdToTtl, Integer requestTtl,
                            CacheTtl accountCacheTtl, boolean isVideoBid) {
    final Integer bidTtl = bid.getExp();
    final Integer impTtl = impIdToTtl.get(bid.getImpid());
    final Integer accountMediaTypeTtl = isVideoBid
            ? accountCacheTtl.getVideoCacheTtl() : accountCacheTtl.getBannerCacheTtl();
    final Integer mediaTypeTtl = isVideoBid
            ? mediaTypeCacheTtl.getVideoCacheTtl() : mediaTypeCacheTtl.getBannerCacheTtl();
    final Integer ttl = ObjectUtils.firstNonNull(bidTtl, impTtl, requestTtl, accountMediaTypeTtl, mediaTypeTtl);

    return CacheBid.of(bid, ttl);
}
 
Example 10
Source File: AmpRequestFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts parameters from http request and overrides corresponding attributes in {@link BidRequest}.
 */
private BidRequest overrideParameters(BidRequest bidRequest, HttpServerRequest request) {
    final String requestConsentParam = request.getParam(CONSENT_PARAM);
    final String requestGdprConsentParam = request.getParam(GDPR_CONSENT_PARAM);
    final String consentString = ObjectUtils.firstNonNull(requestConsentParam, requestGdprConsentParam);

    String gdprConsent = null;
    String ccpaConsent = null;
    if (StringUtils.isNotBlank(consentString)) {
        gdprConsent = TcfDefinerService.isGdprConsentValid(consentString) ? consentString : null;
        ccpaConsent = Ccpa.isValid(consentString) ? consentString : null;

        if (StringUtils.isAllBlank(gdprConsent, ccpaConsent)) {
            logger.debug("Amp request parameter consent_string or gdpr_consent have invalid format: {0}",
                    consentString);
        }
    }

    final Site updatedSite = overrideSite(bidRequest.getSite(), request);
    final Imp updatedImp = overrideImp(bidRequest.getImp().get(0), request);
    final Long updatedTimeout = overrideTimeout(bidRequest.getTmax(), request);
    final User updatedUser = overrideUser(bidRequest.getUser(), gdprConsent);
    final Regs updatedRegs = overrideRegs(bidRequest.getRegs(), ccpaConsent);

    final BidRequest result;
    if (updatedSite != null || updatedImp != null || updatedTimeout != null || updatedUser != null
            || updatedRegs != null) {
        result = bidRequest.toBuilder()
                .site(updatedSite != null ? updatedSite : bidRequest.getSite())
                .imp(updatedImp != null ? Collections.singletonList(updatedImp) : bidRequest.getImp())
                .tmax(updatedTimeout != null ? updatedTimeout : bidRequest.getTmax())
                .user(updatedUser != null ? updatedUser : bidRequest.getUser())
                .regs(updatedRegs != null ? updatedRegs : bidRequest.getRegs())
                .build();
    } else {
        result = bidRequest;
    }
    return result;
}
 
Example 11
Source File: FixedAssetRegistration.java    From estatio with Apache License 2.0 5 votes vote down vote up
public String validateChangeDates(final LocalDate startDate, final LocalDate endDate) {
    return ObjectUtils.firstNonNull(
            getChangeDates().validateChangeDates(startDate, endDate),
            getPrevious() == null ? null : getPrevious().getChangeDates().validateChangeDates(getPrevious().getStartDate(), startDate),
            getNext() == null ? null : getNext().getChangeDates().validateChangeDates(startDate, getNext().getEndDate())
            );
}
 
Example 12
Source File: FileBlobMetadata.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public FileBlobMetadata(@Column("id") String id,
                        @Column("name") String name,
                        @Column("content_size") int contentSize,
                        @Column("content_type") String contentType,
                        @Column("attributes") String attributes) {
    this.id = id;
    this.name = name;
    this.contentSize = contentSize;
    this.contentType = contentType;
    Map<String, String> parsed = Json.GSON.fromJson(attributes, new TypeToken<Map<String, String>>() {}.getType());
    this.attributes = ObjectUtils.firstNonNull(parsed, Collections.emptyMap());
}
 
Example 13
Source File: MockUrlProviderConfiguration.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Override
public CategoryIdentifierType categoryIdentifierType() {
    return ObjectUtils.firstNonNull(categoryIdentifierType, CategoryIdentifierType.ID);
}
 
Example 14
Source File: MockUrlProviderConfiguration.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Override
public IdentifierLocation categoryIdentifierLocation() {
    return ObjectUtils.firstNonNull(categoryIdentifierLocation, IdentifierLocation.SELECTOR);
}
 
Example 15
Source File: TrackedEntityInstanceController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@RequestMapping( value = "/query", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_CSV )
public void queryTrackedEntityInstancesCsv(
    @RequestParam( required = false ) String query,
    @RequestParam( required = false ) Set<String> attribute,
    @RequestParam( required = false ) Set<String> filter,
    @RequestParam( required = false ) String ou,
    @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode,
    @RequestParam( required = false ) String program,
    @RequestParam( required = false ) ProgramStatus programStatus,
    @RequestParam( required = false ) Boolean followUp,
    @RequestParam( required = false ) Date lastUpdatedStartDate,
    @RequestParam( required = false ) Date lastUpdatedEndDate,
    @RequestParam( required = false ) Date programStartDate,
    @RequestParam( required = false ) Date programEnrollmentStartDate,
    @RequestParam( required = false ) Date programEndDate,
    @RequestParam( required = false ) Date programEnrollmentEndDate,
    @RequestParam( required = false ) Date programIncidentStartDate,
    @RequestParam( required = false ) Date programIncidentEndDate,
    @RequestParam( required = false ) String trackedEntityType,
    @RequestParam( required = false ) AssignedUserSelectionMode assignedUserMode,
    @RequestParam( required = false ) String assignedUser,
    @RequestParam( required = false ) EventStatus eventStatus,
    @RequestParam( required = false ) Date eventStartDate,
    @RequestParam( required = false ) Date eventEndDate,
    @RequestParam( required = false ) boolean skipMeta,
    @RequestParam( required = false ) Integer page,
    @RequestParam( required = false ) Integer pageSize,
    @RequestParam( required = false ) boolean totalPages,
    @RequestParam( required = false ) Boolean skipPaging,
    @RequestParam( required = false ) Boolean paging,
    @RequestParam( required = false ) boolean includeDeleted,
    @RequestParam( required = false ) String order,
    HttpServletResponse response ) throws Exception
{
    programEnrollmentStartDate = ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
    programEnrollmentEndDate = ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
    Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON );
    Set<String> assignedUsers = TextUtils.splitToArray( assignedUser, TextUtils.SEMICOLON );

    skipPaging = PagerUtils.isSkipPaging( skipPaging, paging );

    TrackedEntityInstanceQueryParams params = instanceService.getFromUrl( query, attribute, filter, orgUnits, ouMode,
        program, programStatus, followUp, lastUpdatedStartDate, lastUpdatedEndDate, null,
        programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate,
        trackedEntityType, eventStatus, eventStartDate, eventEndDate, assignedUserMode, assignedUsers, skipMeta,
        page, pageSize, totalPages, skipPaging, includeDeleted, false, getOrderParams( order ) );

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_CSV, CacheStrategy.NO_CACHE );
    Grid grid = instanceService.getTrackedEntityInstancesGrid( params );
    GridUtils.toCsv( grid, response.getWriter() );
}
 
Example 16
Source File: EventModification.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
@JsonCreator
public RestrictedValue(@JsonProperty("value") String value, @JsonProperty("enabled") Boolean enabled) {
    this.value = value;
    this.enabled = ObjectUtils.firstNonNull(enabled, Boolean.TRUE);
}
 
Example 17
Source File: AdminReservationApiController.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
public Boolean getNotify() {
    return ObjectUtils.firstNonNull(notify, Boolean.FALSE);
}
 
Example 18
Source File: MockUrlProviderConfiguration.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Override
public IdentifierLocation categoryIdentifierLocation() {
    return ObjectUtils.firstNonNull(categoryIdentifierLocation, IdentifierLocation.SELECTOR);
}
 
Example 19
Source File: OpenPeripheralAddons.java    From OpenPeripheral-Addons with MIT License 4 votes vote down vote up
@Override
public Item getTabIconItem() {
	return ObjectUtils.firstNonNull(Items.glasses, net.minecraft.init.Items.fish);
}
 
Example 20
Source File: GetFirstNonNullObject.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void get_first_non_null_apache () {

	String first = null;
	String second = "On, Wisconsin!";

	String firstNullObject = ObjectUtils.firstNonNull(first, second);
	
	assertEquals(second, firstNullObject);
}