instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
protected DecisionRequirementsDefinitionQuery createNewQuery(ProcessEngine engine) {
return engine.getRepositoryService().createDecisionRequirementsDefinitionQuery();
}
@Override
protected void applyFilters(DecisionRequirementsDefinitionQuery query) {
if (decisionRequirementsDefinitionId != null) {
query.decisionRequirementsDefinitionId(decisionRequirementsDefinitionId);
}
if (decisionRequirementsDefinitionIdIn != null && !decisionRequirementsDefinitionIdIn.isEmpty()) {
query.decisionRequirementsDefinitionIdIn(decisionRequirementsDefinitionIdIn.toArray(new String[decisionRequirementsDefinitionIdIn.size()]));
}
if (category != null) {
query.decisionRequirementsDefinitionCategory(category);
}
if (categoryLike != null) {
query.decisionRequirementsDefinitionCategoryLike(categoryLike);
}
if (name != null) {
query.decisionRequirementsDefinitionName(name);
}
if (nameLike != null) {
query.decisionRequirementsDefinitionNameLike(nameLike);
}
if (deploymentId != null) {
query.deploymentId(deploymentId);
}
if (key != null) {
query.decisionRequirementsDefinitionKey(key);
}
if (keyLike != null) {
query.decisionRequirementsDefinitionKeyLike(keyLike);
}
if (resourceName != null) {
query.decisionRequirementsDefinitionResourceName(resourceName);
}
if (resourceNameLike != null) {
query.decisionRequirementsDefinitionResourceNameLike(resourceNameLike);
}
if (version != null) {
query.decisionRequirementsDefinitionVersion(version);
}
if (TRUE.equals(latestVersion)) {
query.latestVersion();
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeDefinitionsWithoutTenantId)) {
|
query.includeDecisionRequirementsDefinitionsWithoutTenantId();
}
}
@Override
protected void applySortBy(DecisionRequirementsDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) {
query.orderByDecisionRequirementsDefinitionCategory();
} else if (sortBy.equals(SORT_BY_KEY_VALUE)) {
query.orderByDecisionRequirementsDefinitionKey();
} else if (sortBy.equals(SORT_BY_ID_VALUE)) {
query.orderByDecisionRequirementsDefinitionId();
} else if (sortBy.equals(SORT_BY_VERSION_VALUE)) {
query.orderByDecisionRequirementsDefinitionVersion();
} else if (sortBy.equals(SORT_BY_NAME_VALUE)) {
query.orderByDecisionRequirementsDefinitionName();
} else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) {
query.orderByDeploymentId();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DecisionRequirementsDefinitionQueryDto.java
| 2
|
请完成以下Java代码
|
public class SmsAuthenticationProvider implements AuthenticationProvider {
private UserDetailService userDetailService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());
if (userDetails == null)
throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");
SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
authenticationResult.setDetails(authenticationToken.getDetails());
return authenticationResult;
|
}
@Override
public boolean supports(Class<?> aClass) {
return SmsAuthenticationToken.class.isAssignableFrom(aClass);
}
public UserDetailService getUserDetailService() {
return userDetailService;
}
public void setUserDetailService(UserDetailService userDetailService) {
this.userDetailService = userDetailService;
}
}
|
repos\SpringAll-master\38.Spring-Security-SmsCode\src\main\java\cc\mrbird\validate\smscode\SmsAuthenticationProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
|
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
@Override
public String toString() {
return "UserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ChatClient contentGenerator(ChatModel chatModel, VectorStore vectorStore) {
return ChatClient.builder(chatModel)
.defaultAdvisors(new QuestionAnswerAdvisor(vectorStore))
.build();
}
@Bean
public ChatClient contentEvaluator(
OllamaApi olamaApi,
@Value("${com.baeldung.evaluation.model}") String evaluationModel) {
ChatModel chatModel = OllamaChatModel.builder()
.ollamaApi(olamaApi)
.defaultOptions(OllamaOptions.builder()
.model(evaluationModel)
.build())
.modelManagementOptions(ModelManagementOptions.builder()
.pullModelStrategy(PullModelStrategy.WHEN_MISSING)
.build())
.build();
|
return ChatClient.builder(chatModel)
.build();
}
@Bean
public FactCheckingEvaluator factCheckingEvaluator(@Qualifier("contentEvaluator") ChatClient chatClient) {
return new FactCheckingEvaluator(chatClient.mutate());
}
@Bean
public RelevancyEvaluator relevancyEvaluator(@Qualifier("contentEvaluator") ChatClient chatClient) {
return new RelevancyEvaluator(chatClient.mutate());
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\java\com\baeldung\springai\evaluator\LLMConfiguration.java
| 2
|
请完成以下Java代码
|
private static BeanSupport createInstance() {
// Only intended for unit tests. Not intended to be part of public API.
boolean useFull = !Boolean.getBoolean("jakarta.el.BeanSupport.useStandalone");
if (useFull) {
// If not explicitly configured to use standalone, use the full implementation unless it is not available.
try {
Class.forName("java.beans.BeanInfo");
} catch (Exception e) {
// Ignore: Expected if using modules and java.desktop module is not present
useFull = false;
}
}
if (useFull) {
// The full implementation provided by the java.beans package
|
return new BeanSupportFull();
} else {
// The cut-down local implementation that does not depend on the java.beans package
return new BeanSupportStandalone();
}
}
static BeanSupport getInstance() {
if (beanSupport == null) {
return createInstance();
}
return beanSupport;
}
abstract BeanELResolver.BeanProperties getBeanProperties(Class<?> type);
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanSupport.java
| 1
|
请完成以下Java代码
|
public void setIssueSummary(String IssueSummary)
{
final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_IssueSummary);
super.setIssueSummary(truncateExceptionsRelatedString(IssueSummary, maxLength));
}
@Override
public void setStackTrace(String StackTrace)
{
final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_StackTrace);
super.setStackTrace(truncateExceptionsRelatedString(StackTrace, maxLength));
}
@Override
public void setErrorTrace(String ErrorTrace)
{
final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_ErrorTrace);
super.setErrorTrace(truncateExceptionsRelatedString(ErrorTrace, maxLength));
}
private static String truncateExceptionsRelatedString(final String string, final int maxLength)
|
{
if (string == null || string.isEmpty())
{
return string;
}
String stringNorm = string;
stringNorm = stringNorm.replace("java.lang.", "");
stringNorm = stringNorm.replace("java.sql.", "");
// Truncate the string if necessary
if (maxLength > 0 && stringNorm.length() > maxLength)
{
stringNorm = stringNorm.substring(0, maxLength - 1);
}
return stringNorm;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MIssue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private boolean acquireAdvisoryLock() {
try {
Boolean acquired = jdbcTemplate.queryForObject(
"SELECT pg_try_advisory_lock(?)",
Boolean.class,
ADVISORY_LOCK_ID
);
if (Boolean.TRUE.equals(acquired)) {
log.trace("Acquired advisory lock");
return true;
}
return false;
} catch (Exception e) {
log.error("Failed to acquire advisory lock", e);
return false;
}
}
private void releaseAdvisoryLock() {
try {
jdbcTemplate.queryForObject(
"SELECT pg_advisory_unlock(?)",
Boolean.class,
ADVISORY_LOCK_ID
);
log.debug("Released advisory lock");
} catch (Exception e) {
log.error("Failed to release advisory lock", e);
}
|
}
private VersionInfo parseVersion(String version) {
try {
String[] parts = version.split("\\.");
int major = Integer.parseInt(parts[0]);
int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0;
int maintenance = parts.length > 2 ? Integer.parseInt(parts[2]) : 0;
int patch = parts.length > 3 ? Integer.parseInt(parts[3]) : 0;
return new VersionInfo(major, minor, maintenance, patch);
} catch (Exception e) {
log.error("Failed to parse version: {}", version, e);
return null;
}
}
private Stream<Path> listDir(Path dir) {
try {
return Files.list(dir);
} catch (NoSuchFileException e) {
return Stream.empty();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public record VersionInfo(int major, int minor, int maintenance, int patch) {}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\system\SystemPatchApplier.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Git getGit() {
return this.git;
}
/**
* Build specific info properties.
*/
public static class Build {
/**
* Location of the generated build-info.properties file.
*/
private Resource location = new ClassPathResource("META-INF/build-info.properties");
/**
* File encoding.
*/
private Charset encoding = StandardCharsets.UTF_8;
public Resource getLocation() {
return this.location;
}
public void setLocation(Resource location) {
this.location = location;
}
public Charset getEncoding() {
return this.encoding;
}
public void setEncoding(Charset encoding) {
this.encoding = encoding;
}
}
/**
* Git specific info properties.
*/
public static class Git {
/**
* Location of the generated git.properties file.
|
*/
private Resource location = new ClassPathResource("git.properties");
/**
* File encoding.
*/
private Charset encoding = StandardCharsets.UTF_8;
public Resource getLocation() {
return this.location;
}
public void setLocation(Resource location) {
this.location = location;
}
public Charset getEncoding() {
return this.encoding;
}
public void setEncoding(Charset encoding) {
this.encoding = encoding;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\info\ProjectInfoProperties.java
| 2
|
请完成以下Java代码
|
public boolean isExpired() {
return this.cached.isExpired();
}
private boolean hasChangedSessionId() {
return !getId().equals(this.originalSessionId);
}
private Mono<Void> save() {
return Mono.defer(() -> saveChangeSessionId().then(saveDelta()).doOnSuccess((aVoid) -> this.isNew = false));
}
private Mono<Void> saveDelta() {
if (this.delta.isEmpty()) {
return Mono.empty();
}
String sessionKey = getSessionKey(getId());
Mono<Boolean> update = ReactiveRedisSessionRepository.this.sessionRedisOperations.opsForHash()
.putAll(sessionKey, new HashMap<>(this.delta));
Mono<Boolean> setTtl;
if (getMaxInactiveInterval().getSeconds() >= 0) {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.expire(sessionKey,
getMaxInactiveInterval());
}
else {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.persist(sessionKey);
}
Mono<Object> clearDelta = Mono.fromDirect((s) -> {
this.delta.clear();
s.onComplete();
});
return update.flatMap((unused) -> setTtl).flatMap((unused) -> clearDelta).then();
}
private Mono<Void> saveChangeSessionId() {
if (!hasChangedSessionId()) {
return Mono.empty();
}
String sessionId = getId();
|
Publisher<Void> replaceSessionId = (s) -> {
this.originalSessionId = sessionId;
s.onComplete();
};
if (this.isNew) {
return Mono.from(replaceSessionId);
}
else {
String originalSessionKey = getSessionKey(this.originalSessionId);
String sessionKey = getSessionKey(sessionId);
return ReactiveRedisSessionRepository.this.sessionRedisOperations.rename(originalSessionKey, sessionKey)
.flatMap((unused) -> Mono.fromDirect(replaceSessionId))
.onErrorResume((ex) -> {
String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
return StringUtils.startsWithIgnoreCase(message, "ERR no such key");
}, (ex) -> Mono.empty());
}
}
}
private static final class RedisSessionMapperAdapter
implements BiFunction<String, Map<String, Object>, Mono<MapSession>> {
private final RedisSessionMapper mapper = new RedisSessionMapper();
@Override
public Mono<MapSession> apply(String sessionId, Map<String, Object> map) {
return Mono.fromSupplier(() -> this.mapper.apply(sessionId, map));
}
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<AuditEvent> find(String principal, Instant after, String type) {
Iterable<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void add(AuditEvent event) {
if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
!Constants.ANONYMOUS_USER.equals(event.getPrincipal())) {
PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
persistentAuditEvent.setPrincipal(event.getPrincipal());
persistentAuditEvent.setAuditEventType(event.getType());
persistentAuditEvent.setAuditEventDate(event.getTimestamp());
Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData());
persistentAuditEvent.setData(truncate(eventData));
persistenceAuditEventRepository.save(persistentAuditEvent);
}
}
/**
* Truncate event data that might exceed column length.
*/
private Map<String, String> truncate(Map<String, String> data) {
|
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
String value = entry.getValue();
if (value != null) {
int length = value.length();
if (length > EVENT_DATA_COLUMN_MAX_LENGTH) {
value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH);
log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.",
entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH);
}
}
results.put(entry.getKey(), value);
}
}
return results;
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\repository\CustomAuditEventRepository.java
| 2
|
请完成以下Java代码
|
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return /
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0;
}
}
/**
* @param prefix 前缀
* @param ids id
*/
|
public void delByKeys(String prefix, Set<Long> ids) {
Set<Object> keys = new HashSet<>();
for (Long id : ids) {
keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString()));
}
long count = redisTemplate.delete(keys);
}
// ============================incr=============================
/**
* 递增
* @param key
* @return
*/
public Long increment(String key) {
return redisTemplate.opsForValue().increment(key);
}
/**
* 递减
* @param key
* @return
*/
public Long decrement(String key) {
return redisTemplate.opsForValue().decrement(key);
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\RedisUtils.java
| 1
|
请完成以下Java代码
|
public class ActivitiWrongDbException extends ActivitiException {
private static final long serialVersionUID = 1L;
String libraryVersion;
String dbVersion;
public ActivitiWrongDbException(String libraryVersion, String dbVersion) {
super(
"version mismatch: activiti library version is '" +
libraryVersion +
"', db version is " +
dbVersion +
" Hint: Set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in activiti.cfg.xml for automatic schema creation"
);
this.libraryVersion = libraryVersion;
this.dbVersion = dbVersion;
}
|
/**
* The version of the Activiti library used.
*/
public String getLibraryVersion() {
return libraryVersion;
}
/**
* The version of the Activiti library that was used to create the database schema.
*/
public String getDbVersion() {
return dbVersion;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ActivitiWrongDbException.java
| 1
|
请完成以下Java代码
|
public static String createJobConfiguration(ProcessEngineConfiguration processEngineConfiguration, boolean evaluateConditions) {
ObjectMapper objectMapper = processEngineConfiguration.getObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
objectNode.put(FIELD_EVALUATE_CONDITIONS, evaluateConditions);
return objectMapper.writeValueAsString(objectNode);
}
public static String createJobConfiguration(ProcessEngineConfiguration processEngineConfiguration, SequenceFlow sequenceFlow) {
ObjectMapper objectMapper = processEngineConfiguration.getObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
objectNode.put(FIELD_EVALUATE_CONDITIONS, false); // If the sequenceflow is passed, no need to evaluate conditions
// The execution entity does not persistently store when it's currently at a sequence flow (it only has an activityId).
// As such, the information of the current sequence flow needs to be persisted in the job configuration, contrary to the
// the other createJobConfiguration above where the execution entity's activityId will be enough and no extra information is needed.
String sequenceFlowId = sequenceFlow.getId();
if (StringUtils.isNotEmpty(sequenceFlowId)) {
objectNode.put(FIELD_SEQUENCE_FLOW_ID, sequenceFlowId);
|
} else {
// Sequence flow don't have a requied id.
// To be able to find it in the job, the source/target/xml location is stored.
objectNode.put(FIELD_SEQUENCE_FLOW_SOURCE, sequenceFlow.getSourceRef());
objectNode.put(FIELD_SEQUENCE_FLOW_TARGET, sequenceFlow.getTargetRef());
objectNode.put(FIELD_SEQUENCE_FLOW_LINE_NR, sequenceFlow.getXmlRowNumber());
objectNode.put(FIELD_SEQUENCE_FLOW_LINE_COLUMN_NR, sequenceFlow.getXmlColumnNumber());
}
return objectMapper.writeValueAsString(objectNode);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\jobexecutor\AsyncLeaveJobHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setCodeQualifier(String value) {
this.codeQualifier = value;
}
/**
* Gets the value of the internalId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInternalId() {
return internalId;
}
/**
* Sets the value of the internalId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInternalId(String value) {
this.internalId = value;
|
}
/**
* Gets the value of the internalSubId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInternalSubId() {
return internalSubId;
}
/**
* Sets the value of the internalSubId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInternalSubId(String value) {
this.internalSubId = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SenderType.java
| 2
|
请完成以下Java代码
|
protected Dynamic addRegistration(String description, ServletContext servletContext) {
Filter filter = getFilter();
return servletContext.addFilter(getOrDeduceName(filter), filter);
}
/**
* Configure registration settings. Subclasses can override this method to perform
* additional configuration if required.
* @param registration the registration
*/
@Override
protected void configure(FilterRegistration.Dynamic registration) {
super.configure(registration);
EnumSet<DispatcherType> dispatcherTypes = determineDispatcherTypes();
Set<String> servletNames = new LinkedHashSet<>();
for (ServletRegistrationBean<?> servletRegistrationBean : this.servletRegistrationBeans) {
servletNames.add(servletRegistrationBean.getServletName());
}
servletNames.addAll(this.servletNames);
if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
}
else {
if (!servletNames.isEmpty()) {
registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(servletNames));
}
if (!this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(this.urlPatterns));
}
}
}
/**
* Return the {@link Filter} to be registered.
* @return the filter
*/
public abstract @Nullable T getFilter();
/**
* Returns the filter name that will be registered.
* @return the filter name
* @since 3.2.0
|
*/
public String getFilterName() {
return getOrDeduceName(getFilter());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(getOrDeduceName(this));
if (this.servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(Arrays.toString(DEFAULT_URL_MAPPINGS));
}
else {
if (!this.servletNames.isEmpty()) {
builder.append(" servlets=").append(this.servletNames);
}
if (!this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(this.urlPatterns);
}
}
builder.append(" order=").append(getOrder());
return builder.toString();
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\AbstractFilterRegistrationBean.java
| 1
|
请完成以下Java代码
|
public void searchElementInArrayList(Params param, Blackhole blackhole) {
blackhole.consume(param.arrayList.contains(param.searchElement));
}
@Benchmark
public void searchElementInHashSet(Params param, Blackhole blackhole) {
blackhole.consume(param.hashSet.contains(param.searchElement));
}
@State(Scope.Benchmark)
public static class Params {
@Param({"5000000"})
public int searchElement;
@Param({"10000000"})
public int collectionSize;
|
public List<Integer> arrayList;
public Set<Integer> hashSet;
@Setup(Level.Iteration)
public void setup() {
arrayList = new ArrayList<>();
hashSet = new HashSet<>();
for (int i = 0; i < collectionSize; i++) {
arrayList.add(i);
hashSet.add(i);
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\listandset\benchmark\ListAndSetContainsBenchmark.java
| 1
|
请完成以下Java代码
|
public DefaultCmmnElementHandlerRegistry getHandlerRegistry() {
return handlerRegistry;
}
public void setHandlerRegistry(DefaultCmmnElementHandlerRegistry handlerRegistry) {
this.handlerRegistry = handlerRegistry;
}
@SuppressWarnings("unchecked")
protected <V extends CmmnElement> CmmnElementHandler<V, CmmnActivity> getDefinitionHandler(Class<V> cls) {
return (CmmnElementHandler<V, CmmnActivity>) getHandlerRegistry().getDefinitionElementHandlers().get(cls);
}
protected ItemHandler getPlanItemHandler(Class<? extends PlanItemDefinition> cls) {
return getHandlerRegistry().getPlanItemElementHandlers().get(cls);
}
protected ItemHandler getDiscretionaryItemHandler(Class<? extends PlanItemDefinition> cls) {
|
return getHandlerRegistry().getDiscretionaryElementHandlers().get(cls);
}
protected SentryHandler getSentryHandler() {
return getHandlerRegistry().getSentryHandler();
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransform.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long executeCount(CommandContext commandContext) {
return eventSubscriptionServiceConfiguration.getEventSubscriptionEntityManager().findEventSubscriptionCountByQueryCriteria(this);
}
@Override
public List<EventSubscription> executeList(CommandContext commandContext) {
return eventSubscriptionServiceConfiguration.getEventSubscriptionEntityManager().findEventSubscriptionsByQueryCriteria(this);
}
// getters //////////////////////////////////////////
@Override
public String getId() {
return id;
}
public String getEventType() {
return eventType;
}
public String getEventName() {
return eventName;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public boolean isWithoutProcessInstanceId() {
return withoutProcessInstanceId;
}
public String getActivityId() {
return activityId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isWithoutProcessDefinitionId() {
return withoutProcessDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
}
public String getScopeId() {
return scopeId;
}
public boolean isWithoutScopeId() {
return withoutScopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public boolean isWithoutScopeDefinitionId() {
return withoutScopeDefinitionId;
}
public String getScopeDefinitionKey() {
|
return scopeDefinitionKey;
}
public String getScopeType() {
return scopeType;
}
public Date getCreatedBefore() {
return createdBefore;
}
public Date getCreatedAfter() {
return createdAfter;
}
public String getTenantId() {
return tenantId;
}
public Collection<String> getTenantIds() {
return tenantIds;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getConfiguration() {
return configuration;
}
public Collection<String> getConfigurations() {
return configurations;
}
public boolean isWithoutConfiguration() {
return withoutConfiguration;
}
public List<EventSubscriptionQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public EventSubscriptionQueryImpl getCurrentOrQueryObject() {
return currentOrQueryObject;
}
public boolean isInOrStatement() {
return inOrStatement;
}
}
|
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionQueryImpl.java
| 2
|
请完成以下Java代码
|
public DistributionJobLine withNewStep(final DistributionJobStep stepToAdd)
{
final ArrayList<DistributionJobStep> changedSteps = new ArrayList<>(this.steps);
boolean added = false;
boolean changed = false;
for (final DistributionJobStep step : steps)
{
if (DistributionJobStepId.equals(step.getId(), stepToAdd.getId()))
{
changedSteps.add(stepToAdd);
added = true;
if (!Objects.equals(step, stepToAdd))
{
changed = true;
}
}
else
{
changedSteps.add(step);
}
}
if (!added)
{
changedSteps.add(stepToAdd);
changed = true;
}
return changed
? toBuilder().steps(ImmutableList.copyOf(changedSteps)).build()
: this;
}
public DistributionJobLine withChangedSteps(@NonNull final UnaryOperator<DistributionJobStep> stepMapper)
{
final ImmutableList<DistributionJobStep> changedSteps = CollectionUtils.map(steps, stepMapper);
return changedSteps.equals(steps)
? this
: toBuilder().steps(changedSteps).build();
}
|
public DistributionJobLine removeStep(@NonNull final DistributionJobStepId stepId)
{
final ImmutableList<DistributionJobStep> updatedStepCollection = steps.stream()
.filter(step -> !step.getId().equals(stepId))
.collect(ImmutableList.toImmutableList());
return updatedStepCollection.equals(steps)
? this
: toBuilder().steps(updatedStepCollection).build();
}
@NonNull
public Optional<DistributionJobStep> getStepById(@NonNull final DistributionJobStepId stepId)
{
return getSteps().stream().filter(step -> step.getId().equals(stepId)).findFirst();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJobLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SwaggerConfig
{
@Bean
public Docket api()
{
return new Docket(DocumentationType.OAS_30)
.select()
.paths(PathSelectors.any())
.build()
.apiInfo(SwaggerUtil.createApiInfo(
"metasfresh webui REST API" /* title */,
"REST API backend for metasfresh UIs"/* description */));
}
@SuppressWarnings("unused")
private static Predicate<RequestHandler> basePackages(final Class<?>... classes)
|
{
final Set<Predicate<RequestHandler>> predicates = new HashSet<>(classes.length);
for (final Class<?> clazz : classes)
{
final String packageName = clazz.getPackage().getName();
predicates.add((Predicate<RequestHandler>)RequestHandlerSelectors.basePackage(packageName));
}
if(predicates.size() == 1)
{
return predicates.iterator().next();
}
return Predicates.or(predicates);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\SwaggerConfig.java
| 2
|
请完成以下Java代码
|
public V get(K k) throws CacheException {
return (V) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
}
@Override
public V put(K k, V v) throws CacheException {
getRedisTemplate().opsForHash().put(this.cacheName,k.toString(), v);
return null;
}
@Override
public V remove(K k) throws CacheException {
return (V) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
}
@Override
public void clear() throws CacheException {
getRedisTemplate().opsForHash().delete(this.cacheName);
}
|
@Override
public int size() {
return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
}
@Override
public Set<K> keys() {
return getRedisTemplate().opsForHash().keys(this.cacheName);
}
@Override
public Collection<V> values() {
return getRedisTemplate().opsForHash().values(this.cacheName);
}
}
|
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\cache\RedisCache.java
| 1
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBlurb() {
|
return blurb;
}
public void setBlurb(String blurb) {
this.blurb = blurb;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author='" + author + '\'' +
", blurb='" + blurb + '\'' +
", pages=" + pages +
'}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-rest-2\src\main\java\com\baeldung\halbrowser\model\Book.java
| 1
|
请完成以下Java代码
|
private static String extractPrintableTopText(final HUQRCode qrCode)
{
final StringBuilder result = new StringBuilder();
final HUQRCodeProductInfo product = qrCode.getProduct().orElse(null);
if (product != null)
{
result.append(product.getCode());
result.append(" - ");
result.append(product.getName());
}
for (final HUQRCodeAttribute attribute : qrCode.getAttributes())
{
final String displayValue = StringUtils.trimBlankToNull(attribute.getValueRendered());
if (displayValue != null)
{
if (result.length() > 0)
{
result.append(", ");
}
result.append(displayValue);
}
}
return result.toString();
}
@Override
public Optional<BigDecimal> getWeightInKg()
{
return getAttribute(Weightables.ATTR_WeightNet)
.map(HUQRCodeAttribute::getValueAsBigDecimal)
.filter(weight -> weight.signum() > 0);
}
@Override
public Optional<LocalDate> getBestBeforeDate()
{
return getAttribute(AttributeConstants.ATTR_BestBeforeDate).map(HUQRCodeAttribute::getValueAsLocalDate);
}
@Override
public Optional<LocalDate> getProductionDate()
|
{
return getAttribute(AttributeConstants.ProductionDate).map(HUQRCodeAttribute::getValueAsLocalDate);
}
@Override
public Optional<String> getLotNumber()
{
return getAttribute(AttributeConstants.ATTR_LotNumber).map(HUQRCodeAttribute::getValue);
}
private Optional<HUQRCodeAttribute> getAttribute(@NonNull final AttributeCode attributeCode)
{
return attributes.stream().filter(attribute -> AttributeCode.equals(attribute.getCode(), attributeCode)).findFirst();
}
private static String extractPrintableBottomText(final HUQRCode qrCode)
{
return qrCode.getPackingInfo().getHuUnitType().getShortDisplayName() + " ..." + qrCode.toDisplayableQRCode();
}
public Optional<HUQRCodeProductInfo> getProduct() {return Optional.ofNullable(product);}
@JsonIgnore
public Optional<ProductId> getProductId() {return getProduct().map(HUQRCodeProductInfo::getId);}
@JsonIgnore
public ProductId getProductIdNotNull() {return getProductId().orElseThrow(() -> new AdempiereException("QR Code does not contain product information: " + this));}
public HuPackingInstructionsId getPackingInstructionsId() {return getPackingInfo().getPackingInstructionsId();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCode.java
| 1
|
请完成以下Java代码
|
public boolean doesOverlap(Region testRegion) {
// Is test region completely to left of my region?
if (testRegion.getX2() < this.getX1()) {
return false;
}
// Is test region completely to right of my region?
if (testRegion.getX1() > this.getX2()) {
return false;
}
// Is test region completely above my region?
if (testRegion.getY1() > this.getY2()) {
return false;
}
// Is test region completely below my region?
if (testRegion.getY2() < this.getY1()) {
return false;
}
return true;
}
@Override
public String toString() {
return "[Region (x1=" + x1 + ", y1=" + y1 + "), (x2=" + x2 + ", y2=" + y2 + ")]";
}
|
public float getX1() {
return x1;
}
public float getY1() {
return y1;
}
public float getX2() {
return x2;
}
public float getY2() {
return y2;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\quadtree\Region.java
| 1
|
请完成以下Java代码
|
public static final void stop(final Thread thread, final long timeoutMillis) throws TimeoutException
{
Check.assumeNotNull(thread, "thread not null");
Check.assume(timeoutMillis >= 0, "timeoutMillis >= 0");
long timeoutRemaining = timeoutMillis <= 0 ? Long.MAX_VALUE : timeoutMillis;
final long periodMillis = Math.min(100, timeoutRemaining);
//
// As long as the thread is not dead and we did not exceed our timeout, hit the tread unil it dies.
while (thread.isAlive() && timeoutRemaining > 0)
{
thread.interrupt();
// Wait for the thread to die
try
{
thread.join(periodMillis);
}
catch (InterruptedException e)
{
// Thread was interrupted.
// We don't fucking care, we continue to hit it until it's dead or until the timeout is exceeded.
}
timeoutRemaining -= periodMillis;
}
//
// If the thread is still alive we throw an timeout exception
if (thread.isAlive())
{
throw new TimeoutException("Failed to kill thread " + thread.getName() + " in " + timeoutMillis + "ms");
}
}
/**
* Convenient method to set a thread name and also get the previous name.
*
* @param thread
|
* @param name
* @return previous thread name
*/
public static String setThreadName(final Thread thread, final String name)
{
final String nameOld = thread.getName();
thread.setName(name);
return nameOld;
}
/**
* Convenient method to set a current thread's name and also get the previous name.
*
* @param thread
* @param name
* @return previous thread name
*/
public static String setThreadName(final String name)
{
return setThreadName(Thread.currentThread(), name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\Threads.java
| 1
|
请完成以下Java代码
|
private static final class MinuteModel extends SpinnerNumberModel
{
private static final long serialVersionUID = -7328155195096551848L;
/**
* Constructor. Creates Integer Spinner with minimum=0, maximum=59, stepsize=1
*
* @param snapSize snap size
*/
public MinuteModel(final int snapSize)
{
super(0, 0, 59, 1); // Integer Model
m_snapSize = snapSize;
} // MinuteModel
/** Snap size */
private final int m_snapSize;
/**
* Return next full snap value
*
* @return next snap value
*/
@Override
public Object getNextValue()
{
int minutes = ((Integer)getValue()).intValue();
minutes += m_snapSize;
if (minutes >= 60)
|
minutes -= 60;
//
int steps = minutes / m_snapSize;
return steps * m_snapSize;
} // getNextValue
/**
* Return previous full step value
*
* @return previous snap value
*/
@Override
public Object getPreviousValue()
{
int minutes = ((Integer)getValue()).intValue();
minutes -= m_snapSize;
if (minutes < 0)
minutes += 60;
//
int steps = minutes / m_snapSize;
if (minutes % m_snapSize != 0)
steps++;
if (steps * m_snapSize > 59)
steps = 0;
return steps * m_snapSize;
} // getNextValue
} // MinuteModel
} // Calendar
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Calendar.java
| 1
|
请完成以下Java代码
|
public static WarehouseId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<WarehouseId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final WarehouseId warehouseId)
{
return warehouseId != null ? warehouseId.getRepoId() : -1;
}
public static Set<Integer> toRepoIds(final Collection<WarehouseId> warehouseIds)
{
return warehouseIds.stream()
.map(WarehouseId::toRepoId)
.filter(id -> id > 0)
.collect(ImmutableSet.toImmutableSet());
}
|
int repoId;
private WarehouseId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_Warehouse_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final WarehouseId id1, @Nullable final WarehouseId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\WarehouseId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
final class OAuth2ClientBeanDefinitionParserUtils {
private static final String ATT_CLIENT_REGISTRATION_REPOSITORY_REF = "client-registration-repository-ref";
private static final String ATT_AUTHORIZED_CLIENT_REPOSITORY_REF = "authorized-client-repository-ref";
private static final String ATT_AUTHORIZED_CLIENT_SERVICE_REF = "authorized-client-service-ref";
private OAuth2ClientBeanDefinitionParserUtils() {
}
static BeanMetadataElement getClientRegistrationRepository(Element element) {
String clientRegistrationRepositoryRef = element.getAttribute(ATT_CLIENT_REGISTRATION_REPOSITORY_REF);
if (StringUtils.hasLength(clientRegistrationRepositoryRef)) {
return new RuntimeBeanReference(clientRegistrationRepositoryRef);
}
return new RuntimeBeanReference(ClientRegistrationRepository.class);
}
static BeanMetadataElement getAuthorizedClientRepository(Element element) {
String authorizedClientRepositoryRef = element.getAttribute(ATT_AUTHORIZED_CLIENT_REPOSITORY_REF);
if (StringUtils.hasLength(authorizedClientRepositoryRef)) {
return new RuntimeBeanReference(authorizedClientRepositoryRef);
}
return null;
}
static BeanMetadataElement getAuthorizedClientService(Element element) {
|
String authorizedClientServiceRef = element.getAttribute(ATT_AUTHORIZED_CLIENT_SERVICE_REF);
if (StringUtils.hasLength(authorizedClientServiceRef)) {
return new RuntimeBeanReference(authorizedClientServiceRef);
}
return null;
}
static BeanDefinition createDefaultAuthorizedClientRepository(BeanMetadataElement clientRegistrationRepository,
BeanMetadataElement authorizedClientService) {
if (authorizedClientService == null) {
authorizedClientService = BeanDefinitionBuilder
.rootBeanDefinition("org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService")
.addConstructorArgValue(clientRegistrationRepository)
.getBeanDefinition();
}
return BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository")
.addConstructorArgValue(authorizedClientService)
.getBeanDefinition();
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ClientBeanDefinitionParserUtils.java
| 2
|
请完成以下Java代码
|
public HistoricVariableInstanceQuery orderByProcessInstanceId() {
orderBy(HistoricVariableInstanceQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
public HistoricVariableInstanceQuery orderByVariableName() {
orderBy(HistoricVariableInstanceQueryProperty.VARIABLE_NAME);
return this;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
|
public String getActivityInstanceId() {
return activityInstanceId;
}
public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getVariableName() {
return variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public QueryVariableValue getQueryVariableValue() {
return queryVariableValue;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricVariableInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@JsonInclude(Include.NON_NULL)
public Long getItemCount() {
return itemCount;
}
public void setItemCount(Long itemCount) {
this.itemCount = itemCount;
}
public static FilterDto fromFilter(Filter filter) {
FilterDto dto = new FilterDto();
dto.id = filter.getId();
dto.resourceType = filter.getResourceType();
dto.name = filter.getName();
dto.owner = filter.getOwner();
|
if (EntityTypes.TASK.equals(filter.getResourceType())) {
dto.query = TaskQueryDto.fromQuery(filter.getQuery());
}
dto.properties = filter.getProperties();
return dto;
}
public void updateFilter(Filter filter, ProcessEngine engine) {
if (getResourceType() != null && !getResourceType().equals(filter.getResourceType())) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to update filter from resource type '" + filter.getResourceType() + "' to '" + getResourceType() + "'");
}
filter.setName(getName());
filter.setOwner(getOwner());
filter.setQuery(query.toQuery(engine));
filter.setProperties(getProperties());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterDto.java
| 1
|
请完成以下Java代码
|
public class GatewayParamFlowItemEntity {
private Integer parseStrategy;
private String fieldName;
private String pattern;
private Integer matchStrategy;
public Integer getParseStrategy() {
return parseStrategy;
}
public void setParseStrategy(Integer parseStrategy) {
this.parseStrategy = parseStrategy;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public Integer getMatchStrategy() {
|
return matchStrategy;
}
public void setMatchStrategy(Integer matchStrategy) {
this.matchStrategy = matchStrategy;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
GatewayParamFlowItemEntity that = (GatewayParamFlowItemEntity) o;
return Objects.equals(parseStrategy, that.parseStrategy) &&
Objects.equals(fieldName, that.fieldName) &&
Objects.equals(pattern, that.pattern) &&
Objects.equals(matchStrategy, that.matchStrategy);
}
@Override
public int hashCode() {
return Objects.hash(parseStrategy, fieldName, pattern, matchStrategy);
}
@Override
public String toString() {
return "GatewayParamFlowItemEntity{" +
"parseStrategy=" + parseStrategy +
", fieldName='" + fieldName + '\'' +
", pattern='" + pattern + '\'' +
", matchStrategy=" + matchStrategy +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\GatewayParamFlowItemEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<VATIdentifier> getVATTaxId(@NonNull final BPartnerLocationId bpartnerLocationId)
{
final I_C_BPartner_Location bpartnerLocation = bpartnersRepo.getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
if (bpartnerLocation != null && Check.isNotBlank(bpartnerLocation.getVATaxID()))
{
return Optional.of(VATIdentifier.of(bpartnerLocation.getVATaxID()));
}
// if is set on Y, we will not use the vatid from partner
final boolean ignorePartnerVATID = sysConfigBL.getBooleanValue(SYS_CONFIG_IgnorePartnerVATID, false);
if (ignorePartnerVATID)
{
return Optional.empty();
}
else
{
final I_C_BPartner bPartner = getById(bpartnerLocationId.getBpartnerId());
if (bPartner != null && Check.isNotBlank(bPartner.getVATaxID()))
{
return Optional.of(VATIdentifier.of(bPartner.getVATaxID()));
}
}
return Optional.empty();
}
|
@Override
public boolean isInvoiceEmailCcToMember(@NonNull final BPartnerId bpartnerId)
{
final I_C_BPartner bpartner = getById(bpartnerId);
return bpartner.isInvoiceEmailCcToMember();
}
@Override
public I_C_BPartner_Location getBPartnerLocationByIdEvenInactive(@NonNull final BPartnerLocationId bpartnerLocationId)
{
return bpartnersRepo.getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
}
@Override
public List<I_C_BPartner_Location> getBPartnerLocationsByIds(final Set<BPartnerLocationId> bpartnerLocationIds)
{
return bpartnersRepo.retrieveBPartnerLocationsByIds(bpartnerLocationIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerBL.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getExternalId() {
return externalId;
}
public void setExternalId(String externalId) {
this.externalId = externalId;
}
public String getName() {
|
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyUser.java
| 1
|
请完成以下Java代码
|
public static String getSqlInjectSortField(String sortField) {
String field = SqlInjectionUtil.getSqlInjectField(oConvertUtils.camelToUnderline(sortField));
return field;
}
/**
* 获取多个排序字段
* 返回:数组
*
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortFields 多个排序字段
* @return
*/
public static List getSqlInjectSortFields(String... sortFields) {
List list = new ArrayList<String>();
for (String sortField : sortFields) {
list.add(getSqlInjectSortField(sortField));
}
return list;
}
/**
* 获取 orderBy type
* 返回:字符串
* <p>
* 1.检测是否为 asc 或 desc 其中的一个
* 2.限制sql注入
*
|
* @param orderType
* @return
*/
public static String getSqlInjectOrderType(String orderType) {
if (orderType == null) {
return null;
}
orderType = orderType.trim();
if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) {
return CommonConstant.ORDER_TYPE_ASC;
} else {
return CommonConstant.ORDER_TYPE_DESC;
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SqlInjectionUtil.java
| 1
|
请完成以下Java代码
|
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder of {@link WebAuthnAuthentication} instances
*
* @since 7.0
*/
public static final class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> {
private PublicKeyCredentialUserEntity principal;
private Builder(WebAuthnAuthentication token) {
super(token);
this.principal = token.principal;
}
/**
* Use this principal. It must be of type {@link PublicKeyCredentialUserEntity}
|
* @param principal the principal to use
* @return the {@link Builder} for further configurations
*/
@Override
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(PublicKeyCredentialUserEntity.class, principal,
"principal must be of type PublicKeyCredentialUserEntity");
this.principal = (PublicKeyCredentialUserEntity) principal;
return (B) this;
}
@Override
public WebAuthnAuthentication build() {
return new WebAuthnAuthentication(this);
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthentication.java
| 1
|
请完成以下Java代码
|
public class RestartScopeInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.getBeanFactory().registerScope("restart", new RestartScope());
}
/**
* {@link Scope} that stores beans as {@link Restarter} attributes.
*/
private static final class RestartScope implements Scope {
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
return Restarter.getInstance().getOrAddAttribute(name, objectFactory);
}
@Override
public Object remove(String name) {
return Restarter.getInstance().removeAttribute(name);
}
|
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public @Nullable Object resolveContextualObject(String key) {
return null;
}
@Override
public @Nullable String getConversationId() {
return null;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\RestartScopeInitializer.java
| 1
|
请完成以下Java代码
|
public void logout(HttpServletRequest request, HttpServletResponse response,
@Nullable Authentication authentication) {
Assert.notNull(request, "HttpServletRequest required");
if (this.invalidateHttpSession) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Invalidated session %s", session.getId()));
}
}
}
SecurityContext context = this.securityContextHolderStrategy.getContext();
this.securityContextHolderStrategy.clearContext();
if (this.clearAuthentication) {
context.setAuthentication(null);
}
SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext();
this.securityContextRepository.saveContext(emptyContext, request, response);
}
public boolean isInvalidateHttpSession() {
return this.invalidateHttpSession;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Causes the {@link HttpSession} to be invalidated when this {@link LogoutHandler} is
* invoked. Defaults to true.
* @param invalidateHttpSession true if you wish the session to be invalidated
* (default) or false if it should not be.
*/
public void setInvalidateHttpSession(boolean invalidateHttpSession) {
this.invalidateHttpSession = invalidateHttpSession;
|
}
/**
* If true, removes the {@link Authentication} from the {@link SecurityContext} to
* prevent issues with concurrent requests.
* @param clearAuthentication true if you wish to clear the {@link Authentication}
* from the {@link SecurityContext} (default) or false if the {@link Authentication}
* should not be removed.
*/
public void setClearAuthentication(boolean clearAuthentication) {
this.clearAuthentication = clearAuthentication;
}
/**
* Sets the {@link SecurityContextRepository} to use. Default is
* {@link HttpSessionSecurityContextRepository}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\logout\SecurityContextLogoutHandler.java
| 1
|
请完成以下Java代码
|
private void initDb() {
System.out.println(String.format("****** Creating table: %s, and Inserting test data ******", "Employees"));
String sqlStatements[] = {
"drop table employees if exists",
"create table employees(id serial,first_name varchar(255),last_name varchar(255))",
"insert into employees(first_name, last_name) values('Eugen','Paraschiv')",
"insert into employees(first_name, last_name) values('Scott','Tiger')"
};
Arrays.asList(sqlStatements).stream().forEach(sql -> {
System.out.println(sql);
jdbcTemplate.execute(sql);
});
System.out.println(String.format("****** Fetching from table: %s ******", "Employees"));
jdbcTemplate.query("select id,first_name,last_name from employees",
new RowMapper<Object>() {
@Override
|
public Object mapRow(ResultSet rs, int i) throws SQLException {
System.out.println(String.format("id:%s,first_name:%s,last_name:%s",
rs.getString("id"),
rs.getString("first_name"),
rs.getString("last_name")));
return null;
}
});
}
@Bean(initMethod = "start", destroyMethod = "stop")
public Server inMemoryH2DatabaseServer() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9091");
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\java\com\baeldung\h2db\demo\server\SpringBootApp.java
| 1
|
请完成以下Java代码
|
protected @Nullable Object convertPayload(Message<?> message) {
throw new UnsupportedOperationException("Select a subclass that creates a ProducerRecord value "
+ "corresponding to the configured Kafka Serializer");
}
@Override
protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) {
Object value = record.value();
if (record.value() == null) {
return KafkaNull.INSTANCE;
}
JavaType javaType = determineJavaType(record, type);
if (value instanceof Bytes) {
value = ((Bytes) value).get();
}
if (value instanceof String) {
try {
return this.objectMapper.readValue((String) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else if (value instanceof byte[]) {
try {
return this.objectMapper.readValue((byte[]) value, javaType);
}
|
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else {
throw new IllegalStateException("Only String, Bytes, or byte[] supported");
}
}
private JavaType determineJavaType(ConsumerRecord<?, ?> record, @Nullable Type type) {
JavaType javaType = this.typeMapper.getTypePrecedence()
.equals(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper.TypePrecedence.INFERRED) && type != null
? TypeFactory.defaultInstance().constructType(type)
: this.typeMapper.toJavaType(record.headers());
if (javaType == null) { // no headers
if (type != null) {
javaType = TypeFactory.defaultInstance().constructType(type);
}
else {
javaType = OBJECT;
}
}
return javaType;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\JsonMessageConverter.java
| 1
|
请完成以下Java代码
|
public <T> Comparator<T> asComparator(@NonNull final FieldValueExtractor<T> fieldValueExtractor, @NonNull final JSONOptions jsonOpts)
{
final Function<T, Object> keyExtractor = obj -> fieldValueExtractor.getFieldValue(obj, fieldName, jsonOpts);
final Comparator<? super Object> keyComparator = ValueComparator.ofAscendingAndNullsLast(ascending, nullsLast);
return Comparator.comparing(keyExtractor, keyComparator);
}
@Deprecated
@Override
public String toString()
{
return toStringSyntax();
}
public String toStringSyntax()
{
return ascending ? fieldName : "-" + fieldName;
}
@FunctionalInterface
public interface FieldValueExtractor<T>
{
Object getFieldValue(T object, String fieldName, JSONOptions jsonOpts);
}
@ToString
private static final class ValueComparator implements Comparator<Object>
{
public static ValueComparator ofAscendingAndNullsLast(final boolean ascending, final boolean nullsLast)
{
if (ascending)
{
return nullsLast ? ASCENDING_NULLS_LAST : ASCENDING_NULLS_FIRST;
}
else
{
return nullsLast ? DESCENDING_NULLS_LAST : DESCENDING_NULLS_FIRST;
}
}
public static final ValueComparator ASCENDING_NULLS_FIRST = new ValueComparator(true, false);
public static final ValueComparator ASCENDING_NULLS_LAST = new ValueComparator(true, true);
public static final ValueComparator DESCENDING_NULLS_FIRST = new ValueComparator(false, false);
|
public static final ValueComparator DESCENDING_NULLS_LAST = new ValueComparator(false, true);
private final boolean ascending;
private final boolean nullsLast;
private ValueComparator(final boolean ascending, final boolean nullsLast)
{
this.ascending = ascending;
this.nullsLast = nullsLast;
}
@Override
public int compare(final Object o1, final Object o2)
{
if (o1 == o2)
{
return 0;
}
else if (o1 == null || o1 instanceof JSONNullValue)
{
return nullsLast ? +1 : -1;
}
else if (o2 == null || o2 instanceof JSONNullValue)
{
return nullsLast ? -1 : +1;
}
else if (o1 instanceof Comparable)
{
@SuppressWarnings("unchecked") final Comparable<Object> o1cmp = (Comparable<Object>)o1;
return o1cmp.compareTo(o2) * (ascending ? +1 : -1);
}
else
{
return o1.toString().compareTo(o2.toString()) * (ascending ? +1 : -1);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQueryOrderBy.java
| 1
|
请完成以下Java代码
|
public String getValidationId() {
return validationId;
}
/**
* Sets the value of the validationId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValidationId(String value) {
this.validationId = value;
}
/**
* Gets the value of the validationServer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValidationServer() {
return validationServer;
|
}
/**
* Sets the value of the validationServer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValidationServer(String value) {
this.validationServer = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PatientAddressType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void parseHostAndPort(String input, boolean sslEnabled) {
int bracketIndex = input.lastIndexOf(']');
int colonIndex = input.lastIndexOf(':');
if (colonIndex == -1 || colonIndex < bracketIndex) {
this.host = input;
this.port = (determineSslEnabled(sslEnabled)) ? DEFAULT_PORT_SECURE : DEFAULT_PORT;
}
else {
this.host = input.substring(0, colonIndex);
this.port = Integer.parseInt(input.substring(colonIndex + 1));
}
}
private boolean determineSslEnabled(boolean sslEnabled) {
return (this.secureConnection != null) ? this.secureConnection : sslEnabled;
}
}
public static final class Stream {
/**
* Host of a RabbitMQ instance with the Stream plugin enabled.
*/
private String host = "localhost";
/**
* Stream port of a RabbitMQ instance with the Stream plugin enabled.
*/
private int port = DEFAULT_STREAM_PORT;
/**
* Virtual host of a RabbitMQ instance with the Stream plugin enabled. When not
* set, spring.rabbitmq.virtual-host is used.
*/
private @Nullable String virtualHost;
/**
* Login user to authenticate to the broker. When not set,
* spring.rabbitmq.username is used.
*/
private @Nullable String username;
/**
* Login password to authenticate to the broker. When not set
* spring.rabbitmq.password is used.
*/
private @Nullable String password;
/**
* Name of the stream.
*/
private @Nullable String name;
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
|
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public @Nullable String getVirtualHost() {
return this.virtualHost;
}
public void setVirtualHost(@Nullable String virtualHost) {
this.virtualHost = virtualHost;
}
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getName() {
return this.name;
}
public void setName(@Nullable String name) {
this.name = name;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class LocatorQRCode
{
@NonNull LocatorId locatorId;
@NonNull String caption;
public static boolean equals(@Nullable final LocatorQRCode o1, @Nullable final LocatorQRCode o2)
{
return Objects.equals(o1, o2);
}
@Deprecated
public String toString() {return toGlobalQRCodeJsonString();}
@JsonValue
public String toGlobalQRCodeJsonString() {return LocatorQRCodeJsonConverter.toGlobalQRCodeJsonString(this);}
@JsonCreator
public static LocatorQRCode ofGlobalQRCodeJsonString(final String json) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(json);}
public static LocatorQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);}
@JsonCreator
public static LocatorQRCode ofScannedCode(final ScannedCode scannedCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(scannedCode.getAsString());}
public static LocatorQRCode ofLocator(@NonNull final I_M_Locator locator)
{
return builder()
.locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID()))
.caption(locator.getValue())
.build();
|
}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
.qrCode(toGlobalQRCodeJsonString())
.bottomText(caption)
.build();
}
public GlobalQRCode toGlobalQRCode()
{
return LocatorQRCodeJsonConverter.toGlobalQRCode(this);
}
public ScannedCode toScannedCode()
{
return ScannedCode.ofString(toGlobalQRCodeJsonString());
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return LocatorQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCode.java
| 2
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_HR_ListType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Payroll List Type.
@param HR_ListType_ID Payroll List Type */
public void setHR_ListType_ID (int HR_ListType_ID)
{
if (HR_ListType_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID));
}
/** Get Payroll List Type.
@return Payroll List Type */
public int getHR_ListType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java
| 1
|
请完成以下Java代码
|
public IHUAttributeTransferRequestBuilder setProductId(final ProductId productId)
{
this.productId = productId;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQty(final BigDecimal qty)
{
this.qty = qty;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setUOM(final I_C_UOM uom)
{
this.uom = uom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQuantity(final Quantity quantity)
{
qty = quantity.toBigDecimal();
uom = quantity.getUOM();
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageFrom(final IAttributeSet attributeStorageFrom)
{
this.attributeStorageFrom = attributeStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageTo(final IAttributeStorage attributeStorageTo)
{
this.attributeStorageTo = attributeStorageTo;
return this;
|
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageFrom(final IHUStorage huStorageFrom)
{
this.huStorageFrom = huStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageTo(final IHUStorage huStorageTo)
{
this.huStorageTo = huStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQtyUnloaded(final BigDecimal qtyUnloaded)
{
this.qtyUnloaded = qtyUnloaded;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setVHUTransfer(final boolean vhuTransfer)
{
this.vhuTransfer = vhuTransfer;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequestBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GroupDescriptionType {
@XmlValue
protected String content;
@XmlAttribute(name = "Party", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
protected String party;
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* Gets the value of the party property.
*
|
* @return
* possible object is
* {@link String }
*
*/
public String getParty() {
return party;
}
/**
* Sets the value of the party property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParty(String value) {
this.party = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\GroupDescriptionType.java
| 2
|
请完成以下Java代码
|
public class OrderService {
private static final OrdersDAO ORDERS_DAO = new OrdersDAO("jdbc:sqlite:food_delivery.db");
public static String createOrder(OrderRequest orderRequest) {
UUID uuid = UUID.randomUUID();
String uuidAsString = uuid.toString();
Order order = new Order();
order.setOrderId(uuidAsString);
Customer customer = new Customer();
customer.setEmail(orderRequest.getCustomerEmail());
customer.setName(orderRequest.getCustomerName());
customer.setContact(orderRequest.getCustomerContact());
customer.setId(ORDERS_DAO.insertCustomer(customer));
log.info("Upsert customer record in DB with id: {}", customer.getId());
order.setCustomer(customer);
order.setRestaurantId(orderRequest.getRestaurantId());
order.setDeliveryAddress(orderRequest.getDeliveryAddress());
order.setStatus(Order.Status.PENDING);
OrderDetails orderDetails = new OrderDetails();
orderDetails.setOrderId(uuidAsString);
orderDetails.setItems(orderRequest.getItems());
orderDetails.setNotes(orderRequest.getNotes());
order.setOrderDetails(orderDetails);
String error = ORDERS_DAO.insertOrder(order);
if (error.isEmpty()) {
log.info("Created order with id: {}", order.getOrderId());
}
else {
log.error("Order creation failure: {}", error);
|
return null;
}
return uuidAsString;
}
public static Order getOrder(String orderId) {
Order order = new Order();
ORDERS_DAO.readOrder(orderId, order);
return order;
}
public static void cancelOrder(Order order) {
order.setStatus(Order.Status.CANCELLED);
log.info("Cancelling order {}", order.getOrderId());
ORDERS_DAO.updateOrder(order);
}
}
|
repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\service\OrderService.java
| 1
|
请完成以下Java代码
|
public java.lang.String getGeocodingProvider ()
{
return (java.lang.String)get_Value(COLUMNNAME_GeocodingProvider);
}
/** Set Google Maps - API-Schlüssel.
@param gmaps_ApiKey Google Maps - API-Schlüssel */
@Override
public void setgmaps_ApiKey (java.lang.String gmaps_ApiKey)
{
set_Value (COLUMNNAME_gmaps_ApiKey, gmaps_ApiKey);
}
/** Get Google Maps - API-Schlüssel.
@return Google Maps - API-Schlüssel */
@Override
public java.lang.String getgmaps_ApiKey ()
{
return (java.lang.String)get_Value(COLUMNNAME_gmaps_ApiKey);
}
/** Set Open Street Maps - Basis-URL.
@param osm_baseURL
The Base URL after which all parameters are added
*/
@Override
public void setosm_baseURL (java.lang.String osm_baseURL)
{
set_Value (COLUMNNAME_osm_baseURL, osm_baseURL);
}
/** Get Open Street Maps - Basis-URL.
|
@return The Base URL after which all parameters are added
*/
@Override
public java.lang.String getosm_baseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_osm_baseURL);
}
/** Set Open Street Maps - Millisekunden zwischen den Anfragen.
@param osm_millisBetweenRequests
How many milliseconds to wait between 2 consecutive requests
*/
@Override
public void setosm_millisBetweenRequests (int osm_millisBetweenRequests)
{
set_Value (COLUMNNAME_osm_millisBetweenRequests, Integer.valueOf(osm_millisBetweenRequests));
}
/** Get Open Street Maps - Millisekunden zwischen den Anfragen.
@return How many milliseconds to wait between 2 consecutive requests
*/
@Override
public int getosm_millisBetweenRequests ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_osm_millisBetweenRequests);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GeocodingConfig.java
| 1
|
请完成以下Java代码
|
public FeelConvertException unableToConvertValue(Object value, Class<?> type) {
return new FeelConvertException(exceptionMessage(
"013",
"Unable to convert value '{}' of type '{}' to type '{}'", value, value.getClass(), type),
value, type
);
}
public FeelConvertException unableToConvertValue(Object value, Class<?> type, Throwable cause) {
return new FeelConvertException(exceptionMessage(
"014",
"Unable to convert value '{}' of type '{}' to type '{}'", value, value.getClass(), type),
value, type, cause
);
}
public FeelConvertException unableToConvertValue(String feelExpression, FeelConvertException cause) {
Object value = cause.getValue();
Class<?> type = cause.getType();
return new FeelConvertException(exceptionMessage(
"015",
"Unable to convert value '{}' of type '{}' to type '{}' in expression '{}'", value, value.getClass(), type, feelExpression),
cause
);
}
public UnsupportedOperationException simpleExpressionNotSupported() {
return new UnsupportedOperationException(exceptionMessage(
"016",
"Simple Expression not supported by FEEL engine")
);
}
public FeelException unableToEvaluateExpressionAsNotInputIsSet(String simpleUnaryTests, FeelMissingVariableException e) {
return new FeelException(exceptionMessage(
"017",
"Unable to evaluate expression '{}' as no input is set. Maybe the inputExpression is missing or empty.", simpleUnaryTests),
e
);
}
public FeelMethodInvocationException invalidDateAndTimeFormat(String dateTimeString, Throwable cause) {
return new FeelMethodInvocationException(exceptionMessage(
|
"018",
"Invalid date and time format in '{}'", dateTimeString),
cause, "date and time", dateTimeString
);
}
public FeelMethodInvocationException unableToInvokeMethod(String simpleUnaryTests, FeelMethodInvocationException cause) {
String method = cause.getMethod();
String[] parameters = cause.getParameters();
return new FeelMethodInvocationException(exceptionMessage(
"019",
"Unable to invoke method '{}' with parameters '{}' in expression '{}'", method, parameters, simpleUnaryTests),
cause.getCause(), method, parameters
);
}
public FeelSyntaxException invalidListExpression(String feelExpression) {
String description = "List expression can not have empty elements";
return syntaxException("020", feelExpression, description);
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\FeelEngineLogger.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return list.stream().map(ITranslatableString::toString).collect(Collectors.joining(joinString));
}
@Override
public String translate(final String adLanguage)
{
return list.stream().map(trl -> trl.translate(adLanguage)).collect(Collectors.joining(joinString));
}
@Override
public String getDefaultValue()
{
String defaultValue = this.defaultValue;
if (defaultValue == null)
{
this.defaultValue = defaultValue = list.stream().map(trl -> trl.getDefaultValue()).collect(Collectors.joining(joinString));
}
return defaultValue;
}
@Override
|
public Set<String> getAD_Languages()
{
ImmutableSet<String> adLanguages = this.adLanguages;
if (adLanguages == null)
{
this.adLanguages = adLanguages = list.stream().flatMap(trl -> trl.getAD_Languages().stream()).collect(ImmutableSet.toImmutableSet());
}
return adLanguages;
}
@Override
public boolean isTranslatedTo(final String adLanguage)
{
return list.stream().anyMatch(trl -> trl.isTranslatedTo(adLanguage));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\CompositeTranslatableString.java
| 1
|
请完成以下Java代码
|
public Collection<SecurPharmProduct> getProductsByIds(@NonNull final Collection<SecurPharmProductId> productDataResultIds)
{
if (productDataResultIds.isEmpty())
{
return ImmutableList.of();
}
return productDataCache.getAllOrLoad(productDataResultIds, this::retrieveProductDataResultByIds);
}
private Map<SecurPharmProductId, SecurPharmProduct> retrieveProductDataResultByIds(@NonNull final Collection<SecurPharmProductId> productDataResultIds)
{
Check.assumeNotEmpty(productDataResultIds, "productDataResultIds is not empty");
return queryBL
.createQueryBuilder(I_M_Securpharm_Productdata_Result.class)
.addInArrayFilter(I_M_Securpharm_Productdata_Result.COLUMNNAME_M_Securpharm_Productdata_Result_ID, productDataResultIds)
.create()
.stream()
.map(record -> toProductDataResult(record))
.collect(GuavaCollectors.toImmutableMapByKey(SecurPharmProduct::getId));
}
public Collection<SecurPharmProduct> getProductsByHuIds(@NonNull final Collection<HuId> huIds)
{
if (huIds.isEmpty())
{
return ImmutableList.of();
}
final ImmutableSet<SecurPharmProductId> ids = queryBL
.createQueryBuilder(I_M_Securpharm_Productdata_Result.class)
.addInArrayFilter(I_M_Securpharm_Productdata_Result.COLUMNNAME_M_HU_ID, huIds)
.create()
.idsAsSet(SecurPharmProductId::ofRepoId);
|
return getProductsByIds(ids);
}
private static SecurPharmProduct toProductDataResult(@NonNull final I_M_Securpharm_Productdata_Result record)
{
final boolean error = record.isError();
return SecurPharmProduct.builder()
.error(error)
.resultCode(record.getLastResultCode())
.resultMessage(record.getLastResultMessage())
.productDetails(!error ? toProductDetails(record) : null)
.huId(HuId.ofRepoId(record.getM_HU_ID()))
.id(SecurPharmProductId.ofRepoId(record.getM_Securpharm_Productdata_Result_ID()))
.build();
}
private static ProductDetails toProductDetails(final I_M_Securpharm_Productdata_Result record)
{
return ProductDetails.builder()
.productCode(record.getProductCode())
.productCodeType(ProductCodeType.ofCode(record.getProductCodeType()))
//
.lot(record.getLotNumber())
.serialNumber(record.getSerialNumber())
//
.expirationDate(JsonExpirationDate.ofLocalDate(TimeUtil.asLocalDate(record.getExpirationDate())))
//
.activeStatus(JsonProductPackageState.ofYesNoString(record.getActiveStatus()))
.inactiveReason(record.getInactiveReason())
//
.decommissioned(record.isDecommissioned())
.decommissionedServerTransactionId(record.getDecommissionedServerTransactionId())
//
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\product\SecurPharmProductRepository.java
| 1
|
请完成以下Java代码
|
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
/**
* Return the default compatibility range to apply to all dependencies of this group
* unless specified otherwise.
* @return the compatibility range
*/
public String getCompatibilityRange() {
return this.compatibilityRange;
}
public void setCompatibilityRange(String compatibilityRange) {
this.compatibilityRange = compatibilityRange;
}
/**
* Return the default bom to associate to all dependencies of this group unless
* specified otherwise.
* @return the BOM
*/
public String getBom() {
return this.bom;
}
public void setBom(String bom) {
this.bom = bom;
}
/**
* Return the default repository to associate to all dependencies of this group unless
* specified otherwise.
* @return the repository
*/
public String getRepository() {
return this.repository;
}
public void setRepository(String repository) {
|
this.repository = repository;
}
/**
* Return the {@link Dependency dependencies} of this group.
* @return the content
*/
public List<Dependency> getContent() {
return this.content;
}
/**
* Create a new {@link DependencyGroup} instance with the given name.
* @param name the name of the group
* @return a new {@link DependencyGroup} instance
*/
public static DependencyGroup create(String name) {
DependencyGroup group = new DependencyGroup();
group.setName(name);
return group;
}
}
|
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\DependencyGroup.java
| 1
|
请完成以下Java代码
|
public class PPOrderLineRowId
{
@Getter private final int recordId;
@NonNull @Getter private final PPOrderLineRowType type;
@Nullable @Getter private final DocumentId parentRowId;
private transient DocumentId _documentId; // lazy
@Builder
private PPOrderLineRowId(
@NonNull final PPOrderLineRowType type,
@Nullable final DocumentId parentRowId,
final int recordId)
{
Check.assumeGreaterThanZero(recordId, "recordId");
this.type = type;
this.parentRowId = parentRowId;
this.recordId = recordId;
}
static final String PARTS_SEPARATOR = "-";
private static final Splitter PARTS_SPLITTER = Splitter.on(PARTS_SEPARATOR).omitEmptyStrings();
public DocumentId toDocumentId()
{
DocumentId documentId = this._documentId;
if (documentId == null)
{
final String sb = type.getCode()
+ PARTS_SEPARATOR + parentRowId
+ PARTS_SEPARATOR + recordId;
documentId = this._documentId = DocumentId.ofString(sb);
}
return documentId;
}
public static PPOrderLineRowId fromDocumentId(final DocumentId documentId)
{
final List<String> parts = PARTS_SPLITTER.splitToList(documentId.toJson());
return fromStringPartsList(parts);
|
}
private static PPOrderLineRowId fromStringPartsList(final List<String> parts)
{
final int partsCount = parts.size();
if (partsCount < 1)
{
throw new IllegalArgumentException("Invalid id: " + parts);
}
final PPOrderLineRowType type = PPOrderLineRowType.forCode(parts.get(0));
final DocumentId parentRowId = !Check.isEmpty(parts.get(1), true) ? DocumentId.of(parts.get(1)) : null;
final int recordId = Integer.parseInt(parts.get(2));
return new PPOrderLineRowId(type, parentRowId, recordId);
}
public static PPOrderLineRowId ofPPOrderBomLineId(int ppOrderBomLineId)
{
Preconditions.checkArgument(ppOrderBomLineId > 0, "ppOrderBomLineId > 0");
return new PPOrderLineRowId(PPOrderLineRowType.PP_OrderBomLine, null, ppOrderBomLineId);
}
public static PPOrderLineRowId ofPPOrderId(int ppOrderId)
{
Preconditions.checkArgument(ppOrderId > 0, "ppOrderId > 0");
return new PPOrderLineRowId(PPOrderLineRowType.PP_Order, null, ppOrderId);
}
public static PPOrderLineRowId ofIssuedOrReceivedHU(@Nullable DocumentId parentRowId, @NonNull final HuId huId)
{
return new PPOrderLineRowId(PPOrderLineRowType.IssuedOrReceivedHU, parentRowId, huId.getRepoId());
}
public static PPOrderLineRowId ofSourceHU(@NonNull DocumentId parentRowId, @NonNull final HuId sourceHuId)
{
return new PPOrderLineRowId(PPOrderLineRowType.Source_HU, parentRowId, sourceHuId.getRepoId());
}
public Optional<PPOrderBOMLineId> getPPOrderBOMLineIdIfApplies()
{
return type.isPP_OrderBomLine() ? PPOrderBOMLineId.optionalOfRepoId(recordId) : Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRowId.java
| 1
|
请完成以下Java代码
|
public class ShipmentScheduleCreatedEvent extends AbstractShipmentScheduleEvent
{
public static final String TYPE = "ShipmentScheduleCreatedEvent";
@Builder
public ShipmentScheduleCreatedEvent(
@JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor,
@JsonProperty("materialDescriptor") final MaterialDescriptor materialDescriptor,
@JsonProperty("minMaxDescriptor") @Nullable final MinMaxDescriptor minMaxDescriptor,
@JsonProperty("shipmentScheduleDetail") @NonNull final ShipmentScheduleDetail shipmentScheduleDetail,
@JsonProperty("shipmentScheduleId") final int shipmentScheduleId,
@JsonProperty("documentLineDescriptor") final DocumentLineDescriptor documentLineDescriptor)
{
super(
eventDescriptor,
materialDescriptor,
minMaxDescriptor,
shipmentScheduleDetail,
shipmentScheduleId,
documentLineDescriptor);
}
@Override
@NonNull
public BigDecimal getReservedQuantityDelta()
{
return getShipmentScheduleDetail().getReservedQuantity();
|
}
@Override
@NonNull
public BigDecimal getOrderedQuantityDelta()
{
return getShipmentScheduleDetail().getOrderedQuantity();
}
@Override
public void validate()
{
super.validate();
Check.errorIf(getDocumentLineDescriptor() == null, "documentLineDescriptor may not be null");
getDocumentLineDescriptor().validate();
}
@Override
public String getEventName() {return TYPE;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\shipmentschedule\ShipmentScheduleCreatedEvent.java
| 1
|
请完成以下Java代码
|
public class HttpSessionEventPublisher implements HttpSessionListener, HttpSessionIdListener {
private static final String LOGGER_NAME = HttpSessionEventPublisher.class.getName();
ApplicationContext getContext(ServletContext servletContext) {
return SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(servletContext);
}
/**
* Handles the HttpSessionEvent by publishing a {@link HttpSessionCreatedEvent} to the
* application appContext.
* @param event HttpSessionEvent passed in by the container
*/
@Override
public void sessionCreated(HttpSessionEvent event) {
extracted(event.getSession(), new HttpSessionCreatedEvent(event.getSession()));
}
/**
* Handles the HttpSessionEvent by publishing a {@link HttpSessionDestroyedEvent} to
* the application appContext.
* @param event The HttpSessionEvent pass in by the container
|
*/
@Override
public void sessionDestroyed(HttpSessionEvent event) {
extracted(event.getSession(), new HttpSessionDestroyedEvent(event.getSession()));
}
/**
* @inheritDoc
*/
@Override
public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
extracted(event.getSession(), new HttpSessionIdChangedEvent(event.getSession(), oldSessionId));
}
private void extracted(HttpSession session, ApplicationEvent e) {
Log log = LogFactory.getLog(LOGGER_NAME);
log.debug(LogMessage.format("Publishing event: %s", e));
getContext(session.getServletContext()).publishEvent(e);
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\HttpSessionEventPublisher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DeleteProcessDefinitionsBuilderImpl byIds(String... processDefinitionId) {
if (processDefinitionId != null) {
this.processDefinitionIds = new ArrayList<String>();
this.processDefinitionIds.addAll(Arrays.asList(processDefinitionId));
}
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl byKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl withoutTenantId() {
isTenantIdSet = true;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl withTenantId(String tenantId) {
ensureNotNull("tenantId", tenantId);
isTenantIdSet = true;
this.tenantId = tenantId;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl cascade() {
this.cascade = true;
return this;
}
@Override
|
public DeleteProcessDefinitionsBuilderImpl skipCustomListeners() {
this.skipCustomListeners = true;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl skipIoMappings() {
this.skipIoMappings = true;
return this;
}
@Override
public void delete() {
ensureOnlyOneNotNull(NullValueException.class, "'processDefinitionKey' or 'processDefinitionIds' cannot be null", processDefinitionKey, processDefinitionIds);
Command<Void> command;
if (processDefinitionKey != null) {
command = new DeleteProcessDefinitionsByKeyCmd(processDefinitionKey, cascade, skipCustomListeners, skipIoMappings, tenantId, isTenantIdSet);
} else if (processDefinitionIds != null && !processDefinitionIds.isEmpty()) {
command = new DeleteProcessDefinitionsByIdsCmd(processDefinitionIds, cascade, skipCustomListeners, skipIoMappings);
} else {
return;
}
commandExecutor.execute(command);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeleteProcessDefinitionsBuilderImpl.java
| 2
|
请完成以下Java代码
|
public class base extends SinglePartElement
implements Printable
{
/**
*
*/
private static final long serialVersionUID = 7276739960215382631L;
/**
* Private initialization routine.
*/
{
setElementType ("base");
setCase (LOWERCASE);
setAttributeQuote (true);
setBeginEndModifier ('/');
}
/**
* Basic constructor.
*/
public base ()
{
}
/**
* Basic constructor.
*
* @param href
* the URI that goes between double quotes
*/
public base (String href)
{
setHref (href);
}
/**
* Basic constructor.
*
* @param href
* the URI that goes between double quotes
* @param target
* the target that goes between double quotes
*/
public base (String href, String target)
{
setHref (target);
setTarget (target);
}
/**
* Sets the href="" attribute
*
* @param href
* the URI that goes between double quotes
*/
public base setHref (String href)
{
addAttribute ("href", href);
return this;
}
/**
* Sets the target="" attribute
*
* @param target
* the URI that goes between double quotes
*/
public base setTarget (String target)
{
addAttribute ("target", target);
return this;
}
/**
* Sets the lang="" and xml:lang="" attributes
*
* @param lang
* the lang="" and xml:lang="" attributes
*/
public Element setLang (String lang)
{
addAttribute ("lang", lang);
addAttribute ("xml:lang", lang);
return this;
}
/**
* Adds an Element to the element.
*
* @param hashcode
* name of element for hash table
* @param element
* Adds an Element to the element.
*/
public base addElement (String hashcode, Element element)
{
addElementToRegistry (hashcode, element);
return (this);
}
|
/**
* Adds an Element to the element.
*
* @param hashcode
* name of element for hash table
* @param element
* Adds an Element to the element.
*/
public base addElement (String hashcode, String element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param element
* Adds an Element to the element.
*/
public base addElement (Element element)
{
addElementToRegistry (element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param element
* Adds an Element to the element.
*/
public base addElement (String element)
{
addElementToRegistry (element);
return (this);
}
/**
* Removes an Element from the element.
*
* @param hashcode
* the name of the element to be removed.
*/
public base removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\base.java
| 1
|
请完成以下Java代码
|
static SocketPredicate type(final Class<? extends SocketAddress> type) {
requireNonNull(type, "type");
return type::isInstance;
}
/**
* Checks the type of the socket address and the given condition.
*
* @param <T> The expected type of the socket address.
* @param type The expected class of the socket address.
* @param condition The additional condition the socket has to pass.
* @return The newly created socket predicate.
*/
@SuppressWarnings("unchecked")
static <T> SocketPredicate typeAnd(final Class<T> type, final Predicate<T> condition) {
requireNonNull(type, "type");
requireNonNull(condition, "condition");
return s -> type.isInstance(s) && condition.test((T) s);
}
/**
* Checks that the given socket address is an {@link InProcessSocketAddress}.
*
* @return The newly created socket predicate.
*/
static SocketPredicate inProcess() {
return type(InProcessSocketAddress.class);
}
/**
* Checks that the given socket address is an {@link InProcessSocketAddress} with the given name.
*
* @param name The name of in process connection.
* @return The newly created socket predicate.
*/
|
static SocketPredicate inProcess(final String name) {
requireNonNull(name, "name");
return typeAnd(InProcessSocketAddress.class, s -> name.equals(s.getName()));
}
/**
* Checks that the given socket address is a {@link InetSocketAddress}.
*
* @return The newly created socket predicate.
*/
static SocketPredicate inet() {
return type(InetSocketAddress.class);
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\check\AccessPredicate.java
| 1
|
请完成以下Java代码
|
private static void finalizeToken(State state, StringBuilder currentToken, ArrayList<Token> tokens) {
if (State.INVALID == state || State.OPERATOR == state) {
throw new InvalidExpressionException(String.format(MESSAGE_ERROR, currentToken));
} else if (State.NUMBER == state) {
tokens.add(new TokenNumber(currentToken.toString()));
}
}
private enum State {
INITIAL,
NUMBER,
OPERATOR,
INVALID
}
private enum Grammar {
ADDITION('+'),
SUBTRACTION('-'),
MULTIPLICATION('*'),
DIVISION('/');
private final char symbol;
Grammar(char symbol) {
this.symbol = symbol;
}
public static boolean isOperator(char character) {
return Arrays.stream(Grammar.values())
.anyMatch(grammar -> grammar.symbol == character);
|
}
public static boolean isDigit(char character) {
return Character.isDigit(character);
}
public static boolean isWhitespace(char character) {
return Character.isWhitespace(character);
}
public static boolean isValidSymbol(char character) {
return isOperator(character) || isWhitespace(character) || isDigit(character);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-algorithms-5\src\main\java\com\baeldung\lexer\LexerFsm.java
| 1
|
请完成以下Java代码
|
public int numPartitions() {
return this.numPartitions;
}
@Nullable
public Boolean autoStartDltHandler() {
return this.autoStartDltHandler;
}
public Set<Class<? extends Throwable>> usedForExceptions() {
return this.usedForExceptions;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Properties that = (Properties) o;
return this.delayMs == that.delayMs
&& this.maxAttempts == that.maxAttempts
&& this.numPartitions == that.numPartitions
&& this.suffix.equals(that.suffix)
&& this.type == that.type
&& this.dltStrategy == that.dltStrategy
&& this.kafkaOperations.equals(that.kafkaOperations);
}
@Override
public int hashCode() {
return Objects.hash(this.delayMs, this.suffix, this.type, this.maxAttempts, this.numPartitions,
this.dltStrategy, this.kafkaOperations);
}
@Override
public String toString() {
return "Properties{" +
"delayMs=" + this.delayMs +
", suffix='" + this.suffix + '\'' +
", type=" + this.type +
", maxAttempts=" + this.maxAttempts +
", numPartitions=" + this.numPartitions +
", dltStrategy=" + this.dltStrategy +
", kafkaOperations=" + this.kafkaOperations +
", shouldRetryOn=" + this.shouldRetryOn +
", timeout=" + this.timeout +
|
'}';
}
public boolean isMainEndpoint() {
return Type.MAIN.equals(this.type);
}
}
enum Type {
MAIN,
RETRY,
/**
* A retry topic reused along sequential retries
* with the same back off interval.
*
* @since 3.0.4
*/
REUSABLE_RETRY_TOPIC,
DLT,
NO_OPS
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopic.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static JsonArray map(List<Book> books) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
books.forEach(book -> {
JsonObject jsonObject = map(book);
arrayBuilder.add(jsonObject);
});
return arrayBuilder.build();
}
public static Book map(InputStream is) {
try(JsonReader jsonReader = Json.createReader(is)) {
JsonObject jsonObject = jsonReader.readObject();
Book book = new Book();
book.setId(getStringFromJson("id", jsonObject));
book.setIsbn(getStringFromJson("isbn", jsonObject));
book.setName(getStringFromJson("name", jsonObject));
book.setAuthor(getStringFromJson("author", jsonObject));
book.setPages(getIntFromJson("pages",jsonObject));
return book;
}
}
private static String getStringFromJson(String key, JsonObject json) {
String returnedString = null;
if (json.containsKey(key)) {
JsonString value = json.getJsonString(key);
if (value != null) {
|
returnedString = value.getString();
}
}
return returnedString;
}
private static Integer getIntFromJson(String key, JsonObject json) {
Integer returnedValue = null;
if (json.containsKey(key)) {
JsonNumber value = json.getJsonNumber(key);
if (value != null) {
returnedValue = value.intValue();
}
}
return returnedValue;
}
}
|
repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\util\BookMapper.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isFailIfNotCalculated()
{
return failIfNotCalculated;
}
@Override
public IEditablePricingContext setFailIfNotCalculated()
{
this.failIfNotCalculated = true;
return this;
}
@Override
public IEditablePricingContext setSkipCheckingPriceListSOTrxFlag(final boolean skipCheckingPriceListSOTrxFlag)
{
this.skipCheckingPriceListSOTrxFlag = skipCheckingPriceListSOTrxFlag;
return this;
}
@Nullable
public BigDecimal getManualPrice()
{
return manualPrice;
}
@Override
public IEditablePricingContext setManualPrice(@Nullable final BigDecimal manualPrice)
{
this.manualPrice = manualPrice;
return this;
}
@Override
public boolean isSkipCheckingPriceListSOTrxFlag()
{
return skipCheckingPriceListSOTrxFlag;
}
/** If set to not-{@code null}, then the {@link de.metas.pricing.rules.Discount} rule with go with this break as opposed to look for the currently matching break. */
@Override
public IEditablePricingContext setForcePricingConditionsBreak(@Nullable final PricingConditionsBreak forcePricingConditionsBreak)
{
this.forcePricingConditionsBreak = forcePricingConditionsBreak;
return this;
}
@Override
public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware()
{
final Object referencedObj = getReferencedObject();
if (referencedObj == null)
{
return Optional.empty();
}
|
final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class);
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj);
return Optional.ofNullable(asiAware);
}
@Override
public Quantity getQuantity()
{
final BigDecimal ctxQty = getQty();
if (ctxQty == null)
{
return null;
}
final UomId ctxUomId = getUomId();
if (ctxUomId == null)
{
return null;
}
return Quantitys.of(ctxQty, ctxUomId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
| 2
|
请完成以下Java代码
|
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_STAGE;
}
@Override
public boolean hasChildElements() {
return true;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
Stage stage = new Stage();
stage.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
stage.setAutoComplete(Boolean.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IS_AUTO_COMPLETE)));
stage.setAutoCompleteCondition(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_AUTO_COMPLETE_CONDITION));
String displayOrderString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_DISPLAY_ORDER);
if (StringUtils.isNotEmpty(displayOrderString)) {
stage.setDisplayOrder(Integer.valueOf(displayOrderString));
}
String includeInStageOverviewString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INCLUDE_IN_STAGE_OVERVIEW);
if (StringUtils.isNotEmpty(includeInStageOverviewString)) {
stage.setIncludeInStageOverview(includeInStageOverviewString);
} else {
stage.setIncludeInStageOverview("true"); // True by default
}
|
stage.setCase(conversionHelper.getCurrentCase());
stage.setParent(conversionHelper.getCurrentPlanFragment());
conversionHelper.setCurrentStage(stage);
conversionHelper.addStage(stage);
String businessStatus = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_BUSINESS_STATUS);
if (StringUtils.isNotEmpty(businessStatus)) {
stage.setBusinessStatus(businessStatus);
}
return stage;
}
@Override
protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) {
super.elementEnd(xtr, conversionHelper);
conversionHelper.removeCurrentStage();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\StageXmlConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void updateTrxInfo(final I_SAP_GLJournalLine glJournalLine)
{
final FAOpenItemTrxInfo openItemTrxInfo;
final AccountId accountId = AccountId.ofRepoIdOrNull(glJournalLine.getC_ValidCombination_ID());
if (accountId != null)
{
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(glJournalLine.getSAP_GLJournal_ID());
final SAPGLJournalLineId lineId;
if (glJournalLine.getSAP_GLJournalLine_ID() <= 0)
{
lineId = glJournalRepository.acquireLineId(glJournalId);
glJournalLine.setSAP_GLJournalLine_ID(lineId.getRepoId());
}
else
{
lineId = SAPGLJournalLineId.ofRepoId(glJournalId, glJournalLine.getSAP_GLJournalLine_ID());
}
openItemTrxInfo = computeTrxInfo(accountId, lineId).orElse(null);
}
else
{
openItemTrxInfo = null;
}
SAPGLJournalLoaderAndSaver.updateRecordFromOpenItemTrxInfo(glJournalLine, openItemTrxInfo);
}
private Optional<FAOpenItemTrxInfo> computeTrxInfo(
@NonNull final AccountId accountId,
@NonNull final SAPGLJournalLineId sapGLJournalLineId)
{
|
return Optional.empty();
}
public void fireAfterComplete(final I_SAP_GLJournal record)
{
final SAPGLJournal glJournal = glJournalRepository.getByRecord(record);
faOpenItemsService.fireGLJournalCompleted(glJournal);
}
public void fireAfterReactivate(final I_SAP_GLJournal record)
{
final SAPGLJournal glJournal = glJournalRepository.getByRecord(record);
faOpenItemsService.fireGLJournalReactivated(glJournal);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
@SpringBootApplication public class AmqpClient {
@Bean Queue queue() {
return new Queue("remotingQueue");
}
@Bean AmqpProxyFactoryBean amqpFactoryBean(AmqpTemplate amqpTemplate) {
AmqpProxyFactoryBean factoryBean = new AmqpProxyFactoryBean();
factoryBean.setServiceInterface(CabBookingService.class);
factoryBean.setAmqpTemplate(amqpTemplate);
return factoryBean;
}
@Bean Exchange directExchange(Queue someQueue) {
DirectExchange exchange = new DirectExchange("remoting.exchange");
BindingBuilder.bind(someQueue).to(exchange).with("remoting.binding");
|
return exchange;
}
@Bean RabbitTemplate amqpTemplate(ConnectionFactory factory) {
RabbitTemplate template = new RabbitTemplate(factory);
template.setRoutingKey("remoting.binding");
template.setExchange("remoting.exchange");
return template;
}
public static void main(String[] args) throws BookingException {
CabBookingService service = SpringApplication.run(AmqpClient.class, args).getBean(CabBookingService.class);
out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037"));
}
}
|
repos\tutorials-master\spring-remoting-modules\remoting-amqp\remoting-amqp-client\src\main\java\com\baeldung\client\AmqpClient.java
| 2
|
请完成以下Java代码
|
public ListenerContainerFactoryConfigurer listenerContainerFactoryConfigurer(KafkaConsumerBackoffManager kafkaConsumerBackoffManager,
DeadLetterPublishingRecovererFactory deadLetterPublishingRecovererFactory,
Clock clock) {
return new ListenerContainerFactoryConfigurer(kafkaConsumerBackoffManager, deadLetterPublishingRecovererFactory, clock);
}
/**
* Create the {@link RetryTopicNamesProviderFactory} instance that will be used
* to provide the property names for the retry topics' {@link KafkaListenerEndpoint}.
* @return the instance.
*/
public RetryTopicNamesProviderFactory retryTopicNamesProviderFactory() {
return new SuffixingRetryTopicNamesProviderFactory();
}
/**
* Create the {@link KafkaBackOffManagerFactory} that will be used to create the
* {@link KafkaConsumerBackoffManager} instance used to back off the partitions.
* @param registry the {@link ListenerContainerRegistry} used to fetch the
* {@link MessageListenerContainer}.
* @param applicationContext the application context.
* @return the instance.
*/
public KafkaBackOffManagerFactory kafkaBackOffManagerFactory(@Nullable ListenerContainerRegistry registry,
ApplicationContext applicationContext) {
|
return new ContainerPartitionPausingBackOffManagerFactory(registry, applicationContext);
}
/**
* Return the {@link Clock} instance that will be used for all
* time-related operations in the retry topic processes.
* @return the instance.
*/
public Clock internalRetryTopicClock() {
return this.internalRetryTopicClock;
}
/**
* Create a {@link Clock} instance that will be used for all time-related operations
* in the retry topic processes.
* @return the instance.
*/
protected Clock createInternalRetryTopicClock() {
return Clock.systemUTC();
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicComponentFactory.java
| 1
|
请完成以下Java代码
|
public ImmutableList<HUDescriptor> createHuDescriptorsForCostCollector(
@NonNull final I_PP_Cost_Collector costCollector,
final boolean deleted)
{
return createHUDescriptorsUsingHuAssignments(costCollector, deleted);
}
public ImmutableList<HUDescriptor> createHuDescriptorsForMovementLine(
@NonNull final I_M_MovementLine movementLine,
final boolean deleted)
{
return createHUDescriptorsUsingHuAssignments(movementLine, deleted);
}
private ImmutableList<HUDescriptor> createHUDescriptorsUsingHuAssignments(
@NonNull final Object huReferencedModel,
final boolean deleted)
{
final List<HuAssignment> huAssignments = huAssignmentDAO.retrieveLowLevelHUAssignmentsForModel(huReferencedModel);
final ImmutableList.Builder<HUDescriptor> result = ImmutableList.builder();
for (final HuAssignment huAssignment : huAssignments)
{
result.addAll(huDescriptorService.createHuDescriptors(huAssignment.getLowestLevelHU(), deleted));
}
return result.build();
}
@VisibleForTesting
@Builder(builderMethodName = "newMaterialDescriptors", builderClassName = "_MaterialDescriptorsBuilder")
private Map<MaterialDescriptor, Collection<HUDescriptor>> createMaterialDescriptors(
@NonNull final TransactionDescriptor transaction,
@Nullable final BPartnerId customerId,
@Nullable final BPartnerId vendorId,
@NonNull final Collection<HUDescriptor> huDescriptors)
{
// aggregate HUDescriptors based on their product & attributes
final ImmutableListMultimap<ProductDescriptor, HUDescriptor> //
huDescriptorsByProduct = Multimaps.index(huDescriptors, HUDescriptor::getProductDescriptor);
|
final ImmutableMap.Builder<MaterialDescriptor, Collection<HUDescriptor>> result = ImmutableMap.builder();
for (final Map.Entry<ProductDescriptor, Collection<HUDescriptor>> entry : huDescriptorsByProduct.asMap().entrySet())
{
final ProductDescriptor productDescriptor = entry.getKey();
final Collection<HUDescriptor> huDescriptorsForCurrentProduct = entry.getValue();
final BigDecimal quantity = huDescriptorsForCurrentProduct
.stream()
.map(HUDescriptor::getQuantity)
.map(qty -> transaction.getMovementQty().signum() >= 0 ? qty : qty.negate()) // set signum according to transaction.movementQty
.reduce(BigDecimal.ZERO, BigDecimal::add);
final MaterialDescriptor materialDescriptor = MaterialDescriptor.builder()
.warehouseId(transaction.getWarehouseId())
.locatorId(transaction.getLocatorId())
.date(transaction.getTransactionDate())
.productDescriptor(productDescriptor)
.customerId(customerId)
.vendorId(vendorId)
.quantity(quantity)
.build();
result.put(materialDescriptor, huDescriptorsForCurrentProduct);
}
return result.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\HUDescriptorsFromHUAssignmentService.java
| 1
|
请完成以下Java代码
|
public UpdateExternalTaskRetriesBuilder externalTaskIds(List<String> externalTaskIds) {
this.externalTaskIds = externalTaskIds;
return this;
}
public UpdateExternalTaskRetriesBuilder externalTaskIds(String... externalTaskIds) {
if (externalTaskIds == null) {
this.externalTaskIds = Collections.emptyList();
}
else {
this.externalTaskIds = Arrays.asList(externalTaskIds);
}
return this;
}
public UpdateExternalTaskRetriesBuilder processInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
return this;
}
public UpdateExternalTaskRetriesBuilder processInstanceIds(String... processInstanceIds) {
if (processInstanceIds == null) {
this.processInstanceIds = Collections.emptyList();
}
else {
this.processInstanceIds = Arrays.asList(processInstanceIds);
}
return this;
}
public UpdateExternalTaskRetriesBuilder externalTaskQuery(ExternalTaskQuery externalTaskQuery) {
this.externalTaskQuery = externalTaskQuery;
return this;
}
public UpdateExternalTaskRetriesBuilder processInstanceQuery(ProcessInstanceQuery processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
return this;
}
public UpdateExternalTaskRetriesBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
return this;
}
public void set(int retries) {
this.retries = retries;
commandExecutor.execute(new SetExternalTasksRetriesCmd(this));
|
}
@Override
public Batch setAsync(int retries) {
this.retries = retries;
return commandExecutor.execute(new SetExternalTasksRetriesBatchCmd(this));
}
public int getRetries() {
return retries;
}
public List<String> getExternalTaskIds() {
return externalTaskIds;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public ExternalTaskQuery getExternalTaskQuery() {
return externalTaskQuery;
}
public ProcessInstanceQuery getProcessInstanceQuery() {
return processInstanceQuery;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateExternalTaskRetriesBuilderImpl.java
| 1
|
请完成以下Java代码
|
public Set<CostElementId> getIdsByCostingMethod(@NonNull final CostingMethod costingMethod)
{
final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()));
return getIndexedCostElements()
.streamByClientIdAndCostingMethod(clientId, costingMethod)
.map(CostElement::getId)
.collect(ImmutableSet.toImmutableSet());
}
@Override
public List<CostElement> getMaterialCostingElementsForCostingMethod(@NonNull final CostingMethod costingMethod)
{
final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()));
return getIndexedCostElements()
.streamByClientId(clientId)
.filter(ce -> ce.isMaterialCostingMethod(costingMethod))
.collect(ImmutableList.toImmutableList());
}
@Override
public List<CostElement> getActiveMaterialCostingElements(@NonNull final ClientId clientId)
{
return getIndexedCostElements()
.streamByClientId(clientId)
.filter(CostElement::isMaterial)
.collect(ImmutableList.toImmutableList());
}
@Override
public Set<CostElementId> getActiveCostElementIds()
{
return getIndexedCostElements()
.stream()
.map(CostElement::getId)
.collect(ImmutableSet.toImmutableSet());
}
private Stream<CostElement> streamByCostingMethod(@NonNull final CostingMethod costingMethod)
{
final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()));
return getIndexedCostElements()
.streamByClientId(clientId)
|
.filter(ce -> ce.getCostingMethod() == costingMethod);
}
private static class IndexedCostElements
{
private final ImmutableMap<CostElementId, CostElement> costElementsById;
private IndexedCostElements(final Collection<CostElement> costElements)
{
costElementsById = Maps.uniqueIndex(costElements, CostElement::getId);
}
public Optional<CostElement> getById(final CostElementId id)
{
return Optional.ofNullable(costElementsById.get(id));
}
public Stream<CostElement> streamByClientId(@NonNull final ClientId clientId)
{
return stream().filter(ce -> ClientId.equals(ce.getClientId(), clientId));
}
public Stream<CostElement> streamByClientIdAndCostingMethod(@NonNull final ClientId clientId, @NonNull final CostingMethod costingMethod)
{
return streamByClientId(clientId).filter(ce -> costingMethod.equals(ce.getCostingMethod()));
}
public Stream<CostElement> stream()
{
return costElementsById.values().stream();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CostElementRepository.java
| 1
|
请完成以下Java代码
|
public GeometryCollection createGeoCollect(Geometry[] geoArray) throws ParseException{
return geometryFactory.createGeometryCollection(geoArray);
}
/**
* 5.1 根据圆点以及半径创建几何对象:特殊的多边形--圆 【Polygon】
* @param x 圆点x坐标
* @param y 圆点y坐标
* @param radius 半径
* @return
*/
public Polygon createCircle(double x, double y, final double radius){
//圆上面的点个数
final int sides = 32;
Coordinate[] coords = new Coordinate[sides+1];
for( int i = 0; i < sides; i++){
double angle = ((double) i / (double) sides) * Math.PI * 2.0;
double dx = Math.cos( angle ) * radius;
double dy = Math.sin( angle ) * radius;
coords[i] = new Coordinate( (double) x + dx, (double) y + dy );
}
coords[sides] = coords[0];
//线性环
LinearRing ring = geometryFactory.createLinearRing(coords);
return geometryFactory.createPolygon(ring, null);
}
/**
* 6.1 根据WKT创建环
* @param ringWKT
* @return
* @throws ParseException
*/
public LinearRing createLinearRingByWKT(String ringWKT) throws ParseException{
WKTReader reader = new WKTReader( geometryFactory );
return (LinearRing) reader.read(ringWKT);
}
/**
* 几何对象转GeoJson对象
* @param geometry
* @return
* @throws Exception
*/
|
public static String geometryToGeoJson(Geometry geometry) throws Exception {
if (geometry == null) {
return null;
}
StringWriter writer = new StringWriter();
geometryJson.write(geometry, writer);
String geojson = writer.toString();
writer.close();
return geojson;
}
/**
* GeoJson转几何对象
* @param geojson
* @return
* @throws Exception
*/
public static Geometry geoJsonToGeometry(String geojson) throws Exception {
return geometryJson.read(new StringReader(geojson));
}
}
|
repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\geotools\GeometryCreator.java
| 1
|
请完成以下Java代码
|
public <BodyType> ResponseEntity<BodyType> toResponseEntity(final BiFunction<ResponseEntity.BodyBuilder, R, ResponseEntity<BodyType>> toJsonMapper)
{
// Check ETag
final String etag = getETag().toETagString();
if (request.checkNotModified(etag))
{
// Response: 304 Not Modified
return newResponse(HttpStatus.NOT_MODIFIED, etag).build();
}
// Get the result and convert it to JSON
final R result = this.result.get();
final ResponseEntity.BodyBuilder newResponse = newResponse(HttpStatus.OK, etag);
return toJsonMapper.apply(newResponse, result);
}
|
private final ResponseEntity.BodyBuilder newResponse(final HttpStatus status, final String etag)
{
ResponseEntity.BodyBuilder response = ResponseEntity.status(status)
.eTag(etag)
.cacheControl(CacheControl.maxAge(cacheMaxAgeSec, TimeUnit.SECONDS));
final String adLanguage = getAdLanguage();
if (adLanguage != null && !adLanguage.isEmpty())
{
final String contentLanguage = ADLanguageList.toHttpLanguageTag(adLanguage);
response.header(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);
response.header(HttpHeaders.VARY, HttpHeaders.ACCEPT_LANGUAGE); // advice browser to include ACCEPT_LANGUAGE in their caching key
}
return response;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\cache\ETagResponseEntityBuilder.java
| 1
|
请完成以下Java代码
|
class CredProtectAuthenticationExtensionsClientInputJackson2Serializer
extends StdSerializer<CredProtectAuthenticationExtensionsClientInput> {
protected CredProtectAuthenticationExtensionsClientInputJackson2Serializer() {
super(CredProtectAuthenticationExtensionsClientInput.class);
}
@Override
public void serialize(CredProtectAuthenticationExtensionsClientInput input, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
CredProtectAuthenticationExtensionsClientInput.CredProtect credProtect = input.getInput();
String policy = toString(credProtect.getCredProtectionPolicy());
jgen.writeObjectField("credentialProtectionPolicy", policy);
jgen.writeObjectField("enforceCredentialProtectionPolicy", credProtect.isEnforceCredentialProtectionPolicy());
}
|
private static String toString(CredProtectAuthenticationExtensionsClientInput.CredProtect.ProtectionPolicy policy) {
switch (policy) {
case USER_VERIFICATION_OPTIONAL:
return "userVerificationOptional";
case USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST:
return "userVerificationOptionalWithCredentialIdList";
case USER_VERIFICATION_REQUIRED:
return "userVerificationRequired";
default:
throw new IllegalArgumentException("Unsupported ProtectionPolicy " + policy);
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\jackson\CredProtectAuthenticationExtensionsClientInputJackson2Serializer.java
| 1
|
请完成以下Java代码
|
public void createUser(UserDto userDto) {
final IdentityService identityService = getIdentityService();
if(identityService.isReadOnly()) {
throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
}
UserProfileDto profile = userDto.getProfile();
if(profile == null || profile.getId() == null) {
throw new InvalidRequestException(Status.BAD_REQUEST, "request object must provide profile information with valid id.");
}
User newUser = identityService.newUser(profile.getId());
profile.update(newUser);
if(userDto.getCredentials() != null) {
newUser.setPassword(userDto.getCredentials().getPassword());
}
identityService.saveUser(newUser);
}
@Override
public ResourceOptionsDto availableOperations(UriInfo context) {
final IdentityService identityService = getIdentityService();
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(UserRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
|
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if(!identityService.isReadOnly() && isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
// utility methods //////////////////////////////////////
protected IdentityService getIdentityService() {
return getProcessEngine().getIdentityService();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\UserRestServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean dictTableWhiteListCheckByDict(
@RequestParam("tableOrDictCode") String tableOrDictCode,
@RequestParam(value = "fields", required = false) String... fields
) {
return sysBaseApi.dictTableWhiteListCheckByDict(tableOrDictCode, fields);
}
/**
* 自动发布通告
*
* @param dataId 通告ID
* @param currentUserName 发送人
* @return
*/
@GetMapping("/announcementAutoRelease")
public void announcementAutoRelease(
@RequestParam("dataId") String dataId,
@RequestParam(value = "currentUserName", required = false) String currentUserName
) {
sysBaseApi.announcementAutoRelease(dataId, currentUserName);
}
/**
* 根据部门编码查询公司信息
* @param orgCode 部门编码
* @return
* @author chenrui
* @date 2025/8/12 14:45
*/
@GetMapping(value = "/queryCompByOrgCode")
SysDepartModel queryCompByOrgCode(@RequestParam(name = "sysCode") String orgCode) {
return sysBaseApi.queryCompByOrgCode(orgCode);
}
/**
* 根据部门编码和层次查询上级公司
*
* @param orgCode 部门编码
* @param level 可以传空 默认为1级 最小值为1
* @return
*/
@GetMapping(value = "/queryCompByOrgCodeAndLevel")
SysDepartModel queryCompByOrgCodeAndLevel(@RequestParam("orgCode") String orgCode, @RequestParam("level") Integer level){
return sysBaseApi.queryCompByOrgCodeAndLevel(orgCode,level);
}
/**
* 运行AIRag流程
* for [QQYUN-13634]在baseapi里面封装方法,方便其他模块调用
* @param airagFlowDTO
* @return 流程执行结果,可能是String或者Map
* @return
*/
@PostMapping(value = "/runAiragFlow")
Object runAiragFlow(@RequestBody AiragFlowDTO airagFlowDTO) {
return sysBaseApi.runAiragFlow(airagFlowDTO);
}
/**
* 根据部门code或部门id获取部门名称(当前和上级部门)
|
*
* @param orgCode 部门编码
* @param depId 部门id
* @return String 部门名称
*/
@GetMapping(value = "/getDepartPathNameByOrgCode")
String getDepartPathNameByOrgCode(@RequestParam(name = "orgCode", required = false) String orgCode, @RequestParam(name = "depId", required = false) String depId) {
return sysBaseApi.getDepartPathNameByOrgCode(orgCode, depId);
}
/**
* 根据部门ID查询用户ID
* @param deptIds
* @return
*/
@GetMapping("/queryUserIdsByCascadeDeptIds")
public List<String> queryUserIdsByCascadeDeptIds(@RequestParam("deptIds") List<String> deptIds){
return sysBaseApi.queryUserIdsByCascadeDeptIds(deptIds);
}
/**
* 推送uniapp 消息
* @param pushMessageDTO
* @return
*/
@PostMapping("/uniPushMsgToUser")
public void uniPushMsgToUser(@RequestBody PushMessageDTO pushMessageDTO){
sysBaseApi.uniPushMsgToUser(pushMessageDTO);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\api\controller\SystemApiController.java
| 2
|
请完成以下Java代码
|
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Resource resource = getResource();
Assert.state(resource != null, "'resource' must not be null");
Template template = createTemplate(resource);
if (template != null) {
template.execute(model, response.getWriter());
}
}
private @Nullable Resource getResource() {
ApplicationContext applicationContext = getApplicationContext();
String url = getUrl();
if (applicationContext == null || url == null) {
return null;
}
Resource resource = applicationContext.getResource(url);
return (resource.exists()) ? resource : null;
}
|
private Template createTemplate(Resource resource) throws IOException {
try (Reader reader = getReader(resource)) {
Assert.state(this.compiler != null, "'compiler' must not be null");
return this.compiler.compile(reader);
}
}
private Reader getReader(Resource resource) throws IOException {
if (this.charset != null) {
return new InputStreamReader(resource.getInputStream(), this.charset);
}
return new InputStreamReader(resource.getInputStream());
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\servlet\view\MustacheView.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrgId implements RepoIdAware
{
public static final OrgId ANY = new OrgId();
public static final OrgId MAIN = new OrgId(1000000);
int repoId;
private OrgId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Org_ID");
}
private OrgId()
{
this.repoId = Env.CTXVALUE_AD_Org_ID_Any;
}
@JsonCreator
public static OrgId ofRepoId(final int repoId)
{
final OrgId orgId = ofRepoIdOrNull(repoId);
if (orgId == null)
{
throw new AdempiereException("Invalid AD_Org_ID: " + repoId);
}
return orgId;
}
/**
* @return {@link #ANY} if the given {@code repoId} is zero; {@code null} if it is less than zero.
*/
@Nullable
public static OrgId ofRepoIdOrNull(final int repoId)
{
if (repoId == ANY.repoId)
{
return ANY;
}
else if (repoId == MAIN.repoId)
{
return MAIN;
}
else if (repoId < 0)
{
return null;
}
else
{
return new OrgId(repoId);
}
}
/**
* @return {@link #ANY} even if the given {@code repoId} is less than zero.
*/
public static OrgId ofRepoIdOrAny(final int repoId)
{
final OrgId orgId = ofRepoIdOrNull(repoId);
return orgId != null ? orgId : ANY;
}
|
public static Optional<OrgId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : -1;
}
public static int toRepoIdOrAny(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : ANY.repoId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isAny()
{
return repoId == Env.CTXVALUE_AD_Org_ID_Any;
}
/**
* @return {@code true} if the org in question is not {@code *} (i.e. "ANY"), but a specific organisation's ID
*/
public boolean isRegular()
{
return !isAny();
}
public void ifRegular(@NonNull final Consumer<OrgId> consumer)
{
if (isRegular())
{
consumer.accept(this);
}
}
@Nullable
public OrgId asRegularOrNull() {return isRegular() ? this : null;}
public static boolean equals(@Nullable final OrgId id1, @Nullable final OrgId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgId.java
| 2
|
请完成以下Java代码
|
private List<IOParameter> convertToIOParameters(String propertyName, String valueName, JsonNode elementNode) {
List<IOParameter> ioParameters = new ArrayList<IOParameter>();
JsonNode parametersNode = getProperty(propertyName, elementNode);
if (parametersNode != null) {
parametersNode = BpmnJsonConverterUtil.validateIfNodeIsTextual(parametersNode);
JsonNode itemsArrayNode = parametersNode.get(valueName);
if (itemsArrayNode != null) {
for (JsonNode itemNode : itemsArrayNode) {
JsonNode sourceNode = itemNode.get(PROPERTY_IOPARAMETER_SOURCE);
JsonNode sourceExpressionNode = itemNode.get(PROPERTY_IOPARAMETER_SOURCE_EXPRESSION);
if (
(sourceNode != null && StringUtils.isNotEmpty(sourceNode.asText())) ||
(sourceExpressionNode != null && StringUtils.isNotEmpty(sourceExpressionNode.asText()))
) {
IOParameter parameter = new IOParameter();
if (StringUtils.isNotEmpty(getValueAsString(PROPERTY_IOPARAMETER_SOURCE, itemNode))) {
parameter.setSource(getValueAsString(PROPERTY_IOPARAMETER_SOURCE, itemNode));
} else if (
|
StringUtils.isNotEmpty(getValueAsString(PROPERTY_IOPARAMETER_SOURCE_EXPRESSION, itemNode))
) {
parameter.setSourceExpression(
getValueAsString(PROPERTY_IOPARAMETER_SOURCE_EXPRESSION, itemNode)
);
}
if (StringUtils.isNotEmpty(getValueAsString(PROPERTY_IOPARAMETER_TARGET, itemNode))) {
parameter.setTarget(getValueAsString(PROPERTY_IOPARAMETER_TARGET, itemNode));
}
ioParameters.add(parameter);
}
}
}
}
return ioParameters;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\CallActivityJsonConverter.java
| 1
|
请完成以下Spring Boot application配置
|
#服务器端口
server:
port: 8200
#数据源配置
#spring:
# datasource:
# url: ${blade.datasource.dev.url}
# username: ${blade.datasource.dev.username}
# password: ${blade.datasource.dev.password}
spring:
#排除DruidDataSourceAutoConfigure
autoconfigure:
exclude: com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure
datasource:
dynamic:
#设置默认的数据源或者数据源组,默认值即为master
primary: master
datasource:
master:
url: ${blade.datasource.demo.master.url}
username: ${blade.datasource.demo.master.username}
|
password: ${blade.datasource.demo.master.password}
slave:
url: ${blade.datasource.demo.slave.url}
username: ${blade.datasource.demo.slave.username}
password: ${blade.datasource.demo.slave.password}
|
repos\SpringBlade-master\blade-service\blade-demo\src\main\resources\application-dev.yml
| 2
|
请完成以下Java代码
|
public byte hexToByte(String hexString) {
int firstDigit = toDigit(hexString.charAt(0));
int secondDigit = toDigit(hexString.charAt(1));
return (byte) ((firstDigit << 4) + secondDigit);
}
private int toDigit(char hexChar) {
int digit = Character.digit(hexChar, 16);
if(digit == -1) {
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
}
return digit;
}
public String encodeUsingBigIntegerToString(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return bigInteger.toString(16);
}
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
}
public byte[] decodeUsingBigInteger(String hexString) {
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
if (byteArray[0] == 0) {
byte[] output = new byte[byteArray.length - 1];
System.arraycopy(byteArray, 1, output, 0, output.length);
return output;
}
return byteArray;
}
public String encodeUsingDataTypeConverter(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes);
}
public byte[] decodeUsingDataTypeConverter(String hexString) {
return DatatypeConverter.parseHexBinary(hexString);
}
|
public String encodeUsingApacheCommons(byte[] bytes) {
return Hex.encodeHexString(bytes);
}
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
return Hex.decodeHex(hexString);
}
public String encodeUsingGuava(byte[] bytes) {
return BaseEncoding.base16()
.encode(bytes);
}
public byte[] decodeUsingGuava(String hexString) {
return BaseEncoding.base16()
.decode(hexString.toUpperCase());
}
public String encodeUsingHexFormat(byte[] bytes) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.formatHex(bytes);
}
public byte[] decodeUsingHexFormat(String hexString) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.parseHex(hexString);
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\conversion\HexStringConverter.java
| 1
|
请完成以下Java代码
|
public @Nullable Integer getActive() {
try {
HikariPool hikariPool = getHikariPool();
return (hikariPool != null) ? hikariPool.getActiveConnections() : null;
}
catch (Exception ex) {
return null;
}
}
@Override
public @Nullable Integer getIdle() {
try {
HikariPool hikariPool = getHikariPool();
return (hikariPool != null) ? hikariPool.getIdleConnections() : null;
}
catch (Exception ex) {
return null;
}
}
private @Nullable HikariPool getHikariPool() {
return (HikariPool) new DirectFieldAccessor(getDataSource()).getPropertyValue("pool");
}
@Override
public @Nullable Integer getMax() {
return getDataSource().getMaximumPoolSize();
|
}
@Override
public @Nullable Integer getMin() {
return getDataSource().getMinimumIdle();
}
@Override
public @Nullable String getValidationQuery() {
return getDataSource().getConnectionTestQuery();
}
@Override
public @Nullable Boolean getDefaultAutoCommit() {
return getDataSource().isAutoCommit();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\HikariDataSourcePoolMetadata.java
| 1
|
请完成以下Java代码
|
protected void fillMessage(List<DataAssociation> dataInputAssociations, DelegateExecution execution) {
for (DataAssociation dataAssociationElement : dataInputAssociations) {
AbstractDataAssociation dataAssociation = createDataInputAssociation(dataAssociationElement);
dataAssociation.evaluate(execution);
}
}
protected AbstractDataAssociation createDataInputAssociation(DataAssociation dataAssociationElement) {
if (dataAssociationElement.getAssignments().isEmpty()) {
return new MessageImplicitDataInputAssociation(
dataAssociationElement.getSourceRef(),
dataAssociationElement.getTargetRef()
);
} else {
SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(
dataAssociationElement.getSourceRef(),
dataAssociationElement.getTargetRef()
);
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
for (org.activiti.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
if (
StringUtils.isNotEmpty(assignmentElement.getFrom()) &&
StringUtils.isNotEmpty(assignmentElement.getTo())
) {
Expression from = expressionManager.createExpression(assignmentElement.getFrom());
Expression to = expressionManager.createExpression(assignmentElement.getTo());
Assignment assignment = new Assignment(from, to);
dataAssociation.addAssignment(assignment);
}
}
return dataAssociation;
}
|
}
protected AbstractDataAssociation createDataOutputAssociation(DataAssociation dataAssociationElement) {
if (StringUtils.isNotEmpty(dataAssociationElement.getSourceRef())) {
return new MessageImplicitDataOutputAssociation(
dataAssociationElement.getTargetRef(),
dataAssociationElement.getSourceRef()
);
} else {
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
Expression transformation = expressionManager.createExpression(dataAssociationElement.getTransformation());
AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(
null,
dataAssociationElement.getTargetRef(),
transformation
);
return dataOutputAssociation;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\WebServiceActivityBehavior.java
| 1
|
请完成以下Java代码
|
public class InvoiceUserNotificationsProducer
{
public static InvoiceUserNotificationsProducer newInstance()
{
return new InvoiceUserNotificationsProducer();
}
public static final Topic EVENTBUS_TOPIC = Topic.builder()
.name("de.metas.invoicecandidate.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
private static final transient Logger logger = LogManager.getLogger(InvoiceUserNotificationsProducer.class);
private static final AdMessageKey MSG_Event_InvoiceGenerated = AdMessageKey.of("Event_InvoiceGenerated");
private InvoiceUserNotificationsProducer()
{
}
/**
* Post events about given invoice that was generated.
*/
public InvoiceUserNotificationsProducer notifyGenerated(
@Nullable final I_C_Invoice invoice,
@Nullable final UserId recipientUserId)
{
if (invoice == null)
{
return this;
}
try
{
postNotification(createInvoiceGeneratedEvent(invoice, recipientUserId));
}
catch (final Exception ex)
{
logger.warn("Failed creating event for invoice {}. Ignored.", invoice, ex);
}
return this;
}
|
private UserNotificationRequest createInvoiceGeneratedEvent(
@NonNull final I_C_Invoice invoice,
@Nullable final UserId recipientUserId)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner bpartner = bpartnerDAO.getById(invoice.getC_BPartner_ID());
final String bpValue = bpartner.getValue();
final String bpName = bpartner.getName();
final TableRecordReference invoiceRef = TableRecordReference.of(invoice);
return newUserNotificationRequest()
.recipientUserId(recipientUserId != null ? recipientUserId : UserId.ofRepoId(invoice.getCreatedBy()))
.contentADMessage(MSG_Event_InvoiceGenerated)
.contentADMessageParam(invoiceRef)
.contentADMessageParam(bpValue)
.contentADMessageParam(bpName)
.targetAction(TargetRecordAction.of(invoiceRef))
.build();
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private void postNotification(final UserNotificationRequest notification)
{
Services.get(INotificationBL.class).sendAfterCommit(notification);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\invoice\event\InvoiceUserNotificationsProducer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InvoiceDAO extends AbstractInvoiceDAO
{
public static final Logger logger = LogManager.getLogger(InvoiceDAO.class);
public I_C_Invoice createInvoice(String trxName)
{
return InterfaceWrapperHelper.create(Env.getCtx(), I_C_Invoice.class, trxName);
}
@Override
public I_C_InvoiceLine createInvoiceLine(final org.compiere.model.I_C_Invoice invoice)
{
final MInvoice invoicePO = LegacyAdapters.convertToPO(invoice);
final MInvoiceLine invoiceLinePO = new MInvoiceLine(invoicePO);
return InterfaceWrapperHelper.create(invoiceLinePO, I_C_InvoiceLine.class);
}
@Override
public I_C_InvoiceLine createInvoiceLine(final String trxName)
{
return InterfaceWrapperHelper.create(Env.getCtx(), I_C_InvoiceLine.class, trxName);
}
@Override
public List<I_C_LandedCost> retrieveLandedCosts(
final I_C_InvoiceLine invoiceLine, final String whereClause,
final String trxName)
{
final List<I_C_LandedCost> list = new ArrayList<>();
String sql = "SELECT * FROM C_LandedCost WHERE C_InvoiceLine_ID=? ";
if (whereClause != null)
{
sql += whereClause;
}
final PreparedStatement pstmt = DB.prepareStatement(sql, trxName);
ResultSet rs = null;
try
{
pstmt.setInt(1, invoiceLine.getC_InvoiceLine_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
MLandedCost lc = new MLandedCost(Env.getCtx(), rs, trxName);
list.add(lc);
}
}
catch (Exception e)
{
logger.error("getLandedCost", e);
}
finally
{
DB.close(rs, pstmt);
}
|
return list;
} // getLandedCost
@Override
public I_C_LandedCost createLandedCost(String trxName)
{
return new MLandedCost(Env.getCtx(), 0, trxName);
}
@Override
public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice)
{
final MInvoice invoicePO = LegacyAdapters.convertToPO(invoice);
final MInvoiceTax[] resultArray = invoicePO.getTaxes(true);
final List<I_C_InvoiceTax> result = new ArrayList<>();
for (final MInvoiceTax tax : resultArray)
{
result.add(tax);
}
// NOTE: make sure we are returning a read-write list because some API rely on this (doing sorting)
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceDAO.java
| 2
|
请完成以下Java代码
|
public String getSummary()
{
final StringBuilder sb = new StringBuilder();
if (countImportRecordsDeleted > 0)
{
if (sb.length() > 0) {sb.append("; ");}
sb.append(countImportRecordsDeleted).append(" record(s) deleted");
}
if (countImportRecordsWithValidationErrors.isPresent() && countImportRecordsWithValidationErrors.getAsInt() > 0)
{
if (sb.length() > 0) {sb.append("; ");}
sb.append(countImportRecordsWithValidationErrors.getAsInt()).append(" validation errors encountered");
}
return sb.toString();
}
|
public boolean hasErrors()
{
return countImportRecordsWithValidationErrors.orElse(-1) > 0;
}
public String getErrorMessage()
{
int errorsCount = countImportRecordsWithValidationErrors.orElse(-1);
if (errorsCount <= 0)
{
throw new IllegalStateException("no errors expected");
}
return errorsCount + " row(s) have validation errors";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\ValidateImportRecordsResult.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonMetasfreshId
{
int value;
@JsonCreator
public static JsonMetasfreshId of(@NonNull final Object value)
{
try
{
return new JsonMetasfreshId(NumberUtils.asInt(value));
}
catch (Exception ex)
{
throw Check.mkEx("Invalid " + JsonMetasfreshId.class.getSimpleName() + ": `" + value + "` (" + value.getClass() + ")", ex);
}
}
@Nullable
public static JsonMetasfreshId ofOrNull(@Nullable final Integer value)
{
if (isEmpty(value))
{
return null;
}
return new JsonMetasfreshId(value);
}
private static boolean isEmpty(@Nullable final Integer value)
{
return value == null || value < 0;
}
private JsonMetasfreshId(@NonNull final Integer value)
{
if (value < 0)
{
throw new RuntimeException("Given value=" + value + " needs to be >=0");
}
this.value = value;
}
@JsonValue
public int getValue()
{
return value;
}
public static boolean equals(@Nullable final JsonMetasfreshId id1, @Nullable final JsonMetasfreshId id2)
{
return Objects.equals(id1, id2);
}
|
@Nullable
public static Integer toValue(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return null;
}
return externalId.getValue();
}
public static int toValueInt(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return -1;
}
return externalId.getValue();
}
public static String toValueStr(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return "-1";
}
return String.valueOf(externalId.getValue());
}
@NonNull
public static Optional<Integer> toValueOptional(@Nullable final JsonMetasfreshId externalId)
{
return Optional.ofNullable(toValue(externalId));
}
@Nullable
public static <T> T mapToOrNull(@Nullable final JsonMetasfreshId externalId, @NonNull final Function<Integer, T> mapper)
{
return toValueOptional(externalId).map(mapper).orElse(null);
}
@Nullable
public static String toValueStrOrNull(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return null;
}
return String.valueOf(externalId.getValue());
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\common\JsonMetasfreshId.java
| 2
|
请完成以下Java代码
|
public Builder setAD_Client_ID(final int AD_Client_ID)
{
this.AD_Client_ID = AD_Client_ID;
return this;
}
public Builder setAD_Org_ID(final int AD_Org_ID)
{
this.AD_Org_ID = AD_Org_ID;
return this;
}
public Builder setOldValue(final Object oldValue)
{
this.oldValue = oldValue;
return this;
}
public Builder setNewValue(final Object newValue)
{
this.newValue = newValue;
return this;
}
public Builder setEventType(final String eventType)
{
this.eventType = eventType;
return this;
}
public Builder setAD_User_ID(final int AD_User_ID)
{
|
this.AD_User_ID = AD_User_ID;
return this;
}
/**
*
* @param AD_PInstance_ID
* @return
* @task https://metasfresh.atlassian.net/browse/FRESH-314
*/
public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID)
{
this.AD_PInstance_ID = AD_PInstance_ID;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
| 1
|
请完成以下Java代码
|
public static class Mapping {
/**
* The compatibility range of this mapping.
*/
private String compatibilityRange;
/**
* The version to use for this mapping or {@code null} to use the default.
*/
private String groupId;
/**
* The groupId to use for this mapping or {@code null} to use the default.
*/
private String artifactId;
/**
* The artifactId to use for this mapping or {@code null} to use the default.
*/
private String version;
/**
* The starter setting to use for the mapping or {@code null} to use the default.
*/
private Boolean starter;
/**
* The extra Bill of Materials to use for this mapping or {@code null} to use the
* default.
*/
private String bom;
/**
* The extra repository to use for this mapping or {@code null} to use the
* default.
*/
private String repository;
@JsonIgnore
private VersionRange range;
public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return this.artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
|
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public Boolean getStarter() {
return this.starter;
}
public void setStarter(Boolean starter) {
this.starter = starter;
}
public String getBom() {
return this.bom;
}
public void setBom(String bom) {
this.bom = bom;
}
public String getRepository() {
return this.repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
public VersionRange getRange() {
return this.range;
}
public String getCompatibilityRange() {
return this.compatibilityRange;
}
public void setCompatibilityRange(String compatibilityRange) {
this.compatibilityRange = compatibilityRange;
}
public static Mapping create(String range, String groupId, String artifactId, String version, Boolean starter,
String bom, String repository) {
Mapping mapping = new Mapping();
mapping.compatibilityRange = range;
mapping.groupId = groupId;
mapping.artifactId = artifactId;
mapping.version = version;
mapping.starter = starter;
mapping.bom = bom;
mapping.repository = repository;
return mapping;
}
}
}
|
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Dependency.java
| 1
|
请完成以下Java代码
|
private static ClassViewColumnOverrides column(@NonNull final String fieldName)
{
return ClassViewColumnOverrides.builder(fieldName)
.hideIfConfiguredSysConfig(true)
.build();
}
private static ViewLayout.Builder newViewLayout()
{
return ViewLayout.builder()
//
.setHasTreeSupport(true)
.setTreeCollapsible(false)
.setTreeExpandedDepth(Integer.MAX_VALUE);
}
@Override
public ProductsToPickView createView(final @NonNull CreateViewRequest request)
{
throw new UnsupportedOperationException();
}
public ProductsToPickView createView(@NonNull final PackageableRow packageableRow)
{
final ViewId viewId = ViewId.random(PickingConstantsV2.WINDOWID_ProductsToPickView);
final ProductsToPickRowsData rowsData = rowsService.createProductsToPickRowsData(packageableRow);
final ProductsToPickView view = ProductsToPickView.builder()
.viewId(viewId)
.rowsData(rowsData)
.headerProperties(extractViewHeaderProperties(packageableRow))
//
// Picker processes:
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_PickSelected.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_MarkWillNotPickSelected.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_SetPackingInstructions.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_Request4EyesReview.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_PickAndPackSelected.class))
//
// Reviewer processes:
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_4EyesReview_ProcessAll.class))
//
.build();
viewsRepository.getViewsStorageFor(viewId).put(view);
|
return view;
}
private ViewHeaderProperties extractViewHeaderProperties(@NonNull final PackageableRow packageableRow)
{
final IMsgBL msgs = Services.get(IMsgBL.class);
return ViewHeaderProperties.builder()
.group(ViewHeaderPropertiesGroup.builder()
.entry(ViewHeaderProperty.builder()
.caption(msgs.translatable("OrderDocumentNo"))
.value(packageableRow.getOrderDocumentNo())
.build())
.entry(ViewHeaderProperty.builder()
.caption(msgs.translatable("C_BPartner_ID"))
.value(packageableRow.getCustomer().getDisplayNameTrl())
.build())
.entry(ViewHeaderProperty.builder()
.caption(msgs.translatable("PreparationDate"))
.value(packageableRow.getPreparationDate())
.build())
.build())
.build();
}
private RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass);
return RelatedProcessDescriptor.builder()
.processId(processId)
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\ProductsToPickViewFactory.java
| 1
|
请完成以下Java代码
|
private synchronized void fadeAwayAndDisposeNotificationItemNow(final NotificationItem item)
{
assertEventDispatchThread();
// do nothing if disposed
if (disposed)
{
return;
}
final NotificationItemPanel panelToDelete = notification2panel.remove(item);
if (panelToDelete == null)
{
return;
}
panelToDelete.fadeAwayAndDispose();
this.remove(panelToDelete); // remove it from container component
updateUI();
}
private void updateUI()
{
assertEventDispatchThread();
final boolean visibleNew = !notification2panel.isEmpty();
if (visibleNew)
{
revalidate();
pack();
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();// size of the screen
final Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());// height of the task bar
this.setLocation(
screenSize.width - getWidth(),
screenSize.height - screenInsets.bottom - getHeight() - (Math.max(frameBottomGap, 0)));
}
setVisible(visibleNew);
if (visibleNew)
{
repaint();
}
}
/**
* Called when a new event is received from bus
*/
private void onEvent(final Event event)
{
if (!isEligibleToBeDisplayed(event))
{
return;
}
final NotificationItem notificationItem = toNotificationItem(event);
|
// Add the notification item component (in EDT)
executeInEDTAfter(0, () -> addNotificationItemNow(notificationItem));
}
private boolean isEligibleToBeDisplayed(final Event event)
{
final int loginUserId = Env.getAD_User_ID(getCtx());
return event.hasRecipient(loginUserId);
}
private NotificationItem toNotificationItem(final Event event)
{
//
// Build summary text
final String summaryTrl = msgBL.getMsg(getCtx(), MSG_Notification_Summary_Default, new Object[] { Adempiere.getName() });
final UserNotification notification = UserNotificationUtils.toUserNotification(event);
//
// Build detail message
final StringBuilder detailBuf = new StringBuilder();
{
// Add plain detail if any
final String detailPlain = notification.getDetailPlain();
if (!Check.isEmpty(detailPlain, true))
{
detailBuf.append(detailPlain.trim());
}
// Translate, parse and add detail (AD_Message).
final String detailADMessage = notification.getDetailADMessage();
if (!Check.isEmpty(detailADMessage, true))
{
final String detailTrl = msgBL.getMsg(getCtx(), detailADMessage);
final String detailTrlParsed = EventHtmlMessageFormat.newInstance()
.setArguments(notification.getDetailADMessageParams())
.format(detailTrl);
if (!Check.isEmpty(detailTrlParsed, true))
{
if (detailBuf.length() > 0)
{
detailBuf.append("<br>");
}
detailBuf.append(detailTrlParsed);
}
}
}
return NotificationItem.builder()
.setSummary(summaryTrl)
.setDetail(detailBuf.toString())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierFrame.java
| 1
|
请完成以下Java代码
|
public void setIsReadOnly (String IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, IsReadOnly);
}
/** Get Read Only.
@return Field is read only
*/
public String getIsReadOnly ()
{
return (String)get_Value(COLUMNNAME_IsReadOnly);
}
/** IsSameLine AD_Reference_ID=319 */
public static final int ISSAMELINE_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISSAMELINE_Yes = "Y";
/** No = N */
public static final String ISSAMELINE_No = "N";
/** Set Same Line.
@param IsSameLine
Displayed on same line as previous field
*/
public void setIsSameLine (String IsSameLine)
{
set_Value (COLUMNNAME_IsSameLine, IsSameLine);
}
/** Get Same Line.
@return Displayed on same line as previous field
*/
public String getIsSameLine ()
{
return (String)get_Value(COLUMNNAME_IsSameLine);
}
/** IsUpdateable AD_Reference_ID=319 */
public static final int ISUPDATEABLE_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISUPDATEABLE_Yes = "Y";
/** No = N */
public static final String ISUPDATEABLE_No = "N";
/** Set Updateable.
@param IsUpdateable
Determines, if the field can be updated
*/
public void setIsUpdateable (String IsUpdateable)
{
set_Value (COLUMNNAME_IsUpdateable, IsUpdateable);
}
/** Get Updateable.
@return Determines, if the field can be updated
*/
public String getIsUpdateable ()
{
return (String)get_Value(COLUMNNAME_IsUpdateable);
}
/** Set Name.
|
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record Sort No.
@param SortNo
Determines in what order the records are displayed
*/
public void setSortNo (int SortNo)
{
set_Value (COLUMNNAME_SortNo, Integer.valueOf(SortNo));
}
/** Get Record Sort No.
@return Determines in what order the records are displayed
*/
public int getSortNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SortNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Field.java
| 1
|
请完成以下Java代码
|
public void setIsDisplayed (boolean IsDisplayed)
{
set_Value (COLUMNNAME_IsDisplayed, Boolean.valueOf(IsDisplayed));
}
/** Get Displayed.
@return Determines, if this field is displayed
*/
public boolean isDisplayed ()
{
Object oo = get_Value(COLUMNNAME_IsDisplayed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Included.
@param IsInclude
Defines whether this content / template is included into another one
*/
public void setIsInclude (boolean IsInclude)
{
set_Value (COLUMNNAME_IsInclude, Boolean.valueOf(IsInclude));
}
/** Get Included.
@return Defines whether this content / template is included into another one
*/
public boolean isInclude ()
{
Object oo = get_Value(COLUMNNAME_IsInclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Printed.
@param IsPrinted
Indicates if this document / line is printed
*/
public void setIsPrinted (boolean IsPrinted)
{
set_Value (COLUMNNAME_IsPrinted, Boolean.valueOf(IsPrinted));
}
/** Get Printed.
@return Indicates if this document / line is printed
*/
public boolean isPrinted ()
{
Object oo = get_Value(COLUMNNAME_IsPrinted);
if (oo != null)
|
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_PayrollConcept.java
| 1
|
请完成以下Java代码
|
public void createAndRunJob(Map<String, List<String>> jobsData) throws Exception {
List<Job> jobs = new ArrayList<>();
// Create chunk-oriented jobs
for (Map.Entry<String, List<String>> entry : jobsData.entrySet()) {
if (entry.getValue() instanceof List) {
jobs.add(createJob(entry.getKey(), entry.getValue()));
}
}
// Run all jobs
for (Job job : jobs) {
JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
jobLauncher.run(job, jobParameters);
}
|
}
private Job createJob(String jobName, List<String> data) {
return new JobBuilder(jobName, jobRepository).start(createStep(data))
.build();
}
private Step createStep(List<String> data) {
return new StepBuilder("step", jobRepository).<String, String> chunk(10, transactionManager)
.reader(new ListItemReader<>(data))
.processor(item -> item.toUpperCase())
.writer(items -> items.forEach(System.out::println))
.build();
}
}
|
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\springbatch\jobs\DynamicJobService.java
| 1
|
请完成以下Spring Boot application配置
|
nacos:
# Nacos 配置中心的配置项,对应 NacosConfigProperties 配置类
config:
server-addr: 127.0.0.1:18848 # Nacos 服务器地址
bootstrap:
enable: true # 是否开启 Nacos 配置预加载功能。默认为 false。
log-enable: true # 是否开启 Nacos 支持日志级别的加载时机。默认为 false。
data-id: example-auto-refresh # 使用的 Nacos 配置集的 dataId。
type: YAML # 使用的 Nacos 配置集的配置格式。默认为 PROPERTIES。
group: DEFAULT_GROUP # 使用的 Nacos 配置分组,默认为 DEFAULT_GROUP。
namespace: # 使用的 Nacos 的命名空间,默认为 null。
auto-refresh: true # 是否自动刷新,默认为 false。
management:
endpoint:
# Health 端点配置项,对应 HealthProperties 配置类
health:
show-de
|
tails: ALWAYS # 何时显示完整的健康信息。默认为 NEVER 都不展示。可选 WHEN_AUTHORIZED 当经过授权的用户;可选 ALWAYS 总是展示。
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
|
repos\SpringBoot-Labs-master\lab-44\lab-44-nacos-config-demo-actuator\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public class MigratingProcessElementInstanceTopDownWalker extends ReferenceWalker<MigrationContext> {
public MigratingProcessElementInstanceTopDownWalker(MigratingActivityInstance activityInstance) {
super(new MigrationContext(activityInstance, new MigratingScopeInstanceBranch()));
}
@Override
protected Collection<MigrationContext> nextElements() {
Collection<MigrationContext> nextElements = new LinkedList<MigrationContext>();
MigrationContext currentElement = getCurrentElement();
// continue migration for non-leaf instances (i.e. scopes)
if (currentElement.processElementInstance instanceof MigratingScopeInstance) {
// Child instances share the same scope instance branch;
// This ensures "once-per-parent" instantiation semantics,
// i.e. if a new parent scope is added to more than one child, all those children
// will share the same new parent instance.
// By changing the way how the branches are created here, it should be possible
// to implement other strategies, e.g. "once-per-child" semantics
MigratingScopeInstanceBranch childrenScopeBranch = currentElement.scopeInstanceBranch.copy();
MigratingScopeInstanceBranch childrenCompensationScopeBranch = currentElement.scopeInstanceBranch.copy();
MigratingScopeInstance scopeInstance = (MigratingScopeInstance) currentElement.processElementInstance;
childrenScopeBranch.visited(scopeInstance);
childrenCompensationScopeBranch.visited(scopeInstance);
for (MigratingProcessElementInstance child : scopeInstance.getChildren()) {
MigratingScopeInstanceBranch instanceBranch = null;
// compensation and non-compensation scopes cannot share the same scope instance branch
// e.g. when adding a sub process, we want to create a new activity instance as well
// as a new event scope instance for that sub process
if (child instanceof MigratingEventScopeInstance
|| child instanceof MigratingCompensationEventSubscriptionInstance) {
instanceBranch = childrenCompensationScopeBranch;
}
else {
instanceBranch = childrenScopeBranch;
}
nextElements.add(new MigrationContext(
|
child,
instanceBranch));
}
}
return nextElements;
}
public static class MigrationContext {
protected MigratingProcessElementInstance processElementInstance;
protected MigratingScopeInstanceBranch scopeInstanceBranch;
public MigrationContext(MigratingProcessElementInstance processElementInstance, MigratingScopeInstanceBranch scopeInstanceBranch) {
this.processElementInstance = processElementInstance;
this.scopeInstanceBranch = scopeInstanceBranch;
}
public MigratingProcessElementInstance getProcessElementInstance() {
return processElementInstance;
}
public MigratingScopeInstanceBranch getScopeInstanceBranch() {
return scopeInstanceBranch;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingProcessElementInstanceTopDownWalker.java
| 1
|
请完成以下Java代码
|
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Integer getResourceType() {
return resourceType;
}
public void setResourceType(Integer resourceType) {
this.resourceType = resourceType;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
|
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
private static Permission[] getPermissions(Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) {
int givenResourceType = dbAuthorization.getResourceType();
Permission[] permissionsByResourceType = ((ProcessEngineConfigurationImpl) engineConfiguration).getPermissionProvider().getPermissionsForResource(givenResourceType);
return dbAuthorization.getPermissions(permissionsByResourceType);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationDto.java
| 1
|
请完成以下Java代码
|
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPeriod_OpenFuture (final int Period_OpenFuture)
{
set_Value (COLUMNNAME_Period_OpenFuture, Period_OpenFuture);
}
@Override
public int getPeriod_OpenFuture()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenFuture);
}
@Override
public void setPeriod_OpenHistory (final int Period_OpenHistory)
{
set_Value (COLUMNNAME_Period_OpenHistory, Period_OpenHistory);
}
@Override
public int getPeriod_OpenHistory()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenHistory);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
|
/**
* TaxCorrectionType AD_Reference_ID=392
* Reference name: C_AcctSchema TaxCorrectionType
*/
public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392;
/** None = N */
public static final String TAXCORRECTIONTYPE_None = "N";
/** Write_OffOnly = W */
public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */
public static final String TAXCORRECTIONTYPE_DiscountOnly = "D";
/** Write_OffAndDiscount = B */
public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B";
@Override
public void setTaxCorrectionType (final java.lang.String TaxCorrectionType)
{
set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType);
}
@Override
public java.lang.String getTaxCorrectionType()
{
return get_ValueAsString(COLUMNNAME_TaxCorrectionType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java
| 1
|
请完成以下Java代码
|
public Set<CtxName> getParameters()
{
return PARAMETERS;
}
@Override
public String evaluate(final Evaluatee ctx, final IExpressionEvaluator.OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
final ClientId adClientId = Optional.ofNullable(ctx.get_ValueAsInt(PARAMETER_AD_Client_ID, null))
.map(ClientId::ofRepoId)
.orElseGet(() -> ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx())));
final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class);
final String sequenceNo = documentNoFactory.forSequenceId(sequenceId)
.setFailOnError(onVariableNotFound.equals(IExpressionEvaluator.OnVariableNotFound.Fail))
.setClientId(adClientId)
.build();
if (sequenceNo == null && onVariableNotFound == IExpressionEvaluator.OnVariableNotFound.Fail)
|
{
throw new AdempiereException("Failed to compute sequence!")
.appendParametersToMessage()
.setParameter("sequenceId", sequenceId);
}
return sequenceNo;
}
@NonNull
public static DocSequenceAwareFieldStringExpression of(@NonNull final DocSequenceId sequenceId)
{
return new DocSequenceAwareFieldStringExpression(sequenceId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocSequenceAwareFieldStringExpression.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ProcessApplicationDeploymentBuilderImpl enableDuplicateFiltering(boolean deployChangedOnly) {
return (ProcessApplicationDeploymentBuilderImpl) super.enableDuplicateFiltering(deployChangedOnly);
}
@Override
public ProcessApplicationDeploymentBuilderImpl addDeploymentResources(String deploymentId) {
return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResources(deploymentId);
}
@Override
public ProcessApplicationDeploymentBuilderImpl addDeploymentResourceById(String deploymentId, String resourceId) {
return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourceById(deploymentId, resourceId);
}
@Override
public ProcessApplicationDeploymentBuilderImpl addDeploymentResourcesById(String deploymentId, List<String> resourceIds) {
return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourcesById(deploymentId, resourceIds);
}
@Override
public ProcessApplicationDeploymentBuilderImpl addDeploymentResourceByName(String deploymentId, String resourceName) {
return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourceByName(deploymentId, resourceName);
}
@Override
public ProcessApplicationDeploymentBuilderImpl addDeploymentResourcesByName(String deploymentId, List<String> resourceNames) {
|
return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourcesByName(deploymentId, resourceNames);
}
// getters / setters ///////////////////////////////////////////////
public boolean isResumePreviousVersions() {
return isResumePreviousVersions;
}
public ProcessApplicationReference getProcessApplicationReference() {
return processApplicationReference;
}
public String getResumePreviousVersionsBy() {
return resumePreviousVersionsBy;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\ProcessApplicationDeploymentBuilderImpl.java
| 2
|
请完成以下Java代码
|
public void removingEventScope(PvmExecutionImpl childExecution) {
logDebug(
"006", "Removeing event scope {}", childExecution);
}
public void interruptingExecution(String reason, boolean skipCustomListeners) {
logDebug(
"007", "Interrupting execution execution {}, {}", reason, skipCustomListeners);
}
public void debugEnterActivityInstance(PvmExecutionImpl pvmExecutionImpl, String parentActivityInstanceId) {
logDebug(
"008", "Enter activity instance {} parent: {}", pvmExecutionImpl, parentActivityInstanceId);
}
public void exceptionWhileCompletingSupProcess(PvmExecutionImpl execution, Exception e) {
logError(
"009", "Exception while completing subprocess of execution {}", execution, e);
}
|
public void createScope(PvmExecutionImpl execution, PvmExecutionImpl propagatingExecution) {
logDebug(
"010", "Create scope: parent exection {} continues as {}", execution, propagatingExecution);
}
public ProcessEngineException scopeNotFoundException(String activityId, String executionId) {
return new ProcessEngineException(exceptionMessage(
"011",
"Scope with specified activity Id {} and execution {} not found",
activityId,executionId
));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\PvmLogger.java
| 1
|
请完成以下Java代码
|
public int getMD_Candidate_QtyDetails_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_QtyDetails_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setStock_MD_Candidate_ID (final int Stock_MD_Candidate_ID)
{
if (Stock_MD_Candidate_ID < 1)
set_Value (COLUMNNAME_Stock_MD_Candidate_ID, null);
else
set_Value (COLUMNNAME_Stock_MD_Candidate_ID, Stock_MD_Candidate_ID);
}
@Override
public int getStock_MD_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_Stock_MD_Candidate_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_QtyDetails.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.