Java Code Examples for org.apache.commons.lang3.ObjectUtils

The following examples show how to use org.apache.commons.lang3.ObjectUtils. These examples are extracted from open source projects. 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
@Override
protected ConfigurationSubscriptionDto merge(ConfigurationSubscriptionDto existingSubscription,
                                             ConfigurationSubscriptionDto newSubscription) {
    super.merge(existingSubscription, newSubscription);
    String mtaId = ObjectUtils.firstNonNull(newSubscription.getMtaId(), existingSubscription.getMtaId());
    String appName = ObjectUtils.firstNonNull(newSubscription.getAppName(), existingSubscription.getAppName());
    String spaceId = ObjectUtils.firstNonNull(newSubscription.getSpaceId(), existingSubscription.getSpaceId());
    String filter = ObjectUtils.firstNonNull(newSubscription.getFilter(), existingSubscription.getFilter());
    String moduleContent = ObjectUtils.firstNonNull(newSubscription.getModuleContent(), existingSubscription.getModuleContent());
    String resourceProperties = ObjectUtils.firstNonNull(newSubscription.getResourceProperties(),
                                                         existingSubscription.getResourceProperties());
    String resourceName = ObjectUtils.firstNonNull(newSubscription.getResourceName(), existingSubscription.getResourceName());
    return ConfigurationSubscriptionDto.builder()
                                       .id(newSubscription.getPrimaryKey())
                                       .mtaId(mtaId)
                                       .spaceId(spaceId)
                                       .appName(appName)
                                       .filter(filter)
                                       .module(moduleContent)
                                       .resourceName(resourceName)
                                       .resourceProperties(resourceProperties)
                                       .build();
}
 
Example 2
Source Project: syncope   Source File: AnyTypeRestClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int compare(final String o1, final String o2) {
    if (SyncopeConstants.REALM_ANYTYPE.equals(o1)) {
        return -1;
    }
    if (SyncopeConstants.REALM_ANYTYPE.equals(o2)) {
        return 1;
    }
    if (AnyTypeKind.USER.name().equals(o1)) {
        return -1;
    }
    if (AnyTypeKind.USER.name().equals(o2)) {
        return 1;
    }
    if (AnyTypeKind.GROUP.name().equals(o1)) {
        return -1;
    }
    if (AnyTypeKind.GROUP.name().equals(2)) {
        return 1;
    }
    return ObjectUtils.compare(o1, o2);
}
 
Example 3
@SuppressWarnings("deprecation")
private JSMemberExpression createNameExpression(final QName name, final String defaultNamespaceURI) {
	final String draftNamespaceURI = name.getNamespaceURI();
	final String namespaceURI = StringUtils.isEmpty(draftNamespaceURI) ? null : draftNamespaceURI;

	if (ObjectUtils.equals(defaultNamespaceURI, namespaceURI)) {
		return this.codeModel.string(name.getLocalPart());
	} else {

		final JSObjectLiteral nameExpression = this.codeModel.object();

		nameExpression.append(naming.localPart(), this.codeModel.string(name.getLocalPart()));

		if (!StringUtils.isEmpty(namespaceURI)) {
			nameExpression.append(naming.namespaceURI(), this.codeModel.string(namespaceURI));

		}
		return nameExpression;
	}
}
 
Example 4
Source Project: astor   Source File: StrTokenizerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test2() {

    String input = "a;b;c ;\"d;\"\"e\";f; ; ;";
    StrTokenizer tok = new StrTokenizer(input);
    tok.setDelimiterChar(';');
    tok.setQuoteChar('"');
    tok.setIgnoredMatcher(StrMatcher.noneMatcher());
    tok.setIgnoreEmptyTokens(false);
    String tokens[] = tok.getTokenArray();

    String expected[] = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", "",};

    assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
    for (int i = 0; i < expected.length; i++) {
        assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
                ObjectUtils.equals(expected[i], tokens[i]));
    }

}
 
Example 5
Source Project: spring-openapi   Source File: OperationsTransformer.java    License: MIT License 6 votes vote down vote up
private void mapRequestMapping(RequestMapping requestMapping, Method method, Map<String, Path> operationsMap, String controllerClassName,
							   String baseControllerPath) {
	List<HttpMethod> httpMethods = Arrays.stream(requestMapping.method())
										 .map(this::getSpringMethod)
										 .collect(toList());
	httpMethods.forEach(httpMethod -> {
		Operation operation = mapOperation(requestMapping.name(), httpMethod, method, requestMapping.produces(),
										   requestMapping.consumes(), controllerClassName);

		String path = ObjectUtils.defaultIfNull(getFirstFromArray(requestMapping.value()), getFirstFromArray(requestMapping.path()));
		updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap,
							pathItem -> setContentBasedOnHttpMethod(pathItem, httpMethod, operation)
		);
	});

}
 
Example 6
Source Project: astor   Source File: StrTokenizerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test4() {

    String input = "a;b; c;\"d;\"\"e\";f; ; ;";
    StrTokenizer tok = new StrTokenizer(input);
    tok.setDelimiterChar(';');
    tok.setQuoteChar('"');
    tok.setIgnoredMatcher(StrMatcher.trimMatcher());
    tok.setIgnoreEmptyTokens(true);
    String tokens[] = tok.getTokenArray();

    String expected[] = new String[]{"a", "b", "c", "d;\"e", "f",};

    assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
    for (int i = 0; i < expected.length; i++) {
        assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
                ObjectUtils.equals(expected[i], tokens[i]));
    }

}
 
Example 7
Source Project: gvnix   Source File: DynProperty.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc} Two properties are equal if their key and value are equals.
 */
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    DynProperty other = (DynProperty) obj;
    if (!ObjectUtils.equals(key, other.key)) {
        return false;
    }
    if (!ObjectUtils.equals(value, other.value)) {
        return false;
    }
    return true;
}
 
Example 8
Source Project: open-capacity-platform   Source File: SysUserServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PageResult<SysUser> findUsers(Map<String, Object> params) {
	int total = sysUserDao.count(params);
	List<SysUser> list = Collections.emptyList();
	if (total > 0) {
		PageUtil.pageParamConver(params, true);
		list = sysUserDao.findList(params);

		List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());

		List<SysRole> sysRoles = userRoleDao.findRolesByUserIds(userIds);

		list.forEach(u -> {
			u.setRoles(sysRoles.stream().filter(r -> !ObjectUtils.notEqual(u.getId(), r.getUserId()))
					.collect(Collectors.toList()));
		});
	}
	return PageResult.<SysUser>builder().data(list).code(0).count((long)total).build();
}
 
Example 9
Source Project: morf   Source File: TableDataHomology.java    License: Apache License 2.0 6 votes vote down vote up
private int compareKeys(Optional<Record> record1, Optional<Record> record2, List<Column> primaryKeys) {
  if (!record1.isPresent() && !record2.isPresent()) {
    throw new IllegalStateException("Cannot compare two nonexistent records.");
  }
  if (!record1.isPresent()) {
    return 1;
  }
  if (!record2.isPresent()) {
    return -1;
  }
  for (Column keyCol : primaryKeys) {
    @SuppressWarnings({ "rawtypes" })
    Comparable value1 = convertToComparableType(keyCol, record1.get());
    @SuppressWarnings({ "rawtypes" })
    Comparable value2 = convertToComparableType(keyCol, record2.get());
    @SuppressWarnings("unchecked")
    int result = ObjectUtils.compare(value1, value2);
    if (result != 0) {
      return result;
    }
  }
  return 0;
}
 
Example 10
Source Project: multiapps   Source File: YamlRepresenter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
    if (ObjectUtils.isEmpty(propertyValue)) {
        return null;
    }
    Field field = getField(javaBean.getClass(), property.getName());
    String nodeName = field.isAnnotationPresent(YamlElement.class) ? field.getAnnotation(YamlElement.class)
                                                                          .value()
        : property.getName();

    if (field.isAnnotationPresent(YamlAdapter.class)) {
        return getAdaptedTuple(propertyValue, field, nodeName);
    }

    NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
    return new NodeTuple(representData(nodeName), defaultNode.getValueNode());
}
 
Example 11
Source Project: prebid-server-java   Source File: UidsCookieService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enriches {@link Uids} parsed from request cookies with uid from host cookie (if applicable) and removes
 * invalid uids. Also converts legacy uids to uids with expiration.
 */
private Map<String, UidWithExpiry> enrichAndSanitizeUids(Uids uids, Map<String, String> cookies) {
    final Map<String, UidWithExpiry> originalUidsMap = uids != null ? uids.getUids() : null;
    final Map<String, UidWithExpiry> workingUidsMap = new HashMap<>(
            ObjectUtils.defaultIfNull(originalUidsMap, Collections.emptyMap()));

    final Map<String, String> legacyUids = uids != null ? uids.getUidsLegacy() : null;
    if (workingUidsMap.isEmpty() && legacyUids != null) {
        legacyUids.forEach((key, value) -> workingUidsMap.put(key, UidWithExpiry.expired(value)));
    }

    final String hostCookie = parseHostCookie(cookies);
    if (hostCookie != null && hostCookieDiffers(hostCookie, workingUidsMap.get(hostCookieFamily))) {
        // make host cookie precedence over uids
        workingUidsMap.put(hostCookieFamily, UidWithExpiry.live(hostCookie));
    }

    workingUidsMap.entrySet().removeIf(UidsCookieService::facebookSentinelOrEmpty);

    return workingUidsMap;
}
 
Example 12
Source Project: uyuni   Source File: ValueMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert a value to a {@link Long} (if possible).
 * @param value a value
 * @return an {@link Optional} containing a {@link Long}  or empty if
 * the value could not be converted.
 */
public Optional<Long> toLong(Object value) {
    if (value instanceof Double) {
        return Optional.of(((Double)value).longValue());
    }
    else if (value instanceof Long) {
        return Optional.of((Long)value);
    }
    else if (value instanceof Integer) {
        return Optional.of(((Integer)value).longValue());
    }
    else if (value instanceof String) {
        try {
            return Optional.of(Long.parseLong((String) value));
        }
        catch (NumberFormatException e) {
            LOG.warn("Error converting  '" + value + "' to long", e);
            return Optional.empty();
        }
    }
    else {
        LOG.warn("Value '" + ObjectUtils.toString(value) +
                "' could not be converted to long.");
        return Optional.empty();
    }
}
 
Example 13
Source Project: arcusplatform   Source File: ChangeLogSet.java    License: Apache License 2.0 6 votes vote down vote up
public static ChangeLogSet fromChangesets(List<ChangeSet> changeSets) {

      Collections.sort(changeSets, (ChangeSet cs1, ChangeSet cs2) -> ObjectUtils.compare(cs1.getTimestamp(), cs2.getTimestamp()));

      List<ChangeLog> derivedChangeLogs = new LinkedList<ChangeLog>();

      ChangeLog curChangeLog = null;

      for(ChangeSet cs : changeSets) {
         if(curChangeLog == null || !cs.getSource().equals(curChangeLog.getSource())) {
            curChangeLog = new ChangeLog();
            curChangeLog.setSource(cs.getSource());
            curChangeLog.setVersion(cs.getVersion());
            derivedChangeLogs.add(curChangeLog);
         }
         curChangeLog.addChangeSet(cs);
      }

      return new ChangeLogSet(derivedChangeLogs);
   }
 
Example 14
/**
 * Press the delete key on the active element. This step is known to have issues with
 * the Firefox Marionette driver.
 * @param times The number of times to press the delete key
 * @param ignoreErrors Add this text to ignore any exceptions. This is really only useful for debugging.
 */
@When("^I press(?: the)? Delete(?: key)? on the active element(?: \"(\\d+)\" times)?( ignoring errors)?$")
public void pressDeleteStep(final Integer times, final String ignoreErrors) {
	try {
		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
		final WebElement element = webDriver.switchTo().activeElement();

		for (int i = 0; i < ObjectUtils.defaultIfNull(times, 1); ++i) {
			element.sendKeys(Keys.DELETE);
			sleepUtils.sleep(State.getFeatureStateForThread().getDefaultKeyStrokeDelay());
		}

		sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
	} catch (final Exception ex) {
		if (StringUtils.isBlank(ignoreErrors)) {
			throw ex;
		}
	}
}
 
Example 15
Source Project: astor   Source File: StrTokenizerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void test5() {

        String input = "a;b; c;\"d;\"\"e\";f; ; ;";
        StrTokenizer tok = new StrTokenizer(input);
        tok.setDelimiterChar(';');
        tok.setQuoteChar('"');
        tok.setIgnoredMatcher(StrMatcher.trimMatcher());
        tok.setIgnoreEmptyTokens(false);
        tok.setEmptyTokenAsNull(true);
        String tokens[] = tok.getTokenArray();

        String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null,};

        assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
        for (int i = 0; i < expected.length; i++) {
            assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
                    ObjectUtils.equals(expected[i], tokens[i]));
        }

    }
 
Example 16
@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 17
Source Project: syncope   Source File: AnyTypeRestClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int compare(final AnyTypeTO o1, final AnyTypeTO o2) {
    if (o1.getKind() == AnyTypeKind.USER) {
        return -1;
    }
    if (o2.getKind() == AnyTypeKind.USER) {
        return 1;
    }
    if (o1.getKind() == AnyTypeKind.GROUP) {
        return -1;
    }
    if (o2.getKind() == AnyTypeKind.GROUP) {
        return 1;
    }
    return ObjectUtils.compare(o1.getKey(), o2.getKey());
}
 
Example 18
Source Project: prebid-server-java   Source File: RubiconBidder.java    License: Apache License 2.0 5 votes vote down vote up
private Banner makeBanner(Banner banner, List<Format> overriddenSizes) {
    final List<Format> sizes = ObjectUtils.defaultIfNull(overriddenSizes, banner.getFormat());
    if (CollectionUtils.isEmpty(sizes)) {
        throw new PreBidException("rubicon imps must have at least one imp.format element");
    }

    return banner.toBuilder()
            .format(sizes)
            .ext(mapper.mapper().valueToTree(makeBannerExt(sizes)))
            .build();
}
 
Example 19
Source Project: estatio   Source File: CreateRetroInvoices.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void execute(ExecutionContext executionContext) {
    createProperties(
            propertyRepository.allProperties(),
            ObjectUtils.firstNonNull(startDate, EPOCH_START_DATE),
            endDate,
            executionContext);
}
 
Example 20
Source Project: estatio   Source File: FixedAssetRegistration.java    License: 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 21
private Comparator<Patient> getPatientComparator(String sanitizedSearchString, boolean descending) {
	return (a, b) -> {
		if (a==null && b==null) { return 0; }
		if (a==null) { return -1; }
		if (b==null) { return  1; }

		int res = ObjectUtils.compare(sanitizeString(safeConcat(a.getLastName(), a.getFirstName())).startsWith(sanitizedSearchString)?0:1,
				sanitizeString(safeConcat(b.getLastName(), b.getFirstName())).startsWith(sanitizedSearchString)?0:1);
		if (res != 0) return res*(descending ? -1 : 1);
		res = ObjectUtils.compare(sanitizeString(a.getLastName()),sanitizeString(b.getLastName()));
		if (res != 0) return res*(descending ? -1 : 1);
		res = ObjectUtils.compare(sanitizeString(a.getFirstName()),sanitizeString(b.getFirstName()));
		return res*(descending ? -1 : 1);
	};
}
 
Example 22
Source Project: obevo   Source File: PostgreSqlPgDumpReveng.java    License: Apache License 2.0 5 votes vote down vote up
private String getCommandWithDefaults(boolean container, AquaRevengArgs args, File interimDir, String username, String password, String dbHost, String dbPort, String dbName, String dbSchema, String outputDirectory) {
    String prefix = container ? "docker exec $CONTAINER_NAME " : "";
    String fileSuffix = container ? "> " : " -f ";
    fileSuffix += new File(interimDir, "revengoutput.txt").getAbsolutePath();
    return prefix + "pg_dump -O -s --no-privileges" +
            " -h " + ObjectUtils.defaultIfNull(args.getDbHost(), dbHost) +
            " -p " + ObjectUtils.defaultIfNull(args.getDbPort(), dbPort) +
            " --username=" + ObjectUtils.defaultIfNull(args.getUsername(), username) +
            " -d " + ObjectUtils.defaultIfNull(args.getDbServer(), dbName) +
            " -n " + ObjectUtils.defaultIfNull(args.getDbSchema(), dbSchema) +
            " " + fileSuffix;
}
 
Example 23
Source Project: arcusandroid   Source File: CallListController.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean isEnabled(String address, List<Map<String, Object>> callTree) {
    if(callTree == null || callTree.isEmpty()) {
        return false;
    }

    // TODO should cache this into a map lookup
    for(Map<String, Object> entry: callTree) {
        String personAddress = (String) entry.get(CallTreeEntry.ATTR_PERSON);
        if(ObjectUtils.equals(personAddress, address)) {
            return bool(entry.get(CallTreeEntry.ATTR_ENABLED), false);
        }
    }
    return false;
}
 
Example 24
Source Project: incubator-pinot   Source File: RawAnomalyResultBean.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(RawAnomalyResultBean o) {
  // compare by dimension, -startTime, functionId, id
  int diff = ObjectUtils.compare(getDimensions(), o.getDimensions());
  if (diff != 0) {
    return diff;
  }
  diff = -ObjectUtils.compare(startTime, o.getStartTime()); // inverted to sort by
  // decreasing time
  if (diff != 0) {
    return diff;
  }
  return ObjectUtils.compare(getId(), o.getId());
}
 
Example 25
Source Project: cyberduck   Source File: AbstractMantaTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    final Profile profile = new ProfilePlistReader(new ProtocolFactory(Collections.singleton(new MantaProtocol()))).read(
        new Local("../profiles/Joyent Triton Object Storage (us-east).cyberduckprofile"));

    final String hostname;
    final Local file;
    if(ObjectUtils.allNotNull(System.getProperty("manta.key_path"), System.getProperty("manta.url"))) {
        file = new Local(System.getProperty("manta.key_path"));
        hostname = new URL(System.getProperty("manta.url")).getHost();
    }
    else {
        final String key = System.getProperty("manta.key");
        file = TemporaryFileServiceFactory.get().create(new AlphanumericRandomStringService().random());
        LocalTouchFactory.get().touch(file);
        IOUtils.write(key, file.getOutputStream(false), Charset.defaultCharset());
        hostname = profile.getDefaultHostname();
    }

    final String user = System.getProperty("manta.user");
    final Host host = new Host(profile, hostname, new Credentials(user).withIdentity(file));
    session = new MantaSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager());
    session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback());
    final String testRoot = "cyberduck-test-" + new AlphanumericRandomStringService().random();
    testPathPrefix = new Path(new MantaAccountHomeInfo(host.getCredentials().getUsername(), host.getDefaultPath()).getAccountPrivateRoot(), testRoot, EnumSet.of(Type.directory));
    session.getClient().putDirectory(testPathPrefix.getAbsolute());
}
 
Example 26
Source Project: DataFixerUpper   Source File: RecursivePoint.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <S, T> RewriteResult<S, T> cap(final TypeFamily family, final RewriteResult<S, T> result) {
    final Type<?> sourceType = family.apply(index);
    if (!(sourceType instanceof RecursivePointType<?>)) {
        throw new IllegalArgumentException("Type error: Recursive point template template got a non-recursice type as an input.");
    }
    if (!Objects.equals(result.view().type(), ((RecursivePointType<?>) sourceType).unfold())) {
        throw new IllegalArgumentException("Type error: hmap function input type");
    }
    final RecursivePointType<S> sType = (RecursivePointType<S>) sourceType;
    final RecursivePointType<T> tType = sType.family().buildMuType(result.view().newType(), null);
    final BitSet bitSet = ObjectUtils.clone(result.recData());
    bitSet.set(index);
    return RewriteResult.create(View.create(sType, tType, result.view().function()), bitSet);
}
 
Example 27
Source Project: mr4c   Source File: ResourceRequest.java    License: Apache License 2.0 5 votes vote down vote up
public boolean equals(Object obj) {
	if ( this==obj ) return true;
	if ( !obj.getClass().equals(this.getClass()) ) return false;
	ResourceRequest request = (ResourceRequest) obj;
	if ( !ObjectUtils.equals(m_resource, request.m_resource) ) return false;
	if ( !ObjectUtils.equals(m_min, request.m_min) ) return false;
	if ( !ObjectUtils.equals(m_max, request.m_max) ) return false;
	if ( !ObjectUtils.equals(m_actual, request.m_actual) ) return false;
	if ( !ObjectUtils.equals(m_limit, request.m_limit) ) return false;
	if ( !ObjectUtils.equals(m_limited, request.m_limited) ) return false;
	return true; 
}
 
Example 28
Source Project: prebid-server-java   Source File: AmpRequestFactory.java    License: 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 29
Source Project: spring-openapi   Source File: OperationsTransformer.java    License: MIT License 5 votes vote down vote up
private void mapPost(PostMapping postMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName, String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(postMapping.name(), method, HttpMethod.POST));
	operation.setSummary(StringUtils.isBlank(postMapping.name()) ? postMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	operation.setRequestBody(createRequestBody(method, getFirstFromArray(postMapping.consumes())));
	operation.setResponses(createApiResponses(method, getFirstFromArray(postMapping.produces())));
	operation.setParameters(transformParameters(method));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(postMapping.value()), getFirstFromArray(postMapping.path()));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setPost(operation));
}
 
Example 30
Source Project: xxpay-master   Source File: BaseNotify4MchPay.java    License: MIT License 5 votes vote down vote up
/**
 * 处理支付结果后台服务器通知
 */
public void doNotify(PayOrder payOrder, boolean isFirst) {
	_log.info(">>>>>> PAY开始回调通知业务系统 <<<<<<");
	// 发起后台通知业务系统
	JSONObject object = createNotifyInfo(payOrder, isFirst);
	try {
		mq4MchPayNotify.send(object.toJSONString());
	} catch (Exception e) {
		_log.error(e, "payOrderId=%s,sendMessage error.", ObjectUtils.defaultIfNull(payOrder.getPayOrderId(), ""));
	}
	_log.info(">>>>>> PAY回调通知业务系统完成 <<<<<<");
}