instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
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 Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Serial No.
@param SerNo
Product Serial Number
*/
public void setSerNo (String SerNo)
{
set_Value (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
|
{
set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_ValueNoCheck (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_Value (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InMemoryRouteDefinitionRepository implements RouteDefinitionRepository {
private final Map<String, RouteDefinition> routes = synchronizedMap(new LinkedHashMap<String, RouteDefinition>());
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
return route.flatMap(r -> {
if (ObjectUtils.isEmpty(r.getId())) {
return Mono.error(new IllegalArgumentException("id may not be empty"));
}
routes.put(r.getId(), r);
return Mono.empty();
});
}
@Override
public Mono<Void> delete(Mono<String> routeId) {
|
return routeId.flatMap(id -> {
if (routes.containsKey(id)) {
routes.remove(id);
return Mono.empty();
}
return Mono.defer(() -> Mono.error(new NotFoundException("RouteDefinition not found: " + routeId)));
});
}
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
Map<String, RouteDefinition> routesSafeCopy = new LinkedHashMap<>(routes);
return Flux.fromIterable(routesSafeCopy.values());
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\InMemoryRouteDefinitionRepository.java
| 2
|
请完成以下Java代码
|
public ReactorClientHttpRequestFactoryBuilder withHttpClientFactory(Supplier<HttpClient> factory) {
Assert.notNull(factory, "'factory' must not be null");
return new ReactorClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientFactory(factory));
}
/**
* Return a new {@link ReactorClientHttpRequestFactoryBuilder} that applies additional
* customization to the underlying {@link HttpClient}.
* @param httpClientCustomizer the customizer to apply
* @return a new {@link ReactorClientHttpRequestFactoryBuilder} instance
*/
public ReactorClientHttpRequestFactoryBuilder withHttpClientCustomizer(
UnaryOperator<HttpClient> httpClientCustomizer) {
Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null");
return new ReactorClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientCustomizer(httpClientCustomizer));
}
/**
* Return a new {@link ReactorClientHttpRequestFactoryBuilder} that applies the given
* customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply
* @return a new {@link ReactorClientHttpRequestFactoryBuilder}
* @since 4.0.0
*/
public ReactorClientHttpRequestFactoryBuilder with(
UnaryOperator<ReactorClientHttpRequestFactoryBuilder> customizer) {
|
return customizer.apply(this);
}
@Override
protected ReactorClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) {
HttpClient httpClient = this.httpClientBuilder.build(settings.withTimeouts(null, null));
ReactorClientHttpRequestFactory requestFactory = new ReactorClientHttpRequestFactory(httpClient);
PropertyMapper map = PropertyMapper.get();
map.from(settings::connectTimeout).asInt(Duration::toMillis).to(requestFactory::setConnectTimeout);
map.from(settings::readTimeout).asInt(Duration::toMillis).to(requestFactory::setReadTimeout);
return requestFactory;
}
static class Classes {
static final String HTTP_CLIENT = "reactor.netty.http.client.HttpClient";
static boolean present(@Nullable ClassLoader classLoader) {
return ClassUtils.isPresent(HTTP_CLIENT, classLoader);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ReactorClientHttpRequestFactoryBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public UmsResource getItem(Long id) {
return resourceMapper.selectByPrimaryKey(id);
}
@Override
public int delete(Long id) {
int count = resourceMapper.deleteByPrimaryKey(id);
adminCacheService.delResourceListByResource(id);
return count;
}
@Override
public List<UmsResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum,pageSize);
UmsResourceExample example = new UmsResourceExample();
UmsResourceExample.Criteria criteria = example.createCriteria();
if(categoryId!=null){
|
criteria.andCategoryIdEqualTo(categoryId);
}
if(StrUtil.isNotEmpty(nameKeyword)){
criteria.andNameLike('%'+nameKeyword+'%');
}
if(StrUtil.isNotEmpty(urlKeyword)){
criteria.andUrlLike('%'+urlKeyword+'%');
}
return resourceMapper.selectByExample(example);
}
@Override
public List<UmsResource> listAll() {
return resourceMapper.selectByExample(new UmsResourceExample());
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsResourceServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getProcessInstanceId() {
return job.getProcessInstanceId();
}
@Override
public String getExecutionId() {
return job.getExecutionId();
}
@Override
public String getProcessDefinitionId() {
return job.getProcessDefinitionId();
}
@Override
public String getCategory() {
return job.getCategory();
}
@Override
public String getJobType() {
return job.getJobType();
}
@Override
public String getElementId() {
return job.getElementId();
}
@Override
public String getElementName() {
return job.getElementName();
}
@Override
public String getScopeId() {
return job.getScopeId();
}
@Override
public String getSubScopeId() {
return job.getSubScopeId();
}
@Override
public String getScopeType() {
return job.getScopeType();
}
@Override
public String getScopeDefinitionId() {
return job.getScopeDefinitionId();
}
@Override
public String getCorrelationId() {
return job.getCorrelationId();
}
@Override
public boolean isExclusive() {
return job.isExclusive();
}
@Override
public Date getCreateTime() {
return job.getCreateTime();
}
@Override
public String getId() {
return job.getId();
}
@Override
public int getRetries() {
return job.getRetries();
}
|
@Override
public String getExceptionMessage() {
return job.getExceptionMessage();
}
@Override
public String getTenantId() {
return job.getTenantId();
}
@Override
public String getJobHandlerType() {
return job.getJobHandlerType();
}
@Override
public String getJobHandlerConfiguration() {
return job.getJobHandlerConfiguration();
}
@Override
public String getCustomValues() {
return job.getCustomValues();
}
@Override
public String getLockOwner() {
return job.getLockOwner();
}
@Override
public Date getLockExpirationTime() {
return job.getLockExpirationTime();
}
@Override
public String toString() {
return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]")
.add("job=" + job)
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new CustomConverter());
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StringWithoutSpaceDeserializer(String.class));
mapper.registerModule(module);
converter.setObjectMapper(mapper);
return converter;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/user/**")
.allowedMethods("GET", "POST")
.allowedOrigins("https://javastack.cn")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true).maxAge(3600);
}
@Bean
public ServletRegistrationBean registerServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new RegisterServlet(), "/registerServlet");
servletRegistrationBean.addInitParameter("name", "registerServlet");
servletRegistrationBean.addInitParameter("sex", "man");
servletRegistrationBean.setIgnoreRegistrationFailure(true);
return servletRegistrationBean;
|
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return (servletContext) -> {
ServletRegistration initServlet = servletContext.addServlet("initServlet", InitServlet.class);
initServlet.addMapping("/initServlet");
initServlet.setInitParameter("name", "initServlet");
initServlet.setInitParameter("sex", "man");
};
}
@Bean
public RestTemplate defaultRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(5))
.basicAuthentication("test", "test")
.build();
}
@Bean
public RestClient defaultRestClient(RestClient.Builder restClientBuilder) {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS
.withConnectTimeout(Duration.ofSeconds(3))
.withReadTimeout(Duration.ofSeconds(3));
ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories.get(settings);
return restClientBuilder
.baseUrl("http://localhost:8080")
.defaultHeader("Authorization", "Bearer test")
.requestFactory(requestFactory)
.build();
}
}
|
repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\config\WebConfig.java
| 2
|
请完成以下Java代码
|
public Builder setCaption(final ITranslatableString caption)
{
this.caption = caption;
return this;
}
public Builder setDescription(final ITranslatableString description)
{
this.description = description;
return this;
}
public Builder notFoundMessages(@Nullable NotFoundMessages notFoundMessages)
{
this.notFoundMessages = notFoundMessages;
return this;
}
public Builder addSection(@NonNull final DocumentLayoutSectionDescriptor.Builder sectionBuilderToAdd)
|
{
sectionBuilders.add(sectionBuilderToAdd);
return this;
}
public Builder addSections(@NonNull final Collection<DocumentLayoutSectionDescriptor.Builder> sectionBuildersToAdd)
{
sectionBuilders.addAll(sectionBuildersToAdd);
return this;
}
public boolean isEmpty()
{
return sectionBuilders.isEmpty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSingleRow.java
| 1
|
请完成以下Java代码
|
public ProcessInstance startAsync() {
return runtimeService.startProcessInstanceAsync(this);
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionParentDeploymentId() {
return processDefinitionParentDeploymentId;
}
public String getMessageName() {
return messageName;
}
public String getStartEventId() {
return startEventId;
}
public String getProcessInstanceName() {
return processInstanceName;
}
public String getBusinessKey() {
return businessKey;
}
public String getBusinessStatus() {
return businessStatus;
}
public String getCallbackId() {
return callbackId;
}
public String getCallbackType() {
return callbackType;
}
public String getReferenceId() {
return referenceId;
}
public String getReferenceType() {
return referenceType;
}
public String getStageInstanceId() {
return stageInstanceId;
}
public String getTenantId() {
return tenantId;
}
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
public String getPredefinedProcessInstanceId() {
return predefinedProcessInstanceId;
}
public String getOwnerId() {
|
return ownerId;
}
public String getAssigneeId() {
return assigneeId;
}
public Map<String, Object> getVariables() {
return variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
public Map<String, Object> getStartFormVariables() {
return startFormVariables;
}
public String getOutcome() {
return outcome;
}
public Map<String, Object> getExtraFormVariables() {
return extraFormVariables;
}
public FormInfo getExtraFormInfo() {
return extraFormInfo;
}
public String getExtraFormOutcome() {
return extraFormOutcome;
}
public boolean isFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceBuilderImpl.java
| 1
|
请完成以下Java代码
|
public void distributeQuantityToHUs(@NonNull final I_M_InventoryLine inventoryLineRecord)
{
inventoryRepository.updateInventoryLineByRecord(inventoryLineRecord, InventoryLine::distributeQtyCountToHUs);
}
public void deleteInventoryLineHUs(@NonNull final InventoryLineId inventoryLineId)
{
inventoryRepository.deleteInventoryLineHUs(inventoryLineId);
}
public InventoryLine toInventoryLine(final I_M_InventoryLine inventoryLineRecord)
{
return inventoryRepository.toInventoryLine(inventoryLineRecord);
}
public Collection<I_M_InventoryLine> retrieveAllLinesForHU(final HuId huId)
{
return inventoryRepository.retrieveAllLinesForHU(huId);
}
public void saveInventoryLineHURecords(final InventoryLine inventoryLine, final @NonNull InventoryId inventoryId)
{
inventoryRepository.saveInventoryLineHURecords(inventoryLine, inventoryId);
}
public Stream<InventoryReference> streamReferences(@NonNull final InventoryQuery query)
{
return inventoryRepository.streamReferences(query);
}
public Inventory updateById(@NonNull final InventoryId inventoryId, @NonNull final UnaryOperator<Inventory> updater)
{
return inventoryRepository.updateById(inventoryId, updater);
}
public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater)
{
|
inventoryRepository.updateByQuery(query, updater);
}
public DraftInventoryLinesCreateResponse createDraftLines(@NonNull final DraftInventoryLinesCreateRequest request)
{
return DraftInventoryLinesCreateCommand.builder()
.inventoryRepository(inventoryRepository)
.huForInventoryLineFactory(huForInventoryLineFactory)
.request(request)
.build()
.execute();
}
public void setQtyCountToQtyBookForInventory(@NonNull final InventoryId inventoryId)
{
inventoryRepository.setQtyCountToQtyBookForInventory(inventoryId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void updateData(String schemaName, String tableName, DBObject query, Document obj) {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.UPDATE.getNumber();
Document options = new Document(query.toMap());
try {
obj.remove("id");
mongoTemplate.getCollection(tableName).replaceOne(options,obj);
obj.putAll(query.toMap());
SpringUtil.doEvent(path, obj);
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
public void deleteData(String schemaName, String tableName, Document obj) {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.DELETE.getNumber();
//保存原始数据
|
try {
if (obj.containsKey("id")) {
obj.put("_id", obj.get("id"));
obj.remove("id");
mongoTemplate.remove(new BasicQuery(obj),tableName);
}
SpringUtil.doEvent(path, obj);
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
}
|
repos\spring-boot-leaning-master\2.x_data\3-4 解决后期业务变动导致的数据结构不一致的问题\spring-boot-canal-mongodb-cascade\src\main\java\com\neo\service\DataService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void validate() {
baseCalculatedFieldRestriction();
propagationRestriction();
if (!applyExpressionToResolvedArguments) {
arguments.forEach((name, argument) -> {
if (!currentEntitySource(argument)) {
throw new IllegalArgumentException("Arguments in 'Arguments only' propagation mode support only the 'Current entity' source entity type!");
}
if (argument.getRefEntityKey() == null) {
throw new IllegalArgumentException("Argument: '" + name + "' doesn't have reference entity key configured!");
}
if (argument.getRefEntityKey().getType() == ArgumentType.TS_ROLLING) {
throw new IllegalArgumentException("Argument type: 'Time series rolling' detected for argument: '" + name + "'. " +
"Only 'Attribute' or 'Latest telemetry' arguments are allowed for 'Arguments only' propagation mode!");
}
});
} else {
boolean noneMatchCurrentEntitySource = arguments.entrySet()
.stream()
.noneMatch(entry -> currentEntitySource(entry.getValue()));
if (noneMatchCurrentEntitySource) {
throw new IllegalArgumentException("At least one argument must be configured with the 'Current entity' " +
"source entity type for 'Expression result' propagation mode!");
}
if (StringUtils.isBlank(expression)) {
throw new IllegalArgumentException("Expression must be specified for 'Expression result' propagation mode!");
}
|
}
}
public Argument toPropagationArgument() {
var refDynamicSourceConfiguration = new RelationPathQueryDynamicSourceConfiguration();
refDynamicSourceConfiguration.setLevels(List.of(relation));
var propagationArgument = new Argument();
propagationArgument.setRefDynamicSourceConfiguration(refDynamicSourceConfiguration);
return propagationArgument;
}
private void propagationRestriction() {
if (arguments.entrySet().stream().anyMatch(entry -> entry.getKey().equals(PROPAGATION_CONFIG_ARGUMENT))) {
throw new IllegalArgumentException("Argument name '" + PROPAGATION_CONFIG_ARGUMENT + "' is reserved and cannot be used.");
}
}
private boolean currentEntitySource(Argument argument) {
return argument.getRefEntityId() == null && argument.getRefDynamicSourceConfiguration() == null;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\PropagationCalculatedFieldConfiguration.java
| 2
|
请完成以下Java代码
|
protected Object coerceStringToType(String value, Class<?> type) {
PropertyEditor editor = PropertyEditorManager.findEditor(type);
if (editor == null) {
if ("".equals(value)) {
return null;
}
throw new ELException(LocalMessages.get("error.coerce.type", String.class, type));
} else {
if ("".equals(value)) {
try {
editor.setAsText(value);
} catch (IllegalArgumentException e) {
return null;
}
} else {
try {
editor.setAsText(value);
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.coerce.value", value, type));
}
}
return editor.getValue();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object coerceToType(Object value, Class<?> type) {
if (type == String.class) {
return coerceToString(value);
}
if (type == Long.class || type == long.class) {
return coerceToLong(value);
}
if (type == Double.class || type == double.class) {
return coerceToDouble(value);
}
if (type == Boolean.class || type == boolean.class) {
return coerceToBoolean(value);
}
if (type == Integer.class || type == int.class) {
return coerceToInteger(value);
}
if (type == Float.class || type == float.class) {
return coerceToFloat(value);
}
if (type == Short.class || type == short.class) {
return coerceToShort(value);
|
}
if (type == Byte.class || type == byte.class) {
return coerceToByte(value);
}
if (type == Character.class || type == char.class) {
return coerceToCharacter(value);
}
if (type == BigDecimal.class) {
return coerceToBigDecimal(value);
}
if (type == BigInteger.class) {
return coerceToBigInteger(value);
}
if (type.getSuperclass() == Enum.class) {
return coerceToEnum(value, (Class<? extends Enum>) type);
}
if (value == null || value.getClass() == type || type.isInstance(value)) {
return value;
}
if (value instanceof String) {
return coerceStringToType((String) value, type);
}
throw new ELException(LocalMessages.get("error.coerce.type", value.getClass(), type));
}
@Override
public boolean equals(Object obj) {
return obj != null && obj.getClass().equals(getClass());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
@SuppressWarnings("unchecked")
public <T> T convert(Object value, Class<T> type) throws ELException {
return (T) coerceToType(value, type);
}
}
|
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\TypeConverterImpl.java
| 1
|
请完成以下Java代码
|
public List<ReceiptScheduleId> listIdsByQuery(@NonNull final ReceiptScheduleQuery query)
{
return buildQuery(query)
.listIds(ReceiptScheduleId::ofRepoId);
}
@NonNull
@Override
public Optional<ReceiptScheduleId> getIdByQuery(@NonNull final ReceiptScheduleQuery query)
{
return buildQuery(query)
.firstIdOnlyOptional(ReceiptScheduleId::ofRepoId);
}
@NonNull
private IQuery<I_M_ReceiptSchedule> buildQuery(@NonNull final ReceiptScheduleQuery query)
{
final IQueryBuilder<I_M_ReceiptSchedule> builder = queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.addOnlyActiveRecordsFilter();
final ExternalSystemIdWithExternalIds externalSystemIdWithExternalIds = query.getExternalSystemIdWithExternalIds();
if (externalSystemIdWithExternalIds != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalSystem_ID, externalSystemIdWithExternalIds.getExternalSystemId().getRepoId());
final ExternalHeaderIdWithExternalLineIds externalIds = externalSystemIdWithExternalIds.getExternalHeaderIdWithExternalLineIds();
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalHeaderId, externalIds.getExternalHeaderId().getValue());
if (!Check.isEmpty(externalIds.getExternalLineIdsAsString()))
{
builder.addInArrayFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalLineId, externalIds.getExternalLineIdsAsString());
}
}
if (query.getOrderLineId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_C_OrderLine_ID, query.getOrderLineId());
}
|
if (query.getProductId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_Product_ID, query.getProductId());
}
if (query.getWarehouseId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID, query.getWarehouseId());
}
if (query.getOrgId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID, query.getOrgId());
}
if (query.getAttributesKey() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_AttributeSetInstance_ID, query.getAttributesKey().getAsString(), ASIQueryFilterModifier.instance);
}
// Filter by quantity
if (query.isOnlyNonZeroQty())
{
builder.addNotEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_QtyToMove, 0);
}
return builder.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleDAO.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
return Objects.hash(id, name, description, type, required, display, displayName, analytics);
}
@Override
public String toString() {
return (
"VariableDefinitionImpl{" +
"id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", description='" +
description +
'\'' +
", type='" +
type +
|
'\'' +
", required=" +
required +
", display=" +
display +
", displayName='" +
displayName +
'\'' +
", analytics='" +
analytics +
'\'' +
'}'
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\VariableDefinitionImpl.java
| 1
|
请完成以下Java代码
|
protected Environment getEnvironment() {
return environment;
}
/** {@inheritDoc} */
@Override
public void execute() throws MojoExecutionException {
Map<String, Object> defaultProperties = new HashMap<>();
defaultProperties.put("spring.config.location", "optional:file:./src/main/resources/");
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.sources(Application.class)
.bannerMode(Banner.Mode.OFF)
.properties(defaultProperties)
.run();
this.environment = context.getEnvironment();
|
String[] activeProfiles = context.getEnvironment().getActiveProfiles();
String profiles = activeProfiles.length != 0 ? String.join(",", activeProfiles) : "Default";
log.info("Active Profiles: {}", profiles);
StringEncryptor encryptor = context.getBean(StringEncryptor.class);
run(new EncryptionService(encryptor), context, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
}
/**
* Run the encryption task.
*
* @param encryptionService the service for encryption
* @param context app context
*/
abstract void run(EncryptionService encryptionService, ConfigurableApplicationContext context, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException;
}
|
repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\AbstractJasyptMojo.java
| 1
|
请完成以下Java代码
|
public static List<Student> deepCopyUsingSerialization(List<Student> students) {
return students.stream()
.map(SerializationUtils::clone)
.collect(Collectors.toList());
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
@Override
public Student clone() {
Student student;
try {
student = (Student) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
student.course = this.course.clone();
return student;
}
|
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Student that = (Student) o;
return Objects.equals(studentId,that.studentId) &&
Objects.equals(studentName, that.studentName) &&
Objects.equals(course, that.course);
}
@Override
public int hashCode() {
return Objects.hash(studentId,studentName,course);
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\deepcopyarraylist\Student.java
| 1
|
请完成以下Java代码
|
protected void updateAsyncAfterTargetConfiguration(AsyncContinuationConfiguration currentConfiguration) {
ActivityImpl targetActivity = (ActivityImpl) targetScope;
List<PvmTransition> outgoingTransitions = targetActivity.getOutgoingTransitions();
AsyncContinuationConfiguration targetConfiguration = new AsyncContinuationConfiguration();
if (outgoingTransitions.isEmpty()) {
targetConfiguration.setAtomicOperation(PvmAtomicOperation.ACTIVITY_END.getCanonicalName());
}
else {
targetConfiguration.setAtomicOperation(PvmAtomicOperation.TRANSITION_NOTIFY_LISTENER_TAKE.getCanonicalName());
if (outgoingTransitions.size() == 1) {
targetConfiguration.setTransitionId(outgoingTransitions.get(0).getId());
}
else {
TransitionImpl matchingTargetTransition = null;
String currentTransitionId = currentConfiguration.getTransitionId();
if (currentTransitionId != null) {
|
matchingTargetTransition = targetActivity.findOutgoingTransition(currentTransitionId);
}
if (matchingTargetTransition != null) {
targetConfiguration.setTransitionId(matchingTargetTransition.getId());
}
else {
// should not happen since it is avoided by validation
throw new ProcessEngineException("Cannot determine matching outgoing sequence flow");
}
}
}
jobEntity.setJobHandlerConfiguration(targetConfiguration);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingAsyncJobInstance.java
| 1
|
请完成以下Java代码
|
public RefundConfig getRefundConfig(@NonNull final BigDecimal qtyInStockUom)
{
return refundConfigs
.stream()
.filter(config -> config.getMinQty().compareTo(qtyInStockUom) <= 0)
.findFirst()
.orElse(null);
}
public List<RefundConfig> getRefundConfigsToApplyForQuantity(@NonNull final BigDecimal qty)
{
final Predicate<RefundConfig> minQtyLessOrEqual = config -> config.getMinQty().compareTo(qty) <= 0;
return refundConfigs
.stream()
.filter(minQtyLessOrEqual)
.collect(ImmutableList.toImmutableList());
}
public RefundConfig getRefundConfigById(@NonNull final RefundConfigId refundConfigId)
{
for (RefundConfig refundConfig : refundConfigs)
{
if (refundConfig.getId().equals(refundConfigId))
{
return refundConfig;
}
}
Check.fail("This contract has no config with id={}; this={}", refundConfigId, this);
return null;
}
public RefundMode extractRefundMode()
{
return RefundConfigs.extractRefundMode(refundConfigs);
}
public Optional<RefundConfig> getRefundConfigToUseProfitCalculation()
{
return getRefundConfigs()
.stream()
.filter(RefundConfig::isUseInProfitCalculation)
.findFirst();
}
/**
* With this instance's {@code StartDate} as basis, the method returns the first date that is
* after or at the given {@code currentDate} and that is aligned with this instance's invoice schedule.
*/
public NextInvoiceDate computeNextInvoiceDate(@NonNull final LocalDate currentDate)
|
{
final InvoiceSchedule invoiceSchedule = extractSingleElement(refundConfigs, RefundConfig::getInvoiceSchedule);
LocalDate date = invoiceSchedule.calculateNextDateToInvoice(startDate);
while (date.isBefore(currentDate))
{
final LocalDate nextDate = invoiceSchedule.calculateNextDateToInvoice(date);
Check.assume(nextDate.isAfter(date), // make sure not to get stuck in an endless loop
"For the given date={}, invoiceSchedule.calculateNextDateToInvoice needs to return a nextDate that is later; nextDate={}",
date, nextDate);
date = nextDate;
}
return new NextInvoiceDate(invoiceSchedule, date);
}
@Value
public static class NextInvoiceDate
{
InvoiceSchedule invoiceSchedule;
LocalDate dateToInvoice;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundContract.java
| 1
|
请完成以下Java代码
|
public String getDates(Model model) {
// "truthy" values
model.addAttribute("trueValue", true);
model.addAttribute("one", 1);
model.addAttribute("nonZeroCharacter", 'a');
model.addAttribute("emptyString", "");
model.addAttribute("foo", "foo");
model.addAttribute("object", new Object());
model.addAttribute("arrayOfZeros", new Integer[] { 0, 0 });
model.addAttribute("arrayOfZeroAndOne", new Integer[] { 0, 1 });
model.addAttribute("arrayOfOnes", new Integer[] { 1, 1 });
// "falsy" values
model.addAttribute("nullValue", null);
model.addAttribute("falseValue", false);
|
model.addAttribute("zero", 0);
model.addAttribute("zeroCharacter", '\0');
model.addAttribute("falseString", "false");
model.addAttribute("no", "no");
model.addAttribute("off", "off");
model.addAttribute("isRaining", true);
model.addAttribute("isSunny", true);
model.addAttribute("isCold", false);
model.addAttribute("isWarm", true);
return "booleans.html";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\booleanexpressions\BooleanExpressionsController.java
| 1
|
请完成以下Java代码
|
public void addCandidateGroups(Task task, List<IdentityLink> candidateGroups) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateGroups) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks, cmmnEngineConfiguration);
}
@Override
public void addUserIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void addGroupIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
|
}
@Override
public void deleteUserIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, cmmnEngineConfiguration);
}
@Override
public void deleteGroupIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, cmmnEngineConfiguration);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cfg\DefaultTaskAssignmentManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void reservePickFromHUs(final PickingJob pickingJob)
{
for (final PickingJobLine line : pickingJob.getLines())
{
for (final PickingJobStep step : line.getSteps())
{
reservePickFromHU(step, pickingJob.getCustomerId());
}
}
}
private void reservePickFromHU(@NonNull final PickingJobStep step, @Nullable final BPartnerId customerId)
{
huReservationService.makeReservation(
ReserveHUsRequest.builder()
.customerId(customerId)
.documentRef(HUReservationDocRef.ofPickingJobStepId(step.getId()))
.productId(step.getProductId())
.qtyToReserve(step.getQtyToPick())
.huId(step.getPickFrom(PickingJobStepPickFromKey.MAIN).getPickFromHUId())
.build())
.orElseThrow(() -> new AdempiereException("Cannot reserve HU for " + step)); // shall not happen
}
public void releaseAllReservations(@NonNull final PickingJob pickingJob)
{
final ImmutableSet<HUReservationDocRef> reservationDocRefs = pickingJob
.getLines().stream()
.flatMap(line -> line.getSteps().stream())
.map(step -> HUReservationDocRef.ofPickingJobStepId(step.getId()))
.collect(ImmutableSet.toImmutableSet());
huReservationService.deleteReservationsByDocumentRefs(reservationDocRefs);
}
@Nullable
|
public ProductAvailableStocks newAvailableStocksProvider(@NonNull final Workplace workplace)
{
final Set<LocatorId> pickFromLocatorIds = warehouseService.getPickFromLocatorIds(workplace);
if (pickFromLocatorIds.isEmpty())
{
return null;
}
return ProductAvailableStocks.builder()
.handlingUnitsBL(handlingUnitsBL)
.pickFromLocatorIds(pickFromLocatorIds)
.build();
}
public boolean containsProduct(@NonNull final HuId huId, @NonNull ProductId productId)
{
return getHUProductStorage(huId, productId)
.map(IHUProductStorage::getQty)
.map(Quantity::isPositive)
.orElse(false);
}
private Optional<IHUProductStorage> getHUProductStorage(final @NotNull HuId huId, final @NotNull ProductId productId)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
return Optional.ofNullable(storageFactory.getStorage(hu).getProductStorageOrNull(productId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\PickingJobHUService.java
| 2
|
请完成以下Java代码
|
public class StringDictionary extends SimpleDictionary<String>
{
/**
* key value之间的分隔符
*/
protected String separator;
public StringDictionary(String separator)
{
this.separator = separator;
}
public StringDictionary()
{
this("=");
}
@Override
protected Map.Entry<String, String> onGenerateEntry(String line)
{
String[] paramArray = line.split(separator, 2);
if (paramArray.length != 2)
{
Predefine.logger.warning("词典有一行读取错误: " + line);
return null;
}
return new AbstractMap.SimpleEntry<String, String>(paramArray[0], paramArray[1]);
}
/**
* 保存词典
* @param path
* @return 是否成功
*/
public boolean save(String path)
{
try
{
|
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
for (Map.Entry<String, String> entry : trie.entrySet())
{
bw.write(entry.getKey());
bw.write(separator);
bw.write(entry.getValue());
bw.newLine();
}
bw.close();
}
catch (Exception e)
{
Predefine.logger.warning("保存词典到" + path + "失败");
return true;
}
return false;
}
/**
* 将自己逆转过来返回
* @return
*/
public StringDictionary reverse()
{
StringDictionary dictionary = new StringDictionary(separator);
for (Map.Entry<String, String> entry : entrySet())
{
dictionary.trie.put(entry.getValue(), entry.getKey());
}
return dictionary;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\StringDictionary.java
| 1
|
请完成以下Java代码
|
public SetRemovalTimeBatchConfiguration setHierarchical(boolean hierarchical) {
isHierarchical = hierarchical;
return this;
}
public boolean isUpdateInChunks() {
return updateInChunks;
}
public SetRemovalTimeBatchConfiguration setUpdateInChunks(boolean updateInChunks) {
this.updateInChunks = updateInChunks;
return this;
}
public Integer getChunkSize() {
return chunkSize;
}
|
public SetRemovalTimeBatchConfiguration setChunkSize(Integer chunkSize) {
this.chunkSize = chunkSize;
return this;
}
public Set<String> getEntities() {
return entities;
}
public SetRemovalTimeBatchConfiguration setEntities(Set<String> entities) {
this.entities = entities;
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\SetRemovalTimeBatchConfiguration.java
| 1
|
请完成以下Java代码
|
public KeyValues getHighCardinalityKeyValues(KafkaRecordReceiverContext context) {
String clientId = context.getClientId();
String consumerId = getConsumerId(context.getGroupId(), clientId);
KeyValues keyValues = KeyValues.of(
ListenerHighCardinalityTags.MESSAGING_PARTITION.withValue(context.getPartition()),
ListenerHighCardinalityTags.MESSAGING_OFFSET.withValue(context.getOffset())
);
if (StringUtils.hasText(clientId)) {
keyValues = keyValues
.and(ListenerHighCardinalityTags.MESSAGING_CLIENT_ID.withValue(clientId));
}
if (StringUtils.hasText(consumerId)) {
keyValues = keyValues
.and(ListenerHighCardinalityTags.MESSAGING_CONSUMER_ID.withValue(consumerId));
}
return keyValues;
}
@Override
public String getContextualName(KafkaRecordReceiverContext context) {
return context.getSource() + " process";
|
}
private static @Nullable String getConsumerId(@Nullable String groupId, @Nullable String clientId) {
if (StringUtils.hasText(groupId)) {
if (StringUtils.hasText(clientId)) {
return groupId + " - " + clientId;
}
return groupId;
}
return clientId;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaListenerObservation.java
| 1
|
请完成以下Java代码
|
public void setVariable(Variable variable) {
variableChild.setChild(this, variable);
}
public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ContextEntry.class, DMN_ELEMENT_CONTEXT_ENTRY)
.namespaceUri(LATEST_DMN_NS)
.instanceProvider(new ModelTypeInstanceProvider<ContextEntry>() {
public ContextEntry newInstance(ModelTypeInstanceContext instanceContext) {
return new ContextEntryImpl(instanceContext);
|
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
variableChild = sequenceBuilder.element(Variable.class)
.build();
expressionChild = sequenceBuilder.element(Expression.class)
.required()
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ContextEntryImpl.java
| 1
|
请完成以下Java代码
|
protected void fireUserOperationLog(final UserOperationLogContext context) {
if (context.getUserId() == null) {
context.setUserId(getAuthenticatedUserId());
}
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public List<HistoryEvent> createHistoryEvents(HistoryEventProducer producer) {
return producer.createUserOperationLogEvents(context);
}
});
}
protected boolean writeUserOperationLogOnlyWithLoggedInUser() {
return Context.getCommandContext().isRestrictUserOperationLogToAuthenticatedUsers();
}
protected boolean isUserOperationLogEnabledOnCommandContext() {
return Context.getCommandContext().isUserOperationLogEnabled();
}
protected String getOperationType(IdentityOperationResult operationResult) {
switch (operationResult.getOperation()) {
case IdentityOperationResult.OPERATION_CREATE:
|
return UserOperationLogEntry.OPERATION_TYPE_CREATE;
case IdentityOperationResult.OPERATION_UPDATE:
return UserOperationLogEntry.OPERATION_TYPE_UPDATE;
case IdentityOperationResult.OPERATION_DELETE:
return UserOperationLogEntry.OPERATION_TYPE_DELETE;
case IdentityOperationResult.OPERATION_UNLOCK:
return UserOperationLogEntry.OPERATION_TYPE_UNLOCK;
default:
return null;
}
}
protected void configureQuery(UserOperationLogQueryImpl query) {
getAuthorizationManager().configureUserOperationLogQuery(query);
getTenantManager().configureQuery(query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserOperationLogManager.java
| 1
|
请完成以下Java代码
|
public java.math.BigDecimal getUserDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UserDiscount);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/**
* UserLevel AD_Reference_ID=226
* Reference name: AD_Role User Level
*/
public static final int USERLEVEL_AD_Reference_ID=226;
/** System = S__ */
public static final String USERLEVEL_System = "S__";
/** Client = _C_ */
public static final String USERLEVEL_Client = "_C_";
/** Organization = __O */
public static final String USERLEVEL_Organization = "__O";
/** Client+Organization = _CO */
public static final String USERLEVEL_ClientPlusOrganization = "_CO";
/** Set Nutzer-Ebene.
@param UserLevel
System Client Organization
*/
@Override
public void setUserLevel (java.lang.String UserLevel)
{
set_Value (COLUMNNAME_UserLevel, UserLevel);
}
/** Get Nutzer-Ebene.
@return System Client Organization
*/
@Override
public java.lang.String getUserLevel ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserLevel);
}
/** Set Is webui role.
@param WEBUI_Role Is webui role */
@Override
public void setWEBUI_Role (boolean WEBUI_Role)
{
set_Value (COLUMNNAME_WEBUI_Role, Boolean.valueOf(WEBUI_Role));
}
/** Get Is webui role.
@return Is webui role */
|
@Override
public boolean isWEBUI_Role ()
{
Object oo = get_Value(COLUMNNAME_WEBUI_Role);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsAllowPasswordChangeForOthers (final boolean IsAllowPasswordChangeForOthers)
{
set_Value (COLUMNNAME_IsAllowPasswordChangeForOthers, IsAllowPasswordChangeForOthers);
}
@Override
public boolean isAllowPasswordChangeForOthers()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowPasswordChangeForOthers);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Setup
public void setup() {
src = " White spaces left and right ";
ltrimResult = "White spaces left and right ";
rtrimResult = " White spaces left and right";
}
public static String whileLtrim(String s) {
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
return s.substring(i);
}
public static String whileRtrim(String s) {
int i = s.length() - 1;
while (i >= 0 && Character.isWhitespace(s.charAt(i))) {
i--;
}
return s.substring(0, i + 1);
}
private static boolean checkStrings(String ltrim, String rtrim) {
boolean result = false;
if (ltrimResult.equalsIgnoreCase(ltrim) && rtrimResult.equalsIgnoreCase(rtrim))
result = true;
return result;
}
// Going through the String detecting Whitespaces
@Benchmark
public boolean whileCharacters() {
String ltrim = whileLtrim(src);
String rtrim = whileRtrim(src);
return checkStrings(ltrim, rtrim);
}
// replaceAll() and Regular Expressions
@Benchmark
public boolean replaceAllRegularExpression() {
|
String ltrim = src.replaceAll("^\\s+", "");
String rtrim = src.replaceAll("\\s+$", "");
return checkStrings(ltrim, rtrim);
}
public static String patternLtrim(String s) {
return LTRIM.matcher(s)
.replaceAll("");
}
public static String patternRtrim(String s) {
return RTRIM.matcher(s)
.replaceAll("");
}
// Pattern matches() with replaceAll
@Benchmark
public boolean patternMatchesLTtrimRTrim() {
String ltrim = patternLtrim(src);
String rtrim = patternRtrim(src);
return checkStrings(ltrim, rtrim);
}
// Guava CharMatcher trimLeadingFrom / trimTrailingFrom
@Benchmark
public boolean guavaCharMatcher() {
String ltrim = CharMatcher.whitespace().trimLeadingFrom(src);
String rtrim = CharMatcher.whitespace().trimTrailingFrom(src);
return checkStrings(ltrim, rtrim);
}
// Apache Commons StringUtils containsIgnoreCase
@Benchmark
public boolean apacheCommonsStringUtils() {
String ltrim = StringUtils.stripStart(src, null);
String rtrim = StringUtils.stripEnd(src, null);
return checkStrings(ltrim, rtrim);
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\trim\LTrimRTrim.java
| 1
|
请完成以下Java代码
|
public Map<String, Employee> xmlToHashMapUsingDOMParserXpath(String xmlData) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlData)));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression xPathExpr = xpath.compile("/employees/employee");
NodeList nodes = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
HashMap<String, Employee> map = new HashMap<>();
for (int i = 0; i < nodes.getLength(); i++) {
Element node = (Element) nodes.item(i);
Employee employee = new Employee();
employee.setId(node.getElementsByTagName("id")
.item(0)
.getTextContent());
employee.setFirstName(node.getElementsByTagName("firstName")
.item(0)
.getTextContent());
employee.setLastName(node.getElementsByTagName("lastName")
.item(0)
.getTextContent());
map.put(employee.getId(), employee);
}
return map;
}
private static void parseXmlToMap(Map<String, Employee> employeeMap, List<LinkedHashMap<String, String>> list) {
list.forEach(empMap -> {
Employee employee = new Employee();
for (Map.Entry<String, String> key : empMap.entrySet()) {
switch (key.getKey()) {
|
case "id":
employee.setId(key.getValue());
break;
case "firstName":
employee.setFirstName(key.getValue());
break;
case "lastName":
employee.setLastName(key.getValue());
break;
default:
break;
}
}
employeeMap.put(employee.getId(), employee);
});
}
}
|
repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\tohashmap\XmlToHashMap.java
| 1
|
请完成以下Java代码
|
public static Method makeAccessible(Method method) {
ReflectionUtils.makeAccessible(method);
return method;
}
/**
* Returns the given {@link Object value} or throws an {@link IllegalArgumentException}
* if {@link Object value} is {@literal null}.
*
* @param <T> {@link Class type} of the {@link Object value}.
* @param value {@link Object} to return.
* @return the {@link Object value} or throw an {@link IllegalArgumentException}
* if {@link Object value} is {@literal null}.
* @see #returnValueThrowOnNull(Object, RuntimeException)
*/
public static <T> T returnValueThrowOnNull(T value) {
return returnValueThrowOnNull(value, newIllegalArgumentException("Value must not be null"));
}
/**
* Returns the given {@link Object value} or throws the given {@link RuntimeException}
* if {@link Object value} is {@literal null}.
*
* @param <T> {@link Class type} of the {@link Object value}.
* @param value {@link Object} to return.
* @param exception {@link RuntimeException} to throw if {@link Object value} is {@literal null}.
* @return the {@link Object value} or throw the given {@link RuntimeException}
* if {@link Object value} is {@literal null}.
*/
public static <T> T returnValueThrowOnNull(T value, RuntimeException exception) {
if (value == null) {
throw exception;
}
return value;
}
|
/**
* Resolves the {@link Object invocation target} for the given {@link Method}.
*
* If the {@link Method} is {@link Modifier#STATIC} then {@literal null} is returned,
* otherwise {@link Object target} will be returned.
*
* @param <T> {@link Class type} of the {@link Object target}.
* @param target {@link Object} on which the {@link Method} will be invoked.
* @param method {@link Method} to invoke on the {@link Object}.
* @return the resolved {@link Object invocation method}.
* @see java.lang.Object
* @see java.lang.reflect.Method
*/
public static <T> T resolveInvocationTarget(T target, Method method) {
return Modifier.isStatic(method.getModifiers()) ? null : target;
}
@FunctionalInterface
public interface ExceptionThrowingOperation<T> {
T run() throws Exception;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\util\ObjectUtils.java
| 1
|
请完成以下Java代码
|
public Particle[] getParticles() {
return particles;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + Arrays.hashCode(particles);
result = prime * result + ((random == null) ? 0 : random.hashCode());
|
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Swarm other = (Swarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (!Arrays.equals(particles, other.particles))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + "]";
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Swarm.java
| 1
|
请完成以下Java代码
|
public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID)
{
if (M_Picking_Job_Schedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, M_Picking_Job_Schedule_ID);
}
@Override
public int getM_Picking_Job_Schedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
|
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_Value (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java
| 1
|
请完成以下Java代码
|
public List<Map.Entry<String, Float>> analogy(String A, String B, String C)
{
return analogy(A, B, C, 10);
}
/**
* 返回跟 A - B + C 最相似的词语,比如 中国 - 北京 + 东京 = 日本。输入顺序按照 中国 北京 东京
*
* @param A 做加法的词语
* @param B 做减法的词语
* @param C 做加法的词语
* @param size topN个
* @return 与(A - B + C)语义距离最近的词语及其相似度列表
*/
public List<Map.Entry<String, Float>> analogy(String A, String B, String C, int size)
{
Vector a = storage.get(A);
Vector b = storage.get(B);
Vector c = storage.get(C);
if (a == null || b == null || c == null)
{
return Collections.emptyList();
}
List<Map.Entry<String, Float>> resultList = nearest(a.minus(b).add(c), size + 3);
ListIterator<Map.Entry<String, Float>> listIterator = resultList.listIterator();
|
while (listIterator.hasNext())
{
String key = listIterator.next().getKey();
if (key.equals(A) || key.equals(B) || key.equals(C))
{
listIterator.remove();
}
}
if (resultList.size() > size)
{
resultList = resultList.subList(0, size);
}
return resultList;
}
@Override
public Vector query(String query)
{
return vector(query);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\WordVectorModel.java
| 1
|
请完成以下Java代码
|
public void addDataStore(String id, DataStore dataStore) {
if (StringUtils.isNotEmpty(id)) {
dataStoreMap.put(id, dataStore);
}
}
public boolean containsDataStore(String id) {
return dataStoreMap.containsKey(id);
}
public List<Pool> getPools() {
return pools;
}
public void setPools(List<Pool> pools) {
this.pools = pools;
}
public List<Import> getImports() {
return imports;
}
public void setImports(List<Import> imports) {
this.imports = imports;
}
public List<Interface> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<Interface> interfaces) {
this.interfaces = interfaces;
}
public List<Artifact> getGlobalArtifacts() {
return globalArtifacts;
}
public void setGlobalArtifacts(List<Artifact> globalArtifacts) {
this.globalArtifacts = globalArtifacts;
}
public void addNamespace(String prefix, String uri) {
namespaceMap.put(prefix, uri);
}
public boolean containsNamespacePrefix(String prefix) {
return namespaceMap.containsKey(prefix);
}
public String getNamespace(String prefix) {
return namespaceMap.get(prefix);
}
public Map<String, String> getNamespaces() {
return namespaceMap;
}
public String getTargetNamespace() {
return targetNamespace;
}
public void setTargetNamespace(String targetNamespace) {
this.targetNamespace = targetNamespace;
|
}
public String getSourceSystemId() {
return sourceSystemId;
}
public void setSourceSystemId(String sourceSystemId) {
this.sourceSystemId = sourceSystemId;
}
public List<String> getUserTaskFormTypes() {
return userTaskFormTypes;
}
public void setUserTaskFormTypes(List<String> userTaskFormTypes) {
this.userTaskFormTypes = userTaskFormTypes;
}
public List<String> getStartEventFormTypes() {
return startEventFormTypes;
}
public void setStartEventFormTypes(List<String> startEventFormTypes) {
this.startEventFormTypes = startEventFormTypes;
}
@JsonIgnore
public Object getEventSupport() {
return eventSupport;
}
public void setEventSupport(Object eventSupport) {
this.eventSupport = eventSupport;
}
public String getStartFormKey(String processId) {
FlowElement initialFlowElement = getProcessById(processId).getInitialFlowElement();
if (initialFlowElement instanceof StartEvent) {
StartEvent startEvent = (StartEvent) initialFlowElement;
return startEvent.getFormKey();
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BpmnModel.java
| 1
|
请完成以下Java代码
|
public boolean isSelected()
{
return m_selected;
}
/**
* Set Record_ID
* @param record_ID
*/
public void setRecord_ID(Integer record_ID)
{
m_record_ID = record_ID;
}
/**
* Get Record ID
* @return ID
*/
public Integer getRecord_ID()
{
return m_record_ID;
}
|
/**
* To String
* @return String representation
*/
@Override
public String toString()
{
return "IDColumn - ID=" + m_record_ID + ", Selected=" + m_selected;
} // toString
public void addPropertyChangeListener( PropertyChangeListener listener )
{
this.pcs.addPropertyChangeListener( listener );
}
public void removePropertyChangeListener( PropertyChangeListener listener )
{
this.pcs.removePropertyChangeListener( listener );
}
} // IDColumn
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\IDColumn.java
| 1
|
请完成以下Java代码
|
public final boolean hasColumnName(final String columnName)
{
return getDocument().hasField(columnName);
}
public static int getId(final Object model)
{
return getDocument(model).getDocumentIdAsInt();
}
public static boolean isNew(final Object model)
{
return getDocument(model).isNew();
}
public <T> T getDynAttribute(final String attributeName)
{
return getDocument().getDynAttribute(attributeName);
}
public Object setDynAttribute(final String attributeName, final Object value)
{
return getDocument().setDynAttribute(attributeName, value);
}
public final boolean isOldValues()
{
return useOldValues;
}
public static final boolean isOldValues(final Object model)
{
final DocumentInterfaceWrapper wrapper = getWrapper(model);
return wrapper == null ? false : wrapper.isOldValues();
}
@Override
public Set<String> getColumnNames()
{
return document.getFieldNames();
}
@Override
public int getColumnIndex(final String columnName)
{
throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes");
}
@Override
|
public boolean isVirtualColumn(final String columnName)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
return field != null && field.isReadonlyVirtualField();
}
@Override
public boolean isKeyColumnName(final String columnName)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
return field != null && field.isKey();
}
@Override
public boolean isCalculated(final String columnName)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
return field != null && field.isCalculated();
}
@Override
public boolean setValueNoCheck(final String columnName, final Object value)
{
return setValue(columnName, value);
}
@Override
public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
// TODO: implement
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
| 1
|
请完成以下Java代码
|
public void addListDataListener(final ListDataListener l)
{
listenerList.add(ListDataListener.class, l);
if (delegate != null)
{
delegate.addListDataListener(l);
}
}
@Override
public void removeListDataListener(final ListDataListener l)
{
listenerList.remove(ListDataListener.class, l);
if (delegate != null)
{
delegate.removeListDataListener(l);
}
}
@Override
public int getSize()
{
return getDelegateToUse().getSize();
}
@Override
public Object getElementAt(int index)
{
return getDelegateToUse().getElementAt(index);
}
@Override
public void setSelectedItem(Object anItem)
{
getDelegateToUse().setSelectedItem(anItem);
}
@Override
public Object getSelectedItem()
{
return getDelegateToUse().getSelectedItem();
}
@Override
public void addElement(Object obj)
|
{
getDelegateToUse().addElement(obj);
}
@Override
public void removeElement(Object obj)
{
getDelegateToUse().removeElement(obj);
}
@Override
public void insertElementAt(Object obj, int index)
{
getDelegateToUse().insertElementAt(obj, index);
}
@Override
public void removeElementAt(int index)
{
getDelegateToUse().removeElementAt(index);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\MutableComboBoxModelProxy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void deleteIndexRequest(String index) {
DeleteIndexRequest deleteIndexRequest = buildDeleteIndexRequest(index);
try {
client.indices().delete(deleteIndexRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("删除索引 {" + index + "} 失败");
}
}
/**
* build DeleteIndexRequest
*
* @param index elasticsearch index name
* @author fxbin
*/
private static DeleteIndexRequest buildDeleteIndexRequest(String index) {
return new DeleteIndexRequest(index);
}
/**
* build IndexRequest
*
* @param index elasticsearch index name
* @param id request object id
* @param object request object
* @return {@link org.elasticsearch.action.index.IndexRequest}
* @author fxbin
*/
protected static IndexRequest buildIndexRequest(String index, String id, Object object) {
return new IndexRequest(index).id(id).source(BeanUtil.beanToMap(object), XContentType.JSON);
}
/**
* exec updateRequest
*
* @param index elasticsearch index name
* @param id Document id
* @param object request object
* @author fxbin
*/
protected void updateRequest(String index, String id, Object object) {
try {
UpdateRequest updateRequest = new UpdateRequest(index, id).doc(BeanUtil.beanToMap(object), XContentType.JSON);
client.update(updateRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("更新索引 {" + index + "} 数据 {" + object + "} 失败");
}
|
}
/**
* exec deleteRequest
*
* @param index elasticsearch index name
* @param id Document id
* @author fxbin
*/
protected void deleteRequest(String index, String id) {
try {
DeleteRequest deleteRequest = new DeleteRequest(index, id);
client.delete(deleteRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("删除索引 {" + index + "} 数据id {" + id + "} 失败");
}
}
/**
* search all
*
* @param index elasticsearch index name
* @return {@link SearchResponse}
* @author fxbin
*/
protected SearchResponse search(String index) {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = client.search(searchRequest, COMMON_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
}
return searchResponse;
}
}
|
repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\service\base\BaseElasticsearchService.java
| 2
|
请完成以下Java代码
|
public void setAD_Process_Access_ID (int AD_Process_Access_ID)
{
if (AD_Process_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_Access_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_Access_ID, Integer.valueOf(AD_Process_Access_ID));
}
/** Get Process Access.
@return Process Access */
@Override
public int getAD_Process_Access_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Access_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Process getAD_Process() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setAD_Process(org.compiere.model.I_AD_Process AD_Process)
{
set_ValueFromPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class, AD_Process);
}
/** Set Prozess.
@param AD_Process_ID
Process or Report
*/
@Override
public void setAD_Process_ID (int AD_Process_ID)
{
if (AD_Process_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, Integer.valueOf(AD_Process_ID));
}
/** Get Prozess.
@return Process or Report
*/
@Override
public int getAD_Process_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
/** Set Rolle.
@param AD_Role_ID
|
Responsibility Role
*/
@Override
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Rolle.
@return Responsibility Role
*/
@Override
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Access.java
| 1
|
请完成以下Java代码
|
public PricingConditionsView filterView(
@NonNull final IView view,
@NonNull final JSONFilterViewRequest filterViewRequest,
final Supplier<IViewsRepository> viewsRepo_IGNORED)
{
return PricingConditionsView.cast(view)
.filter(filtersFactory.extractFilters(filterViewRequest));
}
private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClass(processClass))
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
|
.build();
}
protected final DocumentFilterList extractFilters(final CreateViewRequest request)
{
return filtersFactory.extractFilters(request);
}
@lombok.Value(staticConstructor = "of")
private static final class ViewLayoutKey
{
WindowId windowId;
JSONViewDataType viewDataType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java
| 1
|
请完成以下Java代码
|
public class CommonStringDictionary
{
BinTrie<Byte> trie;
public boolean load(String path)
{
trie = new BinTrie<Byte>();
if (loadDat(path + Predefine.TRIE_EXT)) return true;
String line = null;
try
{
BufferedReader bw = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path)));
while ((line = bw.readLine()) != null)
{
trie.put(line, null);
}
bw.close();
}
catch (Exception e)
{
logger.warning("加载" + path + "失败," + e);
|
}
if (!trie.save(path + Predefine.TRIE_EXT)) logger.warning("缓存" + path + Predefine.TRIE_EXT + "失败");
return true;
}
boolean loadDat(String path)
{
return trie.load(path);
}
public Set<String> keySet()
{
Set<String> keySet = new LinkedHashSet<String>();
for (Map.Entry<String, Byte> entry : trie.entrySet())
{
keySet.add(entry.getKey());
}
return keySet;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonStringDictionary.java
| 1
|
请完成以下Java代码
|
protected BuiltinAggregator getAggregator() {
return BuiltinAggregator.SUM;
}
@Override
protected Integer aggregateIntegerValues(List<Integer> intValues) {
int sum = 0;
for (Integer intValue : intValues) {
if (intValue != null) {
sum += intValue;
}
}
return sum;
}
@Override
protected Long aggregateLongValues(List<Long> longValues) {
long sum = 0L;
for (Long longValue : longValues) {
if (longValue != null) {
sum += longValue;
}
}
|
return sum;
}
@Override
protected Double aggregateDoubleValues(List<Double> doubleValues) {
double sum = 0.0;
for (Double doubleValue : doubleValues) {
if (doubleValue != null) {
sum += doubleValue;
}
}
return sum;
}
@Override
public String toString() {
return "CollectSumHitPolicyHandler{}";
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\CollectSumHitPolicyHandler.java
| 1
|
请完成以下Java代码
|
public FlowableEventListener createEventThrowingEventListener(EventListener eventListener) {
BaseDelegateEventListener result = null;
if (ImplementationType.IMPLEMENTATION_TYPE_THROW_SIGNAL_EVENT.equals(eventListener.getImplementationType())) {
result = new SignalThrowingEventListener();
((SignalThrowingEventListener) result).setSignalName(eventListener.getImplementation());
((SignalThrowingEventListener) result).setProcessInstanceScope(true);
} else if (ImplementationType.IMPLEMENTATION_TYPE_THROW_GLOBAL_SIGNAL_EVENT.equals(eventListener.getImplementationType())) {
result = new SignalThrowingEventListener();
((SignalThrowingEventListener) result).setSignalName(eventListener.getImplementation());
((SignalThrowingEventListener) result).setProcessInstanceScope(false);
} else if (ImplementationType.IMPLEMENTATION_TYPE_THROW_MESSAGE_EVENT.equals(eventListener.getImplementationType())) {
result = new MessageThrowingEventListener();
((MessageThrowingEventListener) result).setMessageName(eventListener.getImplementation());
} else if (ImplementationType.IMPLEMENTATION_TYPE_THROW_ERROR_EVENT.equals(eventListener.getImplementationType())) {
result = new ErrorThrowingEventListener();
((ErrorThrowingEventListener) result).setErrorCode(eventListener.getImplementation());
}
if (result == null) {
throw new ActivitiIllegalArgumentException("Cannot create an event-throwing event-listener, unknown implementation type: "
+ eventListener.getImplementationType());
}
result.setEntityClass(getEntityType(eventListener.getEntityType()));
return result;
}
/**
|
* @param entityType the name of the entity
* @return
* @throws ActivitiIllegalArgumentException when the given entity name
*/
protected Class<?> getEntityType(String entityType) {
if (entityType != null) {
Class<?> entityClass = ENTITY_MAPPING.get(entityType.trim());
if (entityClass == null) {
throw new ActivitiIllegalArgumentException("Unsupported entity-type for an ActivitiEventListener: " + entityType);
}
return entityClass;
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultListenerFactory.java
| 1
|
请完成以下Java代码
|
static String convertValue(Object value) {
if (value != null) {
String strVal = value.toString();
// check number
if (NumberUtils.isParsable(strVal)) {
if (strVal.startsWith("0") && !strVal.startsWith("0.")) {
return strVal;
}
try {
BigInteger longVal = new BigInteger(strVal);
return longVal.toString();
} catch (NumberFormatException ignored) {
}
try {
double dblVal = Double.parseDouble(strVal);
String doubleAsString = Double.toString(dblVal);
if (!Double.isInfinite(dblVal) && isSimpleDouble(doubleAsString)) {
return doubleAsString;
|
}
} catch (NumberFormatException ignored) {
}
}
return strVal;
} else {
return "";
}
}
private static boolean isSimpleDouble(String valueAsString) {
return valueAsString.contains(".") && !valueAsString.contains("E") && !valueAsString.contains("e");
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\EntityDataAdapter.java
| 1
|
请完成以下Java代码
|
public boolean hasDifferentChildren(TreePath path) {
return pathHasChildrenWithValue(path, !isPathChecked(path));
}
/**
* Update the grayness value of the parents of path. Note: the greyness
* and checking of the other nodes (not ancestors) MUST BE consistent.
*
* @param path the treepath containing the ancestors to be grey-updated
*/
public void updateAncestorsGreyness(TreePath path) {
TreePath[] parents = new TreePath[path.getPathCount()];
parents[0] = path;
boolean greyAll = isPathGreyed(path);
for (int i = 1; i < parents.length; i++) {
parents[i] = parents[i - 1].getParentPath();
if (greyAll) {
addToGreyedPathsSet(parents[i]);
} else {
updatePathGreyness(parents[i]);
greyAll = isPathGreyed(parents[i]);
}
}
}
/**
* Return the paths that are children of path, using methods of
* TreeModel. Nodes don't have to be of type TreeNode.
*
* @param path the parent path
* @return the array of children path
*/
protected TreePath[] getChildrenPath(TreePath path) {
Object node = path.getLastPathComponent();
int childrenNumber = this.model.getChildCount(node);
TreePath[] childrenPath = new TreePath[childrenNumber];
for (int childIndex = 0; childIndex < childrenNumber; childIndex++) {
childrenPath[childIndex] = path.pathByAddingChild(this.model.getChild(node, childIndex));
}
return childrenPath;
}
@Override
public TreeModel getTreeModel() {
return this.model;
}
/**
* Sets the specified tree model. The current cheking is cleared.
*/
@Override
public void setTreeModel(TreeModel newModel) {
TreeModel oldModel = this.model;
if (oldModel != null) {
oldModel.removeTreeModelListener(this.propagateCheckingListener);
}
this.model = newModel;
if (newModel != null) {
newModel.addTreeModelListener(this.propagateCheckingListener);
}
clearChecking();
}
|
/**
* Return a string that describes the tree model including the values of
* checking, enabling, greying.
*/
@Override
public String toString() {
return toString(new TreePath(this.model.getRoot()));
}
/**
* Convenience method for getting a string that describes the tree
* starting at path.
*
* @param path the treepath root of the tree
*/
private String toString(TreePath path) {
String checkString = "n";
String greyString = "n";
String enableString = "n";
if (isPathChecked(path)) {
checkString = "y";
}
if (isPathEnabled(path)) {
enableString = "y";
}
if (isPathGreyed(path)) {
greyString = "y";
}
String description = "Path checked: " + checkString + " greyed: " + greyString + " enabled: " + enableString + " Name: "
+ path.toString() + "\n";
for (TreePath childPath : getChildrenPath(path)) {
description += toString(childPath);
}
return description;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultTreeCheckingModel.java
| 1
|
请完成以下Java代码
|
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
jobDataManager.updateJobTenantIdForDeployment(deploymentId, newTenantId);
}
@Override
public void delete(JobEntity jobEntity) {
super.delete(jobEntity);
deleteExceptionByteArrayRef(jobEntity);
removeExecutionLink(jobEntity);
// Send event
if (getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this)
);
}
}
@Override
public void delete(JobEntity entity, boolean fireDeleteEvent) {
if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) {
CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById(
entity.getExecutionId()
);
if (isExecutionRelatedEntityCountEnabled(executionEntity)) {
executionEntity.setJobCount(executionEntity.getJobCount() - 1);
}
}
super.delete(entity, fireDeleteEvent);
}
/**
* Removes the job's execution's reference to this job, if the job has an associated execution.
* Subclasses may override to provide custom implementations.
*/
protected void removeExecutionLink(JobEntity jobEntity) {
|
if (jobEntity.getExecutionId() != null) {
ExecutionEntity execution = getExecutionEntityManager().findById(jobEntity.getExecutionId());
if (execution != null) {
execution.getJobs().remove(jobEntity);
}
}
}
/**
* Deletes a the byte array used to store the exception information. Subclasses may override
* to provide custom implementations.
*/
protected void deleteExceptionByteArrayRef(JobEntity jobEntity) {
ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef();
if (exceptionByteArrayRef != null) {
exceptionByteArrayRef.delete();
}
}
public JobDataManager getJobDataManager() {
return jobDataManager;
}
public void setJobDataManager(JobDataManager jobDataManager) {
this.jobDataManager = jobDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public Optional<I_M_HU> getHUBySSCC18(@NonNull final String sscc18)
{
final I_M_HU hu = handlingUnitsDAO.createHUQueryBuilder()
.setHUStatus(X_M_HU.HUSTATUS_Active)
// match SSCC18 attribute
.addOnlyWithAttribute(AttributeConstants.ATTR_SSCC18_Value, sscc18)
// only HU's with BPartner set shall be considered (06821)
.setOnlyIfAssignedToBPartner(true)
.firstOnly();
return Optional.ofNullable(hu);
}
public Optional<ProductBarcodeFilterData> createDataFromHU(
final @Nullable String barcode,
final @Nullable I_M_HU hu)
{
if (hu == null)
{
return Optional.empty();
}
final ImmutableSet<ProductId> productIds = extractProductIds(hu);
if (productIds.isEmpty())
{
return Optional.empty();
}
final ICompositeQueryFilter<I_M_Packageable_V> filter = queryBL.createCompositeQueryFilter(I_M_Packageable_V.class)
.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productIds);
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu);
if (warehouseId != null)
{
filter.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Warehouse_ID, null, warehouseId);
}
|
final BPartnerId bpartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(hu);
if (bpartnerId != null)
{
filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, bpartnerId);
}
return Optional.of(ProductBarcodeFilterData.builder()
.barcode(barcode)
.huId(HuId.ofRepoId(hu.getM_HU_ID()))
.sqlWhereClause(toSqlAndParams(filter))
.build());
}
private ImmutableSet<ProductId> extractProductIds(@NonNull final I_M_HU hu)
{
final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(PlainContextAware.newWithThreadInheritedTrx());
return huContext.getHUStorageFactory()
.getStorage(hu)
.getProductStorages()
.stream()
.map(IHUProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\ProductBarcodeFilterServicesFacade.java
| 1
|
请完成以下Java代码
|
public BigDecimal getExpense ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Expense);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Depreciate.
@param IsDepreciated
The asset will be depreciated
*/
public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
|
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Exp.java
| 1
|
请完成以下Java代码
|
public class OrderLineHUPackingGridRowBuilder implements IGridTabRowBuilder
{
private static final transient Logger logger = LogManager.getLogger(OrderLineHUPackingGridRowBuilder.class);
private IHUPackingAware record;
public OrderLineHUPackingGridRowBuilder()
{
super();
}
@Override
public boolean isValid()
{
if (record == null)
{
return false;
}
final int productID = record.getM_Product_ID();
final BigDecimal qty = record.getQty();
// 06730: Removed TU restrictions for now. We can choose no handling unit for a product, even if it has associated TUs.
// final int partnerID = (null == record.getC_BPartner()) ? 0 : record.getC_BPartner().getC_BPartner_ID();
// final Timestamp dateOrdered = record.getDateOrdered();
if (productID <= 0)
{
return false;
}
if (qty == null || qty.signum() == 0)
{
return false;
}
// TODO: check record values
// 06730: Removed TU restrictions for now. We can choose no handling unit for a product, even if it has associated TUs.
// final boolean hasTUs = Services.get(IHUOrderBL.class).hasTUs(Env.getCtx(), partnerID, productID, dateOrdered);
//
// if (hasTUs)
// {
//
// if (record.getM_HU_PI_Item_Product_ID() <= 0)
// {
// return false;
// }
//
// if (record.getQtyPacks() == null || record.getQtyPacks().signum() <= 0)
// {
// return false;
// }
// }
return true;
}
@Override
public void setSource(final Object model)
|
{
if (model instanceof IHUPackingAware)
{
record = (IHUPackingAware)model;
}
else if (InterfaceWrapperHelper.isInstanceOf(model, I_C_Order.class))
{
final I_C_Order order = InterfaceWrapperHelper.create(model, I_C_Order.class);
record = new OrderHUPackingAware(order);
}
else
{
record = null;
}
}
@Override
public void apply(final Object model)
{
if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OrderLine.class))
{
logger.debug("Skip applying because it's not an order line: {}", model);
return;
}
final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class);
applyOnOrderLine(orderLine);
}
public void applyOnOrderLine(final I_C_OrderLine orderLine)
{
final IHUPackingAware to = new OrderLineHUPackingAware(orderLine);
Services.get(IHUPackingAwareBL.class).prepareCopyFrom(record)
.overridePartner(false)
.copyTo(to);
}
@Override
public boolean isCreateNewRecord()
{
if (isValid())
{
return true;
}
return false;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingGridRowBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void createLog(final SumUpLogRequest request)
{
try
{
final I_SUMUP_API_Log record = InterfaceWrapperHelper.newInstanceOutOfTrx(I_SUMUP_API_Log.class);
record.setSUMUP_Config_ID(request.getConfigId().getRepoId());
record.setSUMUP_merchant_code(request.getMerchantCode().getAsString());
record.setMethod(request.getMethod().name());
record.setRequestURI(request.getRequestURI());
record.setRequestBody(toJson(request.getRequestBody()));
if (request.getResponseCode() != null)
{
record.setResponseCode(request.getResponseCode().value());
}
record.setResponseBody(toJson(request.getResponseBody()));
record.setAD_Issue_ID(AdIssueId.toRepoId(request.getAdIssueId()));
record.setC_POS_Order_ID(request.getPosRef() != null ? request.getPosRef().getPosOrderId() : -1);
record.setC_POS_Payment_ID(request.getPosRef() != null ? request.getPosRef().getPosPaymentId() : -1);
InterfaceWrapperHelper.save(record);
}
catch (Exception ex)
{
logger.error("Failed saving log {}", request, ex);
|
}
}
private String toJson(@Nullable final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof String)
{
return StringUtils.trimBlankToNull((String)obj);
}
try
{
return jsonMapper.writeValueAsString(obj);
}
catch (JsonProcessingException ex)
{
logger.error("Failed converting object to json: {}", obj, ex);
return obj.toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\repository\SumUpLogRepository.java
| 2
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_PA_SLA_Criteria[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
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 Manual.
@param IsManual
This is a manual process
*/
public void setIsManual (boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual));
}
/** Get Manual.
@return This is a manual process
*/
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
|
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set SLA Criteria.
@param PA_SLA_Criteria_ID
Service Level Agreement Criteria
*/
public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID)
{
if (PA_SLA_Criteria_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID));
}
/** Get SLA Criteria.
@return Service Level Agreement Criteria
*/
public int getPA_SLA_Criteria_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_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_PA_SLA_Criteria.java
| 1
|
请完成以下Java代码
|
public boolean deleteById(TenantId tenantId, AiModelId modelId) {
return aiModelRepository.deleteByIdIn(Set.of(modelId.getId())) > 0;
}
@Override
public Set<AiModelId> deleteByTenantId(TenantId tenantId) {
return aiModelRepository.deleteByTenantId(tenantId.getId()).stream()
.map(AiModelId::new)
.collect(toSet());
}
@Override
public boolean deleteByTenantIdAndId(TenantId tenantId, AiModelId modelId) {
return aiModelRepository.deleteByTenantIdAndIdIn(tenantId.getId(), Set.of(modelId.getId())) > 0;
}
|
@Override
public EntityType getEntityType() {
return EntityType.AI_MODEL;
}
@Override
protected Class<AiModelEntity> getEntityClass() {
return AiModelEntity.class;
}
@Override
protected JpaRepository<AiModelEntity, UUID> getRepository() {
return aiModelRepository;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\ai\JpaAiModelDao.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() {
Assert.notNull(this.beanClassLoader, "beanClassLoader must not be null");
Assert.notNull(this.beanFactory, "beanFactory must not be null");
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public void setRegistry(ActivitiStateHandlerRegistry registry) {
this.registry = registry;
}
public Object postProcessAfterInitialization(final Object bean,
final String beanName) throws BeansException {
// first sift through and get all the methods
// then get all the annotations
// then build the metadata and register the metadata
final Class<?> targetClass = AopUtils.getTargetClass(bean);
final org.camunda.bpm.engine.spring.annotations.ProcessEngineComponent component = targetClass.getAnnotation(org.camunda.bpm.engine.spring.annotations.ProcessEngineComponent.class);
ReflectionUtils.doWithMethods(targetClass,
new ReflectionUtils.MethodCallback() {
@SuppressWarnings("unchecked")
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
State state = AnnotationUtils.getAnnotation(method, State.class);
String processName = component.processKey();
if (StringUtils.hasText(state.process())) {
processName = state.process();
}
String stateName = state.state();
if (!StringUtils.hasText(stateName)) {
stateName = state.value();
}
Assert.notNull(stateName, "You must provide a stateName!");
Map<Integer, String> vars = new HashMap<Integer, String>();
Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();
int ctr = 0;
int pvMapIndex = -1;
int procIdIndex = -1;
for (Annotation[] paramAnnotations : paramAnnotationsArray) {
ctr += 1;
for (Annotation pa : paramAnnotations) {
if (pa instanceof ProcessVariable) {
ProcessVariable pv = (ProcessVariable) pa;
String pvName = pv.value();
|
vars.put(ctr, pvName);
} else if (pa instanceof ProcessVariables) {
pvMapIndex = ctr;
} else if (pa instanceof ProcessId ) {
procIdIndex = ctr;
}
}
}
ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars,
method, bean, stateName, beanName, pvMapIndex,
procIdIndex, processName);
registry.registerActivitiStateHandler(registration);
}
},
new ReflectionUtils.MethodFilter() {
public boolean matches(Method method) {
return null != AnnotationUtils.getAnnotation(method,
State.class);
}
});
return bean;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\ActivitiStateAnnotationBeanPostProcessor.java
| 1
|
请完成以下Java代码
|
public class Article {
public static final String CREATED_AT_FIELD_NAME = "createdAt";
public static final String ID_FIELD_NAME = "id";
public static final String AUTHOR_ID_FIELD_NAME = "authorId";
public static final String TAGS_FIELD_NAME = "tags";
@Getter
@EqualsAndHashCode.Include
private final String id;
@Getter
private final Instant createdAt;
@Getter
@LastModifiedDate
private final Instant updatedAt;
@Getter
private final List<String> tags;
@Getter
private final List<Comment> comments;
@Getter
private String slug;
@Getter
private String title;
@Getter
@Setter
private String description;
@Getter
@Setter
private String body;
@Getter
private Integer favoritesCount;
@Getter
@Setter
private String authorId;
@Builder
Article(String id,
String title,
String description,
String body,
@Nullable Instant createdAt,
@Nullable Instant updatedAt,
@Nullable Integer favoritesCount,
String authorId,
@Nullable List<String> tags,
@Nullable List<Comment> comments
) {
this.id = id;
setTitle(title);
this.description = description;
this.body = body;
this.createdAt = ofNullable(createdAt).orElse(Instant.now());
this.updatedAt = ofNullable(updatedAt).orElse(createdAt);
this.favoritesCount = ofNullable(favoritesCount).orElse(0);
this.authorId = authorId;
this.tags = ofNullable(tags).orElse(new ArrayList<>());
this.comments = ofNullable(comments).orElse(new ArrayList<>());
}
public void incrementFavoritesCount() {
favoritesCount++;
}
public void decrementFavoritesCount() {
favoritesCount--;
|
}
public void addComment(Comment comment) {
comments.add(comment);
}
public void deleteComment(Comment comment) {
comments.remove(comment);
}
public void setTitle(String title) {
this.title = title;
this.slug = toSlug(title);
}
public Optional<Comment> getCommentById(String commentId) {
return comments.stream()
.filter(comment -> comment.getId().equals(commentId))
.findFirst();
}
private String toSlug(String title) {
return title.toLowerCase().replaceAll("[&|\\uFE30-\\uFFA0’”\\s?,.]+", "-");
}
public boolean hasTag(String tag) {
return tags.contains(tag);
}
public boolean isAuthor(String authorId) {
return this.authorId.equals(authorId);
}
public boolean isAuthor(User author) {
return isAuthor(author.getId());
}
}
|
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\Article.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Redis {
/**
* Entry expiration. By default the entries never expire.
*/
private @Nullable Duration timeToLive;
/**
* Allow caching null values.
*/
private boolean cacheNullValues = true;
/**
* Key prefix.
*/
private @Nullable String keyPrefix;
/**
* Whether to use the key prefix when writing to Redis.
*/
private boolean useKeyPrefix = true;
/**
* Whether to enable cache statistics.
*/
private boolean enableStatistics;
public @Nullable Duration getTimeToLive() {
return this.timeToLive;
}
public void setTimeToLive(@Nullable Duration timeToLive) {
this.timeToLive = timeToLive;
}
|
public boolean isCacheNullValues() {
return this.cacheNullValues;
}
public void setCacheNullValues(boolean cacheNullValues) {
this.cacheNullValues = cacheNullValues;
}
public @Nullable String getKeyPrefix() {
return this.keyPrefix;
}
public void setKeyPrefix(@Nullable String keyPrefix) {
this.keyPrefix = keyPrefix;
}
public boolean isUseKeyPrefix() {
return this.useKeyPrefix;
}
public void setUseKeyPrefix(boolean useKeyPrefix) {
this.useKeyPrefix = useKeyPrefix;
}
public boolean isEnableStatistics() {
return this.enableStatistics;
}
public void setEnableStatistics(boolean enableStatistics) {
this.enableStatistics = enableStatistics;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\CacheProperties.java
| 2
|
请完成以下Java代码
|
public Set<UUID> getRootEntities() {
if (filter.isMultiRoot()) {
return filter.getMultiRootEntityIds().stream().map(UUID::fromString).collect(Collectors.toSet());
} else {
return Set.of(filter.getRootEntity().getId());
}
}
@Override
public EntitySearchDirection getDirection() {
return filter.getDirection();
}
@Override
public int getMaxLevel() {
return filter.getMaxLevel();
}
@Override
public boolean isMultiRoot() {
return filter.isMultiRoot();
}
@Override
public boolean isFetchLastLevelOnly() {
return filter.isFetchLastLevelOnly();
|
}
@Override
protected boolean check(RelationInfo relationInfo) {
if (hasFilters) {
for (var f : filter.getFilters()) {
if (((!filter.isNegate() && !f.isNegate()) || (filter.isNegate() && f.isNegate())) == f.getRelationType().equals(relationInfo.getType())) {
if (f.getEntityTypes() == null || f.getEntityTypes().isEmpty()
|| f.getEntityTypes().contains(relationInfo.getTarget().getEntityType())) {
return super.matches(relationInfo.getTarget());
}
}
}
return false;
} else {
return super.matches(relationInfo.getTarget());
}
}
}
|
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\query\processor\RelationQueryProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class DelegatingSecurityContextScheduledExecutorService extends DelegatingSecurityContextExecutorService
implements ScheduledExecutorService {
/**
* Creates a new {@link DelegatingSecurityContextScheduledExecutorService} that uses
* the specified {@link SecurityContext}.
* @param delegateScheduledExecutorService the {@link ScheduledExecutorService} to
* delegate to. Cannot be null.
* @param securityContext the {@link SecurityContext} to use for each
* {@link DelegatingSecurityContextRunnable} and each
* {@link DelegatingSecurityContextCallable}.
*/
public DelegatingSecurityContextScheduledExecutorService(ScheduledExecutorService delegateScheduledExecutorService,
@Nullable SecurityContext securityContext) {
super(delegateScheduledExecutorService, securityContext);
}
/**
* Creates a new {@link DelegatingSecurityContextScheduledExecutorService} that uses
* the current {@link SecurityContext} from the {@link SecurityContextHolder}.
* @param delegate the {@link ScheduledExecutorService} to delegate to. Cannot be
* null.
*/
public DelegatingSecurityContextScheduledExecutorService(ScheduledExecutorService delegate) {
this(delegate, null);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return getDelegate().schedule(wrap(command), delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return getDelegate().schedule(wrap(callable), delay, unit);
|
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return getDelegate().scheduleAtFixedRate(wrap(command), initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return getDelegate().scheduleWithFixedDelay(wrap(command), initialDelay, delay, unit);
}
private ScheduledExecutorService getDelegate() {
return (ScheduledExecutorService) getDelegateExecutor();
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\concurrent\DelegatingSecurityContextScheduledExecutorService.java
| 2
|
请完成以下Java代码
|
private static Optional<GeoCoordinatesRequest> createGeoCoordinatesRequest(@NonNull final DocumentFilter filter)
{
final String countryCode2 = extractCountryCode2(filter);
if (countryCode2 == null)
{
return Optional.empty();
}
final GeoCoordinatesRequest request = GeoCoordinatesRequest.builder()
.countryCode2(countryCode2)
.postal(filter.getParameterValueAsString(PARAM_Postal, ""))
.address(filter.getParameterValueAsString(PARAM_Address1, ""))
.city(filter.getParameterValueAsString(PARAM_City, ""))
.build();
return Optional.of(request);
}
private static String extractCountryCode2(@NonNull final DocumentFilter filter)
{
|
final CountryId countryId = filter.getParameterValueAsRepoIdOrNull(PARAM_CountryId, CountryId::ofRepoIdOrNull);
if (countryId == null)
{
throw new FillMandatoryException(PARAM_CountryId);
// return null;
}
return Services.get(ICountryDAO.class).retrieveCountryCode2ByCountryId(countryId);
}
private static int extractDistanceInKm(final DocumentFilter filter)
{
final int distanceInKm = filter.getParameterValueAsInt(PARAM_Distance, -1);
return Math.max(distanceInKm, 0);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\geo_location\GeoLocationFilterConverter.java
| 1
|
请完成以下Java代码
|
private Step step() {
return stepBuilderFactory.get("step")
.<String, String>chunk(2)
.reader(listItemReader())
.processor(myProcessor())
.writer(list -> list.forEach(System.out::println))
.faultTolerant() // 配置错误容忍
.retry(MyJobExecutionException.class) // 配置重试的异常类型
.retryLimit(3) // 重试3次,三次过后还是异常的话,则任务会结束,
// 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常重试
.build();
}
private ListItemReader<String> listItemReader() {
ArrayList<String> datas = new ArrayList<>();
IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i)));
return new ListItemReader<>(datas);
}
|
private ItemProcessor<String, String> myProcessor() {
return new ItemProcessor<String, String>() {
private int count;
@Override
public String process(String item) throws Exception {
System.out.println("当前处理的数据:" + item);
if (count >= 2) {
return item;
} else {
count++;
throw new MyJobExecutionException("任务处理出错");
}
}
};
}
}
|
repos\SpringAll-master\72.spring-batch-exception\src\main\java\cc\mrbird\batch\job\RetryExceptionJobDemo.java
| 1
|
请完成以下Java代码
|
public void installUI(final JComponent comp)
{
updateUI(comp);
comp.addPropertyChangeListener("UI", this);
}
/** Actually sets the UI properties */
private void updateUI(final JComponent comp)
{
comp.setBorder(null);
comp.setFont(AdempierePLAF.getFont_Field());
comp.setForeground(AdempierePLAF.getTextColor_Normal());
}
@Override
|
public void propertyChange(PropertyChangeEvent evt)
{
if (PROPERTY_UI.equals(evt.getPropertyName()))
{
final JComponent comp = (JComponent)evt.getSource();
updateUI(comp);
}
}
}
private VEditorUtils()
{
super();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isWithoutTenantId() {
return withoutTenantId;
}
@ApiParam("Only return jobs without a tenantId")
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public boolean isLocked() {
return locked;
}
@ApiParam("Only return jobs that are locked")
public void setLocked(boolean locked) {
this.locked = locked;
}
public boolean isUnlocked() {
return unlocked;
}
|
@ApiParam("Only return jobs that are unlocked")
public void setUnlocked(boolean unlocked) {
this.unlocked = unlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
@ApiParam("Only return jobs without a scope type")
public void setWithoutScopeType(boolean withoutScopeType) {
this.withoutScopeType = withoutScopeType;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobQueryRequest.java
| 2
|
请完成以下Java代码
|
public void setIncidentState(int incidentState) {
this.incidentState = incidentState;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public boolean isOpen() {
return IncidentState.DEFAULT.getStateCode() == incidentState;
}
public boolean isDeleted() {
return IncidentState.DELETED.getStateCode() == incidentState;
}
public boolean isResolved() {
return IncidentState.RESOLVED.getStateCode() == incidentState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
|
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java
| 1
|
请完成以下Java代码
|
public HttpHeaders filter(HttpHeaders headers, ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
if (isGRPC(exchange)) {
String grpcStatus = getGrpcStatus(headers);
String grpcMessage = getGrpcMessage(headers);
if (grpcStatus != null) {
while (response instanceof ServerHttpResponseDecorator) {
response = ((ServerHttpResponseDecorator) response).getDelegate();
}
if (response instanceof AbstractServerHttpResponse) {
((HttpServerResponse) ((AbstractServerHttpResponse) response).getNativeResponse())
.trailerHeaders(h -> {
h.set(GRPC_STATUS_HEADER, grpcStatus);
h.set(GRPC_MESSAGE_HEADER, grpcMessage);
});
}
}
}
return headers;
}
private boolean isGRPC(ServerWebExchange exchange) {
String contentTypeValue = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
return StringUtils.startsWithIgnoreCase(contentTypeValue, "application/grpc");
}
|
private @Nullable String getGrpcStatus(HttpHeaders headers) {
final String grpcStatusValue = headers.getFirst(GRPC_STATUS_HEADER);
return StringUtils.hasText(grpcStatusValue) ? grpcStatusValue : null;
}
private String getGrpcMessage(HttpHeaders headers) {
final String grpcStatusValue = headers.getFirst(GRPC_MESSAGE_HEADER);
return StringUtils.hasText(grpcStatusValue) ? grpcStatusValue : "";
}
@Override
public boolean supports(Type type) {
return Type.RESPONSE.equals(type);
}
@Override
public int getOrder() {
return 0;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\GRPCResponseHeadersFilter.java
| 1
|
请完成以下Java代码
|
public String toJson()
{
return code;
}
/**
* Accepts either the human-readable constant name (e.g. "High") or the code (e.g. "3").
*/
@JsonCreator
@Nullable
public static JsonRequestPriority fromJson(final String value)
{
if (value == null)
{
return null;
}
// Try by code first
for (final JsonRequestPriority t : values())
|
{
if (t.code.equalsIgnoreCase(value))
{
return t;
}
}
// Then by enum name (human-readable constant without the generated prefix)
for (final JsonRequestPriority t : values())
{
if (t.name().equalsIgnoreCase(value))
{
return t;
}
}
throw new IllegalArgumentException("Unknown Request Priority: " + value);
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\request\JsonRequestPriority.java
| 1
|
请完成以下Java代码
|
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 Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/
@Override
public void setMsgText (java.lang.String MsgText)
{
set_ValueNoCheck (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
/** 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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java
| 1
|
请完成以下Java代码
|
public void logEvent(final WebsocketTopicName destination, @Nullable final Object event)
{
if (!logEventsEnabled.get())
{
return;
}
synchronized (loggedEvents)
{
logger.info("{}: {}", destination, event);
loggedEvents.add(new WebsocketEventLogRecord(destination, event));
final int maxSize = logEventsMaxSize.get();
while (loggedEvents.size() > maxSize)
{
loggedEvents.remove(0);
}
}
}
public void setLogEventsEnabled(final boolean enabled)
{
final boolean enabledOld = logEventsEnabled.getAndSet(enabled);
logger.info("Changed logEventsEnabled from {} to {}", enabledOld, enabled);
}
public void setLogEventsMaxSize(final int logEventsMaxSizeNew)
{
Preconditions.checkArgument(logEventsMaxSizeNew > 0, "logEventsMaxSize > 0");
|
final int logEventsMaxSizeOld = logEventsMaxSize.getAndSet(logEventsMaxSizeNew);
logger.info("Changed logEventsMaxSize from {} to {}", logEventsMaxSizeOld, logEventsMaxSizeNew);
}
public List<WebsocketEventLogRecord> getLoggedEvents()
{
synchronized (loggedEvents)
{
return new ArrayList<>(loggedEvents);
}
}
public List<WebsocketEventLogRecord> getLoggedEvents(final String destinationFilter)
{
return getLoggedEvents()
.stream()
.filter(websocketEvent -> websocketEvent.isDestinationMatching(destinationFilter))
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\sender\WebsocketEventsLog.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static final class NimbusJwtDecoderJwkSetUriFactoryBean implements FactoryBean<JwtDecoder> {
private final String jwkSetUri;
NimbusJwtDecoderJwkSetUriFactoryBean(String jwkSetUri) {
this.jwkSetUri = jwkSetUri;
}
@Override
public JwtDecoder getObject() {
return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
@Override
public Class<?> getObjectType() {
return JwtDecoder.class;
}
}
static final class BearerTokenRequestMatcher implements RequestMatcher {
private final BearerTokenResolver bearerTokenResolver;
BearerTokenRequestMatcher(BearerTokenResolver bearerTokenResolver) {
Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null");
this.bearerTokenResolver = bearerTokenResolver;
}
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.bearerTokenResolver.resolve(request) != null;
}
catch (OAuth2AuthenticationException ex) {
return false;
|
}
}
}
static final class BearerTokenAuthenticationRequestMatcher implements RequestMatcher {
private final AuthenticationConverter authenticationConverter;
BearerTokenAuthenticationRequestMatcher() {
this.authenticationConverter = new BearerTokenAuthenticationConverter();
}
BearerTokenAuthenticationRequestMatcher(AuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter;
}
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.authenticationConverter.convert(request) != null;
}
catch (OAuth2AuthenticationException ex) {
return false;
}
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ResourceServerBeanDefinitionParser.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private ImmutableList<I_M_HU_QRCode_Assignment> getAssignmentsByHuIds(@NonNull final ImmutableSet<HuId> huIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMN_M_HU_ID, huIds)
.create()
.listImmutable(I_M_HU_QRCode_Assignment.class);
}
@NonNull
private ImmutableMap<HUQRCodeRepoId, I_M_HU_QRCode> getByIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeId)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID, huQrCodeId)
.create()
.stream()
.collect(ImmutableMap.toImmutableMap(huQrCode -> HUQRCodeRepoId.ofRepoId(huQrCode.getM_HU_QRCode_ID()),
Function.identity()));
}
@NonNull
private Optional<I_M_HU_QRCode> getByUniqueId(final @NonNull HUQRCodeUniqueId uniqueId)
{
return queryByQRCode(uniqueId)
.create()
.firstOnlyOptional(I_M_HU_QRCode.class);
}
private void removeAssignment(@NonNull final I_M_HU_QRCode qrCode, @NonNull final ImmutableSet<HuId> huIdsToRemove)
{
streamAssignmentForQrAndHuIds(ImmutableSet.of(HUQRCodeRepoId.ofRepoId(qrCode.getM_HU_QRCode_ID())), huIdsToRemove)
.forEach(InterfaceWrapperHelper::delete);
}
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMN_M_HU_QRCode_ID, huQrCodeIds)
.create()
.stream();
}
|
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrAndHuIds(
@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds,
@NonNull final ImmutableSet<HuId> huIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_QRCode_ID, huQrCodeIds)
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_ID, huIds)
.create()
.stream();
}
private static HUQRCode toHUQRCode(final I_M_HU_QRCode record)
{
return HUQRCode.fromGlobalQRCodeJsonString(record.getRenderedQRCode());
}
public Stream<HUQRCode> streamQRCodesLike(@NonNull final String like)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode.class)
.addOnlyActiveRecordsFilter()
.addStringLikeFilter(I_M_HU_QRCode.COLUMNNAME_RenderedQRCode, like, false)
.orderBy(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID)
.create()
.stream()
.map(HUQRCodesRepository::toHUQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesRepository.java
| 2
|
请完成以下Java代码
|
public static void givenStack_whenUsingStreamReverse_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(20);
stack.push(10);
stack.push(30);
Collections.reverse(stack);
stack.forEach(System.out::println);
}
public static void givenStack_whenUsingIterator_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
Iterator<Integer> iterator = stack.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
|
public static void givenStack_whenUsingListIteratorReverseOrder_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
ListIterator<Integer> iterator = stack.listIterator(stack.size());
while (iterator.hasPrevious()) {
System.out.print(iterator.previous() + " ");
}
}
public static void givenStack_whenUsingDeque_thenPrintStack() {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.forEach(e -> System.out.print(e + " "));
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\PrintStack.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JobController {
private final JobService jobService;
@Autowired
public JobController(JobService jobService) {
this.jobService = jobService;
}
/**
* 保存定时任务
*/
@PostMapping
public ResponseEntity<ApiResponse> addJob(@Valid JobForm form) {
try {
jobService.addJob(form);
} catch (Exception e) {
return new ResponseEntity<>(ApiResponse.msg(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(ApiResponse.msg("操作成功"), HttpStatus.CREATED);
}
/**
* 删除定时任务
*/
@DeleteMapping
public ResponseEntity<ApiResponse> deleteJob(JobForm form) throws SchedulerException {
if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
}
jobService.deleteJob(form);
return new ResponseEntity<>(ApiResponse.msg("删除成功"), HttpStatus.OK);
}
/**
* 暂停定时任务
*/
@PutMapping(params = "pause")
public ResponseEntity<ApiResponse> pauseJob(JobForm form) throws SchedulerException {
if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
}
jobService.pauseJob(form);
return new ResponseEntity<>(ApiResponse.msg("暂停成功"), HttpStatus.OK);
}
/**
* 恢复定时任务
*/
@PutMapping(params = "resume")
public ResponseEntity<ApiResponse> resumeJob(JobForm form) throws SchedulerException {
if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
}
jobService.resumeJob(form);
return new ResponseEntity<>(ApiResponse.msg("恢复成功"), HttpStatus.OK);
}
|
/**
* 修改定时任务,定时时间
*/
@PutMapping(params = "cron")
public ResponseEntity<ApiResponse> cronJob(@Valid JobForm form) {
try {
jobService.cronJob(form);
} catch (Exception e) {
return new ResponseEntity<>(ApiResponse.msg(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(ApiResponse.msg("修改成功"), HttpStatus.OK);
}
@GetMapping
public ResponseEntity<ApiResponse> jobList(Integer currentPage, Integer pageSize) {
if (ObjectUtil.isNull(currentPage)) {
currentPage = 1;
}
if (ObjectUtil.isNull(pageSize)) {
pageSize = 10;
}
PageInfo<JobAndTrigger> all = jobService.list(currentPage, pageSize);
return ResponseEntity.ok(ApiResponse.ok(Dict.create().set("total", all.getTotal()).set("data", all.getList())));
}
}
|
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\controller\JobController.java
| 2
|
请完成以下Java代码
|
public void onReceiptScheduleDeleted(final I_M_ReceiptSchedule_Alloc receiptScheduleAlloc)
{
final ReceiptQty qtyDiff = getQtysIfActive(receiptScheduleAlloc);
updateQtyMoved(receiptScheduleAlloc, qtyDiff.negateQtys());
}
private final void updateQtyMoved(final I_M_ReceiptSchedule_Alloc receiptScheduleAlloc, final ReceiptQty qtysDiff)
{
if (qtysDiff.isZero())
{
return;
}
final I_M_ReceiptSchedule receiptSchedule = receiptScheduleAlloc.getM_ReceiptSchedule();
// Make sure our receipt schedule is up2date and not some staled cached version
// because we need QtyMoved(old) to be fresh
InterfaceWrapperHelper.refresh(receiptSchedule);
final ReceiptQty receiptScheduleQtys = getQtysForUpdate(receiptSchedule);
receiptScheduleQtys.add(qtysDiff);
setQtys(receiptSchedule, receiptScheduleQtys);
// QtyToMove shall be updated in "onReceiptScheduleChanged"
// NOTE: make sure it is called right away (see 6185, G01T010)
// note: it's called via model interceptor on save.
// onReceiptScheduleChanged(receiptSchedule);
InterfaceWrapperHelper.save(receiptSchedule);
}
protected final BigDecimal calculateQtyToMove(final I_M_ReceiptSchedule rs)
{
final BigDecimal qtyOrdered = getQtyOrdered(rs);
final BigDecimal qtyMoved = getQtyMoved(rs);
BigDecimal qtyToMove = qtyOrdered.subtract(qtyMoved);
// In case there is an over-delivery we don't want our QtyToMove to be negative but ZERO
// qtyOrdered is not updated if receiptSchedule row is closed (isProcessed == true)
if (qtyToMove.signum() <= 0 || rs.isProcessed())
{
qtyToMove = BigDecimal.ZERO;
}
|
return qtyToMove;
}
protected final BigDecimal calculateQtyOverUnderDelivery(final I_M_ReceiptSchedule rs)
{
final BigDecimal qtyOrdered = getQtyOrdered(rs);
final BigDecimal qtyMoved = getQtyMoved(rs);
final BigDecimal qtyOverUnderDelivery = qtyMoved.subtract(qtyOrdered);
//
// Case: receipt schedule was marked as processed.
// Now we precisely know which is the actual Over/Under Delivery.
// i.e. if qtyOverUnder < 0 it means it's an under delivery (we delivered less)
// but we know this for sure ONLY when receipt schedule line is closed.
// Else we can consider that more receipts will come after.
if (rs.isProcessed())
{
return qtyOverUnderDelivery;
}
//
// Case: we have an Over-Delivery (i.e. we delivered more than it was required)
if (qtyOverUnderDelivery.signum() > 0)
{
return qtyOverUnderDelivery;
}
//
// Case: we delivered exactly what was needed
else if (qtyOverUnderDelivery.signum() == 0)
{
return BigDecimal.ZERO;
}
//
// Case: we have an Under-Delivery (i.e. we delivered less than it was required)
// Because receipt schedule is not yet processed, we are not sure this is a true under-delivery so we consider it ZERO
else
{
return BigDecimal.ZERO;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleQtysBL.java
| 1
|
请完成以下Java代码
|
public int countDomainByTenantIdAndOauth2Enabled(TenantId tenantId, boolean enabled) {
return domainRepository.countByTenantIdAndOauth2Enabled(tenantId.getId(), enabled);
}
@Override
public List<DomainOauth2Client> findOauth2ClientsByDomainId(TenantId tenantId, DomainId domainId) {
return DaoUtil.convertDataList(domainOauth2ClientRepository.findAllByDomainId(domainId.getId()));
}
@Override
public void addOauth2Client(DomainOauth2Client domainOauth2Client) {
domainOauth2ClientRepository.save(new DomainOauth2ClientEntity(domainOauth2Client));
}
@Override
public void removeOauth2Client(DomainOauth2Client domainOauth2Client) {
|
domainOauth2ClientRepository.deleteById(new DomainOauth2ClientCompositeKey(domainOauth2Client.getDomainId().getId(),
domainOauth2Client.getOAuth2ClientId().getId()));
}
@Override
public void deleteByTenantId(TenantId tenantId) {
domainRepository.deleteByTenantId(tenantId.getId());
}
@Override
public EntityType getEntityType() {
return EntityType.DOMAIN;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\domain\JpaDomainDao.java
| 1
|
请完成以下Java代码
|
public class HistoricActivityInstanceEntityImpl
extends HistoricScopeInstanceEntityImpl
implements HistoricActivityInstanceEntity {
private static final long serialVersionUID = 1L;
protected String activityId;
protected String activityName;
protected String activityType;
protected String executionId;
protected String assignee;
protected String taskId;
protected String calledProcessInstanceId;
protected String tenantId = ProcessEngineConfiguration.NO_TENANT_ID;
public HistoricActivityInstanceEntityImpl() {}
public Object getPersistentState() {
Map<String, Object> persistentState = (Map<String, Object>) new HashMap<String, Object>();
persistentState.put("endTime", endTime);
persistentState.put("durationInMillis", durationInMillis);
persistentState.put("deleteReason", deleteReason);
persistentState.put("executionId", executionId);
persistentState.put("assignee", assignee);
return persistentState;
}
// getters and setters //////////////////////////////////////////////////////
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getCalledProcessInstanceId() {
|
return calledProcessInstanceId;
}
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getTime() {
return getStartTime();
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return (
"HistoricActivityInstanceEntity[id=" +
id +
", activityId=" +
activityId +
", activityName=" +
activityName +
"]"
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricActivityInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", incidentTimestamp=" + incidentTimestamp
+ ", incidentType=" + incidentType
+ ", executionId=" + executionId
+ ", activityId=" + activityId
+ ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId
+ ", causeIncidentId=" + causeIncidentId
+ ", rootCauseIncidentId=" + rootCauseIncidentId
+ ", configuration=" + configuration
+ ", tenantId=" + tenantId
+ ", incidentMessage=" + incidentMessage
+ ", jobDefinitionId=" + jobDefinitionId
+ ", failedActivityId=" + failedActivityId
+ ", annotation=" + annotation
+ "]";
|
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IncidentEntity other = (IncidentEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentEntity.java
| 1
|
请完成以下Java代码
|
public void publishPartialResults(final List<PartialResultType> partialResults)
{
logger.debug("Publishing partial results to UI thread: {} ({})", partialResults, this);
if (partialResults == null || partialResults.isEmpty())
{
return;
}
for (final PartialResultType partialResult : partialResults)
{
publish(partialResult);
}
}
@Override
public void publishPartialResult(final PartialResultType partialResult)
{
logger.debug("Publishing partial result to UI thread: {} ({})", partialResult, this);
publish(partialResult);
}
private RootPaneContainer findRootPaneContainer(@Nullable final Component comp)
{
final RootPaneContainer rootPaneContainer = AEnv.getParentComponent(comp, RootPaneContainer.class);
if (rootPaneContainer == null)
{
final String errmsg = "No " + RootPaneContainer.class + " found."
+ "Ignore, but please check because this could be a development error."
+ "\n Component: " + comp
+ "\n Executor: " + this;
new AdempiereException(errmsg).throwIfDeveloperModeOrLogWarningElse(logger);
}
return rootPaneContainer;
}
private Window findWindow(@Nullable final RootPaneContainer rootPaneContainer)
{
final Component comp;
if (rootPaneContainer == null)
{
comp = null;
}
else if (rootPaneContainer instanceof Window)
{
return (Window)rootPaneContainer;
|
}
else if (rootPaneContainer instanceof Component)
{
comp = (Component)rootPaneContainer;
}
else
{
comp = rootPaneContainer.getRootPane();
}
final Window window = AEnv.getParentComponent(comp, Window.class);
if (window == null)
{
final String errmsg = "No " + Window.class + " found."
+ "Ignore, but please check because this could be a development error."
+ "\n RootPaneContainer: " + rootPaneContainer
+ "\n Component: " + comp
+ "\n Executor: " + this;
new AdempiereException(errmsg).throwIfDeveloperModeOrLogWarningElse(logger);
}
return window;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingClientUIAsyncInvoker.java
| 1
|
请完成以下Java代码
|
public Filter newTaskFilter() {
return commandExecutor.execute(new CreateFilterCmd(EntityTypes.TASK));
}
public Filter newTaskFilter(String filterName) {
return newTaskFilter().setName(filterName);
}
public FilterQuery createFilterQuery() {
return new FilterQueryImpl(commandExecutor);
}
public FilterQuery createTaskFilterQuery() {
return new FilterQueryImpl(commandExecutor).filterResourceType(EntityTypes.TASK);
}
public Filter saveFilter(Filter filter) {
return commandExecutor.execute(new SaveFilterCmd(filter));
}
public Filter getFilter(String filterId) {
return commandExecutor.execute(new GetFilterCmd(filterId));
}
public void deleteFilter(String filterId) {
commandExecutor.execute(new DeleteFilterCmd(filterId));
}
@SuppressWarnings("unchecked")
public <T> List<T> list(String filterId) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListCmd(filterId));
}
@SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> List<T> list(String filterId, Q extendingQuery) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListCmd(filterId, extendingQuery));
}
@SuppressWarnings("unchecked")
public <T> List<T> listPage(String filterId, int firstResult, int maxResults) {
|
return (List<T>) commandExecutor.execute(new ExecuteFilterListPageCmd(filterId, firstResult, maxResults));
}
@SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> List<T> listPage(String filterId, Q extendingQuery, int firstResult, int maxResults) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListPageCmd(filterId, extendingQuery, firstResult, maxResults));
}
@SuppressWarnings("unchecked")
public <T> T singleResult(String filterId) {
return (T) commandExecutor.execute(new ExecuteFilterSingleResultCmd(filterId));
}
@SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> T singleResult(String filterId, Q extendingQuery) {
return (T) commandExecutor.execute(new ExecuteFilterSingleResultCmd(filterId, extendingQuery));
}
public Long count(String filterId) {
return commandExecutor.execute(new ExecuteFilterCountCmd(filterId));
}
public Long count(String filterId, Query<?, ?> extendingQuery) {
return commandExecutor.execute(new ExecuteFilterCountCmd(filterId, extendingQuery));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\FilterServiceImpl.java
| 1
|
请完成以下Java代码
|
public void notify(
String processInstanceId,
String executionId,
Task task,
Map<String, Object> executionVariables,
Map<String, Object> customPropertiesMap
) {
NoExecutionVariableScope scope = new NoExecutionVariableScope();
Object delegate = expression.getValue(scope);
if (delegate instanceof TransactionDependentTaskListener) {
((TransactionDependentTaskListener) delegate).notify(
processInstanceId,
executionId,
task,
executionVariables,
customPropertiesMap
);
} else {
throw new ActivitiIllegalArgumentException(
|
"Delegate expression " +
expression +
" did not resolve to an implementation of " +
TransactionDependentTaskListener.class
);
}
}
/**
* returns the expression text for this task listener. Comes in handy if you want to check which listeners you already have.
*/
public String getExpressionText() {
return expression.getExpressionText();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\DelegateExpressionTransactionDependentTaskListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonRequestBankAccountUpsertItem
{
@ApiModelProperty(position = 10, allowEmptyValue = false)
@JsonProperty("iban")
final String iban;
@ApiModelProperty(position = 20, allowEmptyValue = true)
@JsonProperty("currencyCode")
final String currencyCode;
@ApiModelProperty(position = 30, required = false, value = "If not specified but required (e.g. because a new contact is created), then `true` is assumed")
@JsonInclude(Include.NON_NULL)
@JsonProperty("active")
Boolean active;
@ApiModelProperty(position = 40, required = false, value = "Sync advise about this contact's individual properties.\n" + PARENT_SYNC_ADVISE_DOC)
|
@JsonInclude(Include.NON_NULL)
SyncAdvise syncAdvise;
@JsonCreator
public JsonRequestBankAccountUpsertItem(
@JsonProperty("iban") @NonNull String iban,
@JsonProperty("currencyCode") @Nullable final String currencyCode,
@JsonProperty("active") @Nullable final Boolean active,
@JsonProperty("syncAdvise") @Nullable final SyncAdvise syncAdvise)
{
this.iban = iban;
this.currencyCode = currencyCode;
this.active = active;
this.syncAdvise = syncAdvise;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBankAccountUpsertItem.java
| 2
|
请完成以下Java代码
|
public class CourseSchedule {
Logger logger = LoggerFactory.getLogger("CourseSchedule");
private List<Integer> roomList;
private List<Integer> periodList;
private List<Lecture> lectureList;
private HardSoftScore score;
public CourseSchedule(){
roomList = new ArrayList<>();
periodList = new ArrayList<>();
lectureList = new ArrayList<>();
}
@ValueRangeProvider(id = "availableRooms")
@ProblemFactCollectionProperty
public List<Integer> getRoomList() {
return roomList;
}
@ValueRangeProvider(id = "availablePeriods")
@ProblemFactCollectionProperty
public List<Integer> getPeriodList() {
return periodList;
}
@PlanningEntityCollectionProperty
public List<Lecture> getLectureList() {
return lectureList;
}
|
@PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
public void printCourseSchedule() {
lectureList.stream()
.map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString())
.forEach(k -> logger.info(k));
}
}
|
repos\tutorials-master\drools\src\main\java\com\baeldung\drools\optaplanner\CourseSchedule.java
| 1
|
请完成以下Java代码
|
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Paths: %s, match trailing slash: %b", config.getPatterns(),
config.isMatchTrailingSlash());
}
};
}
public static class Config {
private List<String> patterns = new ArrayList<>();
private boolean matchTrailingSlash = true;
public List<String> getPatterns() {
return patterns;
}
public Config setPatterns(List<String> patterns) {
this.patterns = patterns;
return this;
}
|
public boolean isMatchTrailingSlash() {
return matchTrailingSlash;
}
public Config setMatchTrailingSlash(boolean matchTrailingSlash) {
this.matchTrailingSlash = matchTrailingSlash;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append("patterns", patterns)
.append(MATCH_TRAILING_SLASH, matchTrailingSlash)
.toString();
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\PathRoutePredicateFactory.java
| 1
|
请完成以下Java代码
|
protected void processWindowEvent(WindowEvent e)
{
super.processWindowEvent(e);
// System.out.println(">> Apps WE_" + e.getID() // + " Frames=" + getFrames().length
// + " " + e);
} // processWindowEvent
/**
* Get Application Panel
* @return application panel
*/
public APanel getAPanel()
{
return m_APanel;
} // getAPanel
/**
* Dispose
*/
@Override
public void dispose()
{
if (Env.hideWindow(this))
{
return;
}
log.debug("disposing: {}", this);
if (m_APanel != null)
{
m_APanel.dispose();
}
m_APanel = null;
this.removeAll();
super.dispose();
// System.gc();
} // dispose
/**
* Get Window No of Panel
* @return window no
*/
public int getWindowNo()
{
if (m_APanel != null)
{
return m_APanel.getWindowNo();
}
return 0;
|
} // getWindowNo
/**
* String Representation
* @return Name
*/
@Override
public String toString()
{
return getName() + "_" + getWindowNo();
} // toString
// metas: begin
public GridWindow getGridWindow()
{
if (m_APanel == null)
{
return null;
}
return m_APanel.getGridWorkbench().getMWindowById(getAdWindowId());
}
// metas: end
} // AWindow
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AWindow.java
| 1
|
请完成以下Java代码
|
public String getTariffType() {
return tariffType;
}
/**
* Sets the value of the tariffType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTariffType(String value) {
this.tariffType = value;
}
/**
* Gets the value of the costFraction property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public BigDecimal getCostFraction() {
if (costFraction == null) {
return new Adapter1().unmarshal("1.0");
} else {
return costFraction;
}
}
/**
* Sets the value of the costFraction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCostFraction(BigDecimal value) {
this.costFraction = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordDRGType.java
| 1
|
请完成以下Java代码
|
public void setRemittance_PrintFormat_ID (int Remittance_PrintFormat_ID)
{
if (Remittance_PrintFormat_ID < 1)
set_Value (COLUMNNAME_Remittance_PrintFormat_ID, null);
else
set_Value (COLUMNNAME_Remittance_PrintFormat_ID, Integer.valueOf(Remittance_PrintFormat_ID));
}
/** Get Remittance Print Format.
@return Print Format for separate Remittances
*/
public int getRemittance_PrintFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Remittance_PrintFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_MailText getShipment_MailText() throws RuntimeException
{
return (I_R_MailText)MTable.get(getCtx(), I_R_MailText.Table_Name)
.getPO(getShipment_MailText_ID(), get_TrxName()); }
/** Set Shipment Mail Text.
@param Shipment_MailText_ID
Email text used for sending delivery notes
*/
public void setShipment_MailText_ID (int Shipment_MailText_ID)
{
if (Shipment_MailText_ID < 1)
set_Value (COLUMNNAME_Shipment_MailText_ID, null);
else
set_Value (COLUMNNAME_Shipment_MailText_ID, Integer.valueOf(Shipment_MailText_ID));
}
/** Get Shipment Mail Text.
|
@return Email text used for sending delivery notes
*/
public int getShipment_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Shipment_MailText_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_PrintFormat getShipment_PrintFormat() throws RuntimeException
{
return (I_AD_PrintFormat)MTable.get(getCtx(), I_AD_PrintFormat.Table_Name)
.getPO(getShipment_PrintFormat_ID(), get_TrxName()); }
/** Set Shipment Print Format.
@param Shipment_PrintFormat_ID
Print Format for Shipments, Receipts, Pick Lists
*/
public void setShipment_PrintFormat_ID (int Shipment_PrintFormat_ID)
{
if (Shipment_PrintFormat_ID < 1)
set_Value (COLUMNNAME_Shipment_PrintFormat_ID, null);
else
set_Value (COLUMNNAME_Shipment_PrintFormat_ID, Integer.valueOf(Shipment_PrintFormat_ID));
}
/** Get Shipment Print Format.
@return Print Format for Shipments, Receipts, Pick Lists
*/
public int getShipment_PrintFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Shipment_PrintFormat_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_AD_PrintForm.java
| 1
|
请完成以下Java代码
|
public class NestedLoopsToStreamsConverter {
public static List<int[]> getAllPairsImperative(List<Integer> list1, List<Integer> list2) {
List<int[]> pairs = new ArrayList<>();
for (Integer num1 : list1) {
for (Integer num2 : list2) {
pairs.add(new int[] { num1, num2 });
}
}
return pairs;
}
public static List<int[]> getAllPairsStream(List<Integer> list1, List<Integer> list2) {
return list1.stream()
.flatMap(num1 -> list2.stream().map(num2 -> new int[] { num1, num2 }))
.collect(Collectors.toList());
}
public static List<int[]> getFilteredPairsImperative(List<Integer> list1, List<Integer> list2) {
List<int[]> pairs = new ArrayList<>();
for (Integer num1 : list1) {
for (Integer num2 : list2) {
if (num1 + num2 > 7) {
pairs.add(new int[] { num1, num2 });
}
}
}
return pairs;
}
public static List<int[]> getFilteredPairsStream(List<Integer> list1, List<Integer> list2) {
return list1.stream()
.flatMap(num1 -> list2.stream().map(num2 -> new int[] { num1, num2 }))
.filter(pair -> pair[0] + pair[1] > 7)
.collect(Collectors.toList());
}
public static Optional<int[]> getFirstMatchingPairImperative(List<Integer> list1, List<Integer> list2) {
|
for (Integer num1 : list1) {
for (Integer num2 : list2) {
if (num1 + num2 > 7) {
return Optional.of(new int[] { num1, num2 });
}
}
}
return Optional.empty();
}
public static Optional<int[]> getFirstMatchingPairStream(List<Integer> list1, List<Integer> list2) {
return list1.stream()
.flatMap(num1 -> list2.stream().map(num2 -> new int[] { num1, num2 }))
.filter(pair -> pair[0] + pair[1] > 7)
.findFirst();
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\NestedLoopsToStreamsConverter.java
| 1
|
请完成以下Java代码
|
class WorkThread extends Thread
{
String[] sentenceArray;
List<Term>[] termListArray;
int from;
int to;
public WorkThread(String[] sentenceArray, List<Term>[] termListArray, int from, int to)
{
this.sentenceArray = sentenceArray;
this.termListArray = termListArray;
this.from = from;
this.to = to;
}
@Override
public void run()
{
for (int i = from; i < to; ++i)
{
termListArray[i] = segSentence(sentenceArray[i].toCharArray());
}
}
}
/**
* 开启多线程
*
* @param enable true表示开启[系统CPU核心数]个线程,false表示单线程
* @return
*/
public Segment enableMultithreading(boolean enable)
{
if (enable) config.threadNumber = Runtime.getRuntime().availableProcessors();
|
else config.threadNumber = 1;
return this;
}
/**
* 开启多线程
*
* @param threadNumber 线程数量
* @return
*/
public Segment enableMultithreading(int threadNumber)
{
config.threadNumber = threadNumber;
return this;
}
/**
* 是否执行字符正规化(繁体->简体,全角->半角,大写->小写),切换配置后必须删CustomDictionary.txt.bin缓存
*/
public Segment enableNormalization(boolean normalization)
{
config.normalization = normalization;
return this;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Segment.java
| 1
|
请完成以下Java代码
|
public class ExecutionDto {
private String id;
private String processInstanceId;
private boolean ended;
private String tenantId;
public static ExecutionDto fromExecution(Execution execution) {
ExecutionDto dto = new ExecutionDto();
dto.id = execution.getId();
dto.processInstanceId = execution.getProcessInstanceId();
dto.ended = execution.isEnded();
dto.tenantId = execution.getTenantId();
return dto;
}
|
public String getId() {
return id;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public boolean isEnded() {
return ended;
}
public String getTenantId() {
return tenantId;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ExecutionDto.java
| 1
|
请完成以下Java代码
|
protected ExpressionFactory getDefaultExpressionFactory() {
return ExpressionFactory.newInstance();
}
/*
* Copied from org.apache.el.lang.ELSupport - keep in sync
*/
static boolean isFunctionalInterface(Class<?> type) {
if (!type.isInterface()) {
return false;
}
boolean foundAbstractMethod = false;
Method[] methods = type.getMethods();
for (Method method : methods) {
if (Modifier.isAbstract(method.getModifiers())) {
// Abstract methods that override one of the public methods
// of Object don't count
if (overridesObjectMethod(method)) {
continue;
}
if (foundAbstractMethod) {
// Found more than one
return false;
} else {
foundAbstractMethod = true;
}
}
}
|
return foundAbstractMethod;
}
/*
* Copied from org.apache.el.lang.ELSupport - keep in sync
*/
private static boolean overridesObjectMethod(Method method) {
// There are three methods that can be overridden
if ("equals".equals(method.getName())) {
if (method.getReturnType().equals(boolean.class)) {
if (method.getParameterCount() == 1) {
return method.getParameterTypes()[0].equals(Object.class);
}
}
} else if ("hashCode".equals(method.getName())) {
if (method.getReturnType().equals(int.class)) {
return method.getParameterCount() == 0;
}
} else if ("toString".equals(method.getName())) {
if (method.getReturnType().equals(String.class)) {
return method.getParameterCount() == 0;
}
}
return false;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ELContext.java
| 1
|
请完成以下Java代码
|
/* package */ abstract class WEBUI_M_ReceiptSchedule_CreateEmptiesReturns_Base extends ReceiptScheduleBasedProcess
{
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.accept();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
// services
private final transient IHUEmptiesService huEmptiesService = Services.get(IHUEmptiesService.class);
private final DocumentCollection documentsRepo = SpringContextHolder.instance.getBean(DocumentCollection.class);
private final String _returnMovementType;
private final AdWindowId _targetWindowId;
public WEBUI_M_ReceiptSchedule_CreateEmptiesReturns_Base(@NonNull final String returnMovementType, @NonNull final AdWindowId targetWindowId)
{
Check.assumeNotEmpty(returnMovementType, "returnMovementType is not empty");
_returnMovementType = returnMovementType;
_targetWindowId = targetWindowId;
}
private String getReturnMovementType()
{
return _returnMovementType;
}
private AdWindowId getTargetWindowId()
{
return _targetWindowId;
}
@Override
protected String doIt() throws Exception
{
final I_M_ReceiptSchedule receiptSchedule = getProcessInfo().getRecordIfApplies(I_M_ReceiptSchedule.class, ITrx.TRXNAME_ThreadInherited).orElse(null);
final int emptiesInOutId;
if (receiptSchedule == null)
{
emptiesInOutId = createDraftEmptiesDocument();
}
else
{
final I_M_InOut emptiesInOut = huEmptiesService.createDraftEmptiesInOutFromReceiptSchedule(receiptSchedule, getReturnMovementType());
emptiesInOutId = emptiesInOut == null ? -1 : emptiesInOut.getM_InOut_ID();
}
//
|
// Notify frontend that the empties document shall be opened in single document layout (not grid)
if (emptiesInOutId > 0)
{
getResult().setRecordToOpen(TableRecordReference.of(I_M_InOut.Table_Name, emptiesInOutId), getTargetWindowId(), OpenTarget.SingleDocument);
}
return MSG_OK;
}
private int createDraftEmptiesDocument()
{
final DocumentPath documentPath = DocumentPath.builder()
.setDocumentType(WindowId.of(getTargetWindowId()))
.setDocumentId(DocumentId.NEW_ID_STRING)
.allowNewDocumentId()
.build();
final DocumentId documentId = documentsRepo.forDocumentWritable(documentPath, NullDocumentChangesCollector.instance, document -> {
huEmptiesService.newReturnsInOutProducer(getCtx())
.setMovementType(getReturnMovementType())
.setMovementDate(de.metas.common.util.time.SystemTime.asDayTimestamp())
.fillReturnsInOutHeader(InterfaceWrapperHelper.create(document, I_M_InOut.class));
return document.getDocumentId();
});
return documentId.toInt();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_CreateEmptiesReturns_Base.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class GatewayRedisAutoConfiguration {
@Bean
@SuppressWarnings("unchecked")
public RedisScript redisRequestRateLimiterScript() {
DefaultRedisScript redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(
new ResourceScriptSource(new ClassPathResource("META-INF/scripts/request_rate_limiter.lua")));
redisScript.setResultType(List.class);
return redisScript;
}
@Bean
@ConditionalOnMissingBean
public RedisRateLimiter redisRateLimiter(ReactiveStringRedisTemplate redisTemplate,
@Qualifier(RedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript<List<Long>> redisScript,
ConfigurationService configurationService) {
return new RedisRateLimiter(redisTemplate, redisScript, configurationService);
}
@Bean
|
@ConditionalOnProperty(value = GatewayProperties.PREFIX + ".redis-route-definition-repository.enabled",
havingValue = "true")
@ConditionalOnClass(ReactiveRedisTemplate.class)
public RedisRouteDefinitionRepository redisRouteDefinitionRepository(
ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisTemplate) {
return new RedisRouteDefinitionRepository(reactiveRedisTemplate);
}
@Bean
public ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisRouteDefinitionTemplate(
ReactiveRedisConnectionFactory factory) {
StringRedisSerializer keySerializer = new StringRedisSerializer();
JacksonJsonRedisSerializer<RouteDefinition> valueSerializer = new JacksonJsonRedisSerializer<>(
RouteDefinition.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, RouteDefinition> builder = RedisSerializationContext
.newSerializationContext(keySerializer);
RedisSerializationContext<String, RouteDefinition> context = builder.value(valueSerializer).build();
return new ReactiveRedisTemplate<>(factory, context);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayRedisAutoConfiguration.java
| 2
|
请完成以下Java代码
|
void attemptEnded() {
boolean shouldRecordFinishedCall = false;
synchronized (lock) {
if (--activeStreams == 0) {
attemptStopwatch.start();
if (callEnded && !finishedCallToBeRecorded) {
shouldRecordFinishedCall = true;
finishedCallToBeRecorded = true;
}
}
}
if (shouldRecordFinishedCall) {
recordFinishedCall();
}
}
void callEnded(Status status) {
clientCallStopWatch.stop();
this.status = status;
boolean shouldRecordFinishedCall = false;
synchronized (lock) {
if (callEnded) {
return;
}
callEnded = true;
if (activeStreams == 0 && !finishedCallToBeRecorded) {
shouldRecordFinishedCall = true;
finishedCallToBeRecorded = true;
}
}
if (shouldRecordFinishedCall) {
recordFinishedCall();
}
}
void recordFinishedCall() {
|
if (attemptsPerCall.get() == 0) {
ClientTracer tracer = new ClientTracer(this, tracerModule, null, fullMethodName,
metricsClientMeters);
tracer.attemptNanos = attemptStopwatch.elapsed(TimeUnit.NANOSECONDS);
tracer.statusCode = status.getCode();
tracer.recordFinishedAttempt();
} else if (inboundMetricTracer != null) {
// activeStreams has been decremented to 0 by attemptEnded(),
// so inboundMetricTracer.statusCode is guaranteed to be assigned already.
inboundMetricTracer.recordFinishedAttempt();
}
callLatencyNanos = clientCallStopWatch.elapsed(TimeUnit.NANOSECONDS);
Tags clientCallMetricTags =
Tags.of("grpc.method", this.fullMethodName,
"grpc.status", status.getCode().toString(),
INSTRUMENTATION_SOURCE_TAG_KEY, Constants.LIBRARY_NAME,
INSTRUMENTATION_VERSION_TAG_KEY, Constants.VERSION);
this.metricsClientMeters.getClientCallDuration()
.withTags(clientCallMetricTags)
.record(callLatencyNanos, TimeUnit.NANOSECONDS);
}
}
}
|
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientStreamTracers.java
| 1
|
请完成以下Java代码
|
void setAdvSearchWindow(
final @NonNull WindowId windowId,
final @Nullable DetailId tabId,
final @NonNull JSONDocumentLayoutOptions jsonOpts)
{
if (lookupTableName == null)
{
return;
}
// avoid enabling advanced search assistant for included tabs,
// because atm frontend does not support it.
if (tabId != null)
{
return;
}
final AdvancedSearchDescriptorsProvider provider = jsonOpts.getAdvancedSearchDescriptorsProvider();
if (provider == null)
|
{
return;
}
final DocumentEntityDescriptor advancedSearchEntityDescriptor = provider.getAdvancedSearchDescriptorIfAvailable(lookupTableName);
if (advancedSearchEntityDescriptor != null)
{
advSearchWindowId = advancedSearchEntityDescriptor.getDocumentTypeId().toJson();
advSearchCaption = advancedSearchEntityDescriptor.getCaption().translate(jsonOpts.getAdLanguage());
}
else
{
advSearchWindowId = null;
advSearchCaption = null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutElementField.java
| 1
|
请完成以下Java代码
|
public FunctionMapper getFunctionMapper() {
if (functions == null) {
functions = new Functions();
}
return functions;
}
/**
* Get our variable mapper.
*/
@Override
public VariableMapper getVariableMapper() {
if (variables == null) {
variables = new Variables();
}
return variables;
}
/**
* Get our resolver. Lazy initialize to a {@link SimpleResolver} if necessary.
|
*/
@Override
public ELResolver getELResolver() {
if (resolver == null) {
resolver = new SimpleResolver();
}
return resolver;
}
/**
* Set our resolver.
*
* @param resolver
*/
public void setELResolver(ELResolver resolver) {
this.resolver = resolver;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\SimpleContext.java
| 1
|
请完成以下Java代码
|
public HUQRCodeGenerateRequest.Attribute string()
{
return resultBuilder.valueString(json.getValue()).build();
}
@Override
public HUQRCodeGenerateRequest.Attribute number()
{
final BigDecimal valueNumber = NumberUtils.asBigDecimal(json.getValue());
return resultBuilder.valueNumber(valueNumber).build();
}
@Override
public HUQRCodeGenerateRequest.Attribute date()
{
final LocalDate valueDate = StringUtils.trimBlankToOptional(json.getValue()).map(LocalDate::parse).orElse(null);
return resultBuilder.valueDate(valueDate).build();
}
@Override
|
public HUQRCodeGenerateRequest.Attribute list()
{
final String listItemCode = json.getValue();
if (listItemCode != null)
{
final AttributeListValue listItem = attributeDAO.retrieveAttributeValueOrNull(attributeId, listItemCode);
if (listItem == null)
{
throw new AdempiereException("No M_AttributeValue_ID found for " + attributeId + " and `" + listItemCode + "`");
}
return resultBuilder.valueListId(listItem.getId()).build();
}
else
{
return resultBuilder.valueListId(null).build();
}
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\JsonQRCodesGenerateRequestConverters.java
| 1
|
请完成以下Java代码
|
public int filterOrder() {
return 0;
}
public boolean shouldFilter() {
return true; // 需要过滤
}
public Object run() throws ZuulException {
// 获取当前请求上下文
RequestContext ctx = RequestContext.getCurrentContext();
// 获得 token
HttpServletRequest request = ctx.getRequest();
String token = request.getHeader(DEFAULT_TOKEN_HEADER_NAME);
// 如果没有 token,则不进行认证。因为可能是无需认证的 API 接口
if (!StringUtils.hasText(token)) {
return null;
|
}
// 进行认证
Integer userId = TOKENS.get(token);
// 通过 token 获取不到 userId,说明认证不通过
if (userId == null) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); // 响应 401 状态码
return null;
}
// 认证通过,将 userId 添加到 Header 中
ctx.getZuulRequestHeaders().put(DEFAULT_HEADER_NAME, String.valueOf(userId));
return null;
}
}
|
repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo05-custom-zuul-filter\src\main\java\cn\iocoder\springcloud\labx21\zuuldemo\filter\AuthZuulFilter.java
| 1
|
请完成以下Java代码
|
void setSummary(int summary)
{
Summary = summary;
}
int getSummary()
{
return Summary;
}
void setFrom(String from)
{
From = from;
}
String getFrom()
{
|
return From;
}
void setTo(String to)
{
To = to;
}
String getTo()
{
return To;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CRPSummary.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerLocation location)
{
final OrgMappingId orgMappingId = location.getOrgMappingId();
if (orgMappingId != null)
{
return orgMappingId;
}
final I_AD_Org_Mapping orgMapping = newInstance(I_AD_Org_Mapping.class);
orgMapping.setAD_Org_ID(0);
orgMapping.setAD_Table_ID(getTableId(I_C_BPartner_Location.class));
orgMapping.setValue(location.getName());
save(orgMapping);
return OrgMappingId.ofRepoId(orgMapping.getAD_Org_Mapping_ID());
}
public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerBankAccount existingBankAccountInInitialPartner)
{
final OrgMappingId orgMappingId = existingBankAccountInInitialPartner.getOrgMappingId();
if (orgMappingId != null)
{
return orgMappingId;
}
final I_AD_Org_Mapping orgMapping = newInstance(I_AD_Org_Mapping.class);
orgMapping.setAD_Org_ID(0);
orgMapping.setAD_Table_ID(getTableId(I_C_BP_BankAccount.class));
orgMapping.setValue(existingBankAccountInInitialPartner.getIban());
save(orgMapping);
return OrgMappingId.ofRepoId(orgMapping.getAD_Org_Mapping_ID());
}
public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerContact contact)
{
|
final OrgMappingId orgMappingId = contact.getOrgMappingId();
if (orgMappingId != null)
{
return orgMappingId;
}
final I_AD_Org_Mapping orgMapping = newInstance(I_AD_Org_Mapping.class);
orgMapping.setAD_Org_ID(0);
orgMapping.setAD_Table_ID(getTableId(I_C_BP_BankAccount.class));
orgMapping.setValue(contact.getValue());
save(orgMapping);
return OrgMappingId.ofRepoId(orgMapping.getAD_Org_Mapping_ID());
}
public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerId bpartnerId)
{
final I_C_BPartner bPartnerRecord = bPartnerDAO.getById(bpartnerId);
OrgMappingId orgMappingId = OrgMappingId.ofRepoIdOrNull(bPartnerRecord.getAD_Org_Mapping_ID());
if (orgMappingId == null)
{
orgMappingId = createOrgMappingForBPartner(bPartnerRecord);
bPartnerRecord.setAD_Org_Mapping_ID(orgMappingId.getRepoId());
save(bPartnerRecord);
}
return orgMappingId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\repository\OrgMappingRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void shutdownExecutor() {
if (wsCallBackExecutor != null) {
wsCallBackExecutor.shutdownNow();
}
}
@Override
protected void onTbApplicationEvent(PartitionChangeEvent partitionChangeEvent) {
if (ServiceType.TB_CORE.equals(partitionChangeEvent.getServiceType())) {
currentPartitions.clear();
currentPartitions.addAll(partitionChangeEvent.getCorePartitions());
}
}
protected void forwardToSubscriptionManagerService(TenantId tenantId, EntityId entityId,
Consumer<SubscriptionManagerService> toSubscriptionManagerService,
Supplier<TransportProtos.ToCoreMsg> toCore) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId);
if (currentPartitions.contains(tpi)) {
if (subscriptionManagerService.isPresent()) {
toSubscriptionManagerService.accept(subscriptionManagerService.get());
} else {
log.warn("Possible misconfiguration because subscriptionManagerService is null!");
}
} else {
TransportProtos.ToCoreMsg toCoreMsg = toCore.get();
clusterService.pushMsgToCore(tpi, entityId.getId(), toCoreMsg, null);
}
}
protected <T> void addWsCallback(ListenableFuture<T> saveFuture, Consumer<T> callback) {
addCallback(saveFuture, callback, wsCallBackExecutor);
}
protected <T> void addCallback(ListenableFuture<T> saveFuture, Consumer<T> callback, Executor executor) {
Futures.addCallback(saveFuture, new FutureCallback<>() {
@Override
|
public void onSuccess(@Nullable T result) {
callback.accept(result);
}
@Override
public void onFailure(Throwable t) {}
}, executor);
}
protected static Consumer<Throwable> safeCallback(FutureCallback<Void> callback) {
if (callback != null) {
return callback::onFailure;
} else {
return throwable -> {};
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\AbstractSubscriptionService.java
| 2
|
请完成以下Java代码
|
public class MultipartVariableMapper {
private static final Pattern PERIOD = Pattern.compile("\\.");
private static final MultipartVariableMapper.Mapper<Map<String, Object>> MAP_MAPPER = new MultipartVariableMapper.Mapper<Map<String, Object>>() {
@Override
public <P> Object set(Map<String, Object> location, String target, P value) {
return location.put(target, value);
}
@Override
public Object recurse(Map<String, Object> location, String target) {
return location.get(target);
}
};
private static final MultipartVariableMapper.Mapper<List<Object>> LIST_MAPPER = new MultipartVariableMapper.Mapper<List<Object>>() {
@Override
public <P> Object set(List<Object> location, String target, P value) {
return location.set(Integer.parseInt(target), value);
}
@Override
public Object recurse(List<Object> location, String target) {
return location.get(Integer.parseInt(target));
}
};
@SuppressWarnings({"unchecked", "rawtypes"})
public static <P> void mapVariable(String objectPath, Map<String, Object> variables, P file) {
String[] segments = PERIOD.split(objectPath);
if (segments.length < 2) {
throw new RuntimeException("object-path in map must have at least two segments");
} else if (!"variables".equals(segments[0])) {
throw new RuntimeException("can only map into variables");
}
Object currentLocation = variables;
for (int i = 1; i < segments.length; i++) {
String segmentName = segments[i];
MultipartVariableMapper.Mapper mapper = determineMapper(currentLocation, objectPath, segmentName);
if (i == segments.length - 1) {
if (null != mapper.set(currentLocation, segmentName, file)) {
throw new RuntimeException("expected null value when mapping " + objectPath);
}
} else {
currentLocation = mapper.recurse(currentLocation, segmentName);
|
if (null == currentLocation) {
throw new RuntimeException("found null intermediate value when trying to map " + objectPath);
}
}
}
}
private static MultipartVariableMapper.Mapper<?> determineMapper(Object currentLocation, String objectPath, String segmentName) {
if (currentLocation instanceof Map) {
return MAP_MAPPER;
} else if (currentLocation instanceof List) {
return LIST_MAPPER;
}
throw new RuntimeException("expected a map or list at " + segmentName + " when trying to map " + objectPath);
}
interface Mapper<T> {
<P> Object set(T location, String target, P value);
Object recurse(T location, String target);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphql\fileupload\MultipartVariableMapper.java
| 1
|
请完成以下Java代码
|
public final class Fact_Acct_OpenLinkedFacts_ProcessHelper
{
final IDocumentBL documentBL = Services.get(IDocumentBL.class);
final IFactAcctDAO factAcctDAO = Services.get(IFactAcctDAO.class);
public void openLinkedFactAccounts(final int factAcctRecordId, final ProcessExecutionResult result)
{
final I_Fact_Acct factAcct = factAcctDAO.getById(factAcctRecordId);
// Fact_Acct_Transactions_View is actually wanted (so it's the right class - not I_Fact_Acct.class)
final int factAcctTableId = getTableId(I_Fact_Acct_Transactions_View.class);
final TableRecordReference documentReference = TableRecordReference.of(factAcct.getAD_Table_ID(), factAcct.getRecord_ID());
|
final IDocument document = documentBL.getDocument(documentReference);
final ImmutableList<TableRecordReference> linkedFactAccts = factAcctDAO.retrieveQueryForDocument(document)
.create()
.listIds()
.stream()
.map(recordId -> TableRecordReference.of(factAcctTableId, recordId))
.collect(ImmutableList.toImmutableList());
result.setRecordToOpen(RecordsToOpen.builder()
.records(linkedFactAccts)
.automaticallySetReferencingDocumentPaths(false)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\Fact_Acct_OpenLinkedFacts_ProcessHelper.java
| 1
|
请完成以下Java代码
|
protected List<ProcessInstance> fetchProcessInstancesPage(
CommandContext commandContext,
ProcessDefinition processDefinition,
int currentPageStartIndex
) {
if (SuspensionState.ACTIVE.equals(getProcessDefinitionSuspensionState())) {
return new ProcessInstanceQueryImpl(commandContext)
.processDefinitionId(processDefinition.getId())
.suspended()
.listPage(
currentPageStartIndex,
commandContext.getProcessEngineConfiguration().getBatchSizeProcessInstances()
);
} else {
return new ProcessInstanceQueryImpl(commandContext)
.processDefinitionId(processDefinition.getId())
.active()
.listPage(
currentPageStartIndex,
commandContext.getProcessEngineConfiguration().getBatchSizeProcessInstances()
);
}
|
}
// ABSTRACT METHODS
// ////////////////////////////////////////////////////////////////////
/**
* Subclasses should return the wanted {@link SuspensionState} here.
*/
protected abstract SuspensionState getProcessDefinitionSuspensionState();
/**
* Subclasses should return the type of the {@link JobHandler} here. it will be used when the user provides an execution date on which the actual state change will happen.
*/
protected abstract String getDelayedExecutionJobHandlerType();
/**
* Subclasses should return a {@link Command} implementation that matches the process definition state change.
*/
protected abstract AbstractSetProcessInstanceStateCmd getProcessInstanceChangeStateCmd(
ProcessInstance processInstance
);
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AbstractSetProcessDefinitionStateCmd.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.