instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class JsonResponseUpsertItem
{
public enum SyncOutcome
{
CREATED,
@ApiEnum("Master data was updated; note that it's possible that nothing really changed due to the update.")
UPDATED,
@ApiEnum("E.g. if a location already exists and the sync advise is to not change existing entities.")
NOTHING_DONE
}
@ApiModelProperty(value = "The identifier that was specified in the repective upsert request",//
position = 10)
String identifier;
@ApiModelProperty(value = "The metasfresh-ID of the upserted record.\n"
+ "Can be null if the respective resource did not exist and the sync-advise indicated to do nothing.",//
position = 20, dataType = "java.lang.Long")
JsonMetasfreshId metasfreshId;
|
SyncOutcome syncOutcome;
@Builder
@JsonCreator
public JsonResponseUpsertItem(
@JsonProperty("identifier") @NonNull final String identifier,
@JsonProperty("metasfreshId") @Nullable final JsonMetasfreshId metasfreshId,
@JsonProperty("syncOutcome") @NonNull final SyncOutcome syncOutcome)
{
this.identifier = identifier;
this.metasfreshId = metasfreshId;
this.syncOutcome = syncOutcome;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\response\JsonResponseUpsertItem.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ITemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) {
|
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
final List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Bean(name = "multipartResolver")
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\spring\web\config\WebConfig.java
| 2
|
请完成以下Java代码
|
public ImpliedRoles role(String role) {
Assert.hasText(role, "role must not be empty");
return new ImpliedRoles(role);
}
/**
* Builds and returns a {@link RoleHierarchyImpl} describing the defined role
* hierarchy.
* @return a {@link RoleHierarchyImpl}
*/
public RoleHierarchyImpl build() {
return new RoleHierarchyImpl(this.hierarchy);
}
private Builder addHierarchy(String role, String... impliedRoles) {
Set<GrantedAuthority> withPrefix = this.hierarchy.computeIfAbsent(this.rolePrefix.concat(role),
(r) -> new HashSet<>());
for (String impliedRole : impliedRoles) {
withPrefix.add(new SimpleGrantedAuthority(this.rolePrefix.concat(impliedRole)));
}
return this;
}
/**
* Builder class for constructing child roles within a role hierarchy branch.
*/
public final class ImpliedRoles {
private final String role;
private ImpliedRoles(String role) {
this.role = role;
}
|
/**
* Specifies implied role(s) for the current role in the hierarchy.
* @param impliedRoles role name(s) implied by the role.
* @return the same {@link Builder} instance
* @throws IllegalArgumentException if <code>impliedRoles</code> is null,
* empty or contains any null element.
*/
public Builder implies(String... impliedRoles) {
Assert.notEmpty(impliedRoles, "at least one implied role must be provided");
Assert.noNullElements(impliedRoles, "implied role name(s) cannot be empty");
return Builder.this.addHierarchy(this.role, impliedRoles);
}
}
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\access\hierarchicalroles\RoleHierarchyImpl.java
| 1
|
请完成以下Java代码
|
public Object convertToValue(JsonNode jsonValue, ValueFields valueFields) {
Object convertedValue = jsonValue;
if (jsonValue != null && StringUtils.isNotBlank(javaClassFieldForJackson)) {
//can find type so long as JsonTypeInfo annotation on the class - see https://stackoverflow.com/a/28384407/9705485
JsonNode classNode = jsonValue.get(javaClassFieldForJackson);
try {
if (classNode != null) {
final String type = classNode.asText();
convertedValue = convertToType(jsonValue, type);
} else if (
valueFields.getTextValue2() != null &&
!jsonValue.getClass().getName().equals(valueFields.getTextValue2())
) {
convertedValue = convertToType(jsonValue, valueFields.getTextValue2());
}
|
} catch (ClassNotFoundException e) {
LOGGER.warn("Unable to obtain type for json variable object " + valueFields.getName(), e);
}
}
return convertedValue;
}
private Object convertToType(JsonNode jsonValue, String type) throws ClassNotFoundException {
return objectMapper.convertValue(jsonValue, loadClass(type));
}
private Class<?> loadClass(String type) throws ClassNotFoundException {
return Class.forName(type, false, this.getClass().getClassLoader());
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JsonTypeConverter.java
| 1
|
请完成以下Java代码
|
public class SUMUP_Transaction_UpdateSelectedRows extends ViewBasedProcessTemplate implements IProcessPrecondition
{
@NonNull private final SumUpService sumUpService = SpringContextHolder.instance.getBean(SumUpService.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal();
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt()
{
final Set<SumUpTransactionId> ids = getSelectedIdsAsSet();
if (ids.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final BulkUpdateByQueryResult result = sumUpService.bulkUpdateTransactions(SumUpTransactionQuery.ofLocalIds(ids), true);
return result.getSummary().translate(Env.getADLanguageOrBaseLanguage());
}
private Set<SumUpTransactionId> getSelectedIdsAsSet()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
|
return ImmutableSet.of();
}
else if (selectedRowIds.isAll())
{
return getView().streamByIds(selectedRowIds)
.map(row -> row.getId().toId(SumUpTransactionId::ofRepoId))
.collect(ImmutableSet.toImmutableSet());
}
else
{
return selectedRowIds.toIds(SumUpTransactionId::ofRepoId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup.webui\src\main\java\de\metas\payment\sumup\webui\process\SUMUP_Transaction_UpdateSelectedRows.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName().replace("EntityImpl", "")).append("[")
.append("id=").append(id)
.append(", eventType=").append(eventType);
if (activityId != null) {
sb.append(", activityId=").append(activityId);
}
if (executionId != null) {
|
sb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId);
} else if (scopeId != null) {
sb.append(", scopeId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeType=").append(scopeType)
.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeDefinitionId != null) {
if (scopeId == null) {
sb.append(", scopeType=").append(scopeType);
}
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (scopeDefinitionKey != null) {
sb.append(", scopeDefinitionKey=").append(scopeDefinitionKey);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\entity\EventSubscriptionEntityImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public final class HazelcastJpaDependencyAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(EntityManagerFactoryDependsOnPostProcessor.class)
@Conditional(OnHazelcastAndJpaCondition.class)
@Import(HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor.class)
static class HazelcastInstanceEntityManagerFactoryDependsOnConfiguration {
}
static class HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor
extends EntityManagerFactoryDependsOnPostProcessor {
HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor() {
super("hazelcastInstance");
}
}
static class OnHazelcastAndJpaCondition extends AllNestedConditions {
OnHazelcastAndJpaCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
|
}
@ConditionalOnBean(name = "hazelcastInstance")
static class HasHazelcastInstance {
}
@ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
static class HasJpa {
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\autoconfigure\HazelcastJpaDependencyAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Flux<UserVO> list() {
// 查询列表
List<UserVO> result = new ArrayList<>();
result.add(new UserVO().setId(1).setUsername("yudaoyuanma"));
result.add(new UserVO().setId(2).setUsername("woshiyutou"));
result.add(new UserVO().setId(3).setUsername("chifanshuijiao"));
// 返回列表
return Flux.fromIterable(result);
}
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/get")
public Mono<UserVO> get(@RequestParam("id") Integer id) {
// 查询用户
UserVO user = new UserVO().setId(id).setUsername("username:" + id);
// 返回
return Mono.just(user);
}
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/v2/get")
public Mono<UserVO> get2(@RequestParam("id") Integer id) {
// 查询用户
UserVO user = userService.get(id);
// 返回
return Mono.just(user);
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("add")
public Mono<Integer> add(@RequestBody Publisher<UserAddDTO> addDTO) {
// 插入用户记录,返回编号
Integer returnId = 1;
// 返回用户编号
return Mono.just(returnId);
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("add2")
public Mono<Integer> add2(Mono<UserAddDTO> addDTO) {
// 插入用户记录,返回编号
Integer returnId = 1;
// 返回用户编号
return Mono.just(returnId);
|
}
/**
* 更新指定用户编号的用户
*
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PostMapping("/update")
public Mono<Boolean> update(@RequestBody Publisher<UserUpdateDTO> updateDTO) {
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return Mono.just(success);
}
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@PostMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE
public Mono<Boolean> delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = true;
// 返回是否更新成功
return Mono.just(success);
}
}
|
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-01\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
| 2
|
请完成以下Java代码
|
public Optional<KPIZoomIntoDetailsInfo> getZoomIntoDetailsInfo(@NonNull final KPIDataRequest request)
{
final KPIDataContext context = request.getContext();
final KPITimeRangeDefaults timeRangeDefaults = request.getTimeRangeDefaults();
final TimeRange timeRange = timeRangeDefaults.createTimeRange(context.getFrom(), context.getTo());
final KPI kpi = kpiRepository.getKPI(request.getKpiId());
final KPIDatasourceType dataSourceType = kpi.getDatasourceType();
if (dataSourceType == KPIDatasourceType.SQL)
{
return Optional.of(
SQLKPIDataLoader.builder()
.permissionsProvider(kpiPermissionsProvider)
.kpi(kpi)
.timeRange(timeRange)
.context(context)
.build()
.getKPIZoomIntoDetailsInfo());
}
else
{
return Optional.empty();
}
}
//
//
// -----------------------------------------
//
//
@Value
@Builder
private static class KPIDataCacheKey
{
@NonNull KPIId kpiId;
@NonNull KPITimeRangeDefaults timeRangeDefaults;
@NonNull KPIDataContext context;
}
@Value
@ToString(exclude = "data" /* because it's too big */)
private static class KPIDataCacheValue
{
public static KPIDataCacheValue ok(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted)
{
return new KPIDataCacheValue(data, defaultMaxStaleAccepted);
}
@NonNull Instant created = SystemTime.asInstant();
|
@NonNull Duration defaultMaxStaleAccepted;
KPIDataResult data;
public KPIDataCacheValue(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted)
{
this.data = data;
this.defaultMaxStaleAccepted = defaultMaxStaleAccepted;
}
public boolean isExpired()
{
return isExpired(null);
}
public boolean isExpired(@Nullable final Duration maxStaleAccepted)
{
final Duration maxStaleAcceptedEffective = maxStaleAccepted != null
? maxStaleAccepted
: defaultMaxStaleAccepted;
final Instant now = SystemTime.asInstant();
final Duration staleActual = Duration.between(created, now);
final boolean expired = staleActual.compareTo(maxStaleAcceptedEffective) > 0;
logger.trace("isExpired={}, now={}, maxStaleAcceptedEffective={}, staleActual={}, cacheValue={}", expired, now, maxStaleAcceptedEffective, staleActual, this);
return expired;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HttpServiceProperties getHttp() {
return this.httpServiceProperties;
}
public MemcachedServerProperties getMemcached() {
return this.memcachedServerProperties;
}
public RedisServerProperties getRedis() {
return this.redisServerProperties;
}
public static class DeveloperRestApiProperties {
private static final boolean DEFAULT_START = false;
private boolean start = DEFAULT_START;
public boolean isStart() {
return this.start;
}
public void setStart(boolean start) {
this.start = start;
}
}
public static class HttpServiceProperties {
private static final boolean DEFAULT_SSL_REQUIRE_AUTHENTICATION = false;
private static final int DEFAULT_PORT = 7070;
private boolean sslRequireAuthentication = DEFAULT_SSL_REQUIRE_AUTHENTICATION;
private int port = DEFAULT_PORT;
private final DeveloperRestApiProperties developerRestApiProperties = new DeveloperRestApiProperties();
private String bindAddress;
public String getBindAddress() {
return this.bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public DeveloperRestApiProperties getDevRestApi() {
return developerRestApiProperties;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isSslRequireAuthentication() {
return this.sslRequireAuthentication;
}
public void setSslRequireAuthentication(boolean sslRequireAuthentication) {
this.sslRequireAuthentication = sslRequireAuthentication;
}
}
public static class MemcachedServerProperties {
private static final int DEFAULT_PORT = 11211;
private int port = DEFAULT_PORT;
|
private EnableMemcachedServer.MemcachedProtocol protocol = EnableMemcachedServer.MemcachedProtocol.ASCII;
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public EnableMemcachedServer.MemcachedProtocol getProtocol() {
return this.protocol;
}
public void setProtocol(EnableMemcachedServer.MemcachedProtocol protocol) {
this.protocol = protocol;
}
}
public static class RedisServerProperties {
public static final int DEFAULT_PORT = 6379;
private int port = DEFAULT_PORT;
private String bindAddress;
public String getBindAddress() {
return this.bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ServiceProperties.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Long.hashCode(createdTime);
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
|
BaseData other = (BaseData) obj;
return createdTime == other.createdTime;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BaseData [createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseData.java
| 1
|
请完成以下Java代码
|
public List<AssetProfileInfo> findAssetProfilesByTenantIdAndIds(UUID tenantId, List<UUID> assetProfileIds) {
return assetProfileRepository.findAssetProfileInfosByTenantIdAndIdIn(tenantId, assetProfileIds);
}
@Override
public AssetProfile findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(assetProfileRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public AssetProfile findByTenantIdAndName(UUID tenantId, String name) {
return DaoUtil.getData(assetProfileRepository.findByTenantIdAndName(tenantId, name));
}
@Override
public PageData<AssetProfile> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAssetProfiles(TenantId.fromUUID(tenantId), pageLink);
}
@Override
public AssetProfileId getExternalIdByInternal(AssetProfileId internalId) {
return Optional.ofNullable(assetProfileRepository.getExternalIdById(internalId.getId()))
.map(AssetProfileId::new).orElse(null);
}
@Override
public AssetProfile findDefaultEntityByTenantId(UUID tenantId) {
return findDefaultAssetProfile(TenantId.fromUUID(tenantId));
}
@Override
public List<AssetProfileInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) {
return assetProfileRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, PageRequest.of(0, limit));
}
@Override
|
public List<AssetProfileInfo> findByImageLink(String imageLink, int limit) {
return assetProfileRepository.findByImageLink(imageLink, PageRequest.of(0, limit));
}
@Override
public PageData<AssetProfile> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<AssetProfileFields> findNextBatch(UUID id, int batchSize) {
return assetProfileRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\asset\JpaAssetProfileDao.java
| 1
|
请完成以下Java代码
|
protected void addWarning(
List<ValidationError> validationErrors,
String problem,
Process process,
BaseElement baseElement,
Map<String, String> params
) {
addError(validationErrors, problem, process, baseElement, true, params);
}
protected void addError(
List<ValidationError> validationErrors,
String problem,
Process process,
BaseElement baseElement,
boolean isWarning
) {
addError(validationErrors, problem, process, baseElement, isWarning, new HashMap<>());
}
protected void addError(
List<ValidationError> validationErrors,
String problem,
Process process,
BaseElement baseElement,
boolean isWarning,
Map<String, String> params
) {
ValidationError error = new ValidationError();
error.setWarning(isWarning);
if (process != null) {
error.setProcessDefinitionId(process.getId());
error.setProcessDefinitionName(process.getName());
}
if (baseElement != null) {
error.setXmlLineNumber(baseElement.getXmlRowNumber());
|
error.setXmlColumnNumber(baseElement.getXmlColumnNumber());
}
error.setKey(problem);
error.setProblem(problem);
error.setDefaultDescription(problem);
error.setParams(params);
if (baseElement instanceof FlowElement) {
FlowElement flowElement = (FlowElement) baseElement;
error.setActivityId(flowElement.getId());
error.setActivityName(flowElement.getName());
}
addError(validationErrors, error);
}
protected void addError(List<ValidationError> validationErrors, String problem, Process process, String id) {
ValidationError error = new ValidationError();
if (process != null) {
error.setProcessDefinitionId(process.getId());
error.setProcessDefinitionName(process.getName());
}
error.setKey(problem);
error.setProblem(problem);
error.setDefaultDescription(problem);
error.setActivityId(id);
addError(validationErrors, error);
}
}
|
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\ValidatorImpl.java
| 1
|
请完成以下Java代码
|
private static LocalDate calculateEarliestDeliveryDate(final PackageableList packageables)
{
final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
return packageables.stream()
.map(Packageable::getDeliveryDate)
.filter(Objects::nonNull)
.map(date -> date.toZonedDateTime(orgDAO::getTimeZone).toLocalDate())
.filter(Objects::nonNull)
.min(LocalDate::compareTo)
.orElse(null);
}
private static Optional<InstantAndOrgId> calculateEarliestPreparationTime(final PackageableList packageables)
{
return packageables.stream()
.map(Packageable::getPreparationDate)
.filter(Objects::nonNull)
.min(InstantAndOrgId::compareTo);
}
@Override
public DocumentId getId()
{
return rowId.getDocumentId();
}
@Override
public boolean isProcessed()
{
return false;
}
@Nullable
@Override
public DocumentPath getDocumentPath()
{
// TODO Auto-generated method stub
return null;
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
|
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
public boolean isLocked()
{
return lockedByUser != null;
}
public boolean isNotLocked()
{
return !isLocked();
}
public boolean isLockedBy(@NonNull final UserId userId)
{
return lockedByUser != null
&& UserId.equals(userId, lockedByUser.getIdAs(UserId::ofRepoId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableRow.java
| 1
|
请完成以下Java代码
|
public ActivityImpl findCompensationHandler() {
String compensationHandlerId = (String) getProperty(BpmnParse.PROPERTYNAME_COMPENSATION_HANDLER_ID);
if(compensationHandlerId != null) {
return getProcessDefinition().findActivity(compensationHandlerId);
} else {
return null;
}
}
/**
* Indicates whether activity is a multi instance activity.
*
* @return true if this activity is a multi instance activity.
*/
public boolean isMultiInstance() {
Boolean isMultiInstance = (Boolean) getProperty(BpmnParse.PROPERTYNAME_IS_MULTI_INSTANCE);
return Boolean.TRUE.equals(isMultiInstance);
}
public boolean isTriggeredByEvent() {
Boolean isTriggeredByEvent = getProperties().get(BpmnProperties.TRIGGERED_BY_EVENT);
return Boolean.TRUE.equals(isTriggeredByEvent);
}
//============================================================================
//===============================DELEGATES====================================
//============================================================================
/**
* The delegate for the async before attribute update.
*/
protected AsyncBeforeUpdate delegateAsyncBeforeUpdate;
/**
* The delegate for the async after attribute update.
*/
protected AsyncAfterUpdate delegateAsyncAfterUpdate;
public AsyncBeforeUpdate getDelegateAsyncBeforeUpdate() {
return delegateAsyncBeforeUpdate;
}
public void setDelegateAsyncBeforeUpdate(AsyncBeforeUpdate delegateAsyncBeforeUpdate) {
this.delegateAsyncBeforeUpdate = delegateAsyncBeforeUpdate;
}
public AsyncAfterUpdate getDelegateAsyncAfterUpdate() {
return delegateAsyncAfterUpdate;
}
public void setDelegateAsyncAfterUpdate(AsyncAfterUpdate delegateAsyncAfterUpdate) {
this.delegateAsyncAfterUpdate = delegateAsyncAfterUpdate;
}
|
/**
* Delegate interface for the asyncBefore property update.
*/
public interface AsyncBeforeUpdate {
/**
* Method which is called if the asyncBefore property should be updated.
*
* @param asyncBefore the new value for the asyncBefore flag
* @param exclusive the exclusive flag
*/
public void updateAsyncBefore(boolean asyncBefore, boolean exclusive);
}
/**
* Delegate interface for the asyncAfter property update
*/
public interface AsyncAfterUpdate {
/**
* Method which is called if the asyncAfter property should be updated.
*
* @param asyncAfter the new value for the asyncBefore flag
* @param exclusive the exclusive flag
*/
public void updateAsyncAfter(boolean asyncAfter, boolean exclusive);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ActivityImpl.java
| 1
|
请完成以下Java代码
|
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessingTag (final @Nullable java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
@Override
public java.lang.String getProcessingTag()
|
{
return get_ValueAsString(COLUMNNAME_ProcessingTag);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Index_Queue.java
| 1
|
请完成以下Java代码
|
private void addTempFile(Path group, Path file) {
this.temporaryFiles.compute(group, (path, paths) -> {
List<Path> newPaths = (paths != null) ? paths : new ArrayList<>();
newPaths.add(file);
return newPaths;
});
}
/**
* Clean all the temporary files that are related to this root directory.
* @param dir the directory to clean
* @see #createDistributionFile
*/
public void cleanTempFiles(Path dir) {
List<Path> tempFiles = this.temporaryFiles.remove(dir);
if (!tempFiles.isEmpty()) {
tempFiles.forEach((path) -> {
try {
FileSystemUtils.deleteRecursively(path);
}
catch (IOException ex) {
// Continue
}
});
}
}
private byte[] generateBuild(ProjectGenerationContext context) throws IOException {
ProjectDescription description = context.getBean(ProjectDescription.class);
StringWriter out = new StringWriter();
BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class).getIfAvailable();
if (buildWriter != null) {
buildWriter.writeBuild(out);
return out.toString().getBytes();
}
|
else {
throw new IllegalStateException("No BuildWriter implementation found for " + description.getLanguage());
}
}
private void customizeProjectGenerationContext(AnnotationConfigApplicationContext context,
InitializrMetadata metadata) {
context.setParent(this.parentApplicationContext);
context.registerBean(InitializrMetadata.class, () -> metadata);
context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(metadata,
context.getBean(ProjectDescription.class).getPlatformVersion()));
context.registerBean(MetadataProjectDescriptionCustomizer.class,
() -> new MetadataProjectDescriptionCustomizer(metadata));
}
private void publishProjectGeneratedEvent(R request, ProjectGenerationContext context) {
InitializrMetadata metadata = context.getBean(InitializrMetadata.class);
ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, metadata);
this.eventPublisher.publishEvent(event);
}
private void publishProjectFailedEvent(R request, InitializrMetadata metadata, Exception cause) {
ProjectFailedEvent event = new ProjectFailedEvent(request, metadata, cause);
this.eventPublisher.publishEvent(event);
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectGenerationInvoker.java
| 1
|
请完成以下Java代码
|
public class Utils {
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
private Utils() {
}
/**
* Download the content of the given url and save it into a file.
* @param url
* @param file
*/
public static void downloadAndSave(String url, File file) throws IOException {
CloseableHttpClient client = HttpClientBuilder.create()
.build();
logger.info("Connecting to {}", url);
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
HttpEntity entity = response.getEntity();
if (entity != null) {
logger.info("Downloaded {} bytes", entity.getContentLength());
try (FileOutputStream outstream = new FileOutputStream(file)) {
logger.info("Saving to the local file");
entity.writeTo(outstream);
outstream.flush();
logger.info("Local file saved");
}
}
}
}
/**
* Extract a "tar.gz" file into a given folder.
* @param file
* @param folder
*/
public static void extractTarArchive(File file, String folder) throws IOException {
logger.info("Extracting archive {} into folder {}", file.getName(), folder);
// @formatter:off
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
GzipCompressorInputStream gzip = new GzipCompressorInputStream(bis);
TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) {
// @formatter:on
TarArchiveEntry entry;
while ((entry = (TarArchiveEntry) tar.getNextEntry()) != null) {
extractEntry(entry, tar, folder);
}
}
|
logger.info("Archive extracted");
}
/**
* Extract an entry of the input stream into a given folder
* @param entry
* @param tar
* @param folder
* @throws IOException
*/
public static void extractEntry(ArchiveEntry entry, InputStream tar, String folder) throws IOException {
final int bufferSize = 4096;
final String path = folder + entry.getName();
if (entry.isDirectory()) {
new File(path).mkdirs();
} else {
int count;
byte[] data = new byte[bufferSize];
// @formatter:off
try (FileOutputStream os = new FileOutputStream(path);
BufferedOutputStream dest = new BufferedOutputStream(os, bufferSize)) {
// @formatter:off
while ((count = tar.read(data, 0, bufferSize)) != -1) {
dest.write(data, 0, count);
}
}
}
}
}
|
repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\logreg\Utils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getAD_User_Performing_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Performing_ID);
}
@Override
public void setBookedDate (final java.sql.Timestamp BookedDate)
{
set_Value (COLUMNNAME_BookedDate, BookedDate);
}
@Override
public java.sql.Timestamp getBookedDate()
{
return get_ValueAsTimestamp(COLUMNNAME_BookedDate);
}
@Override
public void setBookedSeconds (final @Nullable BigDecimal BookedSeconds)
{
set_Value (COLUMNNAME_BookedSeconds, BookedSeconds);
}
@Override
public BigDecimal getBookedSeconds()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_BookedSeconds);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setComments (final @Nullable java.lang.String Comments)
{
set_Value (COLUMNNAME_Comments, Comments);
}
@Override
public java.lang.String getComments()
{
return get_ValueAsString(COLUMNNAME_Comments);
}
@Override
public void setHoursAndMinutes (final java.lang.String HoursAndMinutes)
{
set_Value (COLUMNNAME_HoursAndMinutes, HoursAndMinutes);
}
@Override
public java.lang.String getHoursAndMinutes()
{
return get_ValueAsString(COLUMNNAME_HoursAndMinutes);
}
@Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue()
{
return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class);
}
|
@Override
public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
@Override
public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
}
@Override
public void setS_TimeBooking_ID (final int S_TimeBooking_ID)
{
if (S_TimeBooking_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, S_TimeBooking_ID);
}
@Override
public int getS_TimeBooking_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeBooking_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_TimeBooking.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static boolean between(
@NonNull final LocalDate date,
@Nullable final LocalDate dateFrom,
@Nullable final LocalDate dateTo)
{
if (dateFrom != null && dateFrom.compareTo(date) > 0)
{
return false;
}
return dateTo == null || date.compareTo(dateTo) <= 0;
}
public static String getDayName(@NonNull final LocalDate date, @NonNull final Locale locale)
{
|
return date.format(DateTimeFormatter.ofPattern("EEEE", locale));
}
public static ArrayList<LocalDate> getDaysList(final LocalDate startDate, final LocalDate endDate)
{
final ArrayList<LocalDate> result = new ArrayList<>();
for (LocalDate date = startDate; date.compareTo(endDate) <= 0; date = date.plusDays(1))
{
result.add(date);
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\DateUtils.java
| 2
|
请完成以下Java代码
|
public void setAuftragsreferenzNr(String auftragsreferenzNr) {
this.auftragsreferenzNr = auftragsreferenzNr;
}
public String getBezugsrefernznr() {
return bezugsrefernznr;
}
public void setBezugsrefernznr(String bezugsrefernznr) {
this.bezugsrefernznr = bezugsrefernznr;
}
public BigInteger getAuszugsNr() {
return auszugsNr;
}
public void setAuszugsNr(BigInteger auszugsNr) {
this.auszugsNr = auszugsNr;
}
public Saldo getAnfangsSaldo() {
return anfangsSaldo;
}
public void setAnfangsSaldo(Saldo anfangsSaldo) {
this.anfangsSaldo = anfangsSaldo;
}
public Saldo getSchlussSaldo() {
return schlussSaldo;
|
}
public void setSchlussSaldo(Saldo schlussSaldo) {
this.schlussSaldo = schlussSaldo;
}
public Saldo getAktuellValutenSaldo() {
return aktuellValutenSaldo;
}
public void setAktuellValutenSaldo(Saldo aktuellValutenSaldo) {
this.aktuellValutenSaldo = aktuellValutenSaldo;
}
public Saldo getZukunftValutenSaldo() {
return zukunftValutenSaldo;
}
public void setZukunftValutenSaldo(Saldo zukunftValutenSaldo) {
this.zukunftValutenSaldo = zukunftValutenSaldo;
}
public List<BankstatementLine> getLines() {
return lines;
}
public void setLines(List<BankstatementLine> lines) {
this.lines = lines;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Bankstatement.java
| 1
|
请完成以下Java代码
|
public FacetCollectorRequestBuilder<ModelType> excludeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.exclude(facetCategory);
return this;
}
/**
*
* @param facetCategory
* @return true if given facet category shall be considered when collecting facets
*/
public boolean acceptFacetCategory(final IFacetCategory facetCategory)
{
// Don't accept it if is excluded by includes/excludes list
if (!facetCategoryIncludesExcludes.build().test(facetCategory))
{
return false;
}
// Only categories which have "eager refresh" set (if asked)
if (onlyEagerRefreshCategories && !facetCategory.isEagerRefresh())
{
|
return false;
}
// accept the facet category
return true;
}
/**
* Collect facets only for categories which have {@link IFacetCategory#isEagerRefresh()}.
*/
public FacetCollectorRequestBuilder<ModelType> setOnlyEagerRefreshCategories()
{
this.onlyEagerRefreshCategories = true;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\FacetCollectorRequestBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void attachmentToUserUpsert(@NonNull final Exchange exchange) throws ApiException
{
final Attachment attachment = exchange.getIn().getBody(Attachment.class);
final GetAttachmentRouteContext routeContext =
ProcessorHelper.getPropertyOrThrowError(exchange, GetAttachmentRouteConstants.ROUTE_PROPERTY_GET_ATTACHMENT_CONTEXT, GetAttachmentRouteContext.class);
routeContext.setAttachment(attachment);
final Users createdBy = getUserOrNull(routeContext.getUserApi(), routeContext.getApiKey(), attachment.getMetadata().getCreatedBy());
final Optional<BPUpsertCamelRequest> contactUpsertRequest = DataMapper
.usersToBPartnerUpsert(routeContext.getOrgCode(), routeContext.getRootBPartnerIdForUsers(), createdBy);
if (contactUpsertRequest.isEmpty())
{
exchange.getIn().setBody(null);
return;
}
exchange.getIn().setBody(contactUpsertRequest.get());
}
@Nullable
private Users getUserOrNull(
@NonNull final UserApi userApi,
|
@NonNull final String apiKey,
@Nullable final String userId) throws ApiException
{
if (EmptyUtil.isBlank(userId))
{
return null;
}
final Users user = userApi.getUser(apiKey, userId);
if (user == null)
{
throw new RuntimeException("No info returned for user: " + userId);
}
return user;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\GetAlbertaAttachmentRoute.java
| 2
|
请完成以下Java代码
|
public List<HistoricCaseActivityStatisticsDto> getHistoricCaseActivityStatistics(String caseDefinitionId) {
HistoryService historyService = processEngine.getHistoryService();
HistoricCaseActivityStatisticsQuery historicCaseActivityStatisticsQuery =
historyService.createHistoricCaseActivityStatisticsQuery(caseDefinitionId);
List<HistoricCaseActivityStatistics> statistics =
historicCaseActivityStatisticsQuery.unlimitedList();
List<HistoricCaseActivityStatisticsDto> result = new ArrayList<HistoricCaseActivityStatisticsDto>();
for (HistoricCaseActivityStatistics currentStatistics : statistics) {
result.add(HistoricCaseActivityStatisticsDto.fromHistoricCaseActivityStatistics(currentStatistics));
}
return result;
}
@Override
public List<CleanableHistoricCaseInstanceReportResultDto> getCleanableHistoricCaseInstanceReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
CleanableHistoricCaseInstanceReportDto queryDto = new CleanableHistoricCaseInstanceReportDto(objectMapper, uriInfo.getQueryParameters());
CleanableHistoricCaseInstanceReport query = queryDto.toQuery(processEngine);
List<CleanableHistoricCaseInstanceReportResult> reportResult = QueryUtil.list(query, firstResult, maxResults);
|
return CleanableHistoricCaseInstanceReportResultDto.convert(reportResult);
}
@Override
public CountResultDto getCleanableHistoricCaseInstanceReportCount(UriInfo uriInfo) {
CleanableHistoricCaseInstanceReportDto queryDto = new CleanableHistoricCaseInstanceReportDto(objectMapper, uriInfo.getQueryParameters());
queryDto.setObjectMapper(objectMapper);
CleanableHistoricCaseInstanceReport query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricCaseDefinitionRestServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CreateAllAttributeSetsCommand
{
@NonNull
List<AttributeListValue> attributeListValues;
public static CreateAllAttributeSetsCommand withValues(@NonNull final List<AttributeListValue> attributeListValues)
{
return new CreateAllAttributeSetsCommand(attributeListValues);
}
@NonNull
public List<ImmutableAttributeSet> run()
{
if (attributeListValues.isEmpty())
{ // get this corner-case out of the way first
return ImmutableList.of();
}
// group our attribute values
final MultiValueMap<AttributeId, AttributeListValue> attributeId2Values = new MultiValueMap<>();
final LinkedHashSet<AttributeId> attributeIdsSet = new LinkedHashSet<>();
for (final AttributeListValue attributeListValue : attributeListValues)
{
attributeId2Values.add(attributeListValue.getAttributeId(), attributeListValue);
attributeIdsSet.add(attributeListValue.getAttributeId());
}
final ImmutableList<AttributeId> attributeIds = attributeIdsSet.stream().collect(ImmutableList.toImmutableList());
// we will create plenty of builders & eventually sets from this first one
final ImmutableAttributeSet.Builder builder = ImmutableAttributeSet.builder();
final List<ImmutableAttributeSet.Builder> builderList = recurse(0, attributeIds, attributeId2Values, builder);
return builderList.stream()
.map(ImmutableAttributeSet.Builder::build)
.collect(ImmutableList.toImmutableList());
}
private List<ImmutableAttributeSet.Builder> recurse(
final int currendAttributeIdIdx,
@NonNull final List<AttributeId> attributeIds,
@NonNull final MultiValueMap<AttributeId, AttributeListValue> attributeId2Values,
@NonNull final ImmutableAttributeSet.Builder builder)
|
{
final LinkedList<ImmutableAttributeSet.Builder> result = new LinkedList<>();
final AttributeId currentAttributeId = attributeIds.get(currendAttributeIdIdx);
final List<AttributeListValue> valuesForCurrentAttribute = attributeId2Values.get(currentAttributeId);
for (final AttributeListValue attributeListValue : valuesForCurrentAttribute)
{
final ImmutableAttributeSet.Builder copy = builder.createCopy();
copy.attributeValue(attributeListValue);
final int nextAttributeIdIdx = currendAttributeIdIdx + 1;
final boolean listContainsMore = attributeIds.size() > nextAttributeIdIdx;
if (listContainsMore)
{
result.addAll(recurse(nextAttributeIdIdx, attributeIds, attributeId2Values, copy));
}
else
{
result.add(copy);
}
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\CreateAllAttributeSetsCommand.java
| 2
|
请完成以下Java代码
|
private void setEndDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getEndDate() != null)
{
contract.setEndDate(importRecord.getEndDate());
}
}
private void setMasterStartdDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getMasterStartDate() != null)
{
contract.setMasterStartDate(importRecord.getMasterStartDate());
}
}
private void setMasterEnddDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getMasterEndDate() != null)
{
contract.setMasterEndDate(importRecord.getMasterEndDate());
}
}
private boolean isEndedContract(@NonNull final I_I_Flatrate_Term importRecord)
{
final Timestamp contractEndDate = importRecord.getEndDate();
final Timestamp today = SystemTime.asDayTimestamp();
return contractEndDate != null && today.after(contractEndDate);
}
private void endContractIfNeeded(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (isEndedContract(importRecord))
|
{
contract.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_Quit);
contract.setNoticeDate(contract.getEndDate());
contract.setIsAutoRenew(false);
contract.setProcessed(true);
contract.setDocAction(X_C_Flatrate_Term.DOCACTION_None);
contract.setDocStatus(X_C_Flatrate_Term.DOCSTATUS_Completed);
}
}
private void setTaxCategoryAndIsTaxIncluded(@NonNull final I_C_Flatrate_Term newTerm)
{
final IPricingResult pricingResult = calculateFlatrateTermPrice(newTerm);
newTerm.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingResult.getTaxCategoryId()));
newTerm.setIsTaxIncluded(pricingResult.isTaxIncluded());
}
private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm)
{
return FlatrateTermPricing.builder()
.termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID()))
.qty(newTerm.getPlannedQtyPerUnit())
.term(newTerm)
.priceDate(TimeUtil.asLocalDate(newTerm.getStartDate()))
.build()
.computeOrThrowEx();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImporter.java
| 1
|
请完成以下Java代码
|
public PropertyChangeListener[] getPropertyChangeListeners(final String propertyName)
{
return delegate.getPropertyChangeListeners(propertyName);
}
public boolean hasListeners(final String propertyName)
{
return delegate.hasListeners(propertyName);
}
public final void firePropertyChange(final PropertyChangeEvent event)
{
if (delayedEvents != null)
{
delayedEvents.add(event);
}
else
{
delegate.firePropertyChange(event);
}
}
public void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue)
{
final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event);
}
public void firePropertyChange(final String propertyName, final int oldValue, final int newValue)
{
final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event);
}
public void firePropertyChange(final String propertyName, final boolean oldValue, final boolean newValue)
{
final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event);
}
|
public void fireIndexedPropertyChange(final String propertyName, final int index, final Object oldValue, final Object newValue)
{
final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index);
firePropertyChange(event);
}
public void fireIndexedPropertyChange(final String propertyName, final int index, final int oldValue, final int newValue)
{
final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index);
firePropertyChange(event);
}
public void fireIndexedPropertyChange(final String propertyName, final int index, final boolean oldValue, final boolean newValue)
{
final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index);
firePropertyChange(event);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\DelayedPropertyChangeSupport.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode() {
return Objects.hash(_id, name, type, ikNumber, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Payer {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" ikNumber: ").append(toIndentedString(ikNumber)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
|
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Payer.java
| 2
|
请完成以下Java代码
|
public List<FlowableEventListener> getEventListeners() {
return eventListeners;
}
public AbstractServiceConfiguration<S> setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners;
return this;
}
public Map<String, List<FlowableEventListener>> getTypedEventListeners() {
return typedEventListeners;
}
public AbstractServiceConfiguration<S> setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
public List<EventDispatchAction> getAdditionalEventDispatchActions() {
return additionalEventDispatchActions;
}
public AbstractServiceConfiguration<S> setAdditionalEventDispatchActions(List<EventDispatchAction> additionalEventDispatchActions) {
this.additionalEventDispatchActions = additionalEventDispatchActions;
return this;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public AbstractServiceConfiguration<S> setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
|
}
public Clock getClock() {
return clock;
}
public AbstractServiceConfiguration<S> setClock(Clock clock) {
this.clock = clock;
return this;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public AbstractServiceConfiguration<S> setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractServiceConfiguration.java
| 1
|
请完成以下Java代码
|
public class MapEntry<K, V> {
private K key;
private V value;
public MapEntry() {
super();
}
// generic constructor with two parameters
public MapEntry(K key, V value) {
this.key = key;
this.value = value;
}
// getters and setters
public K getKey() {
|
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-generics-2\src\main\java\com\baeldung\generics\MapEntry.java
| 1
|
请完成以下Java代码
|
String description() {
return "Account description";
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String get$ignored() {
return $ignored;
}
public void set$ignored(String value) {
this.$ignored = value;
}
}
|
repos\tutorials-master\lombok-modules\lombok-2\src\main\java\com\baeldung\lombok\tostring\Account.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TwilioSmsSender extends AbstractSmsSender {
private static final Pattern PHONE_NUMBERS_SID_MESSAGE_SERVICE_SID = Pattern.compile("^(PN|MG).*$");
private TwilioRestClient twilioRestClient;
private String numberFrom;
private String validatePhoneTwilioNumber(String phoneNumber) throws SmsParseException {
phoneNumber = phoneNumber.trim();
if (!E_164_PHONE_NUMBER_PATTERN.matcher(phoneNumber).matches() && !PHONE_NUMBERS_SID_MESSAGE_SERVICE_SID.matcher(phoneNumber).matches()) {
throw new SmsParseException("Invalid phone number format. Phone number must be in E.164 format/Phone Number's SID/Messaging Service SID.");
}
return phoneNumber;
}
public TwilioSmsSender(TwilioSmsProviderConfiguration config) {
if (StringUtils.isEmpty(config.getAccountSid()) || StringUtils.isEmpty(config.getAccountToken()) || StringUtils.isEmpty(config.getNumberFrom())) {
throw new IllegalArgumentException("Invalid twilio sms provider configuration: accountSid, accountToken and numberFrom should be specified!");
}
this.numberFrom = this.validatePhoneTwilioNumber(config.getNumberFrom());
this.twilioRestClient = new TwilioRestClient.Builder(config.getAccountSid(), config.getAccountToken()).build();
|
}
@Override
public int sendSms(String numberTo, String message) throws SmsException {
numberTo = this.validatePhoneNumber(numberTo);
message = this.prepareMessage(message);
try {
String numSegments = Message.creator(new PhoneNumber(numberTo), new PhoneNumber(this.numberFrom), message).create(this.twilioRestClient).getNumSegments();
return Integer.valueOf(numSegments);
} catch (Exception e) {
throw new SmsSendException("Failed to send SMS message - " + e.getMessage(), e);
}
}
@Override
public void destroy() {
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sms\twilio\TwilioSmsSender.java
| 2
|
请完成以下Java代码
|
public List<ExecutionDto> queryExecutions(
ExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
ExecutionQuery query = queryDto.toQuery(engine);
List<Execution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults);
List<ExecutionDto> executionResults = new ArrayList<ExecutionDto>();
for (Execution execution : matchingExecutions) {
ExecutionDto resultExecution = ExecutionDto.fromExecution(execution);
executionResults.add(resultExecution);
}
return executionResults;
}
@Override
|
public CountResultDto getExecutionsCount(UriInfo uriInfo) {
ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryExecutionsCount(queryDto);
}
@Override
public CountResultDto queryExecutionsCount(ExecutionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
ExecutionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ExecutionRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public class Employee {
private String id;
private String name;
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
public Employee() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
|
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id);
}
@Override public int hashCode() {
return Objects.hash(id);
}
}
|
repos\tutorials-master\spring-web-modules\spring-resttemplate\src\main\java\com\baeldung\resttemplate\web\model\Employee.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Boolean getDetectSupported() {
return this.detectSupported;
}
public void setDetectSupported(@Nullable Boolean detectSupported) {
this.detectSupported = detectSupported;
}
public Use getUse() {
return this.use;
}
public static class Use {
/**
* Use the HTTP header with the given name to obtain the version.
*/
private @Nullable String header;
/**
* Use the query parameter with the given name to obtain the version.
*/
private @Nullable String queryParameter;
/**
* Use the path segment at the given index to obtain the version.
*/
private @Nullable Integer pathSegment;
/**
* Use the media type parameter with the given name to obtain the version.
*/
private Map<MediaType, String> mediaTypeParameter = new LinkedHashMap<>();
public @Nullable String getHeader() {
return this.header;
}
public void setHeader(@Nullable String header) {
this.header = header;
}
public @Nullable String getQueryParameter() {
return this.queryParameter;
}
|
public void setQueryParameter(@Nullable String queryParameter) {
this.queryParameter = queryParameter;
}
public @Nullable Integer getPathSegment() {
return this.pathSegment;
}
public void setPathSegment(@Nullable Integer pathSegment) {
this.pathSegment = pathSegment;
}
public Map<MediaType, String> getMediaTypeParameter() {
return this.mediaTypeParameter;
}
public void setMediaTypeParameter(Map<MediaType, String> mediaTypeParameter) {
this.mediaTypeParameter = mediaTypeParameter;
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\WebFluxProperties.java
| 2
|
请完成以下Java代码
|
public void setPO_PricingSystem_ID (final int PO_PricingSystem_ID)
{
if (PO_PricingSystem_ID < 1)
set_Value (COLUMNNAME_PO_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_PO_PricingSystem_ID, PO_PricingSystem_ID);
}
@Override
public int getPO_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_PO_PricingSystem_ID);
}
@Override
public void setPriceMatchTolerance (final @Nullable BigDecimal PriceMatchTolerance)
{
set_Value (COLUMNNAME_PriceMatchTolerance, PriceMatchTolerance);
}
@Override
public BigDecimal getPriceMatchTolerance()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceMatchTolerance);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* PriorityBase AD_Reference_ID=350
* Reference name: C_BP_Group PriorityBase
*/
public static final int PRIORITYBASE_AD_Reference_ID=350;
/** Same = S */
public static final String PRIORITYBASE_Same = "S";
/** Lower = L */
public static final String PRIORITYBASE_Lower = "L";
/** Higher = H */
public static final String PRIORITYBASE_Higher = "H";
@Override
public void setPriorityBase (final @Nullable java.lang.String PriorityBase)
{
set_Value (COLUMNNAME_PriorityBase, PriorityBase);
}
@Override
public java.lang.String getPriorityBase()
{
return get_ValueAsString(COLUMNNAME_PriorityBase);
}
@Override
public void setPurchaser_User_ID (final int Purchaser_User_ID)
{
if (Purchaser_User_ID < 1)
set_Value (COLUMNNAME_Purchaser_User_ID, null);
else
set_Value (COLUMNNAME_Purchaser_User_ID, Purchaser_User_ID);
}
|
@Override
public int getPurchaser_User_ID()
{
return get_ValueAsInt(COLUMNNAME_Purchaser_User_ID);
}
/**
* SOCreditStatus AD_Reference_ID=289
* Reference name: C_BPartner SOCreditStatus
*/
public static final int SOCREDITSTATUS_AD_Reference_ID=289;
/** CreditStop = S */
public static final String SOCREDITSTATUS_CreditStop = "S";
/** CreditHold = H */
public static final String SOCREDITSTATUS_CreditHold = "H";
/** CreditWatch = W */
public static final String SOCREDITSTATUS_CreditWatch = "W";
/** NoCreditCheck = X */
public static final String SOCREDITSTATUS_NoCreditCheck = "X";
/** CreditOK = O */
public static final String SOCREDITSTATUS_CreditOK = "O";
/** NurEineRechnung = I */
public static final String SOCREDITSTATUS_NurEineRechnung = "I";
@Override
public void setSOCreditStatus (final java.lang.String SOCreditStatus)
{
set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus);
}
@Override
public java.lang.String getSOCreditStatus()
{
return get_ValueAsString(COLUMNNAME_SOCreditStatus);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Group.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
this.logger.debug("userinfo returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
private Object getPrincipal(Map<String, Object> map) {
for (String key : PRINCIPAL_KEYS) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return "unknown";
}
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {
Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");
String clientId = (String) request.get("clientId");
Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
(Collection<String>) request.get("scope") : Collections.<String>emptySet());
return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
null, null, null, null);
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
|
@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
this.logger.debug("Getting user info from: " + path);
try {
OAuth2RestOperations restTemplate = this.restTemplate;
if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
resource.setClientId(this.clientId);
restTemplate = new OAuth2RestTemplate(resource);
}
OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext()
.getAccessToken();
if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
restTemplate.getOAuth2ClientContext().setAccessToken(token);
}
return restTemplate.getForEntity(path, Map.class).getBody();
}
catch (Exception ex) {
this.logger.info("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
|
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\service\security\CustomUserInfoTokenServices.java
| 2
|
请完成以下Java代码
|
public void setSubstitute(org.compiere.model.I_AD_User Substitute)
{
set_ValueFromPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class, Substitute);
}
/** Set Ersatz.
@param Substitute_ID
Entity which can be used in place of this entity
*/
@Override
public void setSubstitute_ID (int Substitute_ID)
{
if (Substitute_ID < 1)
set_Value (COLUMNNAME_Substitute_ID, null);
else
set_Value (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID));
}
/** Get Ersatz.
@return Entity which can be used in place of this entity
*/
@Override
public int getSubstitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Valid from including this date (first day)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
|
}
/** Get Gültig ab.
@return Valid from including this date (first day)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Valid to including this date (last day)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Valid to including this date (last day)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Substitute.java
| 1
|
请完成以下Java代码
|
public boolean hasNext() {
return iterator.hasNext();
}
public java.util.Map.Entry<String, Object> next() {
final java.util.Map.Entry<String, TypedValue> underlyingEntry = iterator.next();
// return wrapper backed by the underlying entry
return new Entry<String, Object>() {
public String getKey() {
return underlyingEntry.getKey();
}
public Object getValue() {
return underlyingEntry.getValue().getValue();
}
public Object setValue(Object value) {
TypedValue typedValue = Variables.untypedValue(value);
return underlyingEntry.setValue(typedValue);
}
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Entry e = (Entry) o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public final int hashCode() {
String key = getKey();
Object value = getValue();
return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
};
}
public void remove() {
iterator.remove();
}
};
}
public int size() {
return variables.size();
}
};
}
public String toString() {
|
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{\n");
for (Entry<String, TypedValue> variable : variables.entrySet()) {
stringBuilder.append(" ");
stringBuilder.append(variable.getKey());
stringBuilder.append(" => ");
stringBuilder.append(variable.getValue());
stringBuilder.append("\n");
}
stringBuilder.append("}");
return stringBuilder.toString();
}
public boolean equals(Object obj) {
return asValueMap().equals(obj);
}
public int hashCode() {
return asValueMap().hashCode();
}
public Map<String, Object> asValueMap() {
return new HashMap<String, Object>(this);
}
public TypedValue resolve(String variableName) {
return getValueTyped(variableName);
}
public boolean containsVariable(String variableName) {
return containsKey(variableName);
}
public VariableContext asVariableContext() {
return this;
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\VariableMapImpl.java
| 1
|
请完成以下Java代码
|
public void setMaxDelay(String maxDelay) {
this.maxDelay = maxDelay;
}
public String getMultiplier() {
return multiplier;
}
public void setMultiplier(String multiplier) {
this.multiplier = multiplier;
}
public String getRandom() {
return random;
}
public void setRandom(String random) {
this.random = random;
}
}
public static class TopicPartition {
protected String topic;
|
protected Collection<String> partitions;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Collection<String> getPartitions() {
return partitions;
}
public void setPartitions(Collection<String> partitions) {
this.partitions = partitions;
}
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaInboundChannelModel.java
| 1
|
请完成以下Java代码
|
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return An Error occured in the execution
*/
@Override
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenz.
@param Reference
Reference for this record
*/
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Reference for this record
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
/** Set Zusammenfassung.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
|
/** Get Zusammenfassung.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerLog.java
| 1
|
请完成以下Java代码
|
public class ContextImpl extends ExpressionImpl implements Context {
protected static ChildElementCollection<ContextEntry> contextEntryCollection;
public ContextImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<ContextEntry> getContextEntries() {
return contextEntryCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Context.class, DMN_ELEMENT_CONTEXT)
.namespaceUri(LATEST_DMN_NS)
|
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<Context>() {
public Context newInstance(ModelTypeInstanceContext instanceContext) {
return new ContextImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
contextEntryCollection = sequenceBuilder.elementCollection(ContextEntry.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ContextImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PaymentReconcileReference
{
public enum Type
{
BANK_STATEMENT_LINE, BANK_STATEMENT_LINE_REF, REVERSAL, GL_Journal
}
@NonNull Type type;
@Nullable BankStatementId bankStatementId;
@Nullable BankStatementLineId bankStatementLineId;
@Nullable BankStatementLineRefId bankStatementLineRefId;
@Nullable PaymentId reversalId;
@Nullable SAPGLJournalLineId glJournalLineId;
public static PaymentReconcileReference bankStatementLine(
@NonNull final BankStatementId bankStatementId,
@NonNull final BankStatementLineId bankStatementLineId)
{
return new PaymentReconcileReference(
Type.BANK_STATEMENT_LINE,
bankStatementId,
bankStatementLineId,
null,
null,
null);
}
public static PaymentReconcileReference bankStatementLineRef(@NonNull final BankStatementAndLineAndRefId bankStatementLineRefId)
{
return bankStatementLineRef(
bankStatementLineRefId.getBankStatementId(),
bankStatementLineRefId.getBankStatementLineId(),
bankStatementLineRefId.getBankStatementLineRefId());
}
public static PaymentReconcileReference bankStatementLineRef(
@NonNull final BankStatementId bankStatementId,
@NonNull final BankStatementLineId bankStatementLineId,
@NonNull final BankStatementLineRefId bankStatementLineRefId)
{
|
return new PaymentReconcileReference(
Type.BANK_STATEMENT_LINE_REF,
bankStatementId,
bankStatementLineId,
bankStatementLineRefId,
null,
null);
}
public static PaymentReconcileReference reversal(@NonNull final PaymentId reversalId)
{
return new PaymentReconcileReference(
Type.REVERSAL,
null,
null,
null,
reversalId,
null);
}
public static PaymentReconcileReference glJournalLine(@NonNull final SAPGLJournalLineId glJournalLineId)
{
return new PaymentReconcileReference(
Type.GL_Journal,
null,
null,
null,
null,
glJournalLineId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\PaymentReconcileReference.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private IAttributeStorage getHUAttributes(final I_M_HU hu)
{
final IContextAware ctxAware = getContextAware(hu);
final IHUContext huContext = handlingUnitsBL.createMutableHUContext(ctxAware);
final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory();
return attributeStorageFactory.getAttributeStorage(hu);
}
private IHUProductStorage getProductStorage(final I_M_HU hu)
{
final IHUStorage huStorage = handlingUnitsBL
.getStorageFactory()
.getStorage(hu);
final ProductId productId = huStorage.getSingleProductIdOrNull();
if (productId == null)
{
throw new AdempiereException("HU is empty");
}
return huStorage.getProductStorage(productId);
}
private void updateHUAttributes(
@NonNull final I_M_HU hu,
@NonNull final HUAttributesUpdateRequest from)
{
final IAttributeStorage huAttributes = getHUAttributes(hu);
updateHUAttributes(huAttributes, from);
huAttributes.saveChangesIfNeeded();
}
private static void updateHUAttributes(
@NonNull final IAttributeStorage huAttributes,
@NonNull final HUAttributesUpdateRequest from)
{
huAttributes.setValue(AttributeConstants.ATTR_SecurPharmScannedStatus, from.getStatus().getCode());
if (!from.isSkipUpdatingBestBeforeDate())
{
final JsonExpirationDate bestBeforeDate = from.getBestBeforeDate();
huAttributes.setValue(AttributeConstants.ATTR_BestBeforeDate, bestBeforeDate != null ? bestBeforeDate.toLocalDate() : null);
}
if (!from.isSkipUpdatingLotNo())
{
huAttributes.setValue(AttributeConstants.ATTR_LotNumber, from.getLotNo());
}
|
if (!from.isSkipUpdatingSerialNo())
{
huAttributes.setValue(AttributeConstants.ATTR_SerialNo, from.getSerialNo());
}
}
@Value
@Builder
private static class HUAttributesUpdateRequest
{
public static final HUAttributesUpdateRequest ERROR = builder()
.status(SecurPharmAttributesStatus.ERROR)
// UPDATE just the status field, skip the others
.skipUpdatingBestBeforeDate(true)
.skipUpdatingLotNo(true)
.skipUpdatingSerialNo(true)
.build();
@NonNull
SecurPharmAttributesStatus status;
boolean skipUpdatingBestBeforeDate;
@Nullable
JsonExpirationDate bestBeforeDate;
boolean skipUpdatingLotNo;
@Nullable
String lotNo;
boolean skipUpdatingSerialNo;
String serialNo;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\service\SecurPharmHUAttributesScanner.java
| 2
|
请完成以下Java代码
|
public final class CookieClearingLogoutHandler implements LogoutHandler {
private final List<Function<HttpServletRequest, Cookie>> cookiesToClear;
public CookieClearingLogoutHandler(String... cookiesToClear) {
Assert.notNull(cookiesToClear, "List of cookies cannot be null");
List<Function<HttpServletRequest, Cookie>> cookieList = new ArrayList<>();
for (String cookieName : cookiesToClear) {
cookieList.add((request) -> {
Cookie cookie = new Cookie(cookieName, null);
String contextPath = request.getContextPath();
String cookiePath = StringUtils.hasText(contextPath) ? contextPath : "/";
cookie.setPath(cookiePath);
cookie.setMaxAge(0);
cookie.setSecure(request.isSecure());
return cookie;
});
}
this.cookiesToClear = cookieList;
}
/**
* @param cookiesToClear - One or more Cookie objects that must have maxAge of 0
|
* @since 5.2
*/
public CookieClearingLogoutHandler(Cookie... cookiesToClear) {
Assert.notNull(cookiesToClear, "List of cookies cannot be null");
List<Function<HttpServletRequest, Cookie>> cookieList = new ArrayList<>();
for (Cookie cookie : cookiesToClear) {
Assert.isTrue(cookie.getMaxAge() == 0, "Cookie maxAge must be 0");
cookieList.add((request) -> cookie);
}
this.cookiesToClear = cookieList;
}
@Override
public void logout(HttpServletRequest request, HttpServletResponse response,
@Nullable Authentication authentication) {
this.cookiesToClear.forEach((f) -> response.addCookie(f.apply(request)));
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\logout\CookieClearingLogoutHandler.java
| 1
|
请完成以下Java代码
|
public class RouteFinder<T extends GraphNode> {
private final Graph<T> graph;
private final Scorer<T> nextNodeScorer;
private final Scorer<T> targetScorer;
public RouteFinder(Graph<T> graph, Scorer<T> nextNodeScorer, Scorer<T> targetScorer) {
this.graph = graph;
this.nextNodeScorer = nextNodeScorer;
this.targetScorer = targetScorer;
}
public List<T> findRoute(T from, T to) {
Map<T, RouteNode<T>> allNodes = new HashMap<>();
Queue<RouteNode> openSet = new PriorityQueue<>();
RouteNode<T> start = new RouteNode<>(from, null, 0d, targetScorer.computeCost(from, to));
allNodes.put(from, start);
openSet.add(start);
while (!openSet.isEmpty()) {
log.debug("Open Set contains: " + openSet.stream().map(RouteNode::getCurrent).collect(Collectors.toSet()));
RouteNode<T> next = openSet.poll();
log.debug("Looking at node: " + next);
if (next.getCurrent().equals(to)) {
log.debug("Found our destination!");
List<T> route = new ArrayList<>();
RouteNode<T> current = next;
do {
route.add(0, current.getCurrent());
current = allNodes.get(current.getPrevious());
} while (current != null);
log.debug("Route: " + route);
return route;
}
|
graph.getConnections(next.getCurrent()).forEach(connection -> {
double newScore = next.getRouteScore() + nextNodeScorer.computeCost(next.getCurrent(), connection);
RouteNode<T> nextNode = allNodes.getOrDefault(connection, new RouteNode<>(connection));
allNodes.put(connection, nextNode);
if (nextNode.getRouteScore() > newScore) {
nextNode.setPrevious(next.getCurrent());
nextNode.setRouteScore(newScore);
nextNode.setEstimatedScore(newScore + targetScorer.computeCost(connection, to));
openSet.add(nextNode);
log.debug("Found a better route to node: " + nextNode);
}
});
}
throw new IllegalStateException("No route found");
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\astar\RouteFinder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ConcurrentKafkaListenerContainerFactoryConfigurer configurer() {
ConcurrentKafkaListenerContainerFactoryConfigurer configurer = new ConcurrentKafkaListenerContainerFactoryConfigurer();
configurer.setKafkaProperties(this.properties);
configurer.setBatchMessageConverter(this.batchMessageConverter);
configurer.setRecordMessageConverter(this.recordMessageConverter);
configurer.setRecordFilterStrategy(this.recordFilterStrategy);
configurer.setReplyTemplate(this.kafkaTemplate);
configurer.setTransactionManager(this.transactionManager);
configurer.setRebalanceListener(this.rebalanceListener);
configurer.setCommonErrorHandler(this.commonErrorHandler);
configurer.setAfterRollbackProcessor(this.afterRollbackProcessor);
configurer.setRecordInterceptor(this.recordInterceptor);
configurer.setBatchInterceptor(this.batchInterceptor);
configurer.setThreadNameSupplier(this.threadNameSupplier);
return configurer;
}
@Bean
@ConditionalOnMissingBean(name = "kafkaListenerContainerFactory")
ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
|
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
ObjectProvider<ConsumerFactory<Object, Object>> kafkaConsumerFactory,
ObjectProvider<ContainerCustomizer<Object, Object, ConcurrentMessageListenerContainer<Object, Object>>> kafkaContainerCustomizer) {
ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
configurer.configure(factory, kafkaConsumerFactory
.getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties())));
kafkaContainerCustomizer.ifAvailable(factory::setContainerCustomizer);
return factory;
}
@Configuration(proxyBeanMethods = false)
@EnableKafka
@ConditionalOnMissingBean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
static class EnableKafkaConfiguration {
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaAnnotationDrivenConfiguration.java
| 2
|
请完成以下Java代码
|
public WebEndpointResponse<Object> quartzJobOrTrigger(SecurityContext securityContext,
@Selector String jobsOrTriggers, @Selector String group, @Selector String name) throws SchedulerException {
boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles);
return handle(jobsOrTriggers, () -> this.delegate.quartzJob(group, name, showUnsanitized),
() -> this.delegate.quartzTrigger(group, name, showUnsanitized));
}
/**
* Trigger a Quartz job.
* @param jobs path segment "jobs"
* @param group job's group
* @param name job name
* @param state desired state
* @return web endpoint response
* @throws SchedulerException if there is an error triggering the job
*/
@WriteOperation
public WebEndpointResponse<Object> triggerQuartzJob(@Selector String jobs, @Selector String group,
@Selector String name, String state) throws SchedulerException {
if ("jobs".equals(jobs) && "running".equals(state)) {
return handleNull(this.delegate.triggerQuartzJob(group, name));
}
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST);
}
private <T> WebEndpointResponse<T> handle(String jobsOrTriggers, ResponseSupplier<T> jobAction,
ResponseSupplier<T> triggerAction) throws SchedulerException {
if ("jobs".equals(jobsOrTriggers)) {
return handleNull(jobAction.get());
}
if ("triggers".equals(jobsOrTriggers)) {
return handleNull(triggerAction.get());
}
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST);
}
private <T> WebEndpointResponse<T> handleNull(@Nullable T value) {
return (value != null) ? new WebEndpointResponse<>(value)
: new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND);
}
|
@FunctionalInterface
private interface ResponseSupplier<T> {
@Nullable T get() throws SchedulerException;
}
static class QuartzEndpointWebExtensionRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(), QuartzGroupsDescriptor.class,
QuartzJobDetailsDescriptor.class, QuartzJobGroupSummaryDescriptor.class,
QuartzTriggerGroupSummaryDescriptor.class);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-quartz\src\main\java\org\springframework\boot\quartz\actuate\endpoint\QuartzEndpointWebExtension.java
| 1
|
请完成以下Java代码
|
public static String buildFullRequestUrl(String scheme, String serverName, int serverPort, String requestURI,
@Nullable String queryString) {
scheme = scheme.toLowerCase(Locale.ENGLISH);
StringBuilder url = new StringBuilder();
url.append(scheme).append("://").append(serverName);
// Only add port if not default
if ("http".equals(scheme)) {
if (serverPort != 80) {
url.append(":").append(serverPort);
}
}
else if ("https".equals(scheme)) {
if (serverPort != 443) {
url.append(":").append(serverPort);
}
}
// Use the requestURI as it is encoded (RFC 3986) and hence suitable for
// redirects.
url.append(requestURI);
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
/**
* Obtains the web application-specific fragment of the request URL.
* <p>
* Under normal spec conditions,
*
* <pre>
* requestURI = contextPath + servletPath + pathInfo
* </pre>
*
* But the requestURI is not decoded, whereas the servletPath and pathInfo are
* (SEC-1255). This method is typically used to return a URL for matching against
* secured paths, hence the decoded form is used in preference to the requestURI for
* building the returned value. But this method may also be called using dummy request
* objects which just have the requestURI and contextPatth set, for example, so it
* will fall back to using those.
* @return the decoded URL, excluding any server name, context path or servlet path
*
*/
public static String buildRequestUrl(HttpServletRequest r) {
return buildRequestUrl(r.getServletPath(), r.getRequestURI(), r.getContextPath(), r.getPathInfo(),
r.getQueryString());
}
/**
|
* Obtains the web application-specific fragment of the URL.
*/
private static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo,
String queryString) {
StringBuilder url = new StringBuilder();
if (servletPath != null) {
url.append(servletPath);
if (pathInfo != null) {
url.append(pathInfo);
}
}
else {
url.append(requestURI.substring(contextPath.length()));
}
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
/**
* Returns true if the supplied URL starts with a "/" or is absolute.
*/
public static boolean isValidRedirectUrl(String url) {
return url != null && (url.startsWith("/") || isAbsoluteUrl(url));
}
/**
* Decides if a URL is absolute based on whether it contains a valid scheme name, as
* defined in RFC 1738.
*/
public static boolean isAbsoluteUrl(String url) {
return (url != null) ? ABSOLUTE_URL.matcher(url).matches() : false;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\UrlUtils.java
| 1
|
请完成以下Java代码
|
public class PerceptronNERecognizer extends PerceptronTagger implements NERecognizer
{
final NERTagSet tagSet;
public PerceptronNERecognizer(LinearModel nerModel)
{
super(nerModel);
if (nerModel.tagSet().type != TaskType.NER)
{
throw new IllegalArgumentException(String.format("错误的模型类型: 传入的不是命名实体识别模型,而是 %s 模型", nerModel.featureMap.tagSet.type));
}
this.tagSet = (NERTagSet) model.tagSet();
}
public PerceptronNERecognizer(String nerModelPath) throws IOException
{
this(new LinearModel(nerModelPath));
}
/**
* 加载配置文件指定的模型
*
* @throws IOException
*/
public PerceptronNERecognizer() throws IOException
{
this(HanLP.Config.PerceptronNERModelPath);
}
public String[] recognize(String[] wordArray, String[] posArray)
{
NERInstance instance = new NERInstance(wordArray, posArray, model.featureMap);
return recognize(instance);
}
public String[] recognize(NERInstance instance)
{
|
instance.tagArray = new int[instance.size()];
model.viterbiDecode(instance);
return instance.tags(tagSet);
}
@Override
public NERTagSet getNERTagSet()
{
return tagSet;
}
/**
* 在线学习
*
* @param segmentedTaggedNERSentence 人民日报2014格式的句子
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String segmentedTaggedNERSentence)
{
return learn(new NERInstance(segmentedTaggedNERSentence, model.featureMap));
}
@Override
protected Instance createInstance(Sentence sentence, FeatureMap featureMap)
{
for (IWord word : sentence)
{
if (word instanceof CompoundWord && !tagSet.nerLabels.contains(word.getLabel()))
Predefine.logger.warning("在线学习不可能学习新的标签: " + word + " ;请标注语料库后重新全量训练。");
}
return new NERInstance(sentence, featureMap);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronNERecognizer.java
| 1
|
请完成以下Java代码
|
public void setTypeName(String typeName) {
typedValueField.setSerializerName(typeName);
}
@Override
public Object getValue() {
return typedValueField.getValue();
}
@Override
public TypedValue getTypedValue() {
return typedValueField.getTypedValue(false);
}
public TypedValue getTypedValue(boolean deserializeValue) {
return typedValueField.getTypedValue(deserializeValue, false);
}
@Override
public String getErrorMessage() {
return typedValueField.getErrorMessage();
}
@Override
public String getName() {
// used for save a byte value
return clauseId;
}
@Override
public String getTextValue() {
return textValue;
}
@Override
public void setTextValue(String textValue) {
this.textValue = textValue;
}
@Override
public String getTextValue2() {
return textValue2;
}
@Override
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
@Override
public Long getLongValue() {
return longValue;
}
@Override
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
@Override
public Double getDoubleValue() {
return doubleValue;
}
@Override
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
public String getByteArrayValueId() {
return byteArrayField.getByteArrayId();
}
public void setByteArrayValueId(String byteArrayId) {
byteArrayField.setByteArrayId(byteArrayId);
}
@Override
public byte[] getByteArrayValue() {
|
return byteArrayField.getByteArrayValue();
}
@Override
public void setByteArrayValue(byte[] bytes) {
byteArrayField.setByteArrayValue(bytes);
}
public void setValue(TypedValue typedValue) {
typedValueField.setValue(typedValue);
}
public String getSerializerName() {
return typedValueField.getSerializerName();
}
public void setSerializerName(String serializerName) {
typedValueField.setSerializerName(serializerName);
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public void delete() {
byteArrayField.deleteByteArrayValue();
Context
.getCommandContext()
.getDbEntityManager()
.delete(this);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInputInstanceEntity.java
| 1
|
请完成以下Java代码
|
private static String normalizeRoleGroupValue(String roleGroupValue)
{
String result = LogicExpressionEvaluator.stripQuotes(roleGroupValue);
result = StringUtils.trimBlankToNull(result);
return result != null ? result : "";
}
@NonNull
private static HashMap<String, String> copyToNewParameters(final @NonNull Map<CtxName, String> usedParameters)
{
final HashMap<String, String> newParameters = new HashMap<>(usedParameters.size());
for (Map.Entry<CtxName, String> entry : usedParameters.entrySet())
{
newParameters.put(entry.getKey().getName(), entry.getValue());
}
return newParameters;
}
private static LogicExpressionResult revaluate(
|
@NonNull final LogicExpressionResult result,
@NonNull final Map<String, String> newParameters)
{
try
{
return result.getExpression().evaluateToResult(Evaluatees.ofMap(newParameters), IExpressionEvaluator.OnVariableNotFound.Fail);
}
catch (final Exception ex)
{
// shall not happen
logger.warn("Failed evaluating expression using `{}`. Returning previous result: {}", newParameters, result, ex);
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldLogicExpressionResultRevaluator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public R<IPage<PostVO>> page(PostVO post, Query query) {
IPage<PostVO> pages = postService.selectPostPage(Condition.getPage(query), post);
return R.data(pages);
}
/**
* 新增 岗位表
*/
@PostMapping("/save")
@ApiOperationSupport(order = 4)
@Operation(summary = "新增", description = "传入post")
public R save(@Valid @RequestBody Post post) {
return R.status(postService.save(post));
}
/**
* 修改 岗位表
*/
@PostMapping("/update")
@ApiOperationSupport(order = 5)
@Operation(summary = "修改", description = "传入post")
public R update(@Valid @RequestBody Post post) {
return R.status(postService.updateById(post));
}
/**
* 新增或修改 岗位表
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 6)
@Operation(summary = "新增或修改", description = "传入post")
public R submit(@Valid @RequestBody Post post) {
post.setTenantId(SecureUtil.getTenantId());
return R.status(postService.saveOrUpdate(post));
}
|
/**
* 删除 岗位表
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 7)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(postService.deleteLogic(Func.toLongList(ids)));
}
/**
* 下拉数据源
*/
@GetMapping("/select")
@ApiOperationSupport(order = 8)
@Operation(summary = "下拉数据源", description = "传入post")
public R<List<Post>> select(String tenantId, BladeUser bladeUser) {
List<Post> list = postService.list(Wrappers.<Post>query().lambda().eq(Post::getTenantId, Func.toStr(tenantId, bladeUser.getTenantId())));
return R.data(list);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\PostController.java
| 2
|
请完成以下Java代码
|
public boolean isEventDispatcherEnabled() {
return getEventDispatcher() != null && getEventDispatcher().isEnabled();
}
public boolean isEnableEventDispatcher() {
return enableEventDispatcher;
}
public AbstractServiceConfiguration<S> setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
}
public FlowableEventDispatcher getEventDispatcher() {
return eventDispatcher;
}
public AbstractServiceConfiguration<S> setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
public List<FlowableEventListener> getEventListeners() {
return eventListeners;
}
public AbstractServiceConfiguration<S> setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners;
return this;
}
public Map<String, List<FlowableEventListener>> getTypedEventListeners() {
return typedEventListeners;
}
public AbstractServiceConfiguration<S> setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
public List<EventDispatchAction> getAdditionalEventDispatchActions() {
return additionalEventDispatchActions;
}
public AbstractServiceConfiguration<S> setAdditionalEventDispatchActions(List<EventDispatchAction> additionalEventDispatchActions) {
this.additionalEventDispatchActions = additionalEventDispatchActions;
return this;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
|
public AbstractServiceConfiguration<S> setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public Clock getClock() {
return clock;
}
public AbstractServiceConfiguration<S> setClock(Clock clock) {
this.clock = clock;
return this;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public AbstractServiceConfiguration<S> setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractServiceConfiguration.java
| 1
|
请完成以下Java代码
|
private ProductPrice createProductPriceOrNull(
@Nullable final JsonPrice jsonPrice,
@NonNull final ProductId productId,
@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
if (jsonPrice == null)
{
return null;
}
final CurrencyId currencyId = lookupCurrencyId(jsonPrice);
final UomId priceUomId = lookupUomId(
X12DE355.ofNullableCode(jsonPrice.getPriceUomCode()),
productId,
item);
final ProductPrice price = ProductPrice.builder()
.money(Money.of(jsonPrice.getValue(), currencyId))
.productId(productId)
.uomId(priceUomId)
.build();
return price;
}
private CurrencyId lookupCurrencyId(@NonNull final JsonPrice jsonPrice)
{
final CurrencyId result = currencyService.getCurrencyId(jsonPrice.getCurrencyCode());
if (result == null)
{
throw MissingResourceException.builder().resourceName("currency").resourceIdentifier(jsonPrice.getPriceUomCode()).parentResource(jsonPrice).build();
}
return result;
}
private UomId lookupUomId(
@Nullable final X12DE355 uomCode,
@NonNull final ProductId productId,
@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
if (uomCode == null)
{
return productBL.getStockUOMId(productId);
}
final UomId priceUomId;
|
try
{
priceUomId = uomDAO.getUomIdByX12DE355(uomCode);
}
catch (final AdempiereException e)
{
throw MissingResourceException.builder().resourceName("uom").resourceIdentifier("priceUomCode").parentResource(item).cause(e).build();
}
return priceUomId;
}
private InvoiceCandidateLookupKey createInvoiceCandidateLookupKey(@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
try
{
return InvoiceCandidateLookupKey.builder()
.externalHeaderId(JsonExternalIds.toExternalIdOrNull(item.getExternalHeaderId()))
.externalLineId(JsonExternalIds.toExternalIdOrNull(item.getExternalLineId()))
.build();
}
catch (final AdempiereException e)
{
throw InvalidEntityException.wrapIfNeeded(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoicecandidates\impl\CreateInvoiceCandidatesService.java
| 1
|
请完成以下Java代码
|
private static Optional<SqlAndParams> createSqlWhereClause(
@NonNull final ProductBarcodeFilterServicesFacade services,
@NonNull final ImmutableList<ResolvedScannedProductCode> ediProductLookupList,
@Nullable final ProductId productId)
{
if (productId == null && ediProductLookupList.isEmpty())
{
return Optional.empty();
}
final ICompositeQueryFilter<I_M_Packageable_V> resultFilter = services.createCompositeQueryFilter()
.setJoinOr();
if (!ediProductLookupList.isEmpty())
{
for (final ResolvedScannedProductCode ediProductLookup : ediProductLookupList)
{
final ICompositeQueryFilter<I_M_Packageable_V> filter = resultFilter.addCompositeQueryFilter()
.setJoinAnd()
.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, ediProductLookup.getProductId());
|
if (ediProductLookup.getBpartnerId() != null)
{
filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, ediProductLookup.getBpartnerId());
}
}
}
if (productId != null)
{
resultFilter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productId);
}
return Optional.of(services.toSqlAndParams(resultFilter));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\UPCProductBarcodeFilterDataFactory.java
| 1
|
请完成以下Java代码
|
public String getResourceNameLike() {
return resourceNameLike;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getEngineVersion() {
return engineVersion;
}
public String getAuthorizationUserId() {
return authorizationUserId;
}
public String getProcDefId() {
return procDefId;
|
}
public String getEventSubscriptionName() {
return eventSubscriptionName;
}
public String getEventSubscriptionType() {
return eventSubscriptionType;
}
public boolean isIncludeAuthorization() {
return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty());
}
public List<List<String>> getSafeAuthorizationGroups() {
return safeAuthorizationGroups;
}
public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) {
this.safeAuthorizationGroups = safeAuthorizationGroups;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessDefinitionQueryImpl.java
| 1
|
请完成以下Java代码
|
public void execute(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
try (PreparedStatement psmt = connection.prepareStatement("SELECT id, username, password, create_time FROM users")) {
try (ResultSet rs = psmt.executeQuery()) {
while (rs.next()) {
String username = rs.getString("username");
if ("yudaoyuanma".equals(username)) {
Integer id = rs.getInt("id");
// 这里,再来一刀更新操作,偷懒不写了。
logger.info("[migrate][更新 user({}) 的用户名({} => {})", id, username, "yutou");
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
@Override
public String getConfirmationMessage() {
return null;
}
@Override
public void setUp() throws SetupException {
}
@Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
}
@Override
public ValidationErrors validate(Database database) {
return null;
}
}
|
repos\SpringBoot-Labs-master\lab-20\lab-20-database-version-control-liquibase\src\main\java\cn\iocoder\springboot\lab20\databaseversioncontrol\migration\CHANGE_SET_3_FixUsername.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(super.getId());
sb.append(", version=").append(super.getVersion());
sb.append(", createTime=").append(super.getCreateTime());
sb.append(", editor=").append(super.getEditor());
sb.append(", creater=").append(super.getCreater());
sb.append(", editTime=").append(super.getEditTime());
sb.append(", status=").append(super.getStatus());
sb.append(", productName=").append(productName);
sb.append(", merchantOrderNo=").append(merchantOrderNo);
sb.append(", orderAmount=").append(orderAmount);
sb.append(", orderFrom=").append(orderFrom);
sb.append(", merchantName=").append(merchantName);
sb.append(", merchantNo=").append(merchantNo);
sb.append(", orderTime=").append(orderTime);
sb.append(", orderDate=").append(orderDate);
sb.append(", orderIp=").append(orderIp);
sb.append(", orderRefererUrl=").append(orderRefererUrl);
sb.append(", returnUrl=").append(returnUrl);
sb.append(", notifyUrl=").append(notifyUrl);
sb.append(", cancelReason=").append(cancelReason);
sb.append(", orderPeriod=").append(orderPeriod);
sb.append(", expireTime=").append(expireTime);
sb.append(", payWayCode=").append(payWayCode);
|
sb.append(", payWayName=").append(payWayName);
sb.append(", remark=").append(remark);
sb.append(", trxType=").append(trxType);
sb.append(", payTypeCode=").append(payTypeCode);
sb.append(", payTypeName=").append(payTypeName);
sb.append(", fundIntoType=").append(fundIntoType);
sb.append(", isRefund=").append(isRefund);
sb.append(", refundTimes=").append(refundTimes);
sb.append(", successRefundAmount=").append(successRefundAmount);
sb.append(", trxNo=").append(trxNo);
sb.append(", field1=").append(field1);
sb.append(", field2=").append(field2);
sb.append(", field3=").append(field3);
sb.append(", field4=").append(field4);
sb.append(", field5=").append(field5);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpTradePaymentOrder.java
| 2
|
请完成以下Java代码
|
public void setBpartnerIdentifier(final String bpartnerIdentifier)
{
this.bpartnerIdentifier = bpartnerIdentifier;
this.bpartnerSet = true;
}
public void setActive(final Boolean active)
{
this.active = active;
activeSet = true;
}
public void setSeqNo(final Integer seqNo)
{
this.seqNo = seqNo;
seqNoSet = true;
}
public void setProductNo(final String productNo)
{
this.productNo = productNo;
productNoSet = true;
}
public void setDescription(final String description)
{
this.description = description;
descriptionSet = true;
}
public void setCuEAN(final String cuEAN)
{
this.cuEAN = cuEAN;
cuEANSet = true;
}
public void setGtin(final String gtin)
{
this.gtin = gtin;
gtinSet = true;
}
public void setCustomerLabelName(final String customerLabelName)
{
this.customerLabelName = customerLabelName;
customerLabelNameSet = true;
}
|
public void setIngredients(final String ingredients)
{
this.ingredients = ingredients;
ingredientsSet = true;
}
public void setCurrentVendor(final Boolean currentVendor)
{
this.currentVendor = currentVendor;
currentVendorSet = true;
}
public void setExcludedFromSales(final Boolean excludedFromSales)
{
this.excludedFromSales = excludedFromSales;
excludedFromSalesSet = true;
}
public void setExclusionFromSalesReason(final String exclusionFromSalesReason)
{
this.exclusionFromSalesReason = exclusionFromSalesReason;
exclusionFromSalesReasonSet = true;
}
public void setDropShip(final Boolean dropShip)
{
this.dropShip = dropShip;
dropShipSet = true;
}
public void setUsedForVendor(final Boolean usedForVendor)
{
this.usedForVendor = usedForVendor;
usedForVendorSet = true;
}
public void setExcludedFromPurchase(final Boolean excludedFromPurchase)
{
this.excludedFromPurchase = excludedFromPurchase;
excludedFromPurchaseSet = true;
}
public void setExclusionFromPurchaseReason(final String exclusionFromPurchaseReason)
{
this.exclusionFromPurchaseReason = exclusionFromPurchaseReason;
exclusionFromPurchaseReasonSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestBPartnerProductUpsert.java
| 1
|
请完成以下Java代码
|
public void onTaxAmt(final ITaxAccountable taxAccountable)
{
final BigDecimal taxBaseAmt = taxAccountable.getTaxBaseAmt();
final BigDecimal taxAmt = taxAccountable.getTaxAmt();
final BigDecimal totalAmt = taxBaseAmt.add(taxAmt);
taxAccountable.setTaxTotalAmt(totalAmt);
}
/**
* Called when TaxTotalAmt is changed.
* <p>
* Sets TaxAmt and TaxBaseAmt.
*/
public void onTaxTotalAmt(final ITaxAccountable taxAccountable)
{
final Tax tax = getTaxOrNull(taxAccountable);
if (tax == null)
{
return;
}
if (tax.isReverseCharge())
{
throw new AdempiereException("Reverse Charge Tax is not supported");
}
//
// Calculate TaxAmt
final BigDecimal taxTotalAmt = taxAccountable.getTaxTotalAmt();
final boolean taxIncluded = true;
final CurrencyPrecision precision = taxAccountable.getPrecision();
final BigDecimal taxAmt = tax.calculateTax(taxTotalAmt, taxIncluded, precision.toInt()).getTaxAmount();
final BigDecimal taxBaseAmt = taxTotalAmt.subtract(taxAmt);
taxAccountable.setTaxAmt(taxAmt);
taxAccountable.setTaxBaseAmt(taxBaseAmt);
}
/**
* Called when C_Tax_ID is changed.
* <p>
* Sets Tax_Acct, TaxAmt.
*/
public void onC_Tax_ID(final ITaxAccountable taxAccountable)
{
final TaxAcctType taxAcctType;
if (taxAccountable.isAccountSignDR())
{
taxAcctType = TaxAcctType.TaxCredit;
// taxAcctType = TaxAcctType.TaxExpense; // used for booking services tax
}
else if (taxAccountable.isAccountSignCR())
{
taxAcctType = TaxAcctType.TaxDue;
}
else
{
return;
}
//
// Set DR/CR Tax Account
final TaxId taxId = TaxId.ofRepoIdOrNull(taxAccountable.getC_Tax_ID());
if (taxId != null)
{
final AcctSchemaId acctSchemaId = taxAccountable.getAcctSchemaId();
final MAccount taxAccount = taxAccountsRepository.getAccounts(taxId, acctSchemaId)
.getAccount(taxAcctType)
.map(Account::getAccountId)
.map(accountDAO::getById)
.orElseThrow(() -> new AdempiereException("@NotFound@ " + taxAcctType + " (" + taxId + ", " + acctSchemaId + ")"));
taxAccountable.setTax_Acct(taxAccount);
}
else
{
taxAccountable.setTax_Acct(null);
}
|
//
// Set TaxAmt based on TaxBaseAmt and C_Tax_ID
onTaxBaseAmt(taxAccountable);
}
private I_C_Tax getTaxOrNull(final I_C_ValidCombination accountVC)
{
if (accountVC == null)
{
return null;
}
final I_C_ElementValue account = accountVC.getAccount();
if (account == null)
{
return null;
}
if (!account.isAutoTaxAccount())
{
return null;
}
final TaxId taxId = TaxId.ofRepoIdOrNull(account.getC_Tax_ID());
if (taxId == null)
{
return null;
}
return InterfaceWrapperHelper.load(taxId, I_C_Tax.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\TaxAccountableCallout.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getWarehouseFileEndpoint()
{
return getLocalFileConnectionString(fileNamePatternWarehouse);
}
@Override
@NonNull
public String getPurchaseOrderFileEndpoint()
{
return getLocalFileConnectionString(fileNamePatternPurchaseOrder);
}
@NonNull
private String getLocalFileConnectionString(@Nullable final String includeFilePattern)
{
final StringBuilder fileEndpoint = new StringBuilder("file://");
fileEndpoint.append(rootLocation)
|
.append("?")
.append("charset=utf-8")
.append("&")
.append("delay=").append(pollingFrequency.toMillis())
.append("&")
.append("move=").append(processedFilesFolder).append("/").append(seenFileRenamePattern)
.append("&")
.append("moveFailed=").append(errorFilesFolder).append("/").append(seenFileRenamePattern);
if(Check.isNotBlank(includeFilePattern))
{
fileEndpoint.append("&").append("antInclude=").append(includeFilePattern);
}
return fileEndpoint.toString();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\config\LocalFileConfig.java
| 2
|
请完成以下Java代码
|
public boolean isReadOnlyValues()
{
return get_ValueAsBoolean(COLUMNNAME_IsReadOnlyValues);
}
@Override
public void setIsStorageRelevant (final boolean IsStorageRelevant)
{
set_Value (COLUMNNAME_IsStorageRelevant, IsStorageRelevant);
}
@Override
public boolean isStorageRelevant()
{
return get_ValueAsBoolean(COLUMNNAME_IsStorageRelevant);
}
@Override
public void setM_Attribute_ID (final int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID);
}
@Override
public int getM_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Attribute_ID);
}
@Override
public org.compiere.model.I_M_AttributeSearch getM_AttributeSearch()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class);
}
@Override
public void setM_AttributeSearch(final org.compiere.model.I_M_AttributeSearch M_AttributeSearch)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class, M_AttributeSearch);
}
@Override
public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID)
{
if (M_AttributeSearch_ID < 1)
set_Value (COLUMNNAME_M_AttributeSearch_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID);
}
@Override
public int getM_AttributeSearch_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_ID);
}
@Override
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 setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override)
{
set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override);
}
@Override
public java.lang.String getPrintValue_Override()
{
return get_ValueAsString(COLUMNNAME_PrintValue_Override);
}
@Override
public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueMax (final @Nullable BigDecimal ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
@Override
public BigDecimal getValueMax()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueMin (final @Nullable BigDecimal ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public BigDecimal getValueMin()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Comparator<EntityType> getEntityTypeComparatorForImport() {
return Comparator.comparing(SUPPORTED_ENTITY_TYPES::indexOf);
}
@SuppressWarnings("unchecked")
private <I extends EntityId, E extends ExportableEntity<I>, D extends EntityExportData<E>> EntityExportService<I, E, D> getExportService(EntityType entityType) {
EntityExportService<?, ?, ?> exportService = exportServices.get(entityType);
if (exportService == null) {
throw new IllegalArgumentException("Export for entity type " + entityType + " is not supported");
}
return (EntityExportService<I, E, D>) exportService;
}
@SuppressWarnings("unchecked")
private <I extends EntityId, E extends ExportableEntity<I>, D extends EntityExportData<E>> EntityImportService<I, E, D> getImportService(EntityType entityType) {
EntityImportService<?, ?, ?> importService = importServices.get(entityType);
if (importService == null) {
throw new IllegalArgumentException("Import for entity type " + entityType + " is not supported");
}
return (EntityImportService<I, E, D>) importService;
}
|
@Autowired
private void setExportServices(DefaultEntityExportService<?, ?, ?> defaultExportService,
Collection<BaseEntityExportService<?, ?, ?>> exportServices) {
exportServices.stream()
.sorted(Comparator.comparing(exportService -> exportService.getSupportedEntityTypes().size(), Comparator.reverseOrder()))
.forEach(exportService -> {
exportService.getSupportedEntityTypes().forEach(entityType -> {
this.exportServices.put(entityType, exportService);
});
});
SUPPORTED_ENTITY_TYPES.forEach(entityType -> {
this.exportServices.putIfAbsent(entityType, defaultExportService);
});
}
@Autowired
private void setImportServices(Collection<EntityImportService<?, ?, ?>> importServices) {
importServices.forEach(entityImportService -> {
this.importServices.put(entityImportService.getEntityType(), entityImportService);
});
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\DefaultEntitiesExportImportService.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_C_DunningLevel getC_DunningLevel() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_DunningLevel_ID, org.compiere.model.I_C_DunningLevel.class);
}
@Override
public void setC_DunningLevel(org.compiere.model.I_C_DunningLevel C_DunningLevel)
{
set_ValueFromPO(COLUMNNAME_C_DunningLevel_ID, org.compiere.model.I_C_DunningLevel.class, C_DunningLevel);
}
/** Set Mahnstufe.
@param C_DunningLevel_ID Mahnstufe */
@Override
public void setC_DunningLevel_ID (int C_DunningLevel_ID)
{
if (C_DunningLevel_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, Integer.valueOf(C_DunningLevel_ID));
}
/** Get Mahnstufe.
@return Mahnstufe */
@Override
public int getC_DunningLevel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningLevel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Notiz.
@param Note
Optional weitere Information
*/
@Override
public void setNote (java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Notiz.
@return Optional weitere Information
*/
@Override
public java.lang.String getNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_Note);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
|
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line.java
| 1
|
请完成以下Java代码
|
private I_PP_Product_BOM getBOMIfEligible()
{
final I_M_Product bomProduct = productsRepo.getById(bomProductId);
if (!bomProduct.isBOM())
{
return null;
}
return bomsRepo.getDefaultBOMByProductId(bomProductId)
.filter(this::isEligible)
.orElse(null);
}
private boolean isEligible(final I_PP_Product_BOM bom)
{
final BOMType bomType = BOMType.ofNullableCode(bom.getBOMType());
|
return BOMType.MakeToOrder.equals(bomType);
}
//
//
// ---
//
//
public static class BOMPriceCalculatorBuilder
{
public Optional<BOMPrices> calculate()
{
return build().calculate();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\BOMPriceCalculator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setParameters(Map _parameters) {
this.parameters.putAll(_parameters);
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getCharSet() {
return charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public boolean isSslVerify() {
return sslVerify;
}
public void setSslVerify(boolean sslVerify) {
this.sslVerify = sslVerify;
}
public int getMaxResultSize() {
return maxResultSize;
}
public void setMaxResultSize(int maxResultSize) {
this.maxResultSize = maxResultSize;
}
public Map getHeaders() {
return headers;
}
public void addHeader(String key, String value){
this.headers.put(key, value);
}
public void addHeaders(String key, Collection<String> values){
this.headers.put(key, values);
}
public void setHeaders(Map _headers) {
this.headers.putAll(_headers);
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
|
this.readTimeout = readTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public boolean isIgnoreContentIfUnsuccess() {
return ignoreContentIfUnsuccess;
}
public void setIgnoreContentIfUnsuccess(boolean ignoreContentIfUnsuccess) {
this.ignoreContentIfUnsuccess = ignoreContentIfUnsuccess;
}
public String getPostData() {
return postData;
}
public void setPostData(String postData) {
this.postData = postData;
}
public ClientKeyStore getClientKeyStore() {
return clientKeyStore;
}
public void setClientKeyStore(ClientKeyStore clientKeyStore) {
this.clientKeyStore = clientKeyStore;
}
public com.roncoo.pay.trade.utils.httpclient.TrustKeyStore getTrustKeyStore() {
return TrustKeyStore;
}
public void setTrustKeyStore(com.roncoo.pay.trade.utils.httpclient.TrustKeyStore trustKeyStore) {
TrustKeyStore = trustKeyStore;
}
public boolean isHostnameVerify() {
return hostnameVerify;
}
public void setHostnameVerify(boolean hostnameVerify) {
this.hostnameVerify = hostnameVerify;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpParam.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(id);
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
|
final AbstractEntity other = (AbstractEntity)obj;
return Objects.equals(id, other.id);
}
protected Date getDateCreated()
{
return dateCreated;
}
protected Date getDateUpdated()
{
return dateUpdated;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\AbstractEntity.java
| 2
|
请完成以下Java代码
|
protected ServiceName getProcessApplicationViewServiceName(ComponentDescription paComponent) {
Set<ViewDescription> views = paComponent.getViews();
if(views == null || views.isEmpty()) {
return null;
} else {
ViewDescription next = views.iterator().next();
return next.getServiceName();
}
}
protected ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) {
return ProcessApplicationAttachments.getProcessApplicationComponent(deploymentUnit);
}
protected ServiceName getProcessEngineServiceName(ProcessArchiveXml processArchive) {
ServiceName serviceName = null;
if(processArchive.getProcessEngineName() == null || processArchive.getProcessEngineName().isEmpty()) {
serviceName = ServiceNames.forDefaultProcessEngine();
} else {
serviceName = ServiceNames.forManagedProcessEngine(processArchive.getProcessEngineName());
}
return serviceName;
}
protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) {
final Module module = deploymentUnit.getAttachment(MODULE);
Map<String, byte[]> resources = new HashMap<>();
// first, add all resources listed in the processes.xml
List<String> process = processArchive.getProcessResourceNames();
ModuleClassLoader classLoader = module.getClassLoader();
for (String resource : process) {
|
InputStream inputStream = null;
try {
inputStream = classLoader.getResourceAsStream(resource);
resources.put(resource, IoUtil.readInputStream(inputStream, resource));
} finally {
IoUtil.closeSilently(inputStream);
}
}
// scan for process definitions
if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) {
//always use VFS scanner on JBoss
final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner();
String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH);
String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR);
URL processesXmlUrl = vfsFileAsUrl(processesXmlFile);
resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes));
}
return resources;
}
protected URL vfsFileAsUrl(VirtualFile processesXmlFile) {
try {
return processesXmlFile.toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessApplicationDeploymentProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WidgetTypeDataValidator extends DataValidator<WidgetTypeDetails> {
private final WidgetTypeDao widgetTypeDao;
private final WidgetsBundleDao widgetsBundleDao;
private final TenantService tenantService;
@Override
protected void validateDataImpl(TenantId tenantId, WidgetTypeDetails widgetTypeDetails) {
validateString("Widgets type name", widgetTypeDetails.getName());
if (widgetTypeDetails.getDescriptor() == null || widgetTypeDetails.getDescriptor().size() == 0) {
throw new DataValidationException("Widgets type descriptor can't be empty!");
}
if (widgetTypeDetails.getTenantId() == null) {
widgetTypeDetails.setTenantId(TenantId.fromUUID(ModelConstants.NULL_UUID));
}
if (!widgetTypeDetails.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
if (!tenantService.tenantExists(widgetTypeDetails.getTenantId())) {
throw new DataValidationException("Widget type is referencing to non-existent tenant!");
}
}
}
@Override
protected void validateCreate(TenantId tenantId, WidgetTypeDetails widgetTypeDetails) {
String fqn = widgetTypeDetails.getFqn();
if (fqn == null || fqn.trim().isEmpty()) {
fqn = widgetTypeDetails.getName().toLowerCase().replaceAll("\\W+", "_");
}
String originalFqn = fqn;
int c = 1;
WidgetType withSameFqn;
do {
withSameFqn = widgetTypeDao.findByTenantIdAndFqn(widgetTypeDetails.getTenantId().getId(), fqn);
if (withSameFqn != null) {
fqn = originalFqn + (++c);
|
}
} while (withSameFqn != null);
widgetTypeDetails.setFqn(fqn);
}
@Override
protected WidgetTypeDetails validateUpdate(TenantId tenantId, WidgetTypeDetails widgetTypeDetails) {
WidgetTypeDetails storedWidgetType = widgetTypeDao.findById(tenantId, widgetTypeDetails.getId().getId());
if (!storedWidgetType.getTenantId().getId().equals(widgetTypeDetails.getTenantId().getId())) {
throw new DataValidationException("Can't move existing widget type to different tenant!");
}
if (!storedWidgetType.getFqn().equals(widgetTypeDetails.getFqn())) {
throw new DataValidationException("Update of widget type fqn is prohibited!");
}
return new WidgetTypeDetails(storedWidgetType);
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\WidgetTypeDataValidator.java
| 2
|
请完成以下Java代码
|
public int getLuPiItemId()
{
return lu_PI_Item_ID;
}
public void setLuPiItemId(final int lu_PI_Item_ID)
{
this.lu_PI_Item_ID = lu_PI_Item_ID;
}
private HUPIItemProductId getTU_HU_PI_Item_Product_ID()
{
if (tu_HU_PI_Item_Product_ID <= 0)
{
throw new FillMandatoryException(PARAM_M_HU_PI_Item_Product_ID);
}
return HUPIItemProductId.ofRepoId(tu_HU_PI_Item_Product_ID);
}
public void setTU_HU_PI_Item_Product_ID(final int tu_HU_PI_Item_Product_ID)
{
this.tu_HU_PI_Item_Product_ID = tu_HU_PI_Item_Product_ID;
}
public BigDecimal getQtyCUsPerTU()
{
return qtyCUsPerTU;
}
public void setQtyCUsPerTU(final BigDecimal qtyCU)
{
this.qtyCUsPerTU = qtyCU;
}
/**
* Called from the process class to set the TU qty from the process parameter.
*/
|
public void setQtyTU(final BigDecimal qtyTU)
{
this.qtyTU = qtyTU;
}
public void setQtyLU(final BigDecimal qtyLU)
{
this.qtyLU = qtyLU;
}
private boolean getIsReceiveIndividualCUs()
{
if (isReceiveIndividualCUs == null)
{
isReceiveIndividualCUs = computeIsReceiveIndividualCUs();
}
return isReceiveIndividualCUs;
}
private boolean computeIsReceiveIndividualCUs()
{
if (selectedRow.getType() != PPOrderLineType.MainProduct
|| selectedRow.getUomId() == null
|| !selectedRow.getUomId().isEach())
{
return false;
}
return Optional.ofNullable(selectedRow.getOrderId())
.flatMap(ppOrderBOMBL::getSerialNoSequenceId)
.isPresent();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\PackingInfoProcessParams.java
| 1
|
请完成以下Java代码
|
public boolean isNegateInboundAmounts()
{
return get_ValueAsBoolean(COLUMNNAME_IsNegateInboundAmounts);
}
@Override
public void setIsPlaceBPAccountsOnCredit (final boolean IsPlaceBPAccountsOnCredit)
{
set_Value (COLUMNNAME_IsPlaceBPAccountsOnCredit, IsPlaceBPAccountsOnCredit);
}
@Override
public boolean isPlaceBPAccountsOnCredit()
{
return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit);
}
/**
* IsSOTrx AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISSOTRX_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISSOTRX_Yes = "Y";
/** No = N */
public static final String ISSOTRX_No = "N";
@Override
public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
|
@Override
public java.lang.String getIsSOTrx()
{
return get_ValueAsString(COLUMNNAME_IsSOTrx);
}
@Override
public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo)
{
set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo);
}
@Override
public boolean isSwitchCreditMemo()
{
return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTrxTypeDesc() {
return TrxTypeEnum.getEnum(this.getTrxType()).getDesc();
}
public Integer getRiskDay() {
return riskDay;
}
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
public String getUserNo() {
return userNo;
}
|
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getAmountDesc() {
if(this.getFundDirection().equals(AccountFundDirectionEnum.ADD.name())){
return "<span style=\"color: blue;\">+"+this.amount.doubleValue()+"</span>";
}else{
return "<span style=\"color: red;\">-"+this.amount.doubleValue()+"</span>";
}
}
public String getCreateTimeDesc() {
return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccountHistory.java
| 2
|
请完成以下Java代码
|
public class GetLocalVariableCmd implements Command<Object> {
protected String planItemInstanceId;
protected String variableName;
public GetLocalVariableCmd(String planItemInstanceId, String variableName) {
this.planItemInstanceId = planItemInstanceId;
this.variableName = variableName;
}
@Override
public Object execute(CommandContext commandContext) {
if (planItemInstanceId == null) {
throw new FlowableIllegalArgumentException("planItemInstanceId is null");
}
|
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
VariableInstanceEntity variableInstanceEntity = cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableService()
.createInternalVariableInstanceQuery()
.subScopeId(planItemInstanceId)
.scopeType(ScopeTypes.CMMN)
.name(variableName)
.singleResult();
if (variableInstanceEntity != null) {
return variableInstanceEntity.getValue();
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetLocalVariableCmd.java
| 1
|
请完成以下Java代码
|
public PrintPackage getNextPrintPackage()
{
synchronized (sync)
{
final PrintPackageAndData item = printPackageQueue.poll();
if (item == null)
{
return null;
}
System.out.println("getNextPrintPackage: " + item.printPackage);
return item.printPackage;
}
}
@Override
public InputStream getPrintPackageData(final PrintPackage printPackage)
{
synchronized (sync)
{
final String trx = printPackage.getTransactionId();
final PrintPackageAndData item = trx2PrintPackageMap.remove(trx);
if (item == null)
{
throw new IllegalStateException("No data found for " + printPackage);
}
|
System.out.println("getPrintPackageData: trx=" + trx + " => stream: " + item.printDataStream);
return item.printDataStream;
}
}
@Override
public void sendPrintPackageResponse(final PrintPackage printPackage, final PrintJobInstructionsConfirm response)
{
log.info("Got : " + response + " for " + printPackage);
}
private static class PrintPackageAndData
{
public PrintPackage printPackage;
public InputStream printDataStream;
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\BufferedPrintConnectionEndpoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static LocalDate asJavaLocalDate(@Nullable final org.threeten.bp.LocalDate localDate)
{
if (localDate == null)
{
return null;
}
return LocalDate.ofEpochDay(localDate.getLong(EPOCH_DAY));
}
@Nullable
public static org.threeten.bp.LocalDate fromJavaLocalDate(@Nullable final LocalDate localDate)
{
if (localDate == null)
{
return null;
}
|
return org.threeten.bp.LocalDate.ofEpochDay(localDate.toEpochDay());
}
@Nullable
public static List<BigDecimal> asBigDecimalIds(@Nullable final List<String> ids)
{
if (ids == null || ids.isEmpty())
{
return null;
}
return ids.stream()
.map(BigDecimal::new)
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\common\AlbertaUtil.java
| 2
|
请完成以下Java代码
|
public void setTaxAmt (BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Tax Amount.
@return Tax Amount for a document
*/
public BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_ElementValue getUser1() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
public int getUser1_ID ()
|
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ElementValue getUser2() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
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_C_InvoiceBatchLine.java
| 1
|
请完成以下Java代码
|
public Meter getDbMeterByName(String name) {
return dbMeters.get(name);
}
public Map<String, Meter> getDbMeters() {
return dbMeters;
}
public Map<String, Meter> getDiagnosticsMeters() {
return diagnosticsMeters;
}
public void clearDiagnosticsMetrics() {
diagnosticsMeters.values().forEach(Meter::getAndClear);
}
public void markOccurrence(String name) {
markOccurrence(name, 1);
}
public void markOccurrence(String name, long times) {
markOccurrence(dbMeters, name, times);
markOccurrence(diagnosticsMeters, name, times);
}
public void markDiagnosticsOccurrence(String name, long times) {
markOccurrence(diagnosticsMeters, name, times);
}
protected void markOccurrence(Map<String, Meter> meters, String name, long times) {
Meter meter = meters.get(name);
if (meter != null) {
meter.markTimes(times);
}
}
|
/**
* Creates a meter for both database and diagnostics collection.
*/
public void createMeter(String name) {
Meter dbMeter = new Meter(name);
dbMeters.put(name, dbMeter);
Meter diagnosticsMeter = new Meter(name);
diagnosticsMeters.put(name, diagnosticsMeter);
}
/**
* Creates a meter only for database collection.
*/
public void createDbMeter(String name) {
Meter dbMeter = new Meter(name);
dbMeters.put(name, dbMeter);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsRegistry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static void exceptionHandlingExample() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
// Simulate a task that might throw an exception
if (true) {
throw new RuntimeException("Something went wrong!");
}
return "Success";
});
try {
// This might block the main thread if the task throws an exception
String result = future.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
// Handle exceptions thrown by the task or during retrieval
System.err.println("Error occured: " + e.getMessage());
} finally {
executor.shutdown();
}
}
public static void timeoutExample() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
try {
System.out.println("Start");
Thread.sleep(5000);
System.out.println("End");
} catch (InterruptedException e) {
System.err.println("Error occured: " + e.getMessage());
}
return "Task completed";
});
|
try {
String result = future.get(2, TimeUnit.SECONDS);
System.out.println("Result: " + result);
} catch (TimeoutException e) {
System.err.println("Task execution timed out!");
future.cancel(true);
} catch (Exception e) {
System.err.println("Error occured: " + e.getMessage());
} finally {
executor.shutdown();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
timeoutExample();
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executorservicevscompletablefuture\ExecutorServiceDemo.java
| 2
|
请完成以下Java代码
|
public Date resolveDuedate(String duedateDescription, int maxIterations) {
return resolveDuedate(duedateDescription);
}
public Date resolveDuedate(String duedate) {
Date resolvedDuedate = Context.getProcessEngineConfiguration().getClock().getCurrentTime();
String[] tokens = duedate.split(" and ");
for (String token : tokens) {
resolvedDuedate = addSingleUnitQuantity(resolvedDuedate, token);
}
return resolvedDuedate;
}
@Override
public Boolean validateDuedate(String duedateDescription, int maxIterations, Date endDate, Date newTimer) {
return true;
}
@Override
public Date resolveEndDate(String endDate) {
return null;
}
|
protected Date addSingleUnitQuantity(Date startDate, String singleUnitQuantity) {
int spaceIndex = singleUnitQuantity.indexOf(" ");
if (spaceIndex == -1 || singleUnitQuantity.length() < spaceIndex + 1) {
throw new ActivitiIllegalArgumentException("invalid duedate format: " + singleUnitQuantity);
}
String quantityText = singleUnitQuantity.substring(0, spaceIndex);
Integer quantity = Integer.valueOf(quantityText);
String unitText = singleUnitQuantity.substring(spaceIndex + 1).trim().toLowerCase();
int unit = units.get(unitText);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
calendar.add(unit, quantity);
return calendar.getTime();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\DefaultBusinessCalendar.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RoutingRequest
{
LocalDate sendDate;
LocalDate desiredDeliveryDate;
int services;
BigDecimal weight;
RequestParticipant sender;
RequestParticipant consignee;
@JsonCreator
@Builder
private RoutingRequest(
@JsonProperty("sendDate") @JsonFormat(shape = Shape.STRING, pattern = DATE_FORMAT) final LocalDate sendDate,
@JsonProperty("desiredDeliveryDate") @JsonFormat(shape = Shape.STRING, pattern = DATE_FORMAT) final LocalDate desiredDeliveryDate,
@JsonProperty("services") final int services,
@JsonProperty("weight") final BigDecimal weight,
@JsonProperty("sender") final RequestParticipant sender,
@JsonProperty("consignee") final RequestParticipant consignee)
{
|
Check.assumeNotNull(sendDate, "Parameter sendDate may not be null");
Check.errorIf(sender == null && consignee == null, "At least one of the given sender and consignee parameters has to be not-null");
this.sendDate = sendDate;
this.desiredDeliveryDate = desiredDeliveryDate;
this.services = services;
this.weight = weight;
this.sender = sender;
this.consignee = consignee;
}
public String toLocalDateOrNull(ZonedDateTime desiredDeliveryDate)
{
return desiredDeliveryDate == null ? null : desiredDeliveryDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\restapi\models\RoutingRequest.java
| 2
|
请完成以下Java代码
|
public final Iterator<IDunnableDoc> iterator(final IDunningContext context)
{
final Iterator<IDunnableDoc> sourceIterator = createRawSourceIterator(context);
final Iterator<IDunnableDoc> filteredSourceIterator = new FilterIterator<>(sourceIterator, value -> isEligible(context, value));
return filteredSourceIterator;
}
/**
*
* @param dunnableDoc
* @return true if dunnableDoc is eligible for creating a candidate
*/
protected boolean isEligible(final IDunningContext dunningContext, final IDunnableDoc dunnableDoc)
{
if (dunnableDoc.getOpenAmt().signum() == 0)
{
logger.info("Skip " + dunnableDoc + " because OpenAmt is ZERO");
return false;
}
if (dunnableDoc.isInDispute())
{
logger.info("Skip " + dunnableDoc + " because is in dispute");
return false;
}
final I_C_DunningLevel level = dunningContext.getC_DunningLevel();
final boolean isDue = dunnableDoc.getDaysDue() >= 0;
if (isDue)
{
if (level.isShowAllDue())
{
|
// Document is due, and we are asked to show all due, so there is no point to check if the days after due is valid
return true;
}
}
else
{
// Document is not due yet => not eligible for dunning
return false;
}
final int daysAfterDue = level.getDaysAfterDue().intValue();
if (dunnableDoc.getDaysDue() < daysAfterDue)
{
logger.info("Skip " + dunnableDoc + " because is not already due (DaysAfterDue:" + daysAfterDue + ")");
return false;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\spi\impl\AbstractDunnableSource.java
| 1
|
请完成以下Java代码
|
public class AddEventListenerCommand implements Command<Void> {
protected ActivitiEventListener listener;
protected ActivitiEventType[] types;
public AddEventListenerCommand(ActivitiEventListener listener, ActivitiEventType[] types) {
this.listener = listener;
this.types = types;
}
public AddEventListenerCommand(ActivitiEventListener listener) {
super();
this.listener = listener;
}
|
@Override
public Void execute(CommandContext commandContext) {
if (listener == null) {
throw new ActivitiIllegalArgumentException("listener is null.");
}
if (types != null) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().addEventListener(listener, types);
} else {
commandContext.getProcessEngineConfiguration().getEventDispatcher().addEventListener(listener);
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddEventListenerCommand.java
| 1
|
请完成以下Java代码
|
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Image URL.
@param ImageURL
URL of image
*/
public void setImageURL (String ImageURL)
{
set_Value (COLUMNNAME_ImageURL, ImageURL);
}
/** Get Image URL.
@return URL of image
*/
public String getImageURL ()
{
return (String)get_Value(COLUMNNAME_ImageURL);
}
public I_M_Product_Category getM_Product_Category() throws RuntimeException
{
return (I_M_Product_Category)MTable.get(getCtx(), I_M_Product_Category.Table_Name)
.getPO(getM_Product_Category_ID(), get_TrxName()); }
/** Set Product Category.
@param M_Product_Category_ID
Category of a Product
*/
public void setM_Product_Category_ID (int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, Integer.valueOf(M_Product_Category_ID));
}
/** Get Product Category.
@return Category of a Product
*/
public int getM_Product_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Training.
@param S_Training_ID
Repeated Training
*/
public void setS_Training_ID (int S_Training_ID)
{
if (S_Training_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Training_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID));
}
/** Get Training.
@return Repeated Training
*/
public int getS_Training_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_ID);
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_S_Training.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<ToDo> findAll() {
return null;
}
@Override
public List<ToDo> findAll(Sort sort) {
return null;
}
@Override
public Page<ToDo> findAll(Pageable pageable) {
return null;
}
@Override
public List<ToDo> findAllById(Iterable<Long> iterable) {
return null;
}
@Override
public long count() {
return 0;
}
@Override
public void deleteById(Long aLong) {
}
@Override
public void delete(ToDo toDo) {
}
@Override
public void deleteAll(Iterable<? extends ToDo> iterable) {
}
@Override
public void deleteAll() {
}
@Override
public <S extends ToDo> S save(S s) {
return null;
}
@Override
public <S extends ToDo> List<S> saveAll(Iterable<S> iterable) {
return null;
}
@Override
public Optional<ToDo> findById(Long aLong) {
return Optional.empty();
}
@Override
public boolean existsById(Long aLong) {
return false;
}
@Override
public void flush() {
}
@Override
public <S extends ToDo> S saveAndFlush(S s) {
return null;
}
|
@Override
public void deleteInBatch(Iterable<ToDo> iterable) {
}
@Override
public void deleteAllInBatch() {
}
@Override
public ToDo getOne(Long aLong) {
return null;
}
@Override
public <S extends ToDo> Optional<S> findOne(Example<S> example) {
return Optional.empty();
}
@Override
public <S extends ToDo> List<S> findAll(Example<S> example) {
return null;
}
@Override
public <S extends ToDo> List<S> findAll(Example<S> example, Sort sort) {
return null;
}
@Override
public <S extends ToDo> Page<S> findAll(Example<S> example, Pageable pageable) {
return null;
}
@Override
public <S extends ToDo> long count(Example<S> example) {
return 0;
}
@Override
public <S extends ToDo> boolean exists(Example<S> example) {
return false;
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\3.TodoProjectDB\src\main\java\spring\project\repository\LogicRepository.java
| 2
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) {
this.nameLikeIgnoreCase = nameLikeIgnoreCase;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
|
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public void setInvolvedGroups(List<String> involvedGroups) {
this.involvedGroups = involvedGroups;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
| 1
|
请完成以下Java代码
|
public void setKPI_AllowedStaledTimeInSec (final int KPI_AllowedStaledTimeInSec)
{
set_Value (COLUMNNAME_KPI_AllowedStaledTimeInSec, KPI_AllowedStaledTimeInSec);
}
@Override
public int getKPI_AllowedStaledTimeInSec()
{
return get_ValueAsInt(COLUMNNAME_KPI_AllowedStaledTimeInSec);
}
/**
* KPI_DataSource_Type AD_Reference_ID=541339
* Reference name: KPI_DataSource_Type
*/
public static final int KPI_DATASOURCE_TYPE_AD_Reference_ID=541339;
/** Elasticsearch = E */
public static final String KPI_DATASOURCE_TYPE_Elasticsearch = "E";
/** SQL = S */
public static final String KPI_DATASOURCE_TYPE_SQL = "S";
@Override
public void setKPI_DataSource_Type (final java.lang.String KPI_DataSource_Type)
{
set_Value (COLUMNNAME_KPI_DataSource_Type, KPI_DataSource_Type);
}
@Override
public java.lang.String getKPI_DataSource_Type()
{
return get_ValueAsString(COLUMNNAME_KPI_DataSource_Type);
}
@Override
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 setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setSQL_Details_WhereClause (final @Nullable java.lang.String SQL_Details_WhereClause)
{
set_Value (COLUMNNAME_SQL_Details_WhereClause, SQL_Details_WhereClause);
}
@Override
public java.lang.String getSQL_Details_WhereClause()
|
{
return get_ValueAsString(COLUMNNAME_SQL_Details_WhereClause);
}
@Override
public void setSQL_From (final @Nullable java.lang.String SQL_From)
{
set_Value (COLUMNNAME_SQL_From, SQL_From);
}
@Override
public java.lang.String getSQL_From()
{
return get_ValueAsString(COLUMNNAME_SQL_From);
}
@Override
public void setSQL_GroupAndOrderBy (final @Nullable java.lang.String SQL_GroupAndOrderBy)
{
set_Value (COLUMNNAME_SQL_GroupAndOrderBy, SQL_GroupAndOrderBy);
}
@Override
public java.lang.String getSQL_GroupAndOrderBy()
{
return get_ValueAsString(COLUMNNAME_SQL_GroupAndOrderBy);
}
@Override
public void setSQL_WhereClause (final @Nullable java.lang.String SQL_WhereClause)
{
set_Value (COLUMNNAME_SQL_WhereClause, SQL_WhereClause);
}
@Override
public java.lang.String getSQL_WhereClause()
{
return get_ValueAsString(COLUMNNAME_SQL_WhereClause);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI.java
| 1
|
请完成以下Java代码
|
private boolean isExtraSyncNeededForOldShipmentSchedule(
@NonNull final I_M_ShipmentSchedule currentShipmentScheduleRecord,
@NonNull final I_M_ShipmentSchedule oldShipmentScheduleRecord)
{
final WarehouseId oldRecordWarehouseId = shipmentScheduleEffectiveBL.getWarehouseId(oldShipmentScheduleRecord);
final WarehouseId currentRecordWarehouseId = shipmentScheduleEffectiveBL.getWarehouseId(currentShipmentScheduleRecord);
return oldShipmentScheduleRecord.getM_Product_ID() != currentShipmentScheduleRecord.getM_Product_ID()
|| !oldRecordWarehouseId.equals(currentRecordWarehouseId)
|| oldShipmentScheduleRecord.getM_Warehouse_ID() != currentShipmentScheduleRecord.getM_Warehouse_ID()
|| oldShipmentScheduleRecord.getM_AttributeSetInstance_ID() != currentShipmentScheduleRecord.getM_AttributeSetInstance_ID()
|| oldShipmentScheduleRecord.getAD_Org_ID() != currentShipmentScheduleRecord.getAD_Org_ID();
}
private void syncAvailableForSalesForShipmentSchedule(
@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord,
@NonNull final AvailableForSalesConfig config)
|
{
final Properties ctx = Env.copyCtx(InterfaceWrapperHelper.getCtx(shipmentScheduleRecord));
final ProductId productId = ProductId.ofRepoId(shipmentScheduleRecord.getM_Product_ID());
final OrgId orgId = OrgId.ofRepoId(shipmentScheduleRecord.getAD_Org_ID());
final AttributesKey storageAttributesKey = AttributesKeys
.createAttributesKeyFromASIStorageAttributes(AttributeSetInstanceId.ofRepoIdOrNone(shipmentScheduleRecord.getM_AttributeSetInstance_ID()))
.orElse(AttributesKey.NONE);
final WarehouseId warehouseId = shipmentScheduleEffectiveBL.getWarehouseId(shipmentScheduleRecord);
final EnqueueAvailableForSalesRequest enqueueAvailableForSalesRequest = availableForSalesUtil.
createRequestWithPreparationDateNow(ctx, config, productId, orgId, storageAttributesKey, warehouseId);
trxManager.runAfterCommit(() -> availableForSalesService.enqueueAvailableForSalesRequest(enqueueAvailableForSalesRequest));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\modelvalidator\M_ShipmentSchedule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public List<FormField> getFields() {
return fields;
}
public void setFields(List<FormField> fields) {
this.fields = fields;
}
public List<FormOutcome> getOutcomes() {
|
return outcomes;
}
public void setOutcomes(List<FormOutcome> outcomes) {
this.outcomes = outcomes;
}
public String getOutcomeVariableName() {
return outcomeVariableName;
}
public void setOutcomeVariableName(String outcomeVariableName) {
this.outcomeVariableName = outcomeVariableName;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\FormModelResponse.java
| 2
|
请完成以下Java代码
|
private LookupDataSourceContext.Builder prepareNewContext()
{
return LookupDataSourceContext.builder(LOOKUP_TABLE_NAME);
}
@Override
public LookupValue retrieveLookupValueById(@NonNull final LookupDataSourceContext evalCtx)
{
final Integer listValueIdAsInt = CTX_NAME_LIST_VALUE_ID.getValueAsInteger(evalCtx);
if (listValueIdAsInt <= 0)
{
return null;
}
final DataEntryListValueId listValueId = DataEntryListValueId.ofRepoId(listValueIdAsInt);
return id2LookupValue.get(listValueId);
}
@Override
public LookupValuesPage retrieveEntities(@NonNull final LookupDataSourceContext evalCtx)
{
return LookupValuesList.fromCollection(id2LookupValue.values())
.pageByOffsetAndLimit(
evalCtx.getOffset(0),
evalCtx.getLimit(Integer.MAX_VALUE));
}
private IntegerLookupValue createLookupValue(@NonNull final DataEntryListValue dataEntryListValue)
{
return IntegerLookupValue.of(
dataEntryListValue.getId(),
dataEntryListValue.getName(),
dataEntryListValue.getDescription());
}
@Override
public boolean isCached()
{
return true;
}
@Override
|
public String getCachePrefix()
{
return DataEntryListValueDataSourceFetcher.class.getSimpleName();
}
@Override
public Optional<String> getLookupTableName()
{
return Optional.of(LOOKUP_TABLE_NAME);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
/**
* Does nothing; this class doesn't use a cache; it is disposed as one.
*/
@Override
public void cacheInvalidate()
{
}
public DataEntryListValueId getListValueIdForLookup(@Nullable final IntegerLookupValue value)
{
return id2LookupValue.inverse().get(value);
}
public Object getLookupForForListValueId(@Nullable final DataEntryListValueId dataEntryListValueId)
{
return id2LookupValue.get(dataEntryListValueId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryListValueDataSourceFetcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setRfq_uuid(final String rfq_uuid)
{
this.rfq_uuid = rfq_uuid;
}
public boolean isRfq()
{
return rfq_uuid != null;
}
public List<ContractLine> getContractLines()
{
return Collections.unmodifiableList(contractLines);
}
@Nullable
public ContractLine getContractLineForProductOrNull(final Product product)
{
for (final ContractLine contractLine : getContractLines())
{
if (Product.COMPARATOR_Id.compare(contractLine.getProduct(), product) != 0)
{
continue;
}
return contractLine;
}
return null;
}
public Collection<Product> getProducts()
{
final Set<Product> products = new TreeSet<>(Product.COMPARATOR_Id);
for (final ContractLine contractLine : getContractLines())
|
{
if (contractLine.isDeleted())
{
continue;
}
final Product product = contractLine.getProduct();
if (product.isDeleted())
{
continue;
}
products.add(product);
}
return products;
}
public boolean matchesDate(final LocalDate date)
{
return DateUtils.between(date, getDateFrom(), getDateTo());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contract.java
| 2
|
请完成以下Java代码
|
public LookupValue getLookupValueById(final Object idObj)
{
final LookupValue country = getAllCountriesById().getById(idObj);
return CoalesceUtil.coalesce(country, LOOKUPVALUE_NULL);
}
@Override
public Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(CONTEXT_LookupTableName)
.requiresFilterAndLimit()
.requiresAD_Language();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
//
// Determine what we will filter
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int offset = evalCtx.getOffset(0);
final int limit = evalCtx.getLimit(filter.isMatchAll() ? Integer.MAX_VALUE : 100);
//
// Get, filter, return
return getAllCountriesById()
.getValues()
.stream()
.filter(filter)
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
private LookupValuesList getAllCountriesById()
{
final Object cacheKey = "ALL";
|
return allCountriesCache.getOrLoad(cacheKey, this::retriveAllCountriesById);
}
private LookupValuesList retriveAllCountriesById()
{
return Services.get(ICountryDAO.class)
.getCountries(Env.getCtx())
.stream()
.map(this::createLookupValue)
.collect(LookupValuesList.collect());
}
private IntegerLookupValue createLookupValue(final I_C_Country countryRecord)
{
final int countryId = countryRecord.getC_Country_ID();
final IModelTranslationMap modelTranslationMap = InterfaceWrapperHelper.getModelTranslationMap(countryRecord);
final ITranslatableString countryName = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Name, countryRecord.getName());
final ITranslatableString countryDescription = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Description, countryRecord.getName());
return IntegerLookupValue.of(countryId, countryName, countryDescription);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressCountryLookupDescriptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ContactInfoExpression {
@Id
@Column(name = "expression_type")
private String type;
private String pattern;
public ContactInfoExpression() {
}
public ContactInfoExpression(final String type, final String pattern) {
this.type = type;
this.pattern = pattern;
}
public String getType() {
|
return type;
}
public void setType(final String type) {
this.type = type;
}
public String getPattern() {
return pattern;
}
public void setPattern(final String pattern) {
this.pattern = pattern;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\dynamicvalidation\model\ContactInfoExpression.java
| 2
|
请完成以下Java代码
|
public class CustomerToDataFrameConverterApp {
private static final List<Customer> CUSTOMERS = Arrays.asList(
aCustomerWith("01", "jo", "Female", 2000),
aCustomerWith("02", "jack", "Male", 1200)
);
public static void main(String[] args) {
Dataset<Row> dataFrame = convertAfterMappingRows(CUSTOMERS);
print(dataFrame);
Dataset<Row> customerDF = convertToDataFrameWithNoChange();
print(customerDF);
}
public static Dataset<Row> convertToDataFrameWithNoChange() {
return SparkDriver.getSparkSession().createDataFrame(CUSTOMERS, Customer.class);
}
public static Dataset<Row> convertAfterMappingRows(List<Customer> customer) {
List<Row> rows = customer.stream()
|
.map(c -> new CustomerToRowMapper().call(c))
.collect(Collectors.toList());
return SparkDriver.getSparkSession()
.createDataFrame(rows, SchemaFactory.minimumCustomerDataSchema());
}
private static Customer aCustomerWith(String id, String name, String gender, int amount) {
return new Customer(id, name, gender, amount);
}
private static void print(Dataset<Row> dataFrame) {
dataFrame.printSchema();
dataFrame.show();
}
}
|
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\dataframes\CustomerToDataFrameConverterApp.java
| 1
|
请完成以下Java代码
|
public void process(final I_C_OLCand olCand) throws Exception
{
if (olCand.isProcessed())
{
result.incSkipped();
return;
}
final IParams params = processorCtx.getParams();
Check.errorIf(params == null, "Given processorCtx {} needs to contain params", processorCtx);
// Partner
final int bpartnerId = params.getParameterAsInt(I_C_OLCand.COLUMNNAME_C_BPartner_Override_ID, -1);
olCand.setC_BPartner_Override_ID(bpartnerId);
// Location
final BPartnerLocationId bpartnerLocationId = getBPartnerLocationId(olCand, params, bpartnerId);
olCand.setC_BP_Location_Override_ID(BPartnerLocationId.toRepoId(bpartnerLocationId));
// DatePrommissed
final Timestamp datePromissed = params.getParameterAsTimestamp(I_C_OLCand.COLUMNNAME_DatePromised_Override);
olCand.setDatePromised_Override(datePromissed);
//AD_User_ID
final UserId userId = UserId.ofRepoIdOrNull(olCand.getAD_User_ID());
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bpartnerId, BPartnerLocationId.toRepoId(bpartnerLocationId));
if (bPartnerLocationId != null && userId != null)
{
final boolean userIsValidForBpartner = bpartnerDAO.getUserIdsForBpartnerLocation(bPartnerLocationId).anyMatch(userId::equals);
if (!userIsValidForBpartner)
{
Loggables.withLogger(logger, Level.INFO).addLog("For OLCand: {}, userId {} is not valid for locationId: {}. Setting to null", olCand.getC_OLCand_ID(), userId, bPartnerLocationId);
olCand.setAD_User_ID(-1);
}
}
|
InterfaceWrapperHelper.save(olCand);
result.incUpdated();
}
@Nullable
private BPartnerLocationId getBPartnerLocationId(final I_C_OLCand olCand, final IParams params, final int bpartnerId)
{
final BPartnerLocationId bpartnerLocationId;
if (params.hasParameter(PARAM_C_BPARTNER_LOCATION_MAP))
{
final Map<BPartnerLocationId, BPartnerLocationId> oldToNewLocationIds = (Map<BPartnerLocationId, BPartnerLocationId>)params.getParameterAsObject(PARAM_C_BPARTNER_LOCATION_MAP);
bpartnerLocationId = oldToNewLocationIds.get(BPartnerLocationId.ofRepoId(olCand.getC_BPartner_ID(), olCand.getC_BPartner_Location_ID()));
}
else
{
bpartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bpartnerId, params.getParameterAsInt(I_C_OLCand.COLUMNNAME_C_BP_Location_Override_ID, -1));
}
return bpartnerLocationId;
}
@Override
public OLCandUpdateResult getResult()
{
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\impl\OLCandUpdater.java
| 1
|
请完成以下Java代码
|
public static PickingUnit ofNullableJson(@Nullable final String json)
{
final String jsonNorm = StringUtils.trimBlankToNull(json);
return jsonNorm != null ? ofJson(jsonNorm) : null;
}
@NonNull
public static PickingUnit ofJson(@NonNull final String json)
{
if (Objects.equals(TU.json, json))
{
return TU;
}
else if (Objects.equals(CU.json, json))
{
return CU;
}
else
{
throw new AdempiereException("Cannot convert json `" + json + "` to " + PickingUnit.class.getSimpleName());
}
|
}
@JsonValue
public String toJson() {return json;}
public boolean isTU() {return TU.equals(this);}
public boolean isCU() {return CU.equals(this);}
public void assertIsCU()
{
if (!isCU())
{
throw new AdempiereException("Expected Picking Unit to be CU");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingUnit.java
| 1
|
请完成以下Java代码
|
public class AioServerRunnable implements Runnable {
private AsynchronousServerSocketChannel socketChannel;
private CountDownLatch latch;
public AioServerRunnable(AsynchronousServerSocketChannel socketChannel) {
this.socketChannel = socketChannel;
}
@Override
public void run() {
latch = new CountDownLatch(1);
//用于接收客户端的连接,异步操作,
// 需要实现了CompletionHandler接口的处理器处理和客户端的连接操作
socketChannel.accept(this, new AioAcceptHandler());
|
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public AsynchronousServerSocketChannel getSocketChannel() {
return socketChannel;
}
public CountDownLatch getLatch() {
return latch;
}
}
|
repos\spring-boot-student-master\spring-boot-student-netty\src\main\java\com\xiaolyuh\aio\server\AioServerRunnable.java
| 1
|
请完成以下Java代码
|
public ModelQuery orderByModelVersion() {
return orderBy(ModelQueryProperty.MODEL_VERSION);
}
public ModelQuery orderByModelName() {
return orderBy(ModelQueryProperty.MODEL_NAME);
}
public ModelQuery orderByCreateTime() {
return orderBy(ModelQueryProperty.MODEL_CREATE_TIME);
}
public ModelQuery orderByLastUpdateTime() {
return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME);
}
public ModelQuery orderByTenantId() {
return orderBy(ModelQueryProperty.MODEL_TENANT_ID);
}
// results ////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getModelEntityManager().findModelCountByQueryCriteria(this);
}
public List<Model> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getModelEntityManager().findModelsByQueryCriteria(this, page);
}
// getters ////////////////////////////////////////////
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public Integer getVersion() {
return version;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public static long getSerialversionuid() {
return serialVersionUID;
|
}
public String getKey() {
return key;
}
public boolean isLatest() {
return latest;
}
public String getDeploymentId() {
return deploymentId;
}
public boolean isNotDeployed() {
return notDeployed;
}
public boolean isDeployed() {
return deployed;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
| 1
|
请完成以下Java代码
|
public JsonWorkplaceSettings getStatus()
{
return JsonWorkplaceSettings.builder()
.workplaceRequired(workplaceService.isAnyWorkplaceActive())
.assignedWorkplace(workplaceService.getWorkplaceByUserId(Env.getLoggedUserId())
.map(this::toJson)
.orElse(null))
.build();
}
@PostMapping("/{workplaceId}/assign")
public JsonWorkplace assignWorkplace(@PathVariable("workplaceId") @NonNull final Integer workplaceIdInt)
{
final WorkplaceId workplaceId = WorkplaceId.ofRepoId(workplaceIdInt);
workplaceService.assignWorkplace(WorkplaceAssignmentCreateRequest.builder()
.workplaceId(workplaceId)
.userId(Env.getLoggedUserId())
.build());
return getWorkplaceById(workplaceId);
}
@PostMapping("/byQRCode")
|
public JsonWorkplace getWorkplaceByQRCode(@RequestBody @NonNull final JsonGetWorkplaceByQRCodeRequest request)
{
final WorkplaceQRCode qrCode = WorkplaceQRCode.ofGlobalQRCodeJsonString(request.getQrCode());
return getWorkplaceById(qrCode.getWorkplaceId());
}
private JsonWorkplace getWorkplaceById(@NonNull final WorkplaceId workplaceId)
{
final Workplace workplace = workplaceService.getById(workplaceId);
return toJson(workplace);
}
private JsonWorkplace toJson(final Workplace workplace)
{
return JsonWorkplace.builder()
.id(workplace.getId())
.name(workplace.getName())
.qrCode(WorkplaceQRCode.ofWorkplace(workplace).toGlobalQRCodeJsonString())
.warehouseName(workplace.getWarehouseId() != null ? warehouseService.getWarehouseName(workplace.getWarehouseId()) : null)
.isUserAssigned(workplaceService.isUserAssigned(Env.getLoggedUserId(), workplace.getId()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\workplace\WorkplaceRestController.java
| 1
|
请完成以下Java代码
|
public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID)
{
if (SerialNo_Sequence_ID < 1)
set_Value (COLUMNNAME_SerialNo_Sequence_ID, null);
else
set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID);
}
@Override
public int getSerialNo_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
|
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.