instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setLabel(String label) {
this.label = label;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public List<String> getCandidateUsers() {
return candidateUsers;
} | public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
@Override
public CasePageTask clone() {
CasePageTask clone = new CasePageTask();
clone.setValues(this);
return clone;
}
public void setValues(CasePageTask otherElement) {
super.setValues(otherElement);
setType(otherElement.getType());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setLabel(otherElement.getLabel());
setIcon(otherElement.getIcon());
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CasePageTask.java | 1 |
请完成以下Java代码 | public class BlockingExecutorWrapper implements ExecutorService
{
private final Semaphore semaphore;
@Delegate(excludes = Executor.class) // don't delegate to Executor.execute(); of that, we have our own
private final ThreadPoolExecutor delegate;
private @NonNull Logger logger;
@Builder
private BlockingExecutorWrapper(
final int poolSize,
@NonNull final ThreadPoolExecutor delegate,
@NonNull final Logger loggerToUse)
{
this.semaphore = new Semaphore(poolSize);
this.delegate = delegate;
this.logger = loggerToUse;
}
@Override
public void execute(@NonNull final Runnable command)
{
try
{
logger.debug("Going to acquire semaphore{}", semaphore.toString());
semaphore.acquire();
logger.debug("Done acquiring semaphore={}", semaphore.toString());
}
catch (final InterruptedException e)
{
logger.warn("execute - InterruptedException while acquiring semaphore=" + semaphore + " for command=" + command + ";-> return", e);
return;
}
// wrap 'command' into another runnable, so we can in the end release the semaphore.
final Runnable r = new Runnable()
{
public String toString()
{
return "runnable-wrapper-for[" + command + "]";
}
public void run()
{
try
{
logger.debug("execute - Going to invoke command.run() within delegate thread-pool");
command.run();
logger.debug("execute - Done invoking command.run() within delegate thread-pool"); | }
catch (final Throwable t)
{
logger.error("execute - Caught throwable while running command=" + command + "; -> rethrow", t);
throw t;
}
finally
{
semaphore.release();
logger.debug("Released semaphore={}", semaphore);
}
}
};
try
{
delegate.execute(r); // don't expect RejectedExecutionException because delegate has a small queue that can hold runnables after semaphore-release and before they can actually start
}
catch (final RejectedExecutionException e)
{
semaphore.release();
logger.error("execute - Caught RejectedExecutionException while trying to submit task=" + r + " to delegate thread-pool=" + delegate + "; -> released semaphore=" + semaphore + " and rethrow", e);
throw e;
}
}
public boolean hasAvailablePermits()
{
return semaphore.availablePermits() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\BlockingExecutorWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void prepareExternalReferenceLookupRequest(@NonNull final Exchange exchange)
{
final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class);
final JsonResponseProductBPartner jsonResponseProductBPartner = exchange.getIn().getBody(JsonResponseProductBPartner.class);
if (Check.isEmpty(jsonResponseProductBPartner.getBPartnerProducts()))
{
exchange.getIn().setBody(null);
return;
}
final ImmutableSet<JsonMetasfreshId> productIds = jsonResponseProductBPartner.getBPartnerProducts()
.stream()
.map(JsonProductBPartner::getProductId)
.collect(ImmutableSet.toImmutableSet());
final List<JsonExternalReferenceLookupItem> items = productIds.stream()
.map(productId -> JsonExternalReferenceLookupItem.builder()
.metasfreshId(productId)
.type(EXTERNAL_REF_TYPE_PRODUCT)
.build())
.collect(ImmutableList.toImmutableList()); | final JsonExternalReferenceLookupRequest jsonExternalReferenceLookupRequest = JsonExternalReferenceLookupRequest.builder()
.systemName(JsonExternalSystemName.of(GRSSIGNUM_SYSTEM_NAME))
.items(items)
.build();
final ExternalReferenceLookupCamelRequest externalReferenceSearchCamelRequest = ExternalReferenceLookupCamelRequest.builder()
.externalSystemConfigId(routeContext.getExternalSystemConfigId())
.adPInstanceId(JsonMetasfreshId.ofOrNull(routeContext.getPinstanceId()))
.orgCode(routeContext.getOrgCode())
.jsonExternalReferenceLookupRequest(jsonExternalReferenceLookupRequest)
.build();
exchange.getIn().setBody(externalReferenceSearchCamelRequest);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\ExportBPartnerRequestBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder key(String key) {
deployment.setKey(key);
return this;
}
public DeploymentBuilder disableBpmnValidation() {
this.isProcessValidationEnabled = false;
return this;
}
public DeploymentBuilder disableSchemaValidation() {
this.isBpmn20XsdValidationEnabled = false;
return this;
}
public DeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
public DeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
deploymentProperties.put(propertyKey, propertyValue);
return this; | }
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled;
}
public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public Map<String, Object> getDeploymentProperties() {
return deploymentProperties;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public void setIsApplyToTopLevelHUsOnly (final boolean IsApplyToTopLevelHUsOnly)
{
set_Value (COLUMNNAME_IsApplyToTopLevelHUsOnly, IsApplyToTopLevelHUsOnly);
}
@Override
public boolean isApplyToTopLevelHUsOnly()
{
return get_ValueAsBoolean(COLUMNNAME_IsApplyToTopLevelHUsOnly);
}
@Override
public void setIsApplyToTUs (final boolean IsApplyToTUs)
{
set_Value (COLUMNNAME_IsApplyToTUs, IsApplyToTUs);
}
@Override
public boolean isApplyToTUs()
{
return get_ValueAsBoolean(COLUMNNAME_IsApplyToTUs);
}
@Override
public void setIsProvideAsUserAction (final boolean IsProvideAsUserAction)
{
set_Value (COLUMNNAME_IsProvideAsUserAction, IsProvideAsUserAction);
}
@Override
public boolean isProvideAsUserAction()
{
return get_ValueAsBoolean(COLUMNNAME_IsProvideAsUserAction);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PI getM_HU_PI()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class);
}
@Override
public void setM_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_HU_PI)
{
set_ValueFromPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_HU_PI);
}
@Override
public void setM_HU_PI_ID (final int M_HU_PI_ID) | {
if (M_HU_PI_ID < 1)
set_Value (COLUMNNAME_M_HU_PI_ID, null);
else
set_Value (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID);
}
@Override
public int getM_HU_PI_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID);
}
@Override
public void setM_HU_Process_ID (final int M_HU_Process_ID)
{
if (M_HU_Process_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Process_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Process_ID, M_HU_Process_ID);
}
@Override
public int getM_HU_Process_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Process_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Process.java | 1 |
请完成以下Java代码 | private boolean isCacheControlAllowed(HttpMessage request) {
HttpHeaders headers = request.getHeaders();
List<String> cacheControlHeader = headers.getOrEmpty(HttpHeaders.CACHE_CONTROL);
return cacheControlHeader.stream().noneMatch(forbiddenCacheControlValues::contains);
}
private static boolean hasRequestBody(ServerHttpRequest request) {
return request.getHeaders().getContentLength() > 0;
}
private void saveInCache(String cacheKey, CachedResponse cachedResponse) {
try {
cache.put(cacheKey, cachedResponse);
} | catch (RuntimeException anyException) {
LOGGER.error("Error writing into cache. Data will not be cached", anyException);
}
}
private void saveMetadataInCache(String metadataKey, CachedResponseMetadata metadata) {
try {
cache.put(metadataKey, metadata);
}
catch (RuntimeException anyException) {
LOGGER.error("Error writing into cache. Data will not be cached", anyException);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheManager.java | 1 |
请完成以下Java代码 | public void setId(String groupId) {
this.id = groupId;
}
@CamundaQueryParam(value = "idIn", converter = StringArrayConverter.class)
public void setIdIn(String[] groupIds) {
this.ids = groupIds;
}
@CamundaQueryParam("name")
public void setName(String groupName) {
this.name = groupName;
}
@CamundaQueryParam("nameLike")
public void setNameLike(String groupNameLike) {
this.nameLike = groupNameLike;
}
@CamundaQueryParam("type")
public void setType(String groupType) {
this.type = groupType;
}
@CamundaQueryParam("member")
public void setMember(String member) {
this.member = member;
}
@CamundaQueryParam("memberOfTenant")
public void setMemberOfTenant(String tenantId) {
this.tenantId = tenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected GroupQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createGroupQuery();
}
@Override
protected void applyFilters(GroupQuery query) {
if (id != null) {
query.groupId(id);
}
if (ids != null) {
query.groupIdIn(ids);
}
if (name != null) {
query.groupName(name);
} | if (nameLike != null) {
query.groupNameLike(nameLike);
}
if (type != null) {
query.groupType(type);
}
if (member != null) {
query.groupMember(member);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(GroupQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) {
query.orderByGroupId();
} else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) {
query.orderByGroupName();
} else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) {
query.orderByGroupType();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class AutoConfiguredHealthEndpointGroup implements HealthEndpointGroup {
private final Predicate<String> members;
private final StatusAggregator statusAggregator;
private final HttpCodeStatusMapper httpCodeStatusMapper;
private final @Nullable Show showComponents;
private final Show showDetails;
private final Collection<String> roles;
private final @Nullable AdditionalHealthEndpointPath additionalPath;
/**
* Create a new {@link AutoConfiguredHealthEndpointGroup} instance.
* @param members a predicate used to test for group membership
* @param statusAggregator the status aggregator to use
* @param httpCodeStatusMapper the HTTP code status mapper to use
* @param showComponents the show components setting
* @param showDetails the show details setting
* @param roles the roles to match
* @param additionalPath the additional path to use for this group
*/
AutoConfiguredHealthEndpointGroup(Predicate<String> members, StatusAggregator statusAggregator,
HttpCodeStatusMapper httpCodeStatusMapper, @Nullable Show showComponents, Show showDetails,
Collection<String> roles, @Nullable AdditionalHealthEndpointPath additionalPath) {
this.members = members;
this.statusAggregator = statusAggregator;
this.httpCodeStatusMapper = httpCodeStatusMapper;
this.showComponents = showComponents;
this.showDetails = showDetails;
this.roles = roles;
this.additionalPath = additionalPath; | }
@Override
public boolean isMember(String name) {
return this.members.test(name);
}
@Override
public boolean showComponents(SecurityContext securityContext) {
Show show = (this.showComponents != null) ? this.showComponents : this.showDetails;
return show.isShown(securityContext, this.roles);
}
@Override
public boolean showDetails(SecurityContext securityContext) {
return this.showDetails.isShown(securityContext, this.roles);
}
@Override
public StatusAggregator getStatusAggregator() {
return this.statusAggregator;
}
@Override
public HttpCodeStatusMapper getHttpCodeStatusMapper() {
return this.httpCodeStatusMapper;
}
@Override
public @Nullable AdditionalHealthEndpointPath getAdditionalPath() {
return this.additionalPath;
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\AutoConfiguredHealthEndpointGroup.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(
CacheProperties cacheProperties,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
@Nullable ClassLoader classLoader) {
return redisCacheConfiguration.getIfAvailable(() -> createConfiguration(cacheProperties, classLoader));
}
private org.springframework.data.redis.cache.RedisCacheConfiguration createConfiguration(
CacheProperties cacheProperties, @Nullable ClassLoader classLoader) {
Redis redisProperties = cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig();
config = config
.serializeValuesWith(SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
if (redisProperties.getTimeToLive() != null) { | config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\RedisCacheConfiguration.java | 2 |
请完成以下Java代码 | private ZonedDateTime computeMaxDeliveryDateFromSchedsOrNull(final List<I_M_ShipmentSchedule> schedules)
{
// Services
final IShipmentScheduleEffectiveBL schedEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class);
if (schedules.isEmpty())
{
// nothing to do
return null;
}
// iterate all scheds and return the maximum
ZonedDateTime maxDeliveryDate = schedEffectiveBL.getDeliveryDate(schedules.get(0));
for (int i = 1; i < schedules.size(); i++)
{
final ZonedDateTime currentDate = schedEffectiveBL.getDeliveryDate(schedules.get(i));
if (currentDate.isAfter(maxDeliveryDate))
{
maxDeliveryDate = currentDate;
}
}
return maxDeliveryDate;
}
private void handleInvoices(final I_C_Printing_Queue queueItem, final I_C_Invoice invoice)
{
queueItem.setBill_BPartner_ID(invoice.getC_BPartner_ID());
queueItem.setBill_User_ID(invoice.getAD_User_ID());
queueItem.setBill_Location_ID(invoice.getC_BPartner_Location_ID());
queueItem.setC_BPartner_ID(invoice.getC_BPartner_ID()); | queueItem.setC_BPartner_Location_ID(invoice.getC_BPartner_Location_ID());
logger.debug(
"Setting columns of C_Printing_Queue {} from C_Invoice {}: [Bill_BPartner_ID={}, Bill_Location_ID={}, C_BPartner_ID={}, C_BPartner_Location_ID={}, Copies={}]",
queueItem, invoice, invoice.getC_BPartner_ID(), invoice.getC_BPartner_Location_ID(), invoice.getC_BPartner_ID(), invoice.getC_BPartner_Location_ID(), queueItem.getCopies());
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
private DocumentPrintingQueueHandler()
{
super();
}
/**
* Allays returns <code>true</code>.
*/
@Override
public boolean isApplyHandler(final I_C_Printing_Queue queue_IGNORED, final I_AD_Archive printout_IGNORED)
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\spi\impl\DocumentPrintingQueueHandler.java | 1 |
请完成以下Java代码 | public class InvoiceLineHUPackingAware implements IHUPackingAware
{
private final I_C_InvoiceLine invoiceLine;
private final PlainHUPackingAware values = new PlainHUPackingAware();
private InvoiceLineHUPackingAware(@NonNull final I_C_InvoiceLine invoiceLine)
{
this.invoiceLine = invoiceLine;
}
public static InvoiceLineHUPackingAware of(@NonNull final org.compiere.model.I_C_InvoiceLine invoiceLine )
{
return new InvoiceLineHUPackingAware(InterfaceWrapperHelper.create(invoiceLine, I_C_InvoiceLine.class));
}
@Override
public int getM_Product_ID()
{
return invoiceLine.getM_Product_ID();
}
@Override
public void setM_Product_ID(final int productId)
{
invoiceLine.setM_Product_ID(productId);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return invoiceLine.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
invoiceLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return invoiceLine.getC_UOM_ID();
}
@Override
public void setC_UOM_ID(final int uomId)
{
invoiceLine.setC_UOM_ID(uomId);
}
@Override
public void setQty(@NonNull final BigDecimal qtyInHUsUOM)
{
invoiceLine.setQtyEntered(qtyInHUsUOM);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyInvoiced = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qtyInHUsUOM);
invoiceLine.setQtyInvoiced(qtyInvoiced);
}
@Override
public BigDecimal getQty()
{
return invoiceLine.getQtyEntered();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
//
// Check the invoice line first
final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID();
if (invoiceLine_PIItemProductId > 0)
{
return invoiceLine_PIItemProductId;
}
//
// Check order line
final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class);
if (orderline == null) | {
//
// C_OrderLine not found (i.e Manual Invoice)
return -1;
}
return orderline.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return invoiceLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
invoiceLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java | 1 |
请完成以下Java代码 | private void updatePurchaseCandidateFromOrderLineBuilder(
@NonNull final PurchaseOrderItem purchaseOrderItem,
@NonNull final OrderLineBuilder orderLineBuilder)
{
purchaseOrderItem.setPurchaseOrderLineId(orderLineBuilder.getCreatedOrderAndLineId());
final DocTypeId docTypeTargetId = orderFactory.getDocTypeTargetId();
if (docTypeTargetId != null && docTypeBL.isRequisition(docTypeTargetId))
{
purchaseOrderItem.markReqCreatedIfNeeded();
}
else
{
purchaseOrderItem.markPurchasedIfNeeded();
}
}
@Nullable
private ADMessageAndParams createMessageAndParamsOrNull(@NonNull final I_C_Order order)
{
boolean deviatingDatePromised = false;
boolean deviatingQuantity = false;
for (final PurchaseOrderItem purchaseOrderItem : purchaseItem2OrderLine.keySet())
{
final ZonedDateTime purchaseDatePromised = purchaseOrderItem.getPurchaseDatePromised();
if (!Objects.equals(purchaseDatePromised, TimeUtil.asZonedDateTime(order.getDatePromised(), orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())))))
{
deviatingDatePromised = true;
}
if (!purchaseOrderItem.purchaseMatchesRequiredQty())
{
deviatingQuantity = true;
}
}
if (deviatingDatePromised && deviatingQuantity)
{
return ADMessageAndParams.builder()
.adMessage(MSG_Different_Quantity_AND_DatePromised)
.params(createCommonMessageParams(order))
.build();
}
else if (deviatingQuantity)
{
return ADMessageAndParams.builder()
.adMessage(MSG_Different_Quantity)
.params(createCommonMessageParams(order))
.build();
} | else if (deviatingDatePromised)
{
return ADMessageAndParams.builder()
.adMessage(MSG_Different_DatePromised)
.params(createCommonMessageParams(order))
.build();
}
else
{
return null;
}
}
private static List<Object> createCommonMessageParams(@NonNull final I_C_Order order)
{
final I_C_BPartner bpartner = Services.get(IOrderBL.class).getBPartner(order);
final String bpValue = bpartner.getValue();
final String bpName = bpartner.getName();
return ImmutableList.of(TableRecordReference.of(order), bpValue, bpName);
}
private Set<UserId> getUserIdsToNotify()
{
final ImmutableSet<Integer> salesOrderIds = purchaseItem2OrderLine.keySet()
.stream()
.map(PurchaseOrderItem::getSalesOrderId)
.filter(Objects::nonNull)
.map(OrderId::getRepoId)
.collect(ImmutableSet.toImmutableSet());
return ordersRepo.retriveOrderCreatedByUserIds(salesOrderIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseOrderFromItemFactory.java | 1 |
请完成以下Java代码 | public boolean isAutoInvoice(@NonNull final JsonOLCandCreateRequest request, @NonNull final BPartnerId bpartnerId)
{
return bPartnerMasterdataProvider.isAutoInvoice(request, bpartnerId);
}
@Nullable
public PaymentRule getPaymentRule(final JsonOLCandCreateRequest request)
{
final JSONPaymentRule jsonPaymentRule = request.getPaymentRule();
if (jsonPaymentRule == null)
{
return null;
}
if (JSONPaymentRule.Paypal.equals(jsonPaymentRule))
{
return PaymentRule.PayPal;
}
if (JSONPaymentRule.OnCredit.equals(jsonPaymentRule))
{
return PaymentRule.OnCredit;
}
if (JSONPaymentRule.DirectDebit.equals(jsonPaymentRule))
{
return PaymentRule.DirectDebit;
}
throw MissingResourceException.builder()
.resourceName("paymentRule")
.resourceIdentifier(jsonPaymentRule.getCode())
.parentResource(request)
.build();
}
public PaymentTermId getPaymentTermId(@NonNull final IdentifierString paymentTerm, @NonNull final Object parent, @NonNull final OrgId orgId)
{
final PaymentTermQueryBuilder queryBuilder = PaymentTermQuery.builder();
queryBuilder.orgId(orgId);
switch (paymentTerm.getType())
{
case EXTERNAL_ID:
queryBuilder.externalId(paymentTerm.asExternalId()); | break;
case VALUE:
queryBuilder.value(paymentTerm.asValue());
break;
default:
throw new InvalidIdentifierException(paymentTerm);
}
final Optional<PaymentTermId> paymentTermId = paymentTermRepo.firstIdOnly(queryBuilder.build());
return paymentTermId.orElseThrow(() -> MissingResourceException.builder()
.resourceName("PaymentTerm")
.resourceIdentifier(paymentTerm.toJson())
.parentResource(parent).build());
}
@Nullable
public BPartnerId getSalesRepBPartnerId(@NonNull final BPartnerId bPartnerId)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId);
return BPartnerId.ofRepoIdOrNull(bPartner.getC_BPartner_SalesRep_ID());
}
@NonNull
public ExternalSystemId getExternalSystemId(@NonNull final ExternalSystemType type)
{
return externalSystemRepository.getIdByType(type);
}
@Nullable
public Incoterms getIncoterms(@NonNull final JsonOLCandCreateRequest request,
@NonNull final OrgId orgId,
@NonNull final BPartnerId bPartnerId)
{
return bPartnerMasterdataProvider.getIncoterms(request, orgId, bPartnerId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\MasterdataProvider.java | 1 |
请完成以下Java代码 | public BigDecimal getPdctAmt() {
return pdctAmt;
}
/**
* Sets the value of the pdctAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPdctAmt(BigDecimal value) {
this.pdctAmt = value;
}
/**
* Gets the value of the taxTp property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxTp() {
return taxTp;
}
/**
* Sets the value of the taxTp property.
*
* @param value | * allowed object is
* {@link String }
*
*/
public void setTaxTp(String value) {
this.taxTp = value;
}
/**
* Gets the value of the addtlPdctInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlPdctInf() {
return addtlPdctInf;
}
/**
* Sets the value of the addtlPdctInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlPdctInf(String value) {
this.addtlPdctInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Product2.java | 1 |
请完成以下Java代码 | public class JsonPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final static String CUSTOM_PREFIX = "custom.";
@Override
@SuppressWarnings("unchecked")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
try {
Resource resource = configurableApplicationContext.getResource("classpath:configprops.json");
Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
Set<Map.Entry> set = readValue.entrySet();
List<MapPropertySource> propertySources = convertEntrySet(set, Optional.empty());
for (PropertySource propertySource : propertySources) {
configurableApplicationContext.getEnvironment()
.getPropertySources()
.addFirst(propertySource);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<MapPropertySource> convertEntrySet(Set<Map.Entry> entrySet, Optional<String> parentKey) {
return entrySet.stream()
.map((Map.Entry e) -> convertToPropertySourceList(e, parentKey))
.flatMap(Collection::stream) | .collect(Collectors.toList());
}
private static List<MapPropertySource> convertToPropertySourceList(Map.Entry e, Optional<String> parentKey) {
String key = parentKey.map(s -> s + ".")
.orElse("") + (String) e.getKey();
Object value = e.getValue();
return covertToPropertySourceList(key, value);
}
@SuppressWarnings("unchecked")
private static List<MapPropertySource> covertToPropertySourceList(String key, Object value) {
if (value instanceof LinkedHashMap) {
LinkedHashMap map = (LinkedHashMap) value;
Set<Map.Entry> entrySet = map.entrySet();
return convertEntrySet(entrySet, Optional.ofNullable(key));
}
String finalKey = CUSTOM_PREFIX + key;
return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value)));
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\java\com\baeldung\properties\json\JsonPropertyContextInitializer.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Item other = (Item) obj;
if (itemId == null) {
if (other.itemId != null)
return false;
} else if (!itemId.equals(other.itemId))
return false;
return true;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(final Integer itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(final String itemName) {
this.itemName = itemName;
} | public String getItemDescription() {
return itemDescription;
}
public Integer getItemPrice() {
return itemPrice;
}
public void setItemPrice(final Integer itemPrice) {
this.itemPrice = itemPrice;
}
public void setItemDescription(final String itemDescription) {
this.itemDescription = itemDescription;
}
} | repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\model\Item.java | 1 |
请完成以下Java代码 | public class RemoveRequestParameterGatewayFilterFactory
extends AbstractGatewayFilterFactory<AbstractGatewayFilterFactory.NameConfig> {
public RemoveRequestParameterGatewayFilterFactory() {
super(NameConfig.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(NAME_KEY);
}
@Override
public GatewayFilter apply(NameConfig config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(request.getQueryParams());
queryParams.remove(config.getName());
try {
MultiValueMap<String, String> encodedQueryParams = ServerWebExchangeUtils
.encodeQueryParams(queryParams);
URI newUri = UriComponentsBuilder.fromUri(request.getURI())
.replaceQueryParams(unmodifiableMultiValueMap(encodedQueryParams)) | .build(true)
.toUri();
ServerHttpRequest updatedRequest = exchange.getRequest().mutate().uri(newUri).build();
return chain.filter(exchange.mutate().request(updatedRequest).build());
}
catch (IllegalArgumentException ex) {
throw new IllegalStateException("Invalid URI query: \"" + queryParams + "\"");
}
}
@Override
public String toString() {
return filterToStringCreator(RemoveRequestParameterGatewayFilterFactory.this)
.append("name", config.getName())
.toString();
}
};
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RemoveRequestParameterGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public final void addAttributeValueListener(final IAttributeValueListener listener)
{
listeners.addAttributeValueListener(listener);
}
@Override
public final void removeAttributeValueListener(final IAttributeValueListener listener)
{
listeners.removeAttributeValueListener(listener);
}
@Override
public I_C_UOM getC_UOM()
{
final int uomId = attribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{
return null;
}
}
private IAttributeValueCallout _attributeValueCallout = null;
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
if (_attributeValueCallout == null)
{
final IAttributeValueGenerator attributeValueGenerator = getAttributeValueGeneratorOrNull();
if (attributeValueGenerator instanceof IAttributeValueCallout)
{
_attributeValueCallout = (IAttributeValueCallout)attributeValueGenerator;
}
else
{ | _attributeValueCallout = NullAttributeValueCallout.instance;
}
}
return _attributeValueCallout;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
final I_M_Attribute attribute = getM_Attribute();
final IAttributeValueGenerator attributeValueGenerator = Services.get(IAttributesBL.class).getAttributeValueGeneratorOrNull(attribute);
return attributeValueGenerator;
}
/**
* @return true if NOT disposed
* @see IAttributeStorage#assertNotDisposed()
*/
protected final boolean assertNotDisposed()
{
return getAttributeStorage().assertNotDisposed();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractAttributeValue.java | 1 |
请完成以下Java代码 | public class HistoricScopeInstanceEvent extends HistoryEvent {
private static final long serialVersionUID = 1L;
protected Long durationInMillis;
protected Date startTime;
protected Date endTime;
// getters / setters ////////////////////////////////////
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
} | public Long getDurationInMillis() {
if(durationInMillis != null) {
return durationInMillis;
} else if(startTime != null && endTime != null) {
return endTime.getTime() - startTime.getTime();
} else {
return null;
}
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public Long getDurationRaw() {
return durationInMillis;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricScopeInstanceEvent.java | 1 |
请完成以下Java代码 | public String toString()
{
return expressionStr;
}
@Override
public int hashCode()
{
return Objects.hash(expressionStr);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final ConstantStringExpression other = (ConstantStringExpression)obj;
return Objects.equals(expressionStr, other.expressionStr);
}
@Override
public String getExpressionString()
{
return expressionStr;
}
@Override
public String getFormatedExpressionString() | {
return expressionStr;
}
@Override
public Set<CtxName> getParameters()
{
return ImmutableSet.of();
}
@Override
public String evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{
return expressionStr;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound)
{
return expressionStr;
}
public String getConstantValue()
{
return expressionStr;
}
@Override
public final IStringExpression resolvePartial(final Evaluatee ctx)
{
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\ConstantStringExpression.java | 1 |
请完成以下Java代码 | public class WordCounter {
static final int WORD = 0;
static final int SEPARATOR = 1;
public static int countWordsUsingRegex(String arg) {
if (arg == null) {
return 0;
}
final String[] words = arg.split("[\\pP\\s&&[^']]+");
return words.length;
}
public static int countWordsUsingTokenizer(String arg) {
if (arg == null) {
return 0;
}
final StringTokenizer stringTokenizer = new StringTokenizer(arg);
return stringTokenizer.countTokens();
}
public static int countWordsManually(String arg) {
if (arg == null) {
return 0;
}
int flag = SEPARATOR;
int count = 0;
int stringLength = arg.length(); | int characterCounter = 0;
while (characterCounter < stringLength) {
if (isAllowedInWord(arg.charAt(characterCounter)) && flag == SEPARATOR) {
flag = WORD;
count++;
} else if (!isAllowedInWord(arg.charAt(characterCounter))) {
flag = SEPARATOR;
}
characterCounter++;
}
return count;
}
private static boolean isAllowedInWord(char charAt) {
return charAt == '\'' || Character.isLetter(charAt);
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\wordcount\WordCounter.java | 1 |
请完成以下Java代码 | private void onParameterChanged_ActionCUToNewTUs()
{
final Optional<I_M_HU_PI_Item_Product> packingItemOptional = newParametersFiller().getDefaultM_HU_PI_Item_Product();
if (packingItemOptional.isPresent())
{
final BigDecimal realCUQty = getSingleSelectedRow().getQtyCU();
p_M_HU_PI_Item_Product = packingItemOptional.get();
p_QtyCUsPerTU = realCUQty.min(packingItemOptional.get().getQty());
}
}
private void moveToWarehouse(final WebuiHUTransformCommandResult result)
{
if (moveToWarehouseId != null && showWarehouse)
{
final ImmutableList<I_M_HU> createdHUs = result.getHuIdsCreated() | .stream()
.map(handlingUnitsDAO::getById)
.collect(ImmutableList.toImmutableList());
huMovementBL.moveHUsToWarehouse(createdHUs, moveToWarehouseId);
}
}
private void setShowWarehouseFlag()
{
this.showWarehouse = newParametersFiller().getShowWarehouseFlag();
if (!this.showWarehouse)
{
this.moveToWarehouseId = null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Transform.java | 1 |
请完成以下Java代码 | public void createUnSortedArray() {
unsortedArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
unsortedArray[i] = new Random().nextInt(1000);
}
}
@Setup(Level.Invocation)
public void createUnSortedArrayCopy() {
arrayToSort = unsortedArray.clone();
}
int[] getArrayToSort() {
return arrayToSort;
}
} | @Benchmark
public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) {
int[] arr = d.getArrayToSort();
Arrays.parallelSort(arr);
b.consume(arr);
}
@Benchmark
public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) {
int[] arr = d.getArrayToSort();
Arrays.sort(arr);
b.consume(arr);
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-sorting\src\main\java\com\baeldung\arraysort\ArraySortingBenchmark.java | 1 |
请完成以下Java代码 | public CallConversation newInstance(ModelTypeInstanceContext instanceContext) {
return new CallConversationImpl(instanceContext);
}
});
calledCollaborationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_CALLED_COLLABORATION_REF)
.qNameAttributeReference(GlobalConversation.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
participantAssociationCollection = sequenceBuilder.elementCollection(ParticipantAssociation.class)
.build();
typeBuilder.build();
} | public CallConversationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public GlobalConversation getCalledCollaboration() {
return calledCollaborationRefAttribute.getReferenceTargetElement(this);
}
public void setCalledCollaboration(GlobalConversation calledCollaboration) {
calledCollaborationRefAttribute.setReferenceTargetElement(this, calledCollaboration);
}
public Collection<ParticipantAssociation> getParticipantAssociations() {
return participantAssociationCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallConversationImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
final List<ServiceRepairProjectTask> tasks = getSelectedTasks(context)
.stream()
.filter(this::isEligible)
.collect(ImmutableList.toImmutableList());
if (tasks.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no eligible tasks found");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final List<ServiceRepairProjectTask> tasks = getSelectedTasks()
.stream()
.filter(this::isEligible)
.collect(ImmutableList.toImmutableList());
if (tasks.isEmpty()) | {
throw new AdempiereException("@NoSelection@");
}
projectService.createRepairOrders(tasks);
return MSG_OK;
}
private boolean isEligible(@NonNull final ServiceRepairProjectTask task)
{
return ServiceRepairProjectTaskType.REPAIR_ORDER.equals(task.getType())
&& ServiceRepairProjectTaskStatus.NOT_STARTED.equals(task.getStatus())
&& task.getRepairOrderId() == null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\C_Project_StartRepairOrder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ShipmentSchedulesSupplier
{
private final IShipmentScheduleBL shipmentScheduleBL;
private final HashMap<ShipmentScheduleId, I_M_ShipmentSchedule> shipmentSchedulesById = new HashMap<>();
private final HashMap<ShipmentScheduleId, Quantity> projectedQtyToDeliverById = new HashMap<>();
@Builder
private ShipmentSchedulesSupplier(@NonNull final IShipmentScheduleBL shipmentScheduleBL)
{
this.shipmentScheduleBL = shipmentScheduleBL;
}
public I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return shipmentSchedulesById.computeIfAbsent(shipmentScheduleId, shipmentScheduleBL::getById);
}
public Quantity getProjectedQtyToDeliver(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return projectedQtyToDeliverById.computeIfAbsent(shipmentScheduleId, this::retrieveQtyToDeliver);
} | private Quantity retrieveQtyToDeliver(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule sched = getShipmentScheduleById(shipmentScheduleId);
return shipmentScheduleBL.getQtyToDeliver(sched);
}
public void addQtyDelivered(@NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull final Quantity qtyDelivered)
{
Quantity projectedQtyToDeliver = getProjectedQtyToDeliver(shipmentScheduleId)
.subtract(qtyDelivered);
projectedQtyToDeliverById.put(shipmentScheduleId, projectedQtyToDeliver);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\impl\ShipmentSchedulesSupplier.java | 2 |
请完成以下Java代码 | public static SwingEventNotifierService getInstance()
{
return instance;
}
private SwingEventNotifierService()
{
super();
try
{
JMXRegistry.get().registerJMX(new JMXSwingEventNotifierService(), OnJMXAlreadyExistsPolicy.Replace);
}
catch (Exception e)
{
logger.warn("Failed registering JMX bean", e);
}
}
public final synchronized boolean isRunning()
{
return frame != null && !frame.isDisposed();
}
/**
* Start listening to subscribed topics and display the events.
*
* If this was already started, this method does nothing.
*/
public synchronized void start()
{
if (!EventBusConfig.isEnabled())
{
logger.info("Not starting because it's not enabled");
return;
}
try
{
if (frame != null && frame.isDisposed())
{
frame = null;
}
if (frame == null)
{
frame = new SwingEventNotifierFrame();
}
}
catch (Exception e)
{
logger.warn("Failed starting the notification frame: " + frame, e);
}
}
/** | * Stop listening events and destroy the whole popup.
*
* If this was already started, this method does nothing.
*/
public synchronized void stop()
{
if (frame == null)
{
return;
}
try
{
frame.dispose();
}
catch (Exception e)
{
logger.warn("Failed disposing the notification frame: " + frame, e);
}
}
public synchronized Set<String> getSubscribedTopicNames()
{
if (frame != null && !frame.isDisposed())
{
return frame.getSubscribedTopicNames();
}
else
{
return ImmutableSet.of();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierService.java | 1 |
请完成以下Java代码 | public class Main_Validator implements ModelValidator
{
private int m_AD_Client_ID = -1;
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public void initialize(final ModelValidationEngine engine, final MClient client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
Check.assume(Services.isAutodetectServices(), "Service auto detection is enabled");
if (!Ini.isSwingClient())
{
// make sure that the handlers defined in this module are registered
Services.get(IReplRequestHandlerBL.class).registerHandlerType("LoadPO", LoadPORequestHandler.class, RequestHandler_Constants.ENTITY_TYPE);
}
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) | {
return null; // nothing to do
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
return null; // nothing to do
}
@Override
public String docValidate(PO po, int timing)
{
return null; // nothing to do
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\requesthandler\model\validator\Main_Validator.java | 1 |
请完成以下Java代码 | public class HistoricVariableInstanceQueryProperty implements QueryProperty {
private static final long serialVersionUID = 1L;
private static final Map<String, HistoricVariableInstanceQueryProperty> properties = new HashMap<
String,
HistoricVariableInstanceQueryProperty
>();
public static final HistoricVariableInstanceQueryProperty PROCESS_INSTANCE_ID =
new HistoricVariableInstanceQueryProperty("PROC_INST_ID_");
public static final HistoricVariableInstanceQueryProperty VARIABLE_NAME = new HistoricVariableInstanceQueryProperty(
"NAME_"
); | private String name;
public HistoricVariableInstanceQueryProperty(String name) {
this.name = name;
properties.put(name, this);
}
public String getName() {
return name;
}
public static HistoricVariableInstanceQueryProperty findByName(String propertyName) {
return properties.get(propertyName);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricVariableInstanceQueryProperty.java | 1 |
请完成以下Java代码 | public void onBeforeInvoiceLineCreated(final I_C_InvoiceLine invoiceLine, final IInvoiceLineRW fromInvoiceLine, final List<I_C_Invoice_Candidate> fromCandidates)
{
//
// Get material tracking of those invoice candidates
final I_M_Material_Tracking materialTracking = retrieveMaterialTracking(fromCandidates);
if (materialTracking == null)
{
return;
}
//
// Assign the invoice to material tracking
final I_C_Invoice invoice = invoiceLine.getC_Invoice();
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
materialTrackingBL.linkModelToMaterialTracking(
MTLinkRequest.builder()
.model(invoice)
.materialTrackingRecord(materialTracking)
.ifModelAlreadyLinked(IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS)
.build()
);
}
private I_M_Material_Tracking retrieveMaterialTracking(final List<I_C_Invoice_Candidate> invoiceCandidates)
{
// no candidates => nothing to do (shall not happen)
if (invoiceCandidates == null || invoiceCandidates.isEmpty()) | {
return null;
}
final I_M_Material_Tracking materialTracking = InterfaceWrapperHelper.create(invoiceCandidates.get(0), de.metas.materialtracking.model.I_C_Invoice_Candidate.class).getM_Material_Tracking();
for (final I_C_Invoice_Candidate fromInvoiceCandidate : invoiceCandidates)
{
final de.metas.materialtracking.model.I_C_Invoice_Candidate invoicecandExt = InterfaceWrapperHelper.create(fromInvoiceCandidate,
de.metas.materialtracking.model.I_C_Invoice_Candidate.class);
final int materialTrackingID = materialTracking == null ? 0 : materialTracking.getM_Material_Tracking_ID();
Check.assume(materialTrackingID == invoicecandExt.getM_Material_Tracking_ID(),
"All I_C_InvoiceCandidates from the list have the same M_Material_Tracking_ID: {}", invoiceCandidates);
}
return materialTracking;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\MaterialTrackingInvoiceCandidateListener.java | 1 |
请完成以下Java代码 | public void setC_Async_Batch_ID (int C_Async_Batch_ID)
{
if (C_Async_Batch_ID < 1)
set_Value (COLUMNNAME_C_Async_Batch_ID, null);
else
set_Value (COLUMNNAME_C_Async_Batch_ID, Integer.valueOf(C_Async_Batch_ID));
}
/** Get Async Batch.
@return Async Batch */
@Override
public int getC_Async_Batch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Async_Batch_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.async.model.I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class);
}
@Override
public void setC_Queue_WorkPackage(de.metas.async.model.I_C_Queue_WorkPackage C_Queue_WorkPackage)
{
set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, C_Queue_WorkPackage);
}
/** Set WorkPackage Queue.
@param C_Queue_WorkPackage_ID WorkPackage Queue */
@Override
public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID)
{
if (C_Queue_WorkPackage_ID < 1)
set_Value (COLUMNNAME_C_Queue_WorkPackage_ID, null);
else
set_Value (COLUMNNAME_C_Queue_WorkPackage_ID, Integer.valueOf(C_Queue_WorkPackage_ID));
}
/** Get WorkPackage Queue.
@return WorkPackage Queue */
@Override
public int getC_Queue_WorkPackage_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set WorkPackage Notified. | @param C_Queue_WorkPackage_Notified_ID WorkPackage Notified */
@Override
public void setC_Queue_WorkPackage_Notified_ID (int C_Queue_WorkPackage_Notified_ID)
{
if (C_Queue_WorkPackage_Notified_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Notified_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Notified_ID, Integer.valueOf(C_Queue_WorkPackage_Notified_ID));
}
/** Get WorkPackage Notified.
@return WorkPackage Notified */
@Override
public int getC_Queue_WorkPackage_Notified_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Notified_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Notified.
@param IsNotified Notified */
@Override
public void setIsNotified (boolean IsNotified)
{
set_Value (COLUMNNAME_IsNotified, Boolean.valueOf(IsNotified));
}
/** Get Notified.
@return Notified */
@Override
public boolean isNotified ()
{
Object oo = get_Value(COLUMNNAME_IsNotified);
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.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Notified.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PrivateKey getPrivateKey() {
return this.privateKey;
}
/**
* Get the public certificate for this credential
* @return the public certificate
*/
public X509Certificate getCertificate() {
return this.certificate;
}
/**
* Indicate whether this credential can be used for signing
* @return true if the credential has a {@link Saml2X509CredentialType#SIGNING} type
*/
public boolean isSigningCredential() {
return getCredentialTypes().contains(Saml2X509CredentialType.SIGNING);
}
/**
* Indicate whether this credential can be used for decryption
* @return true if the credential has a {@link Saml2X509CredentialType#DECRYPTION}
* type
*/
public boolean isDecryptionCredential() {
return getCredentialTypes().contains(Saml2X509CredentialType.DECRYPTION);
}
/**
* Indicate whether this credential can be used for verification
* @return true if the credential has a {@link Saml2X509CredentialType#VERIFICATION}
* type
*/
public boolean isVerificationCredential() {
return getCredentialTypes().contains(Saml2X509CredentialType.VERIFICATION);
}
/**
* Indicate whether this credential can be used for encryption
* @return true if the credential has a {@link Saml2X509CredentialType#ENCRYPTION}
* type
*/
public boolean isEncryptionCredential() {
return getCredentialTypes().contains(Saml2X509CredentialType.ENCRYPTION);
}
/**
* List all this credential's intended usages
* @return the set of this credential's intended usages
*/
public Set<Saml2X509CredentialType> getCredentialTypes() {
return this.credentialTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Saml2X509Credential that = (Saml2X509Credential) o;
return Objects.equals(this.privateKey, that.privateKey) && this.certificate.equals(that.certificate)
&& this.credentialTypes.equals(that.credentialTypes);
} | @Override
public int hashCode() {
return Objects.hash(this.privateKey, this.certificate, this.credentialTypes);
}
private void validateUsages(Saml2X509CredentialType[] usages, Saml2X509CredentialType... validUsages) {
for (Saml2X509CredentialType usage : usages) {
boolean valid = false;
for (Saml2X509CredentialType validUsage : validUsages) {
if (usage == validUsage) {
valid = true;
break;
}
}
Assert.state(valid, () -> usage + " is not a valid usage for this credential");
}
}
public enum Saml2X509CredentialType {
VERIFICATION,
ENCRYPTION,
SIGNING,
DECRYPTION,
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2X509Credential.java | 2 |
请完成以下Java代码 | public class LWJGLApp {
private long window;
public static void main(String[] args) {
new LWJGLApp().run();
}
public void run() {
this.initializeGLFW();
this.createAndCenterWindow();
this.setupAndInitializeOpenGLContext();
this.renderTriangle();
}
private void initializeGLFW() {
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialize GLFW");
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
}
private void createAndCenterWindow() {
window = glfwCreateWindow(500, 500, "LWJGL Triangle", 0, 0);
if (window == 0) {
throw new RuntimeException("Failed to create the GLFW window");
}
GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(
window,
(videoMode.width() - 500) / 2,
(videoMode.height() - 500) / 2
);
}
private void setupAndInitializeOpenGLContext() {
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
GL.createCapabilities();
}
private void renderTriangle() {
float[] vertices = {
0.0f, 0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f
}; | FloatBuffer vertexBuffer = memAllocFloat(vertices.length);
vertexBuffer.put(vertices).flip();
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 1.0f, 0.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableClientState(GL_VERTEX_ARRAY);
glfwSwapBuffers(window);
}
memFree(vertexBuffer);
glfwDestroyWindow(window);
glfwTerminate();
}
} | repos\tutorials-master\lwjgl\src\main\java\com\baeldung\lwjgl\LWJGLApp.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SecurityFilterChain filterChain(HttpSecurity http,
AuthorizeTokenFilter authorizeTokenFilter,
@Nullable SsoLogoutSuccessHandler ssoLogoutSuccessHandler) throws Exception {
logger.info("Enabling Camunda Spring Security oauth2 integration");
// @formatter:off
http.authorizeHttpRequests(c -> c
.requestMatchers(webappPath + "/app/**").authenticated()
.requestMatchers(webappPath + "/api/**").authenticated()
.anyRequest().permitAll()
)
.addFilterAfter(authorizeTokenFilter, OAuth2AuthorizationRequestRedirectFilter.class)
.anonymous(AbstractHttpConfigurer::disable)
.oidcLogout(c -> c.backChannel(Customizer.withDefaults()))
.oauth2Login(Customizer.withDefaults())
.logout(c -> c | .clearAuthentication(true)
.invalidateHttpSession(true)
)
.oauth2Client(Customizer.withDefaults())
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable);
// @formatter:on
if (oAuth2Properties.getSsoLogout().isEnabled()) {
http.logout(c -> c.logoutSuccessHandler(ssoLogoutSuccessHandler));
}
return http.build();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\CamundaSpringSecurityOAuth2AutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TextExtractor {
private final TextractClient textractClient;
public TextExtractor(TextractClient textractClient) {
this.textractClient = textractClient;
}
public String extract(@ValidFileType MultipartFile image) throws IOException {
byte[] imageBytes = image.getBytes();
DetectDocumentTextResponse response = textractClient.detectDocumentText(request -> request
.document(document -> document
.bytes(SdkBytes.fromByteArray(imageBytes))
.build())
.build());
return transformTextDetectionResponse(response);
}
public String extract(String bucketName, String objectKey) {
DetectDocumentTextResponse response = textractClient.detectDocumentText(request -> request
.document(document -> document | .s3Object(s3Object -> s3Object
.bucket(bucketName)
.name(objectKey)
.build())
.build())
.build());
return transformTextDetectionResponse(response);
}
private String transformTextDetectionResponse(DetectDocumentTextResponse response) {
return response.blocks()
.stream()
.filter(block -> block.blockType().equals(BlockType.LINE))
.map(Block::text)
.collect(Collectors.joining(" "));
}
} | repos\tutorials-master\aws-modules\amazon-textract\src\main\java\com\baeldung\textract\service\TextExtractor.java | 2 |
请完成以下Java代码 | ConcurrentKafkaListenerContainerFactory<?, ?> addIfAbsent(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation,
Configuration config,
ConcurrentKafkaListenerContainerFactory<?, ?> resolvedFactory) {
synchronized (this.cacheMap) {
Key key = cacheKey(factoryFromKafkaListenerAnnotation, config);
this.cacheMap.putIfAbsent(key, resolvedFactory);
return resolvedFactory;
}
}
@Nullable
ConcurrentKafkaListenerContainerFactory<?, ?> fromCache(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation,
Configuration config) {
synchronized (this.cacheMap) {
return this.cacheMap.get(cacheKey(factoryFromKafkaListenerAnnotation, config));
}
}
private Key cacheKey(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation, Configuration config) {
return new Key(factoryFromKafkaListenerAnnotation, config);
}
static class Key {
private final @Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation;
private final Configuration config;
Key(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation, Configuration config) {
this.factoryFromKafkaListenerAnnotation = factoryFromKafkaListenerAnnotation;
this.config = config;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Key key = (Key) o;
return Objects.equals(this.factoryFromKafkaListenerAnnotation, key.factoryFromKafkaListenerAnnotation)
&& Objects.equals(this.config, key.config);
}
@Override
public int hashCode() {
return Objects.hash(this.factoryFromKafkaListenerAnnotation, this.config);
}
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\ListenerContainerFactoryResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | IntegrationActivityBehavior flowableDelegate(FlowableInboundGateway flowableInboundGateway) {
return new IntegrationActivityBehavior(flowableInboundGateway, null, null);
}
@Bean
FlowableInboundGateway inboundGateway(ProcessEngine processEngine) {
return new FlowableInboundGateway(processEngine, "customerId", "projectId", "orderId");
}
@Bean
AnalysingService analysingService() {
return new AnalysingService();
}
public static class AnalysingService {
private final AtomicReference<String> stringAtomicReference = new AtomicReference<>();
public void dump(String projectId) {
this.stringAtomicReference.set(projectId);
}
public AtomicReference<String> getStringAtomicReference() {
return stringAtomicReference;
}
}
@Bean
IntegrationFlow inboundProcess(FlowableInboundGateway inboundGateway) {
return IntegrationFlow
.from(inboundGateway)
.handle(new GenericHandler<DelegateExecution>() {
@Override
public Object handle(DelegateExecution execution, MessageHeaders headers) { | return MessageBuilder.withPayload(execution)
.setHeader("projectId", "2143243")
.setHeader("orderId", "246")
.copyHeaders(headers).build();
}
})
.get();
}
@Bean
CommandLineRunner init(
final AnalysingService analysingService,
final RuntimeService runtimeService) {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
String integrationGatewayProcess = "integrationGatewayProcess";
runtimeService.startProcessInstanceByKey(
integrationGatewayProcess, Collections.singletonMap("customerId", (Object) 232L));
System.out.println("projectId=" + analysingService.getStringAtomicReference().get());
}
};
} // ...
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-integration\src\main\java\flowable\Application.java | 2 |
请完成以下Java代码 | private final ImageIcon getIcon(String name)
{
final String fullName = name + (drawSmallButtons ? "16" : "24");
return Images.getImageIcon2(fullName);
}
/**
* @return true if the panel is visible and it has at least one field in simple search mode
*/
@Override
public boolean isFocusable()
{
if (!isVisible())
{
return false;
}
if (isSimpleSearchPanelActive())
{
return m_editorFirst != null;
}
return false;
}
@Override
public void setFocusable(final boolean focusable)
{
// ignore it
}
@Override
public void requestFocus()
{
if (isSimpleSearchPanelActive())
{
if (m_editorFirst != null)
{
m_editorFirst.requestFocus();
} | }
}
@Override
public boolean requestFocusInWindow()
{
if (isSimpleSearchPanelActive())
{
if (m_editorFirst != null)
{
return m_editorFirst.requestFocusInWindow();
}
}
return false;
}
private boolean disposed = false;
boolean isDisposed()
{
return disposed;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanel.java | 1 |
请完成以下Java代码 | public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
} | public Date getLastAccess() {
return lastAccess;
}
public void setLastAccess(Date lastAccess) {
this.lastAccess = lastAccess;
}
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
} | repos\tutorials-master\jackson-modules\jackson-custom-conversions\src\main\java\com\baeldung\defaultserializercustomserializer\Folder.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskQueryVariableValue other = ((TaskQueryVariableValueComparable) o).getVariableValue();
return variableValue.getName().equals(other.getName())
&& variableValue.isProcessInstanceVariable() == other.isProcessInstanceVariable()
&& variableValue.isLocal() == other.isLocal();
}
@Override
public int hashCode() {
int result = variableValue.getName() != null ? variableValue.getName().hashCode() : 0;
result = 31 * result + (variableValue.isProcessInstanceVariable() ? 1 : 0);
result = 31 * result + (variableValue.isLocal() ? 1 : 0);
return result;
}
}
public boolean isFollowUpNullAccepted() {
return followUpNullAccepted;
}
@Override
public TaskQuery taskNameNotEqual(String name) {
this.nameNotEqual = name;
return this;
}
@Override
public TaskQuery taskNameNotLike(String nameNotLike) {
ensureNotNull("Task nameNotLike", nameNotLike);
this.nameNotLike = nameNotLike;
return this;
}
/**
* @return true if the query is not supposed to find CMMN or standalone tasks
*/
public boolean isQueryForProcessTasksOnly() {
ProcessEngineConfigurationImpl engineConfiguration = Context.getProcessEngineConfiguration(); | return !engineConfiguration.isCmmnEnabled() && !engineConfiguration.isStandaloneTasksEnabled();
}
@Override
public TaskQuery or() {
if (this != queries.get(0)) {
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query");
}
TaskQueryImpl orQuery = new TaskQueryImpl();
orQuery.isOrQueryActive = true;
orQuery.queries = queries;
queries.add(orQuery);
return orQuery;
}
@Override
public TaskQuery endOr() {
if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()");
}
return queries.get(0);
}
@Override
public TaskQuery matchVariableNamesIgnoreCase() {
this.variableNamesIgnoreCase = true;
for (TaskQueryVariableValue variable : this.variables) {
variable.setVariableNameIgnoreCase(true);
}
return this;
}
@Override
public TaskQuery matchVariableValuesIgnoreCase() {
this.variableValuesIgnoreCase = true;
for (TaskQueryVariableValue variable : this.variables) {
variable.setVariableValueIgnoreCase(true);
}
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskQueryImpl.java | 1 |
请完成以下Java代码 | public TaxAmount1 getTaxAmt() {
return taxAmt;
}
/**
* Sets the value of the taxAmt property.
*
* @param value
* allowed object is
* {@link TaxAmount1 }
*
*/
public void setTaxAmt(TaxAmount1 value) {
this.taxAmt = value;
}
/**
* Gets the value of the addtlInf property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getAddtlInf() {
return addtlInf;
}
/**
* Sets the value of the addtlInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlInf(String value) {
this.addtlInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxRecord1.java | 1 |
请完成以下Java代码 | public class MapBusinessCalendarManager implements BusinessCalendarManager {
private final Map<String, BusinessCalendar> businessCalendars;
public MapBusinessCalendarManager() {
this.businessCalendars = new HashMap<String, BusinessCalendar>();
}
public MapBusinessCalendarManager(Map<String, BusinessCalendar> businessCalendars) {
if (businessCalendars == null) {
throw new IllegalArgumentException("businessCalendars can not be null");
}
this.businessCalendars = new HashMap<String, BusinessCalendar>(businessCalendars);
}
public BusinessCalendar getBusinessCalendar(String businessCalendarRef) {
BusinessCalendar businessCalendar = businessCalendars.get(businessCalendarRef);
if (businessCalendar == null) {
throw new ActivitiException( | "Requested business calendar " +
businessCalendarRef +
" does not exist. Allowed calendars are " +
this.businessCalendars.keySet() +
"."
);
}
return businessCalendar;
}
public BusinessCalendarManager addBusinessCalendar(String businessCalendarRef, BusinessCalendar businessCalendar) {
businessCalendars.put(businessCalendarRef, businessCalendar);
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\MapBusinessCalendarManager.java | 1 |
请完成以下Java代码 | private ImmutableList<XmlDocument> createXmlDocuments(@Nullable final DocumentsType documents)
{
if (documents == null)
{
return ImmutableList.of();
}
final ImmutableList.Builder<XmlDocument> xDocuments = ImmutableList.builder();
for (final DocumentType document : documents.getDocument())
{
xDocuments.add(createXmlDocument(document));
}
return xDocuments.build();
} | private XmlDocument createXmlDocument(@NonNull final DocumentType documentType)
{
final XmlDocumentBuilder xDocument = XmlDocument.builder();
xDocument.filename(documentType.getFilename());
xDocument.mimeType(documentType.getMimeType());
xDocument.viewer(documentType.getViewer());
xDocument.base64(documentType.getBase64());
xDocument.url(documentType.getUrl());
return xDocument.build();
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\Invoice440ToCrossVersionModelTool.java | 1 |
请完成以下Java代码 | public class AuthFilter implements GlobalFilter, Ordered {
private final AuthProperties authProperties;
private final ObjectMapper objectMapper;
private final BladeProperties bladeProperties;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
if (isSkip(path)) {
return chain.filter(exchange);
}
ServerHttpResponse resp = exchange.getResponse();
String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
if (StringUtils.isBlank(headerToken) && StringUtils.isBlank(paramToken)) {
return unAuth(resp, "缺失令牌,鉴权失败");
}
String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
String token = JwtUtil.getToken(auth);
//校验 加密Token 合法性
if (JwtUtil.isCrypto(auth)) {
token = JwtCrypto.decryptToString(token, bladeProperties.getEnvironment().getProperty(BLADE_CRYPTO_AES_KEY));
}
Claims claims = JwtUtil.parseJWT(token);
if (claims == null) {
return unAuth(resp, "请求未授权");
}
return chain.filter(exchange);
}
private boolean isSkip(String path) {
return AuthProvider.getDefaultSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path))
|| authProperties.getSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
}
private Mono<Void> unAuth(ServerHttpResponse resp, String msg) { | resp.setStatusCode(HttpStatus.UNAUTHORIZED);
resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
String result = "";
try {
result = objectMapper.writeValueAsString(ResponseProvider.unAuth(msg));
} catch (JsonProcessingException e) {
log.error(e.getMessage(), e);
}
DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
return resp.writeWith(Flux.just(buffer));
}
@Override
public int getOrder() {
return -100;
}
} | repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\filter\AuthFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LangChainConfiguration {
@Value("${langchain.api.key}")
private String apiKey;
@Value("${langchain.timeout}")
private Long timeout;
private final List<Document> documents;
@Bean
public ConversationalRetrievalChain chain() {
EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel();
EmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder()
.documentSplitter(DocumentSplitters.recursive(500, 0))
.embeddingModel(embeddingModel)
.embeddingStore(embeddingStore)
.build();
log.info("Ingesting Spring Boot Resources ...");
ingestor.ingest(documents);
log.info("Ingested {} documents", documents.size());
EmbeddingStoreRetriever retriever = EmbeddingStoreRetriever.from(embeddingStore, embeddingModel);
EmbeddingStoreLoggingRetriever loggingRetriever = new EmbeddingStoreLoggingRetriever(retriever);
/*MessageWindowChatMemory chatMemory = MessageWindowChatMemory.builder()
.maxMessages(10) | .build();*/
log.info("Building ConversationalRetrievalChain ...");
ConversationalRetrievalChain chain = ConversationalRetrievalChain.builder()
.chatLanguageModel(OpenAiChatModel.builder()
.apiKey(apiKey)
.timeout(Duration.ofSeconds(timeout))
.build()
)
.promptTemplate(PromptTemplate.from(PROMPT_TEMPLATE_2))
//.chatMemory(chatMemory)
.retriever(loggingRetriever)
.build();
log.info("Spring Boot knowledge base is ready!");
return chain;
}
} | repos\springboot-demo-master\rag\src\main\java\com\et\rag\configuration\LangChainConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setPrice (final BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
@Override
public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProductName (final java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override | public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode)
{
set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode);
}
@Override
public java.lang.String getScannedBarcode()
{
return get_ValueAsString(COLUMNNAME_ScannedBarcode);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java | 2 |
请完成以下Java代码 | public class LogDTO implements Serializable {
private static final long serialVersionUID = 8482720462943906924L;
/**内容*/
private String logContent;
/**日志类型(0:操作日志;1:登录日志;2:定时任务) */
private Integer logType;
/**操作类型(1:添加;2:修改;3:删除;) */
private Integer operateType;
/**登录用户 */
private LoginUser loginUser;
private String id;
private String createBy;
private Date createTime;
private Long costTime;
private String ip;
/**请求参数 */
private String requestParam;
/**请求类型*/
private String requestType;
/**请求路径*/
private String requestUrl;
/**请求方法 */
private String method;
/**操作人用户名称*/
private String username;
/**操作人用户账户*/ | private String userid;
/**
* 租户ID
*/
private Integer tenantId;
/**
* 客户终端类型 pc:电脑端 app:手机端 h5:移动网页端
*/
private String clientType;
public LogDTO(){
}
public LogDTO(String logContent, Integer logType, Integer operatetype){
this.logContent = logContent;
this.logType = logType;
this.operateType = operatetype;
}
public LogDTO(String logContent, Integer logType, Integer operatetype, LoginUser loginUser){
this.logContent = logContent;
this.logType = logType;
this.operateType = operatetype;
this.loginUser = loginUser;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\dto\LogDTO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
return obj;
}
private void cleanPdfCache() throws IOException, RocksDBException {
Map<String, String> initPDFCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
} | private void cleanImgCache() throws IOException, RocksDBException {
Map<String, List<String>> initIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
}
private void cleanPdfImgCache() throws IOException, RocksDBException {
Map<String, Integer> initPDFIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
}
private void cleanMediaConvertCache() throws IOException, RocksDBException {
Map<String, String> initMediaConvertCache = new HashMap<>();
db.put(FILE_PREVIEW_MEDIA_CONVERT_KEY.getBytes(), toByteArray(initMediaConvertCache));
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRocksDBImpl.java | 2 |
请完成以下Java代码 | public class ForkFactorialTask extends RecursiveTask<BigInteger> {
private final int start;
private final int end;
private final int threshold;
public ForkFactorialTask(int end, int threshold) {
this.start = 1;
this.end = end;
this.threshold = threshold;
}
public ForkFactorialTask(int start, int end, int threshold) {
this.start = start;
this.end = end;
this.threshold = threshold;
} | @Override
protected BigInteger compute() {
BigInteger sum = BigInteger.ONE;
if (end - start > threshold) {
int middle = (end + start) / 2;
return sum.multiply(new ForkFactorialTask(start, middle, threshold).fork()
.join()
.multiply(new ForkFactorialTask(middle + 1, end, threshold).fork()
.join()));
}
return sum.multiply(factorial(BigInteger.valueOf(start), BigInteger.valueOf(end)));
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-basic-3\src\main\java\com\baeldung\concurrent\threadreturnvalue\task\fork\ForkFactorialTask.java | 1 |
请完成以下Java代码 | public void duplicateProducerClientID() throws Exception {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to create another producer using same client.id
KafkaProducer<String, String> producer2 = new KafkaProducer<>(props);
}
public static void unclosedProducerAndReinitialize() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to reinitialize without proper close
producer1 = new KafkaProducer<>(props);
}
}
class MyMBean implements DynamicMBean {
@Override
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
return null;
}
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { | }
@Override
public AttributeList getAttributes(String[] attributes) {
return null;
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
return null;
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0];
MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
MBeanOperationInfo[] operations = new MBeanOperationInfo[0];
MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0];
return new MBeanInfo(MyMBean.class.getName(), "My MBean", attributes, constructors, operations, notifications);
}
} | repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\kafkaexception\SimulateInstanceAlreadyExistsException.java | 1 |
请完成以下Java代码 | private MultiPolygon readMultiPolygonText() throws IOException, ParseException {
String nextToken = getNextEmptyOrOpener();
if (EMPTY.equals(nextToken)) {
return new MultiPolygon(null, geometryFactory);
}
List<Polygon> polygons = new ArrayList<>();
Polygon polygon = readPolygonText();
polygons.add(polygon);
nextToken = getNextCloserOrComma();
while (COMMA.equals(nextToken)) {
polygon = readPolygonText();
polygons.add(polygon);
nextToken = getNextCloserOrComma();
}
Polygon[] array = new Polygon[polygons.size()];
return geometryFactory.createMultiPolygon(polygons.toArray(array));
}
/**
* Creates a <code>GeometryCollection</code> using the next token in the
* stream.
* <p>
* tokenizer tokenizer over a stream of text in Well-known Text format. The
* next tokens must form a <GeometryCollection Text>.
*
* @return a <code>GeometryCollection</code> specified by the next token in
* the stream
* @throws ParseException if the coordinates used to create a <code>Polygon</code> | * shell and holes do not form closed linestrings, or if an
* unexpected token was encountered
* @throws IOException if an I/O error occurs
*/
private GeometryCollection readGeometryCollectionText() throws IOException, ParseException {
String nextToken = getNextEmptyOrOpener();
if (EMPTY.equals(nextToken)) {
return geometryFactory.createGeometryCollection(new Geometry[]{});
}
List<Geometry> geometries = new ArrayList<>();
Geometry geometry = readGeometryTaggedText();
geometries.add(geometry);
nextToken = getNextCloserOrComma();
while (COMMA.equals(nextToken)) {
geometry = readGeometryTaggedText();
geometries.add(geometry);
nextToken = getNextCloserOrComma();
}
Geometry[] array = new Geometry[geometries.size()];
return geometryFactory.createGeometryCollection(geometries.toArray(array));
}
} | repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\IO\StringTokenReader.java | 1 |
请完成以下Java代码 | public class VariableElResolver implements VariableScopeItemELResolver {
private final ObjectMapper objectMapper;
public VariableElResolver(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean canResolve(String property, VariableScope variableScope) {
return variableScope.hasVariable(property);
}
@Override
public Object resolve(String property, VariableScope variableScope) {
VariableInstance variableInstance = variableScope.getVariableInstance(property); | Object value = variableInstance.getValue();
if (hasJsonType(variableInstance) && (value instanceof JsonNode) && ((JsonNode) value).isArray()) {
return objectMapper.convertValue(value, List.class);
} else {
return value;
}
}
private boolean hasJsonType(VariableInstance variableInstance) {
return (
JsonType.JSON.equals(variableInstance.getTypeName()) ||
LongJsonType.LONG_JSON.equals(variableInstance.getTypeName())
);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\variable\VariableElResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<Long> apiDeleteRule(@PathVariable("id") Long id) {
if (id == null) {
return Result.ofFail(-1, "id cannot be null");
}
ParamFlowRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
publishRules(oldEntity.getApp());
return Result.ofSuccess(id);
} catch (ExecutionException ex) {
logger.error("Error when deleting parameter flow rules", ex.getCause());
if (isNotSupported(ex.getCause())) {
return unsupportedVersion();
} else {
return Result.ofThrowable(-1, ex.getCause());
} | } catch (Throwable throwable) {
logger.error("Error when deleting parameter flow rules", throwable);
return Result.ofFail(-1, throwable.getMessage());
}
}
private void publishRules(String app) throws Exception {
List<ParamFlowRuleEntity> rules = repository.findAllByApp(app);
rulePublisher.publish(app, rules);
//延迟加载
delayTime();
}
private <R> Result<R> unsupportedVersion() {
return Result.ofFail(4041,
"Sentinel client not supported for parameter flow control (unsupported version or dependency absent)");
}
private final SentinelVersion version020 = new SentinelVersion().setMinorVersion(2);
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\ParamFlowRuleController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeService.getEmployeeById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
} | @PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeService.addEmployee(employee);
}
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee updatedEmployee = employeeService.updateEmployee(employeeId, employeeDetails);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
return employeeService.deleteEmployee(employeeId);
}
} | repos\Spring-Boot-Advanced-Projects-main\spring-aop-advice-examples\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\controller\EmployeeController.java | 2 |
请完成以下Java代码 | public TransformsType2 getTransforms() {
return transforms;
}
/**
* Sets the value of the transforms property.
*
* @param value
* allowed object is
* {@link TransformsType2 }
*
*/
public void setTransforms(TransformsType2 value) {
this.transforms = value;
}
/**
* Gets the value of the uri property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getURI() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setURI(String value) {
this.uri = value;
}
/** | * Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = 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\RetrievalMethodType.java | 1 |
请完成以下Java代码 | public I_M_Material_Tracking extractMaterialTrackingIfAny(final IHUContext huContext, final I_M_HU hu)
{
// Do nothing if material tracking module is not activated
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
if (!materialTrackingBL.isEnabled())
{
return null;
}
// If there is no HU => do nothing
if (hu == null)
{
return null;
} | // Services
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class);
//
// Get HU Attributes from top level HU
final I_M_HU huTopLevel = handlingUnitsBL.getTopLevelParent(hu);
final IAttributeStorage huAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(huTopLevel);
//
// Get Material Tracking from HU Attributes
final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTracking(huContext, huAttributes);
return materialTracking;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\impl\HUPPOrderMaterialTrackingBL.java | 1 |
请完成以下Java代码 | protected static I_M_HU_LUTU_Configuration getCurrentLUTUConfiguration(final I_M_ReceiptSchedule receiptSchedule)
{
final I_M_HU_LUTU_Configuration lutuConfig = Services.get(IHUReceiptScheduleBL.class)
.createLUTUConfigurationManager(receiptSchedule)
.getCreateLUTUConfiguration();
// Make sure nobody is overriding the existing configuration
if (lutuConfig.getM_HU_LUTU_Configuration_ID() > 0)
{
InterfaceWrapperHelper.setSaveDeleteDisabled(lutuConfig, true);
}
return lutuConfig;
}
@Override
@RunOutOfTrx
protected final String doIt() throws Exception
{
final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule();
final IMutableHUContext huContextInitial = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(getCtx(), ClientAndOrgId.ofClientAndOrg(receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID()));
final ReceiptScheduleHUGenerator huGenerator = ReceiptScheduleHUGenerator.newInstance(huContextInitial)
.addM_ReceiptSchedule(receiptSchedule)
.setUpdateReceiptScheduleDefaultConfiguration(isUpdateReceiptScheduleDefaultConfiguration());
//
// Get/Create the initial LU/TU configuration
final I_M_HU_LUTU_Configuration lutuConfigurationOrig = getCurrentLUTUConfiguration(receiptSchedule);
//
// Create the effective LU/TU configuration
final I_M_HU_LUTU_Configuration lutuConfiguration = createM_HU_LUTU_Configuration(lutuConfigurationOrig);
Services.get(ILUTUConfigurationFactory.class).save(lutuConfiguration);
huGenerator.setM_HU_LUTU_Configuration(lutuConfiguration);
//
// Calculate the target CUs that we want to allocate
final ILUTUProducerAllocationDestination lutuProducer = huGenerator.getLUTUProducerAllocationDestination();
final Quantity qtyCUsTotal = lutuProducer.calculateTotalQtyCU(); | if (qtyCUsTotal.isInfinite())
{
throw new AdempiereException("LU/TU configuration is resulting to infinite quantity: " + lutuConfiguration);
}
huGenerator.setQtyToAllocateTarget(qtyCUsTotal);
//
// Generate the HUs
final List<I_M_HU> hus = huGenerator.generateWithinOwnTransaction();
hus.forEach(hu -> {
updateAttributes(hu, receiptSchedule);
});
openHUsToReceive(hus);
return MSG_OK;
}
protected final I_M_ReceiptSchedule getM_ReceiptSchedule()
{
return getRecord(I_M_ReceiptSchedule.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_Base.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
/** BEGIN theme configuration */
@Bean
public ResourceBundleThemeSource themeSource() {
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
themeSource.setDefaultEncoding("UTF-8");
themeSource.setBasenamePrefix("themes.");
return themeSource;
}
@Bean
public CookieThemeResolver themeResolver() {
CookieThemeResolver resolver = new CookieThemeResolver();
resolver.setDefaultThemeName("default");
resolver.setCookieName("example-theme-cookie");
return resolver;
}
@Bean
public ThemeChangeInterceptor themeChangeInterceptor() {
ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor();
interceptor.setParamName("theme");
return interceptor;
} | @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(themeChangeInterceptor());
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() {
return factory -> factory.setRegisterDefaultServlet(true);
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\web\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void scheduleTimerJob(TimerJobEntity timerJob) {
getJobManager().scheduleTimerJob(timerJob);
}
@Override
public AbstractRuntimeJobEntity moveJobToTimerJob(JobEntity job) {
return getJobManager().moveJobToTimerJob(job);
}
@Override
public TimerJobEntity createTimerJob() {
return getTimerJobEntityManager().create();
}
@Override
public void insertTimerJob(TimerJobEntity timerJob) {
getTimerJobEntityManager().insert(timerJob);
}
@Override
public void deleteTimerJob(TimerJobEntity timerJob) { | getTimerJobEntityManager().delete(timerJob);
}
@Override
public void deleteTimerJobsByExecutionId(String executionId) {
TimerJobEntityManager timerJobEntityManager = getTimerJobEntityManager();
Collection<TimerJobEntity> timerJobsForExecution = timerJobEntityManager.findJobsByExecutionId(executionId);
for (TimerJobEntity job : timerJobsForExecution) {
timerJobEntityManager.delete(job);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
FlowableEngineEventType.JOB_CANCELED, job), configuration.getEngineName());
}
}
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\TimerJobServiceImpl.java | 2 |
请完成以下Java代码 | public List<String> getPhone() {
if (phone == null) {
phone = new ArrayList<String>();
}
return this.phone;
}
/**
* Gets the value of the fax property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the fax property.
*
* <p>
* For example, to add a new item, do as follows: | * <pre>
* getFax().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getFax() {
if (fax == null) {
fax = new ArrayList<String>();
}
return this.fax;
}
} | 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\TelecomAddressType.java | 1 |
请完成以下Java代码 | public Map<String, String> getStatementMappings() {
return statementMappings;
}
public void setStatementMappings(Map<String, String> statementMappings) {
this.statementMappings = statementMappings;
}
public Map<Class<?>, String> getInsertStatements() {
return insertStatements;
}
public void setInsertStatements(Map<Class<?>, String> insertStatements) {
this.insertStatements = insertStatements;
}
public Map<Class<?>, String> getBulkInsertStatements() {
return bulkInsertStatements;
}
public void setBulkInsertStatements(Map<Class<?>, String> bulkInsertStatements) {
this.bulkInsertStatements = bulkInsertStatements;
}
public Map<Class<?>, String> getUpdateStatements() {
return updateStatements;
}
public void setUpdateStatements(Map<Class<?>, String> updateStatements) {
this.updateStatements = updateStatements;
}
public Map<Class<?>, String> getDeleteStatements() {
return deleteStatements;
}
public void setDeleteStatements(Map<Class<?>, String> deleteStatements) {
this.deleteStatements = deleteStatements;
}
public Map<Class<?>, String> getBulkDeleteStatements() {
return bulkDeleteStatements;
}
public void setBulkDeleteStatements(Map<Class<?>, String> bulkDeleteStatements) {
this.bulkDeleteStatements = bulkDeleteStatements;
}
public Map<Class<?>, String> getSelectStatements() {
return selectStatements;
}
public void setSelectStatements(Map<Class<?>, String> selectStatements) {
this.selectStatements = selectStatements;
}
public boolean isDbHistoryUsed() {
return isDbHistoryUsed;
} | public void setDbHistoryUsed(boolean isDbHistoryUsed) {
this.isDbHistoryUsed = isDbHistoryUsed;
}
public void setDatabaseTablePrefix(String databaseTablePrefix) {
this.databaseTablePrefix = databaseTablePrefix;
}
public String getDatabaseTablePrefix() {
return databaseTablePrefix;
}
public String getDatabaseCatalog() {
return databaseCatalog;
}
public void setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog;
}
public String getDatabaseSchema() {
return databaseSchema;
}
public void setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
}
public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) {
this.tablePrefixIsSchema = tablePrefixIsSchema;
}
public boolean isTablePrefixIsSchema() {
return tablePrefixIsSchema;
}
public int getMaxNrOfStatementsInBulkInsert() {
return maxNrOfStatementsInBulkInsert;
}
public void setMaxNrOfStatementsInBulkInsert(int maxNrOfStatementsInBulkInsert) {
this.maxNrOfStatementsInBulkInsert = maxNrOfStatementsInBulkInsert;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSessionFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PriceListSchemaRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
public void createPriceListSchemaLine(@NonNull final CreatePriceListSchemaRequest request)
{
final I_M_DiscountSchemaLine schemaLine = InterfaceWrapperHelper.newInstance(I_M_DiscountSchemaLine.class);
schemaLine.setM_DiscountSchema_ID(getRepoIdOrDefault(request.getDiscountSchemaId()));
schemaLine.setSeqNo(request.getSeqNo());
schemaLine.setM_Product_ID(getRepoIdOrDefault(request.getProductId()));
schemaLine.setM_Product_Category_ID(getRepoIdOrDefault(request.getProductCategoryId()));
schemaLine.setC_BPartner_ID(getRepoIdOrDefault(request.getBPartnerId()));
schemaLine.setC_TaxCategory_ID(getRepoIdOrDefault(request.getTaxCategoryId()));
schemaLine.setStd_AddAmt(request.getStd_AddAmt());
schemaLine.setStd_Rounding(request.getStd_Rounding());
schemaLine.setC_TaxCategory_Target_ID(getRepoIdOrDefault(request.getTaxCategoryTargetId()));
schemaLine.setConversionDate(TimeUtil.asTimestamp(request.getConversionDate()));
schemaLine.setList_Base(request.getList_Base());
schemaLine.setC_ConversionType_ID(getRepoIdOrDefault(request.getConversionTypeId()));
schemaLine.setLimit_AddAmt(request.getLimit_AddAmt());
schemaLine.setLimit_Base(request.getLimit_Base());
schemaLine.setLimit_Discount(request.getLimit_Discount());
schemaLine.setLimit_MaxAmt(request.getLimit_MaxAmt());
schemaLine.setLimit_MinAmt(request.getLimit_MinAmt());
schemaLine.setLimit_Rounding(request.getLimit_Rounding());
schemaLine.setList_AddAmt(request.getList_AddAmt());
schemaLine.setList_Discount(request.getList_Discount());
schemaLine.setList_MaxAmt(request.getList_MaxAmt());
schemaLine.setList_MinAmt(request.getList_MinAmt()); | schemaLine.setList_Rounding(request.getList_Rounding());
schemaLine.setStd_Base(request.getStd_Base());
schemaLine.setStd_Discount(request.getStd_Discount());
schemaLine.setStd_MaxAmt(request.getStd_MaxAmt());
schemaLine.setStd_MinAmt(request.getStd_MinAmt());
InterfaceWrapperHelper.save(schemaLine);
}
private int getRepoIdOrDefault(@Nullable final RepoIdAware repoId)
{
if (repoId == null)
{
return 0;
}
return repoId.getRepoId();
}
public boolean hasAnyLines(final PricingConditionsId priceListSchemaId)
{
return queryBL.createQueryBuilder(I_M_DiscountSchemaLine.class)
.addEqualsFilter(I_M_DiscountSchemaLine.COLUMNNAME_M_DiscountSchema_ID, priceListSchemaId)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\pricelistschema\PriceListSchemaRepository.java | 2 |
请完成以下Java代码 | public PickingJob setLUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId,
@Nullable final LUPickingTarget target)
{
return pickingJobService.setLUPickingTarget(pickingJob, lineId, target);
}
public PickingJob setTUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId,
@Nullable final TUPickingTarget target)
{
return pickingJobService.setTUPickingTarget(pickingJob, lineId, target);
}
public PickingJob closeLUAndTUPickingTargets(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJobService.closeLUAndTUPickingTargets(pickingJob, lineId);
}
public PickingJob closeTUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJobService.closeTUPickingTarget(pickingJob, lineId);
}
@NonNull
public PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId) {return configService.getPickingJobOptions(customerId);}
@NonNull
public List<HuId> getClosedLUs(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
final Set<HuId> pickedHuIds = pickingJob.getPickedHuIds(lineId);
if (pickedHuIds.isEmpty())
{
return ImmutableList.of();
}
final HuId currentlyOpenedLUId = pickingJob.getLuPickingTarget(lineId)
.map(LUPickingTarget::getLuId)
.orElse(null);
return handlingUnitsBL.getTopLevelHUs(IHandlingUnitsBL.TopLevelHusQuery.builder()
.hus(handlingUnitsBL.getByIds(pickedHuIds)) | .build())
.stream()
.filter(handlingUnitsBL::isLoadingUnit)
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.filter(huId -> !HuId.equals(huId, currentlyOpenedLUId))
.collect(ImmutableList.toImmutableList());
}
public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final PickingJob pickingJob)
{
return pickingJobService.getPickingSlotsSuggestions(pickingJob);
}
public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return pickingJobService.pickAll(pickingJobId, callerId);
}
public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return pickingJobService.getQtyAvailable(pickingJobId, callerId);
}
public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(final @NonNull GetNextEligibleLineToPackRequest request)
{
return pickingJobService.getNextEligibleLineToPack(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\PickingJobRestService.java | 1 |
请完成以下Java代码 | public void setInternalName(final String internalName)
{
this.internalName = internalName;
}
private int AD_Window_ID = -1;
private int AD_Process_ID = -1;
private int AD_Form_ID = -1;
private int AD_Workflow_ID = -1;
private int AD_Task_ID = -1;
private int WEBUI_Board_ID = -1;
private boolean isCreateNewRecord = false;
private String webuiNameBrowse;
private String webuiNameNew;
private String webuiNameNewBreadcrumb;
private String mainTableName;
public int getAD_Window_ID()
{
return AD_Window_ID;
}
public void setAD_Window_ID(int aD_Window_ID)
{
AD_Window_ID = aD_Window_ID;
}
public int getAD_Process_ID()
{
return AD_Process_ID;
}
public void setAD_Process_ID(int aD_Process_ID)
{
AD_Process_ID = aD_Process_ID;
}
public int getAD_Form_ID()
{
return AD_Form_ID;
}
public void setAD_Form_ID(int aD_Form_ID)
{
AD_Form_ID = aD_Form_ID;
}
public int getAD_Workflow_ID()
{
return AD_Workflow_ID;
}
public void setAD_Workflow_ID(int aD_Workflow_ID)
{
AD_Workflow_ID = aD_Workflow_ID;
}
public int getAD_Task_ID()
{
return AD_Task_ID;
}
public void setAD_Task_ID(int aD_Task_ID)
{
AD_Task_ID = aD_Task_ID;
}
public int getWEBUI_Board_ID()
{
return WEBUI_Board_ID;
}
public void setWEBUI_Board_ID(final int WEBUI_Board_ID)
{
this.WEBUI_Board_ID = WEBUI_Board_ID;
}
public void setIsCreateNewRecord(final boolean isCreateNewRecord)
{
this.isCreateNewRecord = isCreateNewRecord;
}
public boolean isCreateNewRecord()
{
return isCreateNewRecord;
}
public void setWEBUI_NameBrowse(final String webuiNameBrowse)
{
this.webuiNameBrowse = webuiNameBrowse; | }
public String getWEBUI_NameBrowse()
{
return webuiNameBrowse;
}
public void setWEBUI_NameNew(final String webuiNameNew)
{
this.webuiNameNew = webuiNameNew;
}
public String getWEBUI_NameNew()
{
return webuiNameNew;
}
public void setWEBUI_NameNewBreadcrumb(final String webuiNameNewBreadcrumb)
{
this.webuiNameNewBreadcrumb = webuiNameNewBreadcrumb;
}
public String getWEBUI_NameNewBreadcrumb()
{
return webuiNameNewBreadcrumb;
}
/**
* @param mainTableName table name of main tab or null
*/
public void setMainTableName(String mainTableName)
{
this.mainTableName = mainTableName;
}
/**
* @return table name of main tab or null
*/
public String getMainTableName()
{
return mainTableName;
}
} // MTreeNode | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTreeNode.java | 1 |
请完成以下Java代码 | public class StreamEX {
public static void main(String[] args) {
// Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
List<User> users = Arrays.asList(new User("name"), new User(), new User());
users.stream().map(User::getName).collect(Collectors.toList());
List<String> userNames = StreamEx.of(users).map(User::getName).toList();
Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole);
StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
// Selecting stream elements of specific type
List usersAndRoles = Arrays.asList(new User(), new Role());
List<Role> roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
System.out.println(roles);
// adding elements to Stream
List<String> appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
System.out.println(appendedUsers);
// Removing unwanted elements and using the stream as Iterable:
for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
System.out.println(line);
}
// Selecting map keys by value predicate:
Map<String, Role> nameToRole = new HashMap<>();
nameToRole.put("first", new Role());
nameToRole.put("second", null); | Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
System.out.println(nonNullRoles);
// Operating on key-value pairs:
Map<User, List<Role>> users2roles = transformMap(role2users);
Map<String, String> mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
// Support of byte/char/short/float types:
short[] src = { 1, 2, 3 };
char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
}
public double[] getDiffBetweenPairs(double... numbers) {
return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray();
}
public static Map<User, List<Role>> transformMap(Map<Role, List<User>> role2users) {
Map<User, List<Role>> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping();
return users2roles;
}
} | repos\tutorials-master\libraries-stream\src\main\java\com\baeldung\streamex\StreamEX.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* This segment contains references related to the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferences() {
return references;
}
/**
* Sets the value of the references property.
*
* @param value
* allowed object is | * {@link String }
*
*/
public void setReferences(String value) {
this.references = value;
}
/**
* Flag indicating whether the message is a test message or not.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTestIndicator() {
return testIndicator;
}
/**
* Sets the value of the testIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTestIndicator(Boolean value) {
this.testIndicator = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\ErpelBusinessDocumentHeaderType.java | 2 |
请完成以下Java代码 | CurrencyConversionContext getCurrencyConversionCtxForBankAsset()
{
CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankAsset;
if (currencyConversionContext == null)
{
currencyConversionContext = this._currencyConversionContextForBankAsset = createCurrencyConversionCtxForBankAsset();
}
return currencyConversionContext;
}
private CurrencyConversionContext createCurrencyConversionCtxForBankAsset()
{
final I_C_BankStatementLine line = getC_BankStatementLine();
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
// IMPORTANT for Bank Asset Account booking,
// * we shall NOT consider the fixed Currency Rate because we want to compute currency gain/loss
// * use default conversion types
return services.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone),
null,
ClientId.ofRepoId(line.getAD_Client_ID()));
}
CurrencyConversionContext getCurrencyConversionCtxForBankInTransit()
{
CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankInTransit;
if (currencyConversionContext == null)
{
currencyConversionContext = this._currencyConversionContextForBankInTransit = createCurrencyConversionCtxForBankInTransit();
}
return currencyConversionContext;
}
private CurrencyConversionContext createCurrencyConversionCtxForBankInTransit()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return paymentBL.extractCurrencyConversionContext(payment);
}
else
{ | final I_C_BankStatementLine line = getC_BankStatementLine();
final PaymentCurrencyContext paymentCurrencyContext = bankStatementBL.getPaymentCurrencyContext(line);
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
CurrencyConversionContext conversionCtx = services.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone),
paymentCurrencyContext.getCurrencyConversionTypeId(),
ClientId.ofRepoId(line.getAD_Client_ID()));
final FixedConversionRate fixedCurrencyRate = paymentCurrencyContext.toFixedConversionRateOrNull();
if (fixedCurrencyRate != null)
{
conversionCtx = conversionCtx.withFixedConversionRate(fixedCurrencyRate);
}
return conversionCtx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\DocLine_BankStatement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class CheckConnectionFaultCustomizer implements WebServiceTemplateCustomizer {
private final boolean checkConnectionFault;
private CheckConnectionFaultCustomizer(boolean checkConnectionFault) {
this.checkConnectionFault = checkConnectionFault;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setCheckConnectionForFault(this.checkConnectionFault);
}
}
/**
* {@link WebServiceTemplateCustomizer} to set
* {@link WebServiceTemplate#setCheckConnectionForError(boolean)
* checkConnectionForError}.
*/
private static final class CheckConnectionForErrorCustomizer implements WebServiceTemplateCustomizer {
private final boolean checkConnectionForError;
private CheckConnectionForErrorCustomizer(boolean checkConnectionForError) {
this.checkConnectionForError = checkConnectionForError;
} | @Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setCheckConnectionForError(this.checkConnectionForError);
}
}
/**
* {@link WebServiceTemplateCustomizer} to set
* {@link WebServiceTemplate#setFaultMessageResolver(FaultMessageResolver)
* faultMessageResolver}.
*/
private static final class FaultMessageResolverCustomizer implements WebServiceTemplateCustomizer {
private final FaultMessageResolver faultMessageResolver;
private FaultMessageResolverCustomizer(FaultMessageResolver faultMessageResolver) {
this.faultMessageResolver = faultMessageResolver;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setFaultMessageResolver(this.faultMessageResolver);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\client\WebServiceTemplateBuilder.java | 2 |
请完成以下Java代码 | protected IAggregationKeyBuilder<I_C_Invoice_Candidate> getDelegate(final I_C_Invoice_Candidate ic)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner bpartner = bpartnerDAO.getById(ic.getBill_BPartner_ID(), I_C_BPartner.class);
if (bpartner == null)
{
return null;
}
final Properties ctx = InterfaceWrapperHelper.getCtx(ic);
final OrderId prepayOrderId = OrderId.ofRepoIdOrNull(ic.getC_Order_ID());
if (prepayOrderId != null
&& Services.get(IOrderBL.class).isPrepay(prepayOrderId)
&& X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header.equals(aggregationUsageLevel))
{
return invoiceAggregationFactory.getPrepayOrderAggregationKeyBuilder(ctx);
}
final boolean isSOTrx = ic.isSOTrx(); | return invoiceAggregationFactory.getAggregationKeyBuilder(ctx, bpartner, isSOTrx, aggregationUsageLevel);
}
@Override
public final boolean isSame(final I_C_Invoice_Candidate ic1, final I_C_Invoice_Candidate ic2)
{
final AggregationKey aggregationKey1 = buildAggregationKey(ic1);
if (aggregationKey1 == null)
{
return false;
}
final AggregationKey aggregationKey2 = buildAggregationKey(ic2);
if (aggregationKey2 == null)
{
return false;
}
final boolean same = Objects.equals(aggregationKey1, aggregationKey2);
return same;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ForwardingICAggregationKeyBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/**
* Gets the value of the message property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessage() {
return message;
}
/**
* Sets the value of the message property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessage(String value) {
this.message = value;
}
/**
* Gets the value of the shortMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShortMessage() {
return shortMessage;
}
/**
* Sets the value of the shortMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShortMessage(String value) {
this.shortMessage = value;
}
/**
* Gets the value of the systemFullMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSystemFullMessage() {
return systemFullMessage;
}
/**
* Sets the value of the systemFullMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemFullMessage(String value) {
this.systemFullMessage = value;
}
/**
* Gets the value of the systemMessage property. | *
* @return
* possible object is
* {@link String }
*
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Sets the value of the systemMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemMessage(String value) {
this.systemMessage = value;
}
/**
* Gets the value of the systemShortMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSystemShortMessage() {
return systemShortMessage;
}
/**
* Sets the value of the systemShortMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemShortMessage(String value) {
this.systemShortMessage = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\LoginException.java | 2 |
请完成以下Java代码 | public java.lang.String getTooltipType()
{
return get_ValueAsString(COLUMNNAME_TooltipType);
}
@Override
public void setWEBUI_View_PageLength (final int WEBUI_View_PageLength)
{
set_Value (COLUMNNAME_WEBUI_View_PageLength, WEBUI_View_PageLength);
}
@Override
public int getWEBUI_View_PageLength()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_View_PageLength);
}
/**
* WhenChildCloningStrategy AD_Reference_ID=541756
* Reference name: AD_Table_CloningStrategy
*/ | public static final int WHENCHILDCLONINGSTRATEGY_AD_Reference_ID=541756;
/** Skip = S */
public static final String WHENCHILDCLONINGSTRATEGY_Skip = "S";
/** AllowCloning = A */
public static final String WHENCHILDCLONINGSTRATEGY_AllowCloning = "A";
/** AlwaysInclude = I */
public static final String WHENCHILDCLONINGSTRATEGY_AlwaysInclude = "I";
@Override
public void setWhenChildCloningStrategy (final java.lang.String WhenChildCloningStrategy)
{
set_Value (COLUMNNAME_WhenChildCloningStrategy, WhenChildCloningStrategy);
}
@Override
public java.lang.String getWhenChildCloningStrategy()
{
return get_ValueAsString(COLUMNNAME_WhenChildCloningStrategy);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table.java | 1 |
请完成以下Java代码 | public class Evaluator
{
private Evaluator()
{
}
public static FMeasure evaluate(IClassifier classifier, IDataSet testingDataSet)
{
int c = classifier.getModel().catalog.length;
double[] TP_FP = new double[c]; // 判定为某个类别的数量
double[] TP_FN = new double[c]; // 某个类别的样本数量
double[] TP = new double[c]; // 判定为某个类别且判断正确的数量
double time = System.currentTimeMillis();
for (Document document : testingDataSet)
{
final int out = classifier.label(document);
final int key = document.category;
++TP_FP[out];
++TP_FN[key];
if (key == out)
{
++TP[out];
}
}
time = System.currentTimeMillis() - time;
FMeasure result = calculate(c, testingDataSet.size(), TP, TP_FP, TP_FN);
result.catalog = testingDataSet.getCatalog().toArray();
result.speed = result.size / (time / 1000.);
return result;
}
public static FMeasure evaluate(IClassifier classifier, Map<String, String[]> testingDataSet)
{
return evaluate(classifier, new MemoryDataSet(classifier.getModel()).add(testingDataSet));
}
/**
*
* @param c 类目数量
* @param size 样本数量
* @param TP 判定为某个类别且判断正确的数量
* @param TP_FP 判定为某个类别的数量
* @param TP_FN 某个类别的样本数量
* @return
*/
private static FMeasure calculate(int c, int size, double[] TP, double[] TP_FP, double[] TP_FN)
{
double precision[] = new double[c];
double recall[] = new double[c];
double f1[] = new double[c];
double accuracy[] = new double[c];
FMeasure result = new FMeasure();
result.size = size;
for (int i = 0; i < c; i++) | {
double TN = result.size - TP_FP[i] - (TP_FN[i] - TP[i]);
accuracy[i] = (TP[i] + TN) / result.size;
if (TP[i] != 0)
{
precision[i] = TP[i] / TP_FP[i];
recall[i] = TP[i] / TP_FN[i];
result.average_accuracy += TP[i];
}
else
{
precision[i] = 0;
recall[i] = 0;
}
f1[i] = 2 * precision[i] * recall[i] / (precision[i] + recall[i]);
}
result.average_precision = MathUtility.average(precision);
result.average_recall = MathUtility.average(recall);
result.average_f1 = 2 * result.average_precision * result.average_recall
/ (result.average_precision + result.average_recall);
result.average_accuracy /= (double) result.size;
result.accuracy = accuracy;
result.precision = precision;
result.recall = recall;
result.f1 = f1;
return result;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\statistics\evaluations\Evaluator.java | 1 |
请完成以下Java代码 | public OrderPayScheduleLine getLineById(@NonNull final OrderPayScheduleId payScheduleLineId)
{
return lines.stream()
.filter(line -> line.getId().equals(payScheduleLineId))
.findFirst()
.orElseThrow(() -> new AdempiereException("OrderPayScheduleLine not found for ID: " + payScheduleLineId));
}
public void updateStatusFromContext(final OrderSchedulingContext context)
{
final PaymentTerm paymentTerm = context.getPaymentTerm();
for (final OrderPayScheduleLine line : lines)
{
if (line.getStatus().isPending()) | {
final PaymentTermBreak termBreak = paymentTerm.getBreakById(line.getPaymentTermBreakId());
final DueDateAndStatus dueDateAndStatus = context.computeDueDate(termBreak);
line.applyAndProcess(dueDateAndStatus);
}
}
}
public void markAsPaid(final OrderPayScheduleId orderPayScheduleId)
{
final OrderPayScheduleLine line = getLineById(orderPayScheduleId);
final DueDateAndStatus dueDateAndStatus = DueDateAndStatus.paid(line.getDueDate());
line.applyAndProcess(dueDateAndStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderPaySchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this).addValue(_asi).toString();
}
@Override
public boolean accept(@Nullable final I_M_ProductPrice productPrice)
{
// Guard against null, shall not happen
if (productPrice == null)
{
return false;
}
if (!productPrice.isAttributeDependant())
{
return _acceptNotAttributeDependent; // either way, there is nothing more to do or match here
}
// If our ASI does not have attributes set, consider this product price as matching
final Map<Integer, I_M_AttributeInstance> asiAttributes = getASIAttributes();
if (asiAttributes.isEmpty())
{
return true;
}
// If there are no expected attributes (in product price),
// consider it as matching
final List<I_M_AttributeInstance> expectedAttributes = extractProductPriceAttributes(productPrice);
if (expectedAttributes.isEmpty())
{
return true;
}
for (final I_M_AttributeInstance expectedAttribute : expectedAttributes)
{
final int attributeId = expectedAttribute.getM_Attribute_ID();
final I_M_AttributeInstance asiAttribute = asiAttributes.get(attributeId);
if (!isAttributeInstanceMatching(expectedAttribute, asiAttribute))
{
return false;
}
}
return true;
}
private static boolean isAttributeInstanceMatching(final I_M_AttributeInstance expected, final I_M_AttributeInstance actual)
{
final int expectedAttributeValueId = CoalesceUtil.firstGreaterThanZero(expected.getM_AttributeValue_ID(), 0);
final int actualAttributeValueId;
if (actual == null)
{
actualAttributeValueId = 0;
}
else
{
actualAttributeValueId = CoalesceUtil.firstGreaterThanZero(actual.getM_AttributeValue_ID(), 0);
} | if (expectedAttributeValueId != actualAttributeValueId)
{
return false;
}
return true;
}
private Map<Integer, I_M_AttributeInstance> getASIAttributes()
{
if (_asiAttributes == null)
{
final List<I_M_AttributeInstance> asiAttributesList = asiBL.getAttributeInstances(_asi);
_asiAttributes = Maps.uniqueIndex(asiAttributesList, I_M_AttributeInstance::getM_Attribute_ID);
}
return _asiAttributes;
}
private List<I_M_AttributeInstance> extractProductPriceAttributes(final I_M_ProductPrice productPrice)
{
final I_M_AttributeSetInstance productPriceASI = productPrice.getM_AttributeSetInstance();
if (productPriceASI == null || productPriceASI.getM_AttributeSetInstance_ID() <= 0)
{
return ImmutableList.of();
}
final List<I_M_AttributeInstance> productPriceAttributes = asiBL.getAttributeInstances(productPriceASI);
return productPriceAttributes;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\ProductPriceQuery.java | 2 |
请完成以下Java代码 | public ClientId getClientId()
{
return resource.getClientId();
}
public OrgId getOrgId()
{
return resource.getOrgId();
}
@Override
public OrgResource getResource()
{
return resource;
}
@Override
public Permission mergeWith(final Permission permissionFrom)
{
final OrgPermission orgPermissionFrom = checkCompatibleAndCast(permissionFrom);
final ImmutableSet<Access> accesses = ImmutableSet.<Access> builder()
.addAll(this.accesses) | .addAll(orgPermissionFrom.accesses)
.build();
return new OrgPermission(resource, accesses);
}
/**
* Creates a copy of this permission but it will use the given resource.
*
* @return copy of this permission but having the given resource
*/
public OrgPermission copyWithResource(final OrgResource resource)
{
return new OrgPermission(resource, this.accesses);
}
} // OrgAccess | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermission.java | 1 |
请完成以下Java代码 | public void onError(Throwable e) {
log.error(e.getMessage(), e);
latch.countDown();
}
});
latch.await(10, TimeUnit.SECONDS);
ValidateDeviceCredentialsResponse msg = deviceCredentialsResponse[0];
if (msg != null && strCert.equals(msg.getCredentials())) {
DeviceProfile deviceProfile = msg.getDeviceProfile();
if (msg.hasDeviceInfo() && deviceProfile != null) {
TbCoapDtlsSessionKey tbCoapDtlsSessionKey = new TbCoapDtlsSessionKey(remotePeer, msg.getCredentials());
tbCoapDtlsSessionInMemoryStorage.put(tbCoapDtlsSessionKey, new TbCoapDtlsSessionInfo(msg, deviceProfile));
}
break;
}
} catch (InterruptedException |
CertificateEncodingException |
CertificateExpiredException |
CertificateNotYetValidException e) {
log.error(e.getMessage(), e);
AlertMessage alert = new AlertMessage(AlertMessage.AlertLevel.FATAL, AlertMessage.AlertDescription.BAD_CERTIFICATE);
throw new HandshakeException("Certificate chain could not be validated", alert);
}
}
return new CertificateVerificationResult(cid, certpath, null);
} catch (HandshakeException e) {
log.trace("Certificate validation failed!", e);
return new CertificateVerificationResult(cid, e, null); | }
}
@Override
public List<X500Principal> getAcceptedIssuers() {
return CertPathUtil.toSubjects(null);
}
@Override
public void setResultHandler(HandshakeResultHandler resultHandler) {
}
public ConcurrentMap<TbCoapDtlsSessionKey, TbCoapDtlsSessionInfo> getTbCoapDtlsSessionsMap() {
return tbCoapDtlsSessionInMemoryStorage.getDtlsSessionsMap();
}
public void evictTimeoutSessions() {
tbCoapDtlsSessionInMemoryStorage.evictTimeoutSessions();
}
public long getDtlsSessionReportTimeout() {
return tbCoapDtlsSessionInMemoryStorage.getDtlsSessionReportTimeout();
}
} | repos\thingsboard-master\common\coap-server\src\main\java\org\thingsboard\server\coapserver\TbCoapDtlsCertificateVerifier.java | 1 |
请完成以下Java代码 | public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Pet status(StatusEnum status) {
this.status = status;
return this;
}
/**
* pet status in the store
* @return status
**/
@ApiModelProperty(value = "pet status in the store")
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(this.id, pet.id) &&
Objects.equals(this.category, pet.category) &&
Objects.equals(this.name, pet.name) &&
Objects.equals(this.photoUrls, pet.photoUrls) &&
Objects.equals(this.tags, pet.tags) &&
Objects.equals(this.status, pet.status);
}
@Override
public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java | 1 |
请完成以下Java代码 | public void setManufacturing_Warehouse_Group_ID (final int Manufacturing_Warehouse_Group_ID)
{
if (Manufacturing_Warehouse_Group_ID < 1)
set_Value (COLUMNNAME_Manufacturing_Warehouse_Group_ID, null);
else
set_Value (COLUMNNAME_Manufacturing_Warehouse_Group_ID, Manufacturing_Warehouse_Group_ID);
}
@Override
public int getManufacturing_Warehouse_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_Manufacturing_Warehouse_Group_ID);
}
/**
* MRP_Exclude AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int MRP_EXCLUDE_AD_Reference_ID=319;
/** Yes = Y */
public static final String MRP_EXCLUDE_Yes = "Y";
/** No = N */
public static final String MRP_EXCLUDE_No = "N";
@Override
public void setMRP_Exclude (final @Nullable java.lang.String MRP_Exclude)
{
set_Value (COLUMNNAME_MRP_Exclude, MRP_Exclude);
}
@Override
public java.lang.String getMRP_Exclude()
{
return get_ValueAsString(COLUMNNAME_MRP_Exclude);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public org.compiere.model.I_S_Resource getPP_Plant()
{
return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant)
{
set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant);
}
@Override
public void setPP_Plant_ID (final int PP_Plant_ID)
{
if (PP_Plant_ID < 1)
set_Value (COLUMNNAME_PP_Plant_ID, null);
else
set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID);
}
@Override
public int getPP_Plant_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); | }
@Override
public void setReplenishmentClass (final @Nullable java.lang.String ReplenishmentClass)
{
set_Value (COLUMNNAME_ReplenishmentClass, ReplenishmentClass);
}
@Override
public java.lang.String getReplenishmentClass()
{
return get_ValueAsString(COLUMNNAME_ReplenishmentClass);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_Location getWarehouse_Location()
{
return get_ValueAsPO(COLUMNNAME_Warehouse_Location_ID, org.compiere.model.I_C_Location.class);
}
@Override
public void setWarehouse_Location(final org.compiere.model.I_C_Location Warehouse_Location)
{
set_ValueFromPO(COLUMNNAME_Warehouse_Location_ID, org.compiere.model.I_C_Location.class, Warehouse_Location);
}
@Override
public void setWarehouse_Location_ID (final int Warehouse_Location_ID)
{
if (Warehouse_Location_ID < 1)
set_Value (COLUMNNAME_Warehouse_Location_ID, null);
else
set_Value (COLUMNNAME_Warehouse_Location_ID, Warehouse_Location_ID);
}
@Override
public int getWarehouse_Location_ID()
{ | return get_ValueAsInt(COLUMNNAME_Warehouse_Location_ID);
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_Order_Header_v.java | 1 |
请完成以下Java代码 | public class CmmnHandlerContext implements HandlerContext {
protected ExpressionManager expressionManager;
protected CmmnCaseDefinition caseDefinition;
protected CmmnModelInstance model;
protected CmmnActivity parent;
protected Deployment deployment;
public CmmnHandlerContext() {
}
public CmmnModelInstance getModel() {
return model;
}
public void setModel(CmmnModelInstance model) {
this.model = model;
}
public CmmnCaseDefinition getCaseDefinition() {
return caseDefinition;
}
public void setCaseDefinition(CmmnCaseDefinition caseDefinition) {
this.caseDefinition = caseDefinition;
}
public CmmnActivity getParent() {
return parent;
}
public void setParent(CmmnActivity parent) {
this.parent = parent;
}
public Deployment getDeployment() { | return deployment;
}
public void setDeployment(Deployment deployment) {
this.deployment = deployment;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\CmmnHandlerContext.java | 1 |
请完成以下Java代码 | private I_MSV3_BestellungAntwortAuftrag createRecord(@NonNull final OrderResponsePackage responseOrder)
{
final I_MSV3_BestellungAntwortAuftrag record = newInstanceOutOfTrx(I_MSV3_BestellungAntwortAuftrag.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setMSV3_Auftragsart(responseOrder.getOrderType().getV2SoapCode().value());
record.setMSV3_Auftragskennung(responseOrder.getOrderIdentification());
record.setMSV3_AuftragsSupportID(responseOrder.getSupportId().getValueAsInt());
record.setMSV3_GebindeId(responseOrder.getPackingMaterialId());
record.setMSV3_Id(responseOrder.getId().getValueAsString());
final I_MSV3_FaultInfo faultInfoRecord = Msv3FaultInfoDataPersister
.newInstanceWithOrgId(orgId)
.storeMsv3FaultInfoOrNull(responseOrder.getFaultInfo());
record.setMSV3_Auftragsfehler(faultInfoRecord);
return record;
}
private I_MSV3_BestellungAntwortPosition createRecord(@NonNull final OrderResponsePackageItem responseItem)
{
final I_MSV3_BestellungAntwortPosition record = newInstanceOutOfTrx(I_MSV3_BestellungAntwortPosition.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setMSV3_BestellLiefervorgabe(responseItem.getDeliverySpecifications().getV2SoapCode().value());
record.setMSV3_BestellMenge(responseItem.getQty().getValueAsInt());
record.setMSV3_BestellPzn(responseItem.getPzn().getValueAsString());
record.setC_PurchaseCandidate_ID(MSV3PurchaseCandidateId.toRepoId(responseItem.getPurchaseCandidateId()));
final I_MSV3_Substitution substitutionRecord = Msv3SubstitutionDataPersister.newInstanceWithOrgId(orgId)
.storeSubstitutionOrNull(responseItem.getSubstitution());
record.setMSV3_BestellungSubstitution(substitutionRecord); | return record;
}
private I_MSV3_BestellungAnteil createRecord(@NonNull final OrderResponsePackageItemPart anteil)
{
final I_MSV3_BestellungAnteil bestellungAnteilRecord = newInstanceOutOfTrx(I_MSV3_BestellungAnteil.class);
bestellungAnteilRecord.setAD_Org_ID(orgId.getRepoId());
Optional.ofNullable(anteil.getDefectReason())
.map(OrderDefectReason::value)
.ifPresent(bestellungAnteilRecord::setMSV3_Grund);
bestellungAnteilRecord.setMSV3_Lieferzeitpunkt(TimeUtil.asTimestamp(anteil.getDeliveryDate()));
bestellungAnteilRecord.setMSV3_Menge(anteil.getQty().getValueAsInt());
bestellungAnteilRecord.setMSV3_Tourabweichung(anteil.isTourDeviation());
bestellungAnteilRecord.setMSV3_Typ(Type.getValueOrNull(anteil.getType()));
return bestellungAnteilRecord;
}
public MSV3OrderResponsePackageItemPartRepoIds getResponseItemPartRepoIds()
{
return responseItemPartRepoIds.copyAsImmutable();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\purchaseOrder\MSV3PurchaseOrderResponsePersister.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getSessionTimeoutInSeconds() {
return sessionTimeoutInSeconds;
}
public void setSessionTimeoutInSeconds(int sessionTimeoutInSeconds) {
this.sessionTimeoutInSeconds = sessionTimeoutInSeconds;
}
public String getCookieDomain() {
return cookieDomain;
}
public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
}
public static class SignatureVerification {
/**
* Maximum refresh rate for public keys in ms.
* We won't fetch new public keys any faster than that to avoid spamming UAA in case
* we receive a lot of "illegal" tokens.
*/
private long publicKeyRefreshRateLimit = 10 * 1000L;
/**
* Maximum TTL for the public key in ms.
* The public key will be fetched again from UAA if it gets older than that.
* That way, we make sure that we get the newest keys always in case they are updated there.
*/
private long ttl = 24 * 60 * 60 * 1000L; | /**
* Endpoint where to retrieve the public key used to verify token signatures.
*/
private String publicKeyEndpointUri = "http://uaa/oauth/token_key";
public long getPublicKeyRefreshRateLimit() {
return publicKeyRefreshRateLimit;
}
public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) {
this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit;
}
public long getTtl() {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
public String getPublicKeyEndpointUri() {
return publicKeyEndpointUri;
}
public void setPublicKeyEndpointUri(String publicKeyEndpointUri) {
this.publicKeyEndpointUri = publicKeyEndpointUri;
}
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2Properties.java | 2 |
请完成以下Java代码 | public void setHttpResponseHandler(FlowableHttpResponseHandler httpResponseHandler) {
this.httpResponseHandler = httpResponseHandler;
}
public Boolean getParallelInSameTransaction() {
return parallelInSameTransaction;
}
public void setParallelInSameTransaction(Boolean parallelInSameTransaction) {
this.parallelInSameTransaction = parallelInSameTransaction;
}
@Override
public HttpServiceTask clone() {
HttpServiceTask clone = new HttpServiceTask();
clone.setValues(this);
return clone; | }
public void setValues(HttpServiceTask otherElement) {
super.setValues(otherElement);
setParallelInSameTransaction(otherElement.getParallelInSameTransaction());
if (otherElement.getHttpRequestHandler() != null) {
setHttpRequestHandler(otherElement.getHttpRequestHandler().clone());
}
if (otherElement.getHttpResponseHandler() != null) {
setHttpResponseHandler(otherElement.getHttpResponseHandler().clone());
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\HttpServiceTask.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setFrom_Product_ID (final int From_Product_ID)
{
if (From_Product_ID < 1)
set_Value (COLUMNNAME_From_Product_ID, null);
else
set_Value (COLUMNNAME_From_Product_ID, From_Product_ID);
}
@Override
public int getFrom_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_From_Product_ID);
}
@Override
public void setMatured_Product_ID (final int Matured_Product_ID)
{
if (Matured_Product_ID < 1)
set_Value (COLUMNNAME_Matured_Product_ID, null);
else
set_Value (COLUMNNAME_Matured_Product_ID, Matured_Product_ID);
}
@Override
public int getMatured_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Matured_Product_ID);
}
@Override
public void setMaturityAge (final int MaturityAge)
{
set_Value (COLUMNNAME_MaturityAge, MaturityAge);
}
@Override
public int getMaturityAge()
{
return get_ValueAsInt(COLUMNNAME_MaturityAge);
}
@Override | public org.compiere.model.I_M_Maturing_Configuration getM_Maturing_Configuration()
{
return get_ValueAsPO(COLUMNNAME_M_Maturing_Configuration_ID, org.compiere.model.I_M_Maturing_Configuration.class);
}
@Override
public void setM_Maturing_Configuration(final org.compiere.model.I_M_Maturing_Configuration M_Maturing_Configuration)
{
set_ValueFromPO(COLUMNNAME_M_Maturing_Configuration_ID, org.compiere.model.I_M_Maturing_Configuration.class, M_Maturing_Configuration);
}
@Override
public void setM_Maturing_Configuration_ID (final int M_Maturing_Configuration_ID)
{
if (M_Maturing_Configuration_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, M_Maturing_Configuration_ID);
}
@Override
public int getM_Maturing_Configuration_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_ID);
}
@Override
public void setM_Maturing_Configuration_Line_ID (final int M_Maturing_Configuration_Line_ID)
{
if (M_Maturing_Configuration_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_Line_ID, M_Maturing_Configuration_Line_ID);
}
@Override
public int getM_Maturing_Configuration_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_Line_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Maturing_Configuration_Line.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HTRSD1 getHTRSD1() {
return htrsd1;
}
/**
* Sets the value of the htrsd1 property.
*
* @param value
* allowed object is
* {@link HTRSD1 }
*
*/
public void setHTRSD1(HTRSD1 value) {
this.htrsd1 = value;
}
/**
* Gets the value of the packin property.
*
* @return | * possible object is
* {@link PACKINXlief }
*
*/
public PACKINXlief getPACKIN() {
return packin;
}
/**
* Sets the value of the packin property.
*
* @param value
* allowed object is
* {@link PACKINXlief }
*
*/
public void setPACKIN(PACKINXlief value) {
this.packin = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HEADERXlief.java | 2 |
请完成以下Spring Boot application配置 | #server.port=8081#配置服务器端口,默认为8080
#server.session-timeout=1000000#用户回话session过期时间,以秒为单位
#server.context-path=/index#配置访问路径,默认为/
#
#server.tomcat.uri-encoding=UTF-8#配置Tomcat编码,默认为UTF-8
#server.tomcat.compression=on#Tomcat是否开启压缩,默认为关闭
#-storetype 选项指定密钥仓库类型
#keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keysto | re.p12 -validity 3650
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=111111
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias:tomcat | repos\JavaEETest-master\Test20-Thymeleaf1\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static WorkpackageSkipRequestException create(final String message)
{
return new WorkpackageSkipRequestException(message,
Async_Constants.DEFAULT_RETRY_TIMEOUT_MILLIS,
null);
}
public static WorkpackageSkipRequestException createWithThrowable(final String message, final Throwable cause)
{
return new WorkpackageSkipRequestException(message,
Async_Constants.DEFAULT_RETRY_TIMEOUT_MILLIS,
cause);
}
public static WorkpackageSkipRequestException createWithTimeoutAndThrowable(
final String message,
final int skipTimeoutMillis,
final Throwable cause)
{
return new WorkpackageSkipRequestException(message,
skipTimeoutMillis,
cause);
}
public static WorkpackageSkipRequestException createWithTimeout(
final String message,
final int skipTimeoutMillis)
{
return new WorkpackageSkipRequestException(message,
skipTimeoutMillis,
null);
}
/**
* A random int between 0 and 5000 is added to the {@link Async_Constants#DEFAULT_RETRY_TIMEOUT_MILLIS} timeout. Use this if you want workpackages that are postponed at the same time to be
* retried at different times.
*/
public static WorkpackageSkipRequestException createWithRandomTimeout(final String message)
{
return new WorkpackageSkipRequestException(message,
Async_Constants.DEFAULT_RETRY_TIMEOUT_MILLIS + RANDOM.nextInt(5001),
null);
}
private WorkpackageSkipRequestException(final String message, final int skipTimeoutMillis, final Throwable cause)
{
super(message, cause);
this.skipTimeoutMillis = skipTimeoutMillis;
} | @Override
public String getSkipReason()
{
return getLocalizedMessage();
}
@Override
public boolean isSkip()
{
return true;
}
@Override
public int getSkipTimeoutMillis()
{
return skipTimeoutMillis;
}
@Override
public Exception getException()
{
return this;
}
/**
* No need to fill the log if this exception is thrown.
*/
protected boolean isLoggedInTrxManager()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\exceptions\WorkpackageSkipRequestException.java | 1 |
请完成以下Java代码 | private Method findMethod(String name, Class<?> declaringType, Class<?>[] params) {
Method method = null;
try {
method = declaringType.getMethod(name, params);
}
catch (NoSuchMethodException ignored) {
}
if (method == null) {
try {
method = declaringType.getDeclaredMethod(name, params);
}
catch (NoSuchMethodException ignored) {
}
}
return method;
}
@Override
public Method getMethod() {
return this.method;
}
@Override
public Object[] getArguments() {
return this.jp.getArgs();
} | @Override
public AccessibleObject getStaticPart() {
return this.method;
}
@Override
public Object getThis() {
return this.target;
}
@Override
public Object proceed() throws Throwable {
return this.jp.proceed();
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\aspectj\MethodInvocationAdapter.java | 1 |
请完成以下Java代码 | public class Pbkdf2Password4jPasswordEncoder extends AbstractValidatingPasswordEncoder {
private static final String DELIMITER = ":";
private static final int DEFAULT_SALT_LENGTH = 32;
private final PBKDF2Function pbkdf2Function;
private final SecureRandom secureRandom;
private final int saltLength;
/**
* Constructs a PBKDF2 password encoder using the default PBKDF2 configuration from
* Password4j's AlgorithmFinder.
*/
public Pbkdf2Password4jPasswordEncoder() {
this(AlgorithmFinder.getPBKDF2Instance());
}
/**
* Constructs a PBKDF2 password encoder with a custom PBKDF2 function.
* @param pbkdf2Function the PBKDF2 function to use for encoding passwords, must not
* be null
* @throws IllegalArgumentException if pbkdf2Function is null
*/
public Pbkdf2Password4jPasswordEncoder(PBKDF2Function pbkdf2Function) {
this(pbkdf2Function, DEFAULT_SALT_LENGTH);
}
/**
* Constructs a PBKDF2 password encoder with a custom PBKDF2 function and salt length.
* @param pbkdf2Function the PBKDF2 function to use for encoding passwords, must not
* be null
* @param saltLength the length of the salt in bytes, must be positive
* @throws IllegalArgumentException if pbkdf2Function is null or saltLength is not
* positive
*/
public Pbkdf2Password4jPasswordEncoder(PBKDF2Function pbkdf2Function, int saltLength) {
Assert.notNull(pbkdf2Function, "pbkdf2Function cannot be null");
Assert.isTrue(saltLength > 0, "saltLength must be positive");
this.pbkdf2Function = pbkdf2Function;
this.saltLength = saltLength;
this.secureRandom = new SecureRandom();
}
@Override
protected String encodeNonNullPassword(String rawPassword) {
byte[] salt = new byte[this.saltLength];
this.secureRandom.nextBytes(salt);
Hash hash = Password.hash(rawPassword).addSalt(salt).with(this.pbkdf2Function);
String encodedSalt = Base64.getEncoder().encodeToString(salt);
String encodedHash = hash.getResult(); | return encodedSalt + DELIMITER + encodedHash;
}
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
if (!encodedPassword.contains(DELIMITER)) {
return false;
}
String[] parts = encodedPassword.split(DELIMITER, 2);
if (parts.length != 2) {
return false;
}
try {
byte[] salt = Base64.getDecoder().decode(parts[0]);
String expectedHash = parts[1];
Hash hash = Password.hash(rawPassword).addSalt(salt).with(this.pbkdf2Function);
return expectedHash.equals(hash.getResult());
}
catch (IllegalArgumentException ex) {
// Invalid Base64 encoding
return false;
}
}
@Override
protected boolean upgradeEncodingNonNull(String encodedPassword) {
// For now, we'll return false to maintain existing behavior
// This could be enhanced in the future to check if the encoding parameters
// match the current configuration
return false;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password4j\Pbkdf2Password4jPasswordEncoder.java | 1 |
请完成以下Java代码 | protected Date calculateNextTimer(JobEntity timerEntity, VariableScope variableScope) {
BusinessCalendar businessCalendar = getProcessEngineConfiguration()
.getBusinessCalendarManager()
.getBusinessCalendar(
getBusinessCalendarName(
TimerEventHandler.geCalendarNameFromConfiguration(timerEntity.getJobHandlerConfiguration()),
variableScope
)
);
return businessCalendar.resolveDuedate(timerEntity.getRepeat(), timerEntity.getMaxIterations());
}
protected int calculateRepeatValue(JobEntity timerEntity) {
int times = -1;
List<String> expression = asList(timerEntity.getRepeat().split("/"));
if (expression.size() > 1 && expression.get(0).startsWith("R") && expression.get(0).length() > 1) {
times = Integer.parseInt(expression.get(0).substring(1));
if (times > 0) {
times--;
}
}
return times;
}
protected String getBusinessCalendarName(String calendarName, VariableScope variableScope) {
String businessCalendarName = CycleBusinessCalendar.NAME;
if (StringUtils.isNotEmpty(calendarName)) {
businessCalendarName = (String) Context.getProcessEngineConfiguration() | .getExpressionManager()
.createExpression(calendarName)
.getValue(variableScope);
}
return businessCalendarName;
}
protected TimerJobDataManager getDataManager() {
return jobDataManager;
}
public void setJobDataManager(TimerJobDataManager jobDataManager) {
this.jobDataManager = jobDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntityManagerImpl.java | 1 |
请完成以下Java代码 | public ImmutableList<HUDescriptor> createHuDescriptorsForMovementLine(
@NonNull final I_M_MovementLine movementLine,
final boolean deleted)
{
return createHUDescriptorsUsingHuAssignments(movementLine, deleted);
}
private ImmutableList<HUDescriptor> createHUDescriptorsUsingHuAssignments(
@NonNull final Object huReferencedModel,
final boolean deleted)
{
final List<HuAssignment> huAssignments = huAssignmentDAO.retrieveLowLevelHUAssignmentsForModel(huReferencedModel);
final ImmutableList.Builder<HUDescriptor> result = ImmutableList.builder();
for (final HuAssignment huAssignment : huAssignments)
{
result.addAll(huDescriptorService.createHuDescriptors(huAssignment.getLowestLevelHU(), deleted));
}
return result.build();
}
@VisibleForTesting
@Builder(builderMethodName = "newMaterialDescriptors", builderClassName = "_MaterialDescriptorsBuilder")
private Map<MaterialDescriptor, Collection<HUDescriptor>> createMaterialDescriptors(
@NonNull final TransactionDescriptor transaction,
@Nullable final BPartnerId customerId,
@Nullable final BPartnerId vendorId,
@NonNull final Collection<HUDescriptor> huDescriptors)
{
// aggregate HUDescriptors based on their product & attributes
final ImmutableListMultimap<ProductDescriptor, HUDescriptor> //
huDescriptorsByProduct = Multimaps.index(huDescriptors, HUDescriptor::getProductDescriptor);
final ImmutableMap.Builder<MaterialDescriptor, Collection<HUDescriptor>> result = ImmutableMap.builder();
for (final Map.Entry<ProductDescriptor, Collection<HUDescriptor>> entry : huDescriptorsByProduct.asMap().entrySet())
{
final ProductDescriptor productDescriptor = entry.getKey();
final Collection<HUDescriptor> huDescriptorsForCurrentProduct = entry.getValue();
final BigDecimal quantity = huDescriptorsForCurrentProduct
.stream() | .map(HUDescriptor::getQuantity)
.map(qty -> transaction.getMovementQty().signum() >= 0 ? qty : qty.negate()) // set signum according to transaction.movementQty
.reduce(BigDecimal.ZERO, BigDecimal::add);
final MaterialDescriptor materialDescriptor = MaterialDescriptor.builder()
.warehouseId(transaction.getWarehouseId())
.locatorId(transaction.getLocatorId())
.date(transaction.getTransactionDate())
.productDescriptor(productDescriptor)
.customerId(customerId)
.vendorId(vendorId)
.quantity(quantity)
.build();
result.put(materialDescriptor, huDescriptorsForCurrentProduct);
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\HUDescriptorsFromHUAssignmentService.java | 1 |
请完成以下Java代码 | public class RemoveProcessVariablesPayload implements Payload {
private String id;
private String processInstanceId;
private List<String> variableNames = new ArrayList<>();
public RemoveProcessVariablesPayload() {
this.id = UUID.randomUUID().toString();
}
public RemoveProcessVariablesPayload(String processInstanceId, List<String> variableNames) {
this();
this.processInstanceId = processInstanceId;
this.variableNames = variableNames;
}
@Override
public String getId() {
return id;
} | public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public List<String> getVariableNames() {
return variableNames;
}
public void setVariableNames(List<String> variableNames) {
this.variableNames = variableNames;
}
} | repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\RemoveProcessVariablesPayload.java | 1 |
请完成以下Java代码 | public void validate(Node xmlToValidate) throws InvalidDDFFileException {
try {
validate(new DOMSource(xmlToValidate));
} catch (SAXException | IOException e) {
throw new InvalidDDFFileException(e);
}
}
/**
* Validate a XML {@link Source} against the embedded LWM2M Schema.
*
* @param xmlToValidate an XML source to validate
* @throws SAXException see {@link Validator#validate(Source)}
* @throws IOException see {@link Validator#validate(Source)}
*/
public void validate(Source xmlToValidate) throws SAXException, IOException {
Validator validator = getEmbeddedLwM2mSchema().newValidator();
validator.validate(xmlToValidate);
}
/**
* Get the Embedded the LWM2M.xsd Schema.
*
* @throws SAXException see {@link SchemaFactory#newSchema(Source)}
*/
protected Schema getEmbeddedLwM2mSchema() throws SAXException {
InputStream inputStream = DDFFileValidator.class.getResourceAsStream(schema);
Source source = new StreamSource(inputStream);
SchemaFactory schemaFactory = createSchemaFactory();
return schemaFactory.newSchema(source);
}
protected SchemaFactory createSchemaFactory() {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
try {
// Create Safe SchemaFactory (not vulnerable to XXE Attacks) | // --------------------------------------------------------
// There is several recommendation from different source we try to apply all, even if some are maybe
// redundant.
// from :
// https://semgrep.dev/docs/cheat-sheets/java-xxe/
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// from :
// https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#schemafactory
// factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
// factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
} catch (SAXNotRecognizedException | SAXNotSupportedException e) {
throw new IllegalStateException("Unable to create SchemaFactory", e);
}
return factory;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\util\TbDefaultDDFFileValidator.java | 1 |
请完成以下Java代码 | public DmnDecisionQuery orderByDecisionVersion() {
return orderBy(DecisionQueryProperty.DECISION_VERSION);
}
@Override
public DmnDecisionQuery orderByDecisionName() {
return orderBy(DecisionQueryProperty.DECISION_NAME);
}
@Override
public DmnDecisionQuery orderByTenantId() {
return orderBy(DecisionQueryProperty.DECISION_TENANT_ID);
}
@Override
public DmnDecisionQuery orderByDecisionType() {
return orderBy(DecisionQueryProperty.DECISION_TYPE);
}
// results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionCountByQueryCriteria(this);
}
@Override
public List<DmnDecision> executeList(CommandContext commandContext) {
return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getDecisionId() {
return decisionId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
}
public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() { | return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getDecisionType() {
return decisionType;
}
public String getDecisionTypeLike() {
return decisionTypeLike;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DecisionQueryImpl.java | 1 |
请完成以下Java代码 | public <T> List<T> getDeployedArtifacts(Class<T> clazz) {
for (Class<?> deployedArtifactsClass : deployedArtifacts.keySet()) {
if (clazz.isAssignableFrom(deployedArtifactsClass)) {
return (List<T>) deployedArtifacts.get(deployedArtifactsClass);
}
}
return null;
}
// getters and setters ////////////////////////////////////////////////////////
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
}
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isNew() {
return isNew; | }
public void setNew(boolean isNew) {
this.isNew = isNew;
}
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getProjectReleaseVersion() {
return projectReleaseVersion;
}
public void setProjectReleaseVersion(String projectReleaseVersion) {
this.projectReleaseVersion = projectReleaseVersion;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java | 1 |
请完成以下Java代码 | public static class ActorCreator extends ContextBasedCreator {
private static final long serialVersionUID = 1L;
private final TenantId tenantId;
private final RuleChain ruleChain;
public ActorCreator(ActorSystemContext context, TenantId tenantId, RuleChain ruleChain) {
super(context);
this.tenantId = tenantId;
this.ruleChain = ruleChain;
}
@Override
public TbActorId createActorId() {
return new TbEntityActorId(ruleChain.getId());
}
@Override
public TbActor createActor() {
return new RuleChainActor(context, tenantId, ruleChain);
}
} | @Override
protected RuleChainId getRuleChainId() {
return ruleChain.getId();
}
@Override
protected String getRuleChainName() {
return ruleChain.getName();
}
@Override
protected long getErrorPersistFrequency() {
return systemContext.getRuleChainErrorPersistFrequency();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleChainActor.java | 1 |
请完成以下Java代码 | private CustomizedWindowInfo retrieveCustomizedWindowInfo(final ResultSet rs) throws SQLException
{
return CustomizedWindowInfo.builder()
.customizationWindowId(AdWindowId.ofRepoId(rs.getInt(I_AD_Window.COLUMNNAME_AD_Window_ID)))
.customizationWindowCaption(retrieveWindowCaption(rs))
.baseWindowId(AdWindowId.ofRepoId(rs.getInt(I_AD_Window.COLUMNNAME_Overrides_Window_ID)))
.overrideInMenu(StringUtils.toBoolean(rs.getString(I_AD_Window.COLUMNNAME_IsOverrideInMenu)))
.build();
}
private static ImmutableTranslatableString retrieveWindowCaption(final ResultSet rs) throws SQLException
{
final ImmutableTranslatableString.ImmutableTranslatableStringBuilder result = ImmutableTranslatableString.builder()
.defaultValue(rs.getString(I_AD_Window.COLUMNNAME_Name));
final Array sqlArray = rs.getArray("name_trls");
if (sqlArray != null)
{
final String[][] trls = (String[][])sqlArray.getArray();
for (final String[] languageAndName : trls)
{
final String adLanguage = languageAndName[0];
final String name = languageAndName[1];
result.trl(adLanguage, name);
}
}
return result.build();
}
@Override
public void assertNoCycles(@NonNull final AdWindowId adWindowId)
{
final LinkedHashSet<AdWindowId> seenWindowIds = new LinkedHashSet<>();
AdWindowId currentWindowId = adWindowId;
while (currentWindowId != null)
{ | if (!seenWindowIds.add(currentWindowId))
{
throw new AdempiereException("Avoid cycles in customization window chain: " + seenWindowIds);
}
currentWindowId = retrieveBaseWindowId(currentWindowId);
}
}
@Nullable
private AdWindowId retrieveBaseWindowId(@NonNull final AdWindowId customizationWindowId)
{
final String sql = "SELECT " + I_AD_Window.COLUMNNAME_Overrides_Window_ID
+ " FROM " + I_AD_Window.Table_Name
+ " WHERE " + I_AD_Window.COLUMNNAME_AD_Window_ID + "=?";
final int baseWindowRepoId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, customizationWindowId);
return AdWindowId.ofRepoIdOrNull(baseWindowRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\SqlCustomizedWindowInfoMapRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ScopesController {
public static final Logger LOG = LoggerFactory.getLogger(ScopesController.class);
@Resource(name = "requestScopedBean")
HelloMessageGenerator requestScopedBean;
@Resource(name = "sessionScopedBean")
HelloMessageGenerator sessionScopedBean;
@Resource(name = "applicationScopedBean")
HelloMessageGenerator applicationScopedBean;
@RequestMapping("/scopes/request")
public String getRequestScopeMessage(final Model model) {
model.addAttribute("previousMessage", requestScopedBean.getMessage());
requestScopedBean.setMessage("Request Scope Message!");
model.addAttribute("currentMessage", requestScopedBean.getMessage());
return "scopesExample";
} | @RequestMapping("/scopes/session")
public String getSessionScopeMessage(final Model model) {
model.addAttribute("previousMessage", sessionScopedBean.getMessage());
sessionScopedBean.setMessage("Session Scope Message!");
model.addAttribute("currentMessage", sessionScopedBean.getMessage());
return "scopesExample";
}
@RequestMapping("/scopes/application")
public String getApplicationScopeMessage(final Model model) {
model.addAttribute("previousMessage", applicationScopedBean.getMessage());
applicationScopedBean.setMessage("Application Scope Message!");
model.addAttribute("currentMessage", applicationScopedBean.getMessage());
return "scopesExample";
}
} | repos\tutorials-master\spring-core\src\main\java\com\baeldung\beanscopes\ScopesController.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final boolean foundAtLeastOneUnprocessedSchedule = context.streamSelectedModels(I_M_ShipmentSchedule.class)
.anyMatch(sched -> sched.isActive() && !sched.isProcessed());
return ProcessPreconditionsResolution.acceptIf(foundAtLeastOneUnprocessedSchedule);
}
@Override
protected String doIt() throws Exception
{
final IQueryFilter<I_M_ShipmentSchedule> queryFilters = createShipmentSchedulesQueryFilters();
Check.assumeNotNull(queryFilters, "Shipment Schedule queryFilters shall not be null");
final ShipmentScheduleWorkPackageParameters workPackageParameters = ShipmentScheduleWorkPackageParameters.builder()
.adPInstanceId(getPinstanceId())
.queryFilters(queryFilters)
.quantityType(quantityType)
.completeShipments(isCompleteShipments)
.isShipmentDateToday(isShipToday)
.build();
final Result result = ShipmentScheduleEnqueuer.newInstance(getCtx(), getTrxName())
.createWorkpackages(workPackageParameters);
return "@Created@: " + result.getEnqueuedPackagesCount() + " @" + I_C_Queue_WorkPackage.COLUMNNAME_C_Queue_WorkPackage_ID + "@; @Skip@ " + result.getSkippedPackagesCount();
}
@NonNull
private IQueryFilter<I_M_ShipmentSchedule> createShipmentSchedulesQueryFilters()
{
final ICompositeQueryFilter<I_M_ShipmentSchedule> filters = queryBL.createCompositeQueryFilter(I_M_ShipmentSchedule.class);
filters.addOnlyActiveRecordsFilter(); | //
// Filter only selected shipment schedules
if (Ini.isSwingClient())
{
final IQueryFilter<I_M_ShipmentSchedule> selectionFilter = getProcessInfo().getQueryFilterOrElseTrue();
filters.addFilter(selectionFilter);
}
else
{
final IQueryFilter<I_M_ShipmentSchedule> selectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (selectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
filters.addFilter(selectionFilter);
}
return shipmentService.createShipmentScheduleEnqueuerQueryFilters(filters, nowInstant);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\process\M_ShipmentSchedule_EnqueueSelection.java | 1 |
请完成以下Java代码 | public final class MaximumAllowableTagsMeterFilter implements MeterFilter {
private final Log logger;
private final AtomicBoolean alreadyWarned = new AtomicBoolean();
private final String meterNamePrefix;
private final int maximumTagValues;
private final String tagKey;
private final Supplier<String> message;
private final Set<String> observedTagValues = ConcurrentHashMap.newKeySet();
/**
* Create a new {@link MaximumAllowableTagsMeterFilter} with an upper bound on the
* number of tags produced by matching metrics.
* @param meterNamePrefix the prefix of the meter name to apply the filter to
* @param tagKey the tag to place an upper bound on
* @param maximumTagValues the total number of tag values that are allowable
*/
public MaximumAllowableTagsMeterFilter(String meterNamePrefix, String tagKey, int maximumTagValues) {
this(meterNamePrefix, tagKey, maximumTagValues, (String) null);
}
/**
* Create a new {@link MaximumAllowableTagsMeterFilter} with an upper bound on the
* number of tags produced by matching metrics.
* @param meterNamePrefix the prefix of the meter name to apply the filter to
* @param tagKey the tag to place an upper bound on
* @param maximumTagValues the total number of tag values that are allowable
* @param hint an additional hint to add to the logged message or {@code null}
*/
public MaximumAllowableTagsMeterFilter(String meterNamePrefix, String tagKey, int maximumTagValues,
@Nullable String hint) {
this(null, meterNamePrefix, tagKey, maximumTagValues,
() -> String.format("Reached the maximum number of '%s' tags for '%s'.%s", tagKey, meterNamePrefix,
(hint != null) ? " " + hint : ""));
}
private MaximumAllowableTagsMeterFilter(@Nullable Log logger, String meterNamePrefix, String tagKey,
int maximumTagValues, Supplier<String> message) {
Assert.notNull(message, "'message' must not be null");
Assert.isTrue(maximumTagValues >= 0, "'maximumTagValues' must be positive");
this.logger = (logger != null) ? logger : LogFactory.getLog(MaximumAllowableTagsMeterFilter.class);
this.meterNamePrefix = meterNamePrefix;
this.maximumTagValues = maximumTagValues;
this.tagKey = tagKey;
this.message = message; | }
@Override
public MeterFilterReply accept(Id id) {
if (this.meterNamePrefix == null) {
return logAndDeny();
}
String tagValue = id.getName().startsWith(this.meterNamePrefix) ? id.getTag(this.tagKey) : null;
if (tagValue != null && !this.observedTagValues.contains(tagValue)) {
if (this.observedTagValues.size() >= this.maximumTagValues) {
return logAndDeny();
}
this.observedTagValues.add(tagValue);
}
return MeterFilterReply.NEUTRAL;
}
private MeterFilterReply logAndDeny() {
if (this.logger.isWarnEnabled() && this.alreadyWarned.compareAndSet(false, true)) {
this.logger.warn(this.message.get());
}
return MeterFilterReply.DENY;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\MaximumAllowableTagsMeterFilter.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.