instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public List<HistoricEntityLink> getHistoricEntityLinkChildrenForCaseInstance(String caseInstanceId) {
return commandExecutor.execute(new GetHistoricEntityLinkChildrenForCaseInstanceCmd(caseInstanceId));
}
@Override
public List<HistoricEntityLink> getHistoricEntityLinkChildrenWithSameRootAsCaseInstance(String caseInstanceId) {
return commandExecutor.execute(new GetHistoricEntityLinkChildrenWithSameRootAsCaseInstanceCmd(caseInstanceId));
}
@Override
public List<HistoricEntityLink> getHistoricEntityLinkParentsForCaseInstance(String caseInstanceId) {
return commandExecutor.execute(new GetHistoricEntityLinkParentsForCaseInstanceCmd(caseInstanceId));
}
@Override
public List<HistoricEntityLink> getHistoricEntityLinkChildrenForTask(String taskId) {
return commandExecutor.execute(new GetHistoricEntityLinkChildrenForTaskCmd(taskId));
}
@Override
public List<HistoricEntityLink> getHistoricEntityLinkParentsForTask(String taskId) {
return commandExecutor.execute(new GetHistoricEntityLinkParentsForTaskCmd(taskId));
}
@Override
public void deleteHistoricTaskLogEntry(long logNumber) {
commandExecutor.execute(new CmmnDeleteHistoricTaskLogEntryCmd(logNumber, configuration));
}
@Override
public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder(TaskInfo task) {
return new HistoricTaskLogEntryBuilderImpl(commandExecutor, task, configuration.getTaskServiceConfiguration());
}
|
@Override
public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder() {
return new HistoricTaskLogEntryBuilderImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
@Override
public HistoricTaskLogEntryQuery createHistoricTaskLogEntryQuery() {
return new HistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
@Override
public NativeHistoricTaskLogEntryQuery createNativeHistoricTaskLogEntryQuery() {
return new NativeHistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnHistoryServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ParentAwareNamingStrategy extends MetadataNamingStrategy implements ApplicationContextAware {
@SuppressWarnings("NullAway.Init")
private ApplicationContext applicationContext;
private boolean ensureUniqueRuntimeObjectNames;
public ParentAwareNamingStrategy(JmxAttributeSource attributeSource) {
super(attributeSource);
}
/**
* Set if unique runtime object names should be ensured.
* @param ensureUniqueRuntimeObjectNames {@code true} if unique names should be
* ensured.
*/
public void setEnsureUniqueRuntimeObjectNames(boolean ensureUniqueRuntimeObjectNames) {
this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
ObjectName name = super.getObjectName(managedBean, beanKey);
if (this.ensureUniqueRuntimeObjectNames) {
return JmxUtils.appendIdentityToObjectName(name, managedBean);
}
if (parentContextContainsSameBean(this.applicationContext, beanKey)) {
return appendToObjectName(name, "context", ObjectUtils.getIdentityHexString(this.applicationContext));
}
return name;
}
|
private boolean parentContextContainsSameBean(ApplicationContext context, @Nullable String beanKey) {
if (context.getParent() == null) {
return false;
}
try {
ApplicationContext parent = this.applicationContext.getParent();
Assert.state(parent != null, "'parent' must not be null");
Assert.state(beanKey != null, "'beanKey' must not be null");
parent.getBean(beanKey);
return true;
}
catch (BeansException ex) {
return parentContextContainsSameBean(context.getParent(), beanKey);
}
}
private ObjectName appendToObjectName(ObjectName name, String key, String value)
throws MalformedObjectNameException {
Hashtable<String, String> keyProperties = name.getKeyPropertyList();
keyProperties.put(key, value);
return ObjectNameManager.getInstance(name.getDomain(), keyProperties);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\jmx\ParentAwareNamingStrategy.java
| 2
|
请完成以下Java代码
|
public static Attributes ofList(final List<Attribute> list)
{
return list.isEmpty() ? EMPTY : new Attributes(list);
}
public boolean hasAttribute(final @NonNull AttributeCode attributeCode)
{
return byCode.containsKey(attributeCode);
}
@NonNull
public Attribute getAttribute(@NonNull final AttributeCode attributeCode)
{
final Attribute attribute = byCode.get(attributeCode);
if (attribute == null)
{
throw new AdempiereException("No attribute `" + attributeCode + "` found in " + byCode.keySet());
}
return attribute;
}
public List<Attribute> getAttributes() {return list;}
|
public Attributes retainOnly(@NonNull final Set<AttributeCode> attributeCodes, @NonNull final Attributes fallback)
{
Check.assumeNotEmpty(attributeCodes, "attributeCodes is not empty");
final ArrayList<Attribute> newList = new ArrayList<>();
for (AttributeCode attributeCode : attributeCodes)
{
if (hasAttribute(attributeCode))
{
newList.add(getAttribute(attributeCode));
}
else if (fallback.hasAttribute(attributeCode))
{
newList.add(fallback.getAttribute(attributeCode));
}
}
return ofList(newList);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\Attributes.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void beforeDelete(final I_C_Order order)
{
salesOrderService.extractSalesProposalInfo(order).ifPresent(salesOrderService::unlinkProposalFromProject);
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void afterComplete(final I_C_Order order)
{
salesOrderService.extractSalesOrderInfo(order).ifPresent(salesOrderService::transferVHUsFromProjectToSalesOrderLine);
}
@DocValidate(timings = {
ModelValidator.TIMING_BEFORE_REACTIVATE,
ModelValidator.TIMING_BEFORE_VOID,
ModelValidator.TIMING_BEFORE_REVERSECORRECT })
public void beforeVoid(
@NonNull final I_C_Order order,
@NonNull final DocTimingType timing)
{
final RepairSalesProposalInfo proposal = salesOrderService.extractSalesProposalInfo(order).orElse(null);
if (proposal != null)
{
beforeVoid_Proposal(proposal, timing);
}
else
|
{
salesOrderService.extractSalesOrderInfo(order).ifPresent(this::beforeVoid_SalesOrder);
}
}
private void beforeVoid_Proposal(
@NonNull final RepairSalesProposalInfo proposal,
@NonNull final DocTimingType timing)
{
if (timing.isVoid() || timing.isReverse())
{
salesOrderService.unlinkProposalFromProject(proposal);
}
}
private void beforeVoid_SalesOrder(@NonNull final RepairSalesOrderInfo salesOrder)
{
salesOrderService.transferVHUsFromSalesOrderToProject(salesOrder);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\sales_order\interceptor\C_Order.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public MessageInstance sendFor(MessageInstance message, Operation operation, ConcurrentMap<QName, URL> overridenEndpointAddresses) throws Exception {
Object[] inArguments = this.getInArguments(message);
Object[] outArguments = this.getOutArguments(operation);
// For each out parameters, a value 'null' must be set in arguments passed to the Apache CXF API to invoke
// web-service operation
Object[] arguments = new Object[inArguments.length + outArguments.length];
System.arraycopy(inArguments, 0, arguments, 0, inArguments.length);
Object[] results = this.safeSend(arguments, overridenEndpointAddresses);
return this.createResponseMessage(results, operation);
}
private Object[] getInArguments(MessageInstance message) {
return message.getStructureInstance().toArray();
}
private Object[] getOutArguments(Operation operation) {
MessageDefinition outMessage = operation.getOutMessage();
if (outMessage != null) {
return outMessage.createInstance().getStructureInstance().toArray();
} else {
return new Object[] {};
}
}
|
private Object[] safeSend(Object[] arguments, ConcurrentMap<QName, URL> overridenEndpointAddresses) throws Exception {
Object[] results = null;
results = this.service.getClient().send(this.name, arguments, overridenEndpointAddresses);
if (results == null) {
results = new Object[] {};
}
return results;
}
private MessageInstance createResponseMessage(Object[] results, Operation operation) {
MessageInstance message = null;
MessageDefinition outMessage = operation.getOutMessage();
if (outMessage != null) {
message = outMessage.createInstance();
message.getStructureInstance().loadFrom(results);
}
return message;
}
public WSService getService() {
return this.service;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\webservice\WSOperation.java
| 2
|
请完成以下Java代码
|
public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds)
{
return rows.streamByIds(rowIds);
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO Auto-generated method stub
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return additionalRelatedProcessDescriptors;
|
}
/**
* @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}.
*/
@NonNull
public ShipmentScheduleId getCurrentShipmentScheduleId()
{
return currentShipmentScheduleId;
}
@Override
public void invalidateAll()
{
rows.invalidateAll();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static InvoiceId extractInvoiceId(@NonNull final I_C_InvoicePaySchedule record)
{
return InvoiceId.ofRepoId(record.getC_Invoice_ID());
}
private void save0(@NonNull final InvoicePaySchedule invoicePaySchedule)
{
final InvoiceId invoiceId = invoicePaySchedule.getInvoiceId();
final HashMap<InvoicePayScheduleLineId, I_C_InvoicePaySchedule> records = getRecordsByInvoiceId(invoiceId)
.stream()
.collect(GuavaCollectors.toHashMapByKey(record -> InvoicePayScheduleLineId.ofRepoId(record.getC_InvoicePaySchedule_ID())));
for (final InvoicePayScheduleLine line : invoicePaySchedule.getLines())
{
final I_C_InvoicePaySchedule record = records.remove(line.getId());
if (record == null)
{
throw new AdempiereException("No record found by " + line.getId());
}
InvoicePayScheduleConverter.updateRecord(record, line);
InterfaceWrapperHelper.save(record);
}
InterfaceWrapperHelper.deleteAll(records.values());
invalidateCache(invoiceId);
}
public void updateByIds(@NonNull final Set<InvoiceId> invoiceIds, @NonNull final Consumer<InvoicePaySchedule> updater)
{
if (invoiceIds.isEmpty()) {return;}
trxManager.runInThreadInheritedTrx(() -> {
warmUpByInvoiceIds(invoiceIds);
|
invoiceIds.forEach(invoiceId -> updateById0(invoiceId, updater));
});
}
public void updateById(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater)
{
trxManager.runInThreadInheritedTrx(() -> updateById0(invoiceId, updater));
}
private void updateById0(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater)
{
final InvoicePaySchedule paySchedules = loadByInvoiceId(invoiceId).orElse(null);
if (paySchedules == null)
{
return;
}
updater.accept(paySchedules);
save0(paySchedules);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\repository\InvoicePayScheduleLoaderAndSaver.java
| 2
|
请完成以下Java代码
|
public void setGroupIdIn(String[] groupIdIn) {
this.groupIdIn = groupIdIn;
}
@CamundaQueryParam(value="resourceType", converter = IntegerConverter.class)
public void setResourceType(int resourceType) {
this.resourceType = resourceType;
}
@CamundaQueryParam("resourceId")
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
protected AuthorizationQuery createNewQuery(ProcessEngine engine) {
return engine.getAuthorizationService().createAuthorizationQuery();
}
protected void applyFilters(AuthorizationQuery query) {
if (id != null) {
query.authorizationId(id);
}
if (type != null) {
query.authorizationType(type);
}
|
if (userIdIn != null) {
query.userIdIn(userIdIn);
}
if (groupIdIn != null) {
query.groupIdIn(groupIdIn);
}
if (resourceType != null) {
query.resourceType(resourceType);
}
if (resourceId != null) {
query.resourceId(resourceId);
}
}
@Override
protected void applySortBy(AuthorizationQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_RESOURCE_ID)) {
query.orderByResourceId();
} else if (sortBy.equals(SORT_BY_RESOURCE_TYPE)) {
query.orderByResourceType();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationQueryDto.java
| 1
|
请完成以下Java代码
|
public I_M_Product getM_Product()
{
return product;
}
@Override
public void setM_Product(final I_M_Product product)
{
this.product = product;
}
@Override
public String getName()
{
return name;
}
@Override
public void setName(final String name)
{
this.name = name;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public void setC_UOM(final I_C_UOM uom)
{
this.uom = uom;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public void setQty(final BigDecimal qty)
{
this.qty = qty;
}
@Override
public BigDecimal getQtyProjected()
{
return qtyProjected;
}
@Override
public void setQtyProjected(final BigDecimal qtyProjected)
{
this.qtyProjected = qtyProjected;
}
@Override
public BigDecimal getPercentage()
{
return percentage;
}
@Override
public void setPercentage(final BigDecimal percentage)
{
this.percentage = percentage;
}
|
@Override
public boolean isNegateQtyInReport()
{
return negateQtyInReport;
}
@Override
public void setNegateQtyInReport(final boolean negateQtyInReport)
{
this.negateQtyInReport = negateQtyInReport;
}
@Override
public String getComponentType()
{
return componentType;
}
@Override
public void setComponentType(final String componentType)
{
this.componentType = componentType;
}
@Override
public String getVariantGroup()
{
return variantGroup;
}
@Override
public void setVariantGroup(final String variantGroup)
{
this.variantGroup = variantGroup;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
handlingUnitsInfoProjected = handlingUnitsInfo;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfoProjected()
{
return handlingUnitsInfoProjected;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java
| 1
|
请完成以下Java代码
|
public boolean hasConfigurationForTopics(String[] topics) {
return this.topicAllowListManager.areAllowed(topics);
}
public TopicCreation forKafkaTopicAutoCreation() {
return this.kafkaTopicAutoCreationConfig;
}
public ListenerContainerFactoryResolver.Configuration forContainerFactoryResolver() {
return this.factoryResolverConfig;
}
public @Nullable EndpointHandlerMethod getDltHandlerMethod() {
return this.dltHandlerMethod;
}
public List<DestinationTopic.Properties> getDestinationTopicProperties() {
return this.destinationTopicProperties;
}
@Nullable
public Integer getConcurrency() {
return this.concurrency;
}
static class TopicCreation {
private final boolean shouldCreateTopics;
private final int numPartitions;
private final short replicationFactor;
TopicCreation(@Nullable Boolean shouldCreate, @Nullable Integer numPartitions, @Nullable Short replicationFactor) {
this.shouldCreateTopics = shouldCreate == null || shouldCreate;
this.numPartitions = numPartitions == null ? 1 : numPartitions;
this.replicationFactor = replicationFactor == null ? -1 : replicationFactor;
}
TopicCreation() {
this.shouldCreateTopics = true;
this.numPartitions = 1;
|
this.replicationFactor = -1;
}
TopicCreation(boolean shouldCreateTopics) {
this.shouldCreateTopics = shouldCreateTopics;
this.numPartitions = 1;
this.replicationFactor = -1;
}
public int getNumPartitions() {
return this.numPartitions;
}
public short getReplicationFactor() {
return this.replicationFactor;
}
public boolean shouldCreateTopics() {
return this.shouldCreateTopics;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfiguration.java
| 1
|
请完成以下Java代码
|
public String showHomePage(HttpServletRequest req, Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(HttpServletRequest req, Model model) {
addUserAttributes(model);
model.addAttribute("adminContent", "only admin can view this");
return "comparison/home";
}
private void addUserAttributes(Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null && !auth.getClass()
.equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
|
model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority()
.contains("USER")) {
model.addAttribute("role", "USER");
model.addAttribute("permission", "READ");
} else if (authority.getAuthority()
.contains("ADMIN")) {
model.addAttribute("role", "ADMIN");
model.addAttribute("permission", "READ WRITE");
}
}
}
}
}
|
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\springsecurity\web\SpringController.java
| 1
|
请完成以下Java代码
|
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryRelease(1);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(0);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
|
public static void main(String[] args) {
MutexLock lock = new MutexLock();
final User user = new User();
for (int i = 0; i < 100; i++) {
new Thread(() -> {
lock.lock();
try {
user.setAge(user.getAge() + 1);
System.out.println(user.getAge());
} finally {
lock.unlock();
}
}).start();
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\MutexLock.java
| 1
|
请完成以下Java代码
|
public class Cheque6CH {
@XmlElement(name = "ChqTp")
@XmlSchemaType(name = "string")
protected ChequeType2Code chqTp;
@XmlElement(name = "DlvryMtd")
protected ChequeDeliveryMethod1Choice dlvryMtd;
/**
* Gets the value of the chqTp property.
*
* @return
* possible object is
* {@link ChequeType2Code }
*
*/
public ChequeType2Code getChqTp() {
return chqTp;
}
/**
* Sets the value of the chqTp property.
*
* @param value
* allowed object is
* {@link ChequeType2Code }
*
*/
public void setChqTp(ChequeType2Code value) {
this.chqTp = value;
}
/**
* Gets the value of the dlvryMtd property.
*
* @return
* possible object is
|
* {@link ChequeDeliveryMethod1Choice }
*
*/
public ChequeDeliveryMethod1Choice getDlvryMtd() {
return dlvryMtd;
}
/**
* Sets the value of the dlvryMtd property.
*
* @param value
* allowed object is
* {@link ChequeDeliveryMethod1Choice }
*
*/
public void setDlvryMtd(ChequeDeliveryMethod1Choice value) {
this.dlvryMtd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\Cheque6CH.java
| 1
|
请完成以下Java代码
|
public class M_ProductPrice
{
/**
* Set {@link I_M_ProductPrice}'s C_UOM_ID to {@link I_M_Product}'s C_UOM_ID
*
* @param productPrice
* @param field
*/
@CalloutMethod(columnNames = { I_M_ProductPrice.COLUMNNAME_M_Product_ID })
public void onProductID(final I_M_ProductPrice productPrice, final ICalloutField field)
{
final ProductId productId = ProductId.ofRepoIdOrNull(productPrice.getM_Product_ID());
if (productId != null)
{
final UomId stockingUOMId = Services.get(IProductBL.class).getStockUOMId(productId);
productPrice.setC_UOM_ID(stockingUOMId.getRepoId());
}
}
@CalloutMethod(columnNames = { I_M_ProductPrice.COLUMNNAME_IsAttributeDependant })
public void onIsAttributeDependent(final I_M_ProductPrice productPrice)
{
if (!productPrice.isAttributeDependant())
{
return;
}
if (productPrice.getSeqNo() <= 0)
{
final int nextMatchSeqNo = Services.get(IPriceListDAO.class).retrieveNextMatchSeqNo(productPrice);
productPrice.setMatchSeqNo(nextMatchSeqNo);
}
}
@CalloutMethod(columnNames = { I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID })
public void onPriceListVersionId(final I_M_ProductPrice productPrice)
{
setTaxCategoryIdFromPriceListVersion(productPrice);
}
static void setTaxCategoryIdFromPriceListVersion(final I_M_ProductPrice productPrice)
{
|
final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoIdOrNull(productPrice.getM_PriceList_Version_ID());
if (priceListVersionId == null)
{
return;
}
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
final TaxCategoryId defaultTaxCategoryId = priceListsRepo
.getDefaultTaxCategoryByPriceListVersionId(priceListVersionId)
.orElse(null);
if (defaultTaxCategoryId == null)
{
return;
}
productPrice.setC_TaxCategory_ID(defaultTaxCategoryId.getRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\pricing\callout\M_ProductPrice.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* Attribute AD_Reference_ID=540749
* Reference name: C_BPartner_Attribute
*/
public static final int ATTRIBUTE_AD_Reference_ID=540749;
/** Verband D = K_Verband_D */
public static final String ATTRIBUTE_VerbandD = "K_Verband_D";
/** Firma = K_Firma */
public static final String ATTRIBUTE_Firma = "K_Firma";
/** Bildungsinstitut = K_Bildungsinstitut */
public static final String ATTRIBUTE_Bildungsinstitut = "K_Bildungsinstitut";
/** Schule = K_Schule */
public static final String ATTRIBUTE_Schule = "K_Schule";
/** Oberstufe = K_Oberstufe */
public static final String ATTRIBUTE_Oberstufe = "K_Oberstufe";
/** Gymnasium = K_Gymnasium */
public static final String ATTRIBUTE_Gymnasium = "K_Gymnasium";
/** BIZ_Berufsberatung = K_BIZ_Berufsberatung */
public static final String ATTRIBUTE_BIZ_Berufsberatung = "K_BIZ_Berufsberatung";
/** Partner = K_Partner */
public static final String ATTRIBUTE_Partner = "K_Partner";
/** Lieferant = K_Lieferant */
public static final String ATTRIBUTE_Lieferant = "K_Lieferant";
/** Behörden = K_Behörden */
public static final String ATTRIBUTE_Behoerden = "K_Behörden";
/** Sponsor = K_Sponsor */
public static final String ATTRIBUTE_Sponsor = "K_Sponsor";
/** Massenmedien = K_Massenmedien */
public static final String ATTRIBUTE_Massenmedien = "K_Massenmedien";
@Override
public void setAttribute (final java.lang.String Attribute)
{
set_Value (COLUMNNAME_Attribute, Attribute);
}
@Override
public java.lang.String getAttribute()
{
return get_ValueAsString(COLUMNNAME_Attribute);
}
@Override
|
public void setC_BPartner_Attribute_ID (final int C_BPartner_Attribute_ID)
{
if (C_BPartner_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute_ID, C_BPartner_Attribute_ID);
}
@Override
public int getC_BPartner_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Attribute_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Attribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserOperationLogRestServiceImpl implements UserOperationLogRestService {
protected ObjectMapper objectMapper;
protected ProcessEngine processEngine;
public UserOperationLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) {
this.objectMapper = objectMapper;
this.processEngine = processEngine;
}
@Override
public CountResultDto queryUserOperationCount(UriInfo uriInfo) {
UserOperationLogQueryDto queryDto = new UserOperationLogQueryDto(objectMapper, uriInfo.getQueryParameters());
UserOperationLogQuery query = queryDto.toQuery(processEngine);
return new CountResultDto(query.count());
}
@Override
public List<UserOperationLogEntryDto> queryUserOperationEntries(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
UserOperationLogQueryDto queryDto = new UserOperationLogQueryDto(objectMapper, uriInfo.getQueryParameters());
UserOperationLogQuery query = queryDto.toQuery(processEngine);
return UserOperationLogEntryDto.map(QueryUtil.list(query, firstResult, maxResults));
}
|
@Override
public Response setAnnotation(String operationId, AnnotationDto annotationDto) {
String annotation = annotationDto.getAnnotation();
processEngine.getHistoryService()
.setAnnotationForOperationLogById(operationId, annotation);
return Response.noContent().build();
}
@Override
public Response clearAnnotation(String operationId) {
processEngine.getHistoryService()
.clearAnnotationForOperationLogById(operationId);
return Response.noContent().build();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\UserOperationLogRestServiceImpl.java
| 2
|
请完成以下Java代码
|
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
|
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", deploymentId=" + deploymentId
+ ", tenantId=" + tenantId
+ ", type=" + type
+ ", createTime=" + createTime
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void saveAndPush(@NonNull final WeekSupply weeklySupply)
{
weekSupplyRepository.save(weeklySupply);
senderToMetasfreshService.syncAfterCommit().add(weeklySupply);
}
@Override
public Product getProductById(final long productId)
{
return productRepository.getOne(productId);
}
@Override
public void importPlanningSupply(@NonNull final ImportPlanningSupplyRequest request)
{
final BPartner bpartner = request.getBpartner();
final ContractLine contractLine = request.getContractLine();
final Product product = productRepository.findByUuid(request.getProduct_uuid());
final LocalDate day = request.getDate();
final BigDecimal qty = request.getQty();
ProductSupply productSupply = productSupplyRepository.findByProductAndBpartnerAndDay(product, bpartner, DateUtils.toSqlDate(day));
final boolean isNew;
if (productSupply == null)
{
isNew = true;
productSupply = ProductSupply.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.product(product)
.day(day)
.build();
}
else
{
isNew = false;
}
//
// Contract line
if (!isNew)
{
final ContractLine contractLineOld = productSupply.getContractLine();
if (!Objects.equals(contractLine, contractLineOld))
{
logger.warn("Changing contract line {}->{} for {} because of planning supply: {}", contractLineOld, contractLine, productSupply, request);
}
productSupply.setContractLine(contractLine);
}
|
//
// Quantity
if (!isNew)
{
final BigDecimal qtyOld = productSupply.getQty();
if (qty.compareTo(qtyOld) != 0)
{
logger.warn("Changing quantity {}->{} for {} because of planning supply: {}", qtyOld, qty, productSupply, request);
}
}
productSupply.setQtyUserEntered(qty);
productSupply.setQty(qty);
//
// Save the product supply
saveAndPush(productSupply);
}
@Override
@Transactional
public void confirmUserEntries(@NonNull final User user)
{
final BPartner bpartner = user.getBpartner();
final List<ProductSupply> productSupplies = productSupplyRepository.findUnconfirmed(bpartner);
for (final ProductSupply productSupply : productSupplies)
{
productSupply.setQty(productSupply.getQtyUserEntered());
saveAndPush(productSupply);
}
}
@Override
public long getCountUnconfirmed(@NonNull final User user)
{
return productSupplyRepository.countUnconfirmed(user.getBpartner());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\ProductSuppliesService.java
| 2
|
请完成以下Java代码
|
public ProfileModel getProfileByUsername(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable UserName username) {
return ofNullable(jwtPayload)
.map(JWTPayload::getUserId)
.map(viewerId -> profileService.viewProfile(viewerId, username))
.map(ProfileModel::fromProfile)
.orElseGet(() -> fromProfile(profileService.viewProfile(username)));
}
@PostMapping("/{username}/follow")
public ProfileModel followUser(@AuthenticationPrincipal UserJWTPayload followerPayload,
@PathVariable UserName username) {
return fromProfile(
profileService.followAndViewProfile(followerPayload.getUserId(), username));
}
|
@DeleteMapping("/{username}/follow")
public ProfileModel unfollowUser(@AuthenticationPrincipal UserJWTPayload followerPayload,
@PathVariable UserName username) {
return fromProfile(
profileService.unfollowAndViewProfile(followerPayload.getUserId(), username)
);
}
@ResponseStatus(NOT_FOUND)
@ExceptionHandler(NoSuchElementException.class)
void handleNoSuchElementException(NoSuchElementException exception) {
// return NOT FOUND status
}
}
|
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\user\ProfileRestController.java
| 1
|
请完成以下Java代码
|
private DDOrderLineToAllocate toDDOrderLineToAllocate(@NonNull final I_DD_OrderLine_Or_Alternative ddOrderLineOrAlt)
{
final I_DD_OrderLine ddOrderLine;
final int ddOrderLineAlternativeId;
final AttributeSetInstanceId fromAsiId;
final AttributeSetInstanceId toAsiId;
if (InterfaceWrapperHelper.isInstanceOf(ddOrderLineOrAlt, I_DD_OrderLine.class))
{
ddOrderLineAlternativeId = -1;
ddOrderLine = InterfaceWrapperHelper.create(ddOrderLineOrAlt, I_DD_OrderLine.class);
fromAsiId = AttributeSetInstanceId.ofRepoIdOrNone(ddOrderLine.getM_AttributeSetInstance_ID());
toAsiId = AttributeSetInstanceId.ofRepoIdOrNone(ddOrderLine.getM_AttributeSetInstanceTo_ID());
}
else if (InterfaceWrapperHelper.isInstanceOf(ddOrderLineOrAlt, I_DD_OrderLine_Alternative.class))
{
final I_DD_OrderLine_Alternative ddOrderLineAlt = InterfaceWrapperHelper.create(ddOrderLineOrAlt, I_DD_OrderLine_Alternative.class);
ddOrderLineAlternativeId = ddOrderLineAlt.getDD_OrderLine_Alternative_ID();
ddOrderLine = ddOrderLineAlt.getDD_OrderLine();
fromAsiId = AttributeSetInstanceId.ofRepoIdOrNone(ddOrderLineAlt.getM_AttributeSetInstance_ID());
toAsiId = AttributeSetInstanceId.ofRepoIdOrNone(ddOrderLine.getM_AttributeSetInstanceTo_ID());
}
else
{
throw new AdempiereException("Invalid I_DD_OrderLine_Or_Alternative implementation passed; Expected " + I_DD_OrderLine.class + " or " + I_DD_OrderLine_Alternative.COLUMNNAME_AD_Client_ID + ", but was " + ddOrderLineOrAlt);
|
}
return DDOrderLineToAllocate.builder()
.uomConversionBL(uomConversionBL)
//
.ddOrderId(DDOrderId.ofRepoId(ddOrderLine.getDD_Order_ID()))
.ddOrderLineId(DDOrderLineId.ofRepoId(ddOrderLine.getDD_OrderLine_ID()))
.ddOrderLineAlternativeId(ddOrderLineAlternativeId)
.description(ddOrderLine.getDescription())
.pickFromLocatorId(warehouseBL.getLocatorIdByRepoId(ddOrderLine.getM_Locator_ID()))
.dropToLocatorId(warehouseBL.getLocatorIdByRepoId(ddOrderLine.getM_LocatorTo_ID()))
.productId(ProductId.ofRepoId(ddOrderLineOrAlt.getM_Product_ID()))
.fromAsiId(fromAsiId)
.toAsiId(toAsiId)
.qtyToShip(ddOrderService.getQtyToShip(ddOrderLineOrAlt))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\generate_from_hu\DDOrderLineToAllocateFactory.java
| 1
|
请完成以下Java代码
|
class DelayedLiveReloadTrigger implements Runnable {
private static final long SHUTDOWN_TIME = 1000;
private static final long SLEEP_TIME = 500;
private static final long TIMEOUT = 30000;
private static final Log logger = LogFactory.getLog(DelayedLiveReloadTrigger.class);
private final OptionalLiveReloadServer liveReloadServer;
private final ClientHttpRequestFactory requestFactory;
private final URI uri;
private long shutdownTime = SHUTDOWN_TIME;
private long sleepTime = SLEEP_TIME;
private long timeout = TIMEOUT;
DelayedLiveReloadTrigger(OptionalLiveReloadServer liveReloadServer, ClientHttpRequestFactory requestFactory,
String url) {
Assert.notNull(liveReloadServer, "'liveReloadServer' must not be null");
Assert.notNull(requestFactory, "'requestFactory' must not be null");
Assert.hasLength(url, "'url' must not be empty");
this.liveReloadServer = liveReloadServer;
this.requestFactory = requestFactory;
try {
this.uri = new URI(url);
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
}
protected void setTimings(long shutdown, long sleep, long timeout) {
this.shutdownTime = shutdown;
this.sleepTime = sleep;
this.timeout = timeout;
}
|
@Override
public void run() {
try {
Thread.sleep(this.shutdownTime);
long start = System.currentTimeMillis();
while (!isUp()) {
long runTime = System.currentTimeMillis() - start;
if (runTime > this.timeout) {
return;
}
Thread.sleep(this.sleepTime);
}
logger.info("Remote server has changed, triggering LiveReload");
this.liveReloadServer.triggerReload();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
private boolean isUp() {
try {
ClientHttpRequest request = createRequest();
try (ClientHttpResponse response = request.execute()) {
return response.getStatusCode() == HttpStatus.OK;
}
}
catch (Exception ex) {
return false;
}
}
private ClientHttpRequest createRequest() throws IOException {
return this.requestFactory.createRequest(this.uri, HttpMethod.GET);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\DelayedLiveReloadTrigger.java
| 1
|
请完成以下Java代码
|
public @Nullable String getMethod() {
return this.method;
}
@NullUnmarked
public void setMethod(String method) {
this.method = (method != null) ? method.toUpperCase(Locale.ENGLISH) : null;
}
private SecurityContext getContext() {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
String[] names = appContext.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = appContext.getBean(SecurityContextHolderStrategy.class);
return strategy.getContext();
}
return SecurityContextHolder.getContext();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler handler : handlers.values()) {
if (FilterInvocation.class
.equals(GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) {
return handler;
}
}
throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application "
|
+ "context. There must be at least one in order to support expressions in JSP 'authorize' tags.");
}
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
WebInvocationPrivilegeEvaluator privEvaluatorFromRequest = (WebInvocationPrivilegeEvaluator) getRequest()
.getAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE);
if (privEvaluatorFromRequest != null) {
return privEvaluatorFromRequest;
}
ApplicationContext ctx = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.isEmpty()) {
throw new IOException(
"No visible WebInvocationPrivilegeEvaluator instance could be found in the application "
+ "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags.");
}
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
}
}
|
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTag.java
| 1
|
请完成以下Java代码
|
public String getConditionsType()
{
return X_C_Flatrate_Conditions.TYPE_CONDITIONS_Subscription;
}
/**
* Set the quantity from the term.
*/
@Override
public Quantity calculateQtyEntered(@NonNull final I_C_Invoice_Candidate icRecord)
{
final UomId uomId = HandlerTools.retrieveUomId(icRecord);
final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(icRecord);
return new Quantity(
term.getPlannedQtyPerUnit(),
loadOutOfTrx(uomId, I_C_UOM.class));
}
@Override
public Consumer<I_C_Invoice_Candidate> getInvoiceScheduleSetterFunction(@NonNull final Consumer<I_C_Invoice_Candidate> defaultImplementation)
{
return defaultImplementation;
}
@Override
public Timestamp calculateDateOrdered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(invoiceCandidateRecord);
final Timestamp dateOrdered;
final boolean termHasAPredecessor = Services.get(IContractsDAO.class).termHasAPredecessor(term);
if (!termHasAPredecessor)
{
dateOrdered = term.getStartDate();
}
// If the term was extended (meaning that there is a predecessor term),
// C_Invoice_Candidate.DateOrdered should rather be the StartDate minus TermOfNoticeDuration/TermOfNoticeUnit
else
{
|
final Timestamp firstDayOfNewTerm = getGetExtentionDateOfNewTerm(term);
dateOrdered = firstDayOfNewTerm;
}
return dateOrdered;
}
/**
* For the given <code>term</code> and its <code>C_Flatrate_Transition</code> record, this method returns the term's start date minus the period specified by <code>TermOfNoticeDuration</code> and
* <code>TermOfNoticeUnit</code>.
*/
private static Timestamp getGetExtentionDateOfNewTerm(@NonNull final I_C_Flatrate_Term term)
{
final Timestamp startDateOfTerm = term.getStartDate();
final I_C_Flatrate_Conditions conditions = term.getC_Flatrate_Conditions();
final I_C_Flatrate_Transition transition = conditions.getC_Flatrate_Transition();
final String termOfNoticeUnit = transition.getTermOfNoticeUnit();
final int termOfNotice = transition.getTermOfNotice();
final Timestamp minimumDateToStart;
if (X_C_Flatrate_Transition.TERMOFNOTICEUNIT_MonatE.equals(termOfNoticeUnit))
{
minimumDateToStart = TimeUtil.addMonths(startDateOfTerm, termOfNotice * -1);
}
else if (X_C_Flatrate_Transition.TERMOFNOTICEUNIT_WocheN.equals(termOfNoticeUnit))
{
minimumDateToStart = TimeUtil.addWeeks(startDateOfTerm, termOfNotice * -1);
}
else if (X_C_Flatrate_Transition.TERMOFNOTICEUNIT_TagE.equals(termOfNoticeUnit))
{
minimumDateToStart = TimeUtil.addDays(startDateOfTerm, termOfNotice * -1);
}
else
{
Check.assume(false, "TermOfNoticeDuration " + transition.getTermOfNoticeUnit() + " doesn't exist");
minimumDateToStart = null; // code won't be reached
}
return minimumDateToStart;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\invoicecandidatehandler\FlatrateTermSubscription_Handler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public void setVariableNameLike(String variableNameLike) {
|
this.variableNameLike = variableNameLike;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class)
public List<QueryVariable> getVariables() {
return variables;
}
public void setVariables(List<QueryVariable> variables) {
this.variables = variables;
}
public void setExcludeLocalVariables(Boolean excludeLocalVariables) {
this.excludeLocalVariables = excludeLocalVariables;
}
public Boolean getExcludeLocalVariables() {
return excludeLocalVariables;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
public final boolean isReadonlyUI()
{
return huPIAttribute.isReadOnly();
}
@Override
public final boolean isDisplayedUI()
{
return huPIAttribute.isDisplayed();
}
@Override
public final boolean isMandatory()
{
return huPIAttribute.isMandatory();
}
@Override
public final int getDisplaySeqNo()
{
final int seqNo = huPIAttribute.getSeqNo();
|
if (seqNo > 0)
{
return seqNo;
}
// Fallback: if SeqNo was not set, return max int (i.e. show them last)
return Integer.MAX_VALUE;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return huPIAttribute.isOnlyIfInProductAttributeSet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractHUAttributeValue.java
| 1
|
请完成以下Java代码
|
public List<ReceiptScheduleId> retainLUQtySchedules(@NonNull final List<ReceiptScheduleId> receiptSchedules)
{
return queryBL.createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addNotNull(I_C_OrderLine.COLUMNNAME_QtyLU)
.addCompareFilter(I_C_OrderLine.COLUMNNAME_QtyLU, CompareQueryFilter.Operator.GREATER, 0)
.andCollectChildren(I_M_ReceiptSchedule.COLUMNNAME_C_OrderLine_ID, I_M_ReceiptSchedule.class)
.addInArrayFilter(I_M_ReceiptSchedule.COLUMNNAME_M_ReceiptSchedule_ID, receiptSchedules)
.create()
.listIds(ReceiptScheduleId::ofRepoId);
}
@Override
@NonNull
public List<ReceiptScheduleId> listIdsByQuery(@NonNull final ReceiptScheduleQuery query)
{
return buildQuery(query)
.listIds(ReceiptScheduleId::ofRepoId);
}
@NonNull
@Override
public Optional<ReceiptScheduleId> getIdByQuery(@NonNull final ReceiptScheduleQuery query)
{
return buildQuery(query)
.firstIdOnlyOptional(ReceiptScheduleId::ofRepoId);
}
@NonNull
private IQuery<I_M_ReceiptSchedule> buildQuery(@NonNull final ReceiptScheduleQuery query)
{
final IQueryBuilder<I_M_ReceiptSchedule> builder = queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.addOnlyActiveRecordsFilter();
final ExternalSystemIdWithExternalIds externalSystemIdWithExternalIds = query.getExternalSystemIdWithExternalIds();
if (externalSystemIdWithExternalIds != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalSystem_ID, externalSystemIdWithExternalIds.getExternalSystemId().getRepoId());
final ExternalHeaderIdWithExternalLineIds externalIds = externalSystemIdWithExternalIds.getExternalHeaderIdWithExternalLineIds();
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalHeaderId, externalIds.getExternalHeaderId().getValue());
if (!Check.isEmpty(externalIds.getExternalLineIdsAsString()))
{
builder.addInArrayFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalLineId, externalIds.getExternalLineIdsAsString());
}
}
if (query.getOrderLineId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_C_OrderLine_ID, query.getOrderLineId());
}
if (query.getProductId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_Product_ID, query.getProductId());
}
|
if (query.getWarehouseId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID, query.getWarehouseId());
}
if (query.getOrgId() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID, query.getOrgId());
}
if (query.getAttributesKey() != null)
{
builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_AttributeSetInstance_ID, query.getAttributesKey().getAsString(), ASIQueryFilterModifier.instance);
}
// Filter by quantity
if (query.isOnlyNonZeroQty())
{
builder.addNotEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_QtyToMove, 0);
}
return builder.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleDAO.java
| 1
|
请完成以下Java代码
|
public int getSupportUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SupportUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* SystemStatus AD_Reference_ID=374
* Reference name: AD_System Status
*/
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
@Override
public void setSystemStatus (java.lang.String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
@Override
public java.lang.String getSystemStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SystemStatus);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
/** Set Version.
@param Version
Version of the table definition
*/
|
@Override
public void setVersion (java.lang.String Version)
{
set_ValueNoCheck (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
/** Set ZK WebUI URL.
@param WebUI_URL
ZK WebUI root URL
*/
@Override
public void setWebUI_URL (java.lang.String WebUI_URL)
{
set_Value (COLUMNNAME_WebUI_URL, WebUI_URL);
}
/** Get ZK WebUI URL.
@return ZK WebUI root URL
*/
@Override
public java.lang.String getWebUI_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java
| 1
|
请完成以下Java代码
|
public void autoDeployResources(Set<Resource> resources) {
// Only log the description of `Resource` objects since log libraries that serialize them and
// therefore consume the input stream make the deployment fail since the input stream has
// already been consumed.
Set<String> resourceDescriptions = resources.stream()
.filter(Objects::nonNull)
.map(Resource::getDescription)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
logInfo("021", "Auto-Deploying resources: {}", resourceDescriptions);
}
public void enterLicenseKey(String licenseKeySource) {
logInfo("030", "Setting up license key: {}", licenseKeySource);
}
|
public void enterLicenseKeyFailed(URL licenseKeyFile, Exception e) {
logWarn("031", "Failed setting up license key: {}", licenseKeyFile, e);
}
public void configureJobExecutorPool(Integer corePoolSize, Integer maxPoolSize) {
logInfo("040", "Setting up jobExecutor with corePoolSize={}, maxPoolSize:{}", corePoolSize, maxPoolSize);
}
public SpringBootStarterException exceptionDuringBinding(String message) {
return new SpringBootStarterException(exceptionMessage(
"050", message));
}
public void propertiesApplied(GenericProperties genericProperties) {
logDebug("051", "Properties bound to configuration: {}", genericProperties);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\SpringBootProcessEngineLogger.java
| 1
|
请完成以下Java代码
|
public <T> T getCustomMapper(Class<T> type) {
return sqlSession.getMapper(type);
}
// query factory methods ////////////////////////////////////////////////////
public DeploymentQueryImpl createDeploymentQuery() {
return new DeploymentQueryImpl();
}
public ModelQueryImpl createModelQueryImpl() {
return new ModelQueryImpl();
}
public ProcessDefinitionQueryImpl createProcessDefinitionQuery() {
return new ProcessDefinitionQueryImpl();
}
public ProcessInstanceQueryImpl createProcessInstanceQuery() {
return new ProcessInstanceQueryImpl();
}
public ExecutionQueryImpl createExecutionQuery() {
return new ExecutionQueryImpl();
}
public TaskQueryImpl createTaskQuery() {
return new TaskQueryImpl();
}
public JobQueryImpl createJobQuery() {
return new JobQueryImpl();
}
public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() {
return new HistoricProcessInstanceQueryImpl();
}
public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() {
return new HistoricActivityInstanceQueryImpl();
|
}
public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() {
return new HistoricTaskInstanceQueryImpl();
}
public HistoricDetailQueryImpl createHistoricDetailQuery() {
return new HistoricDetailQueryImpl();
}
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl();
}
// getters and setters //////////////////////////////////////////////////////
public SqlSession getSqlSession() {
return sqlSession;
}
public DbSqlSessionFactory getDbSqlSessionFactory() {
return dbSqlSessionFactory;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8079
# rocketmq 配置项,对应 RocketMQProperties 配置类
rocketmq:
name-server: 127.0.0.1:9876 # RocketMQ Namesrv
# Producer 配置项
producer:
group: demo-produc
|
er-group # 生产者分组
send-message-timeout: 3000 # 发送消息超时时间,单位:毫秒。默认为 3000 。
|
repos\SpringBoot-Labs-master\lab-39\lab-39-rocketmq\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
private void judgePageBoudary() {
isFirstPage = pageNum == 1;
isLastPage = pageNum == pages;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public List<T> getList() {
|
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public boolean isIsFirstPage() {
return isFirstPage;
}
public void setIsFirstPage(boolean isFirstPage) {
this.isFirstPage = isFirstPage;
}
public boolean isIsLastPage() {
return isLastPage;
}
public void setIsLastPage(boolean isLastPage) {
this.isLastPage = isLastPage;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PageInfo{");
sb.append("pageNum=").append(pageNum);
sb.append(", pageSize=").append(pageSize);
sb.append(", total=").append(total);
sb.append(", pages=").append(pages);
sb.append(", list=").append(list);
sb.append(", isFirstPage=").append(isFirstPage);
sb.append(", isLastPage=").append(isLastPage);
sb.append(", navigatepageNums=");
sb.append('}');
return sb.toString();
}
}
|
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\page\PageInfo.java
| 1
|
请完成以下Java代码
|
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** RecurringType AD_Reference_ID=282 */
public static final int RECURRINGTYPE_AD_Reference_ID=282;
/** Invoice = I */
public static final String RECURRINGTYPE_Invoice = "I";
/** Order = O */
public static final String RECURRINGTYPE_Order = "O";
/** GL Journal = G */
public static final String RECURRINGTYPE_GLJournal = "G";
/** Project = J */
public static final String RECURRINGTYPE_Project = "J";
/** Set Recurring Type.
@param RecurringType
Type of Recurring Document
*/
public void setRecurringType (String RecurringType)
{
set_Value (COLUMNNAME_RecurringType, RecurringType);
}
/** Get Recurring Type.
@return Type of Recurring Document
*/
public String getRecurringType ()
{
return (String)get_Value(COLUMNNAME_RecurringType);
}
/** Set Maximum Runs.
@param RunsMax
|
Number of recurring runs
*/
public void setRunsMax (int RunsMax)
{
set_Value (COLUMNNAME_RunsMax, Integer.valueOf(RunsMax));
}
/** Get Maximum Runs.
@return Number of recurring runs
*/
public int getRunsMax ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RunsMax);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Remaining Runs.
@param RunsRemaining
Number of recurring runs remaining
*/
public void setRunsRemaining (int RunsRemaining)
{
set_ValueNoCheck (COLUMNNAME_RunsRemaining, Integer.valueOf(RunsRemaining));
}
/** Get Remaining Runs.
@return Number of recurring runs remaining
*/
public int getRunsRemaining ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RunsRemaining);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring.java
| 1
|
请完成以下Java代码
|
private boolean checkAvailableActions()
{
initActions();
final boolean available = checkAvailable(this);
return available;
}
/**
* Check and update menu item if available
*
* @return true if item is available
*/
private boolean checkAvailable(MenuElement item)
{
final Component itemComp = item.getComponent();
final boolean isRoot = item == this;
if (!isRoot)
{
final IContextMenuAction action = getAction(item);
if (action == null)
{
// not controlled by this editor, take it's status and return
final boolean available = itemComp.isVisible();
return available;
}
if (!action.isAvailable())
{
itemComp.setVisible(false);
return false;
}
if (!action.isRunnable())
{
final boolean hideWhenNotRunnable = action.isHideWhenNotRunnable();
itemComp.setVisible(!hideWhenNotRunnable);
itemComp.setEnabled(false);
return false;
}
}
final MenuElement[] children = getSubElements(item);
if (children != null && children.length > 0)
{
boolean submenuAvailable = false;
for (MenuElement subitem : children)
{
final boolean subitemAvailable = checkAvailable(subitem);
if (subitemAvailable)
{
submenuAvailable = true;
}
}
itemComp.setVisible(submenuAvailable);
return submenuAvailable;
}
else
{
itemComp.setVisible(true);
|
itemComp.setEnabled(true);
}
return true;
}
private final IContextMenuAction getAction(MenuElement me)
{
final Component c = me.getComponent();
if (c instanceof JComponent)
{
final JComponent jc = (JComponent)c;
final IContextMenuAction action = (IContextMenuAction)jc.getClientProperty(ATTR_Action);
return action;
}
return null;
}
public void add(final IContextMenuAction action)
{
Check.assumeNotNull(action, "action not null");
// make sure actions are initialized and UI created before we are adding our new action
initActions();
createUI(this, action);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\EditorContextPopupMenu.java
| 1
|
请完成以下Java代码
|
protected void dispatchActivitiesCanceledIfNeeded(EventSubscriptionEntity eventSubscription, ExecutionEntity execution, ActivityImpl boundaryEventActivity, CommandContext commandContext) {
ActivityBehavior boundaryActivityBehavior = boundaryEventActivity.getActivityBehavior();
if (boundaryActivityBehavior instanceof BoundaryEventActivityBehavior) {
BoundaryEventActivityBehavior boundaryEventActivityBehavior = (BoundaryEventActivityBehavior) boundaryActivityBehavior;
if (boundaryEventActivityBehavior.isInterrupting()) {
dispatchExecutionCancelled(eventSubscription, execution, commandContext);
}
}
}
protected void dispatchExecutionCancelled(EventSubscriptionEntity eventSubscription, ExecutionEntity execution, CommandContext commandContext) {
// subprocesses
for (ExecutionEntity subExecution : execution.getExecutions()) {
dispatchExecutionCancelled(eventSubscription, subExecution, commandContext);
}
// call activities
ExecutionEntity subProcessInstance = commandContext.getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId());
if (subProcessInstance != null) {
dispatchExecutionCancelled(eventSubscription, subProcessInstance, commandContext);
}
// activity with message/signal boundary events
ActivityImpl activity = execution.getActivity();
if (activity != null && activity.getActivityBehavior() != null) {
|
dispatchActivityCancelled(eventSubscription, execution, activity, commandContext);
}
}
protected void dispatchActivityCancelled(EventSubscriptionEntity eventSubscription, ExecutionEntity execution, ActivityImpl activity, CommandContext commandContext) {
commandContext.getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createActivityCancelledEvent(activity.getId(),
(String) activity.getProperties().get("name"),
execution.getId(),
execution.getProcessInstanceId(), execution.getProcessDefinitionId(),
(String) activity.getProperties().get("type"),
activity.getActivityBehavior().getClass().getCanonicalName(),
eventSubscription),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\event\AbstractEventHandler.java
| 1
|
请完成以下Java代码
|
class SpringPropertyModelHandler extends ModelHandlerBase {
private final @Nullable Environment environment;
SpringPropertyModelHandler(Context context, @Nullable Environment environment) {
super(context);
this.environment = environment;
}
@Override
public void handle(ModelInterpretationContext intercon, Model model) throws ModelHandlerException {
SpringPropertyModel propertyModel = (SpringPropertyModel) model;
Scope scope = ActionUtil.stringToScope(propertyModel.getScope());
String defaultValue = propertyModel.getDefaultValue();
String source = propertyModel.getSource();
|
if (OptionHelper.isNullOrEmpty(propertyModel.getName()) || OptionHelper.isNullOrEmpty(source)) {
addError("The \"name\" and \"source\" attributes of <springProperty> must be set");
}
PropertyModelHandlerHelper.setProperty(intercon, propertyModel.getName(), getValue(source, defaultValue),
scope);
}
private String getValue(String source, String defaultValue) {
if (this.environment == null) {
addWarn("No Spring Environment available to resolve " + source);
return defaultValue;
}
return this.environment.getProperty(source, defaultValue);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\SpringPropertyModelHandler.java
| 1
|
请完成以下Java代码
|
public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId)
{
return computeQtyTUsOfTotalCUs(totalCUs, productId, QuantityUOMConverters.noConversion());
}
@NonNull
public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId, @NonNull final QuantityUOMConverter uomConverter)
{
assertProductMatches(productId);
if (totalCUs.signum() <= 0)
{
return QtyTU.ZERO;
}
// Infinite capacity
if (qtyCUsPerTU == null)
{
return QtyTU.ONE;
}
final Quantity totalCUsConv = uomConverter.convertQuantityTo(totalCUs, productId, qtyCUsPerTU.getUomId());
final BigDecimal qtyTUs = totalCUsConv.toBigDecimal().divide(qtyCUsPerTU.toBigDecimal(), 0, RoundingMode.UP);
return QtyTU.ofBigDecimal(qtyTUs);
}
@NonNull
public Quantity computeQtyCUsOfQtyTUs(@NonNull final QtyTU qtyTU)
{
|
if (qtyCUsPerTU == null)
{
throw new AdempiereException("Cannot calculate qty of CUs for infinite capacity");
}
return qtyTU.computeTotalQtyCUsUsingQtyCUsPerTU(qtyCUsPerTU);
}
public Capacity toCapacity()
{
if (productId == null)
{
throw new AdempiereException("Cannot convert to Capacity when no product is specified")
.setParameter("huPIItemProduct", this);
}
if (qtyCUsPerTU == null)
{
throw new AdempiereException("Cannot determine the UOM of " + this)
.setParameter("huPIItemProduct", this);
}
return Capacity.createCapacity(qtyCUsPerTU, productId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUPIItemProduct.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getDATE() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE(String value) {
this.date = value;
}
/**
* Gets the value of the quantity property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQUANTITY() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITY(String value) {
this.quantity = value;
}
/**
|
* Gets the value of the quantitymeasureunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQUANTITYMEASUREUNIT() {
return quantitymeasureunit;
}
/**
* Sets the value of the quantitymeasureunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITYMEASUREUNIT(String value) {
this.quantitymeasureunit = 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\DPLAC1.java
| 2
|
请完成以下Java代码
|
public class CompletionEvaluationResult {
protected final boolean isCompletable;
protected final boolean shouldBeCompleted;
protected final PlanItemInstanceEntity planItemInstance;
public CompletionEvaluationResult(boolean isCompletable, boolean shouldBeCompleted,
PlanItemInstanceEntity planItemInstance) {
this.isCompletable = isCompletable;
this.shouldBeCompleted = shouldBeCompleted;
this.planItemInstance = planItemInstance;
}
/**
* Returns true, if the plan item (most likely a stage or a case plan model) is completable, meaning, there is no more active or required work to be done,
* but it might still have available or enabled plan items.
*
* @return true if the plan item is completable
*/
public boolean isCompletable() {
return isCompletable;
}
/**
* Returns true, if the plan item (most likely a stage or case plan model) should be completed according the state of all of its enclosed plan items, their
|
* required rules, availability state and the plan items autocomplete mode. If autocomplete is activated, this flag will represent the same as the
* completable one, if not, it might be different.
*
* @return whether the plan item should be completed
*/
public boolean shouldBeCompleted() {
return shouldBeCompleted;
}
/**
* Returns the first plan item preventing the stage or case from being completed. This will be null, if {@link #isCompletable()} is true, otherwise it
* contains the plan item which first prevented it from being completed.
*
* @return the plan item first preventing the case or stage from being completable, might be null if it is actually completable
*/
public PlanItemInstanceEntity getPlanItemInstance() {
return planItemInstance;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\CompletionEvaluationResult.java
| 1
|
请完成以下Java代码
|
public boolean isReadOnly() {
return this.fileSystem.isReadOnly();
}
@Override
public long getTotalSpace() throws IOException {
return 0;
}
@Override
public long getUsableSpace() throws IOException {
return 0;
}
@Override
public long getUnallocatedSpace() throws IOException {
return 0;
}
@Override
public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) {
return getJarPathFileStore().supportsFileAttributeView(type);
}
@Override
public boolean supportsFileAttributeView(String name) {
return getJarPathFileStore().supportsFileAttributeView(name);
}
@Override
public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) {
return getJarPathFileStore().getFileStoreAttributeView(type);
}
|
@Override
public Object getAttribute(String attribute) throws IOException {
try {
return getJarPathFileStore().getAttribute(attribute);
}
catch (UncheckedIOException ex) {
throw ex.getCause();
}
}
protected FileStore getJarPathFileStore() {
try {
return Files.getFileStore(this.fileSystem.getJarPath());
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileStore.java
| 1
|
请完成以下Java代码
|
public void updateProcessInstanceLockTime(String processInstanceId, Date lockDate, String lockOwner, Date expirationTime) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", processInstanceId);
params.put("lockTime", lockDate);
params.put("expirationTime", expirationTime);
params.put("lockOwner", lockOwner);
int result = getDbSqlSession().directUpdate("updateProcessInstanceLockTime", params);
if (result == 0) {
throw new FlowableOptimisticLockingException("Could not lock process instance");
}
}
@Override
public void updateAllExecutionRelatedEntityCountFlags(boolean newValue) {
getDbSqlSession().directUpdate("updateExecutionRelatedEntityCountEnabled", newValue);
}
@Override
public void clearProcessInstanceLockTime(String processInstanceId) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", processInstanceId);
getDbSqlSession().directUpdate("clearProcessInstanceLockTime", params);
}
@Override
public void clearAllProcessInstanceLockTimes(String lockOwner) {
HashMap<String, Object> params = new HashMap<>();
params.put("lockOwner", lockOwner);
getDbSqlSession().directUpdate("clearAllProcessInstanceLockTimes", params);
}
protected void setSafeInValueLists(ExecutionQueryImpl executionQuery) {
if (executionQuery.getInvolvedGroups() != null) {
executionQuery.setSafeInvolvedGroups(createSafeInValuesList(executionQuery.getInvolvedGroups()));
}
if (executionQuery.getProcessInstanceIds() != null) {
executionQuery.setSafeProcessInstanceIds(createSafeInValuesList(executionQuery.getProcessInstanceIds()));
}
if (executionQuery.getOrQueryObjects() != null && !executionQuery.getOrQueryObjects().isEmpty()) {
|
for (ExecutionQueryImpl orExecutionQuery : executionQuery.getOrQueryObjects()) {
setSafeInValueLists(orExecutionQuery);
}
}
}
protected void setSafeInValueLists(ProcessInstanceQueryImpl processInstanceQuery) {
if (processInstanceQuery.getProcessInstanceIds() != null) {
processInstanceQuery.setSafeProcessInstanceIds(createSafeInValuesList(processInstanceQuery.getProcessInstanceIds()));
}
if (processInstanceQuery.getInvolvedGroups() != null) {
processInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(processInstanceQuery.getInvolvedGroups()));
}
if (processInstanceQuery.getOrQueryObjects() != null && !processInstanceQuery.getOrQueryObjects().isEmpty()) {
for (ProcessInstanceQueryImpl orProcessInstanceQuery : processInstanceQuery.getOrQueryObjects()) {
setSafeInValueLists(orProcessInstanceQuery);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java
| 1
|
请完成以下Java代码
|
public class BPartnerCompositeRestUtils
{
public static Predicate<BPartnerLocation> createLocationFilterFor(@NonNull final IdentifierString locationIdentifier)
{
return l -> matches(locationIdentifier, l);
}
public static boolean matches(
@NonNull final IdentifierString locationIdentifier,
@NonNull final BPartnerLocation location)
{
switch (locationIdentifier.getType())
{
case EXTERNAL_ID:
return locationIdentifier.asExternalId().equals(location.getExternalId());
case GLN:
return locationIdentifier.asGLN().equals(location.getGln());
case METASFRESH_ID:
return locationIdentifier.asMetasfreshId().equals(MetasfreshId.of(location.getId()));
case VALUE:
throw new AdempiereException("IdentifierStrings with type=" + Type.VALUE + " are not supported for locations")
.appendParametersToMessage()
.setParameter("locationIdentifier", locationIdentifier);
default:
throw new AdempiereException("Unexpected type; locationIdentifier=" + locationIdentifier);
}
}
public static Predicate<BPartnerContact> createContactFilterFor(@NonNull final IdentifierString contactIdentifier)
{
return c -> matches(contactIdentifier, c);
}
private boolean matches(
@NonNull final IdentifierString contactIdentifier,
@NonNull final BPartnerContact contact)
{
switch (contactIdentifier.getType())
{
case EXTERNAL_ID:
return contactIdentifier.asExternalId().equals(contact.getExternalId());
|
case GLN:
throw new AdempiereException("IdentifierStrings with type=" + Type.GLN + " are not supported for contacts")
.appendParametersToMessage()
.setParameter("contactIdentifier", contactIdentifier);
case METASFRESH_ID:
return contactIdentifier.asMetasfreshId().equals(MetasfreshId.of(contact.getId()));
case VALUE:
return contactIdentifier.asValue().equals(contact.getValue());
default:
throw new AdempiereException("Unexpected type; contactIdentifier=" + contactIdentifier);
}
}
@Nullable
public static InvoiceRule getInvoiceRule(@Nullable final JsonInvoiceRule jsonInvoiceRule)
{
if (jsonInvoiceRule == null)
{
return null;
}
switch (jsonInvoiceRule)
{
case AfterDelivery:
return InvoiceRule.AfterDelivery;
case CustomerScheduleAfterDelivery:
return InvoiceRule.CustomerScheduleAfterDelivery;
case Immediate:
return InvoiceRule.Immediate;
case OrderCompletelyDelivered:
return InvoiceRule.OrderCompletelyDelivered;
case AfterPick:
return InvoiceRule.AfterPick;
default:
throw new AdempiereException("Unsupported JsonInvliceRule " + jsonInvoiceRule);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\BPartnerCompositeRestUtils.java
| 1
|
请完成以下Java代码
|
public OrderItemBuilder transactionReference(final ITableRecordReference transactionReference)
{
innerBuilder.transactionReference(transactionReference);
return this;
}
public OrderItemBuilder dimension(final Dimension dimension)
{
innerBuilder.dimension(dimension);
return this;
}
public PurchaseOrderItem buildAndAddToParent()
{
final PurchaseOrderItem newItem = innerBuilder.build();
parent.purchaseOrderItems.add(newItem);
return newItem;
}
}
public OrderItemBuilder createOrderItem()
{
return new OrderItemBuilder(this);
}
/**
* Intended to be used by the persistence layer
*/
public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem)
{
final PurchaseCandidateId id = getId();
Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this);
|
Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(),
"The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}",
purchaseOrderItem, this);
purchaseOrderItems.add(purchaseOrderItem);
}
public Quantity getPurchasedQty()
{
return purchaseOrderItems.stream()
.map(PurchaseOrderItem::getPurchasedQty)
.reduce(Quantity::add)
.orElseGet(() -> getQtyToPurchase().toZero());
}
public List<PurchaseOrderItem> getPurchaseOrderItems()
{
return ImmutableList.copyOf(purchaseOrderItems);
}
public List<PurchaseErrorItem> getPurchaseErrorItems()
{
return ImmutableList.copyOf(purchaseErrorItems);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java
| 1
|
请完成以下Java代码
|
protected final int getAD_Form_ID()
{
return _adFormId;
}
private final synchronized I_AD_Form getAD_Form()
{
if (!_adFormLoaded)
{
_adForm = retrieveAD_Form();
_adFormLoaded = true;
}
return _adForm;
}
private final I_AD_Form retrieveAD_Form()
{
final IContextMenuActionContext context = getContext();
Check.assumeNotNull(context, "context not null");
final Properties ctx = context.getCtx();
// Check if user has access to Payment Allocation form
|
final int adFormId = getAD_Form_ID();
final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId);
if (formAccess == null || !formAccess)
{
return null;
}
// Retrieve the form
final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None);
// Translate it to user's language
final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class);
return formTrl;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java
| 1
|
请完成以下Java代码
|
static SslManagerBundle from(TrustManager... trustManagers) {
Assert.notNull(trustManagers, "'trustManagers' must not be null");
KeyManagerFactory defaultKeyManagerFactory = createDefaultKeyManagerFactory();
TrustManagerFactory defaultTrustManagerFactory = createDefaultTrustManagerFactory();
return of(defaultKeyManagerFactory, FixedTrustManagerFactory.of(defaultTrustManagerFactory, trustManagers));
}
private static TrustManagerFactory createDefaultTrustManagerFactory() {
String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory;
try {
trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm);
trustManagerFactory.init((KeyStore) null);
}
catch (NoSuchAlgorithmException | KeyStoreException ex) {
throw new IllegalStateException(
"Unable to create TrustManagerFactory for default '%s' algorithm".formatted(defaultAlgorithm), ex);
}
|
return trustManagerFactory;
}
private static KeyManagerFactory createDefaultKeyManagerFactory() {
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory;
try {
keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
keyManagerFactory.init(null, null);
}
catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException ex) {
throw new IllegalStateException(
"Unable to create KeyManagerFactory for default '%s' algorithm".formatted(defaultAlgorithm), ex);
}
return keyManagerFactory;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\SslManagerBundle.java
| 1
|
请完成以下Java代码
|
public boolean isLineTypeIncluded()
{
return LINETYPE_IncludedLineSet.equals(this.getLineType());
}
public int getIncluded_ReportLineSet_ID()
{
return this.get_ValueAsInt("Included_ReportLineSet_ID");
}
public boolean isSuppressZeroLine()
{
return this.get_ValueAsBoolean("IsSuppressZeroLine");
}
@Override
public MReportLineSet getPA_ReportLineSet()
{
if (parent == null)
{
parent = (MReportLineSet)super.getPA_ReportLineSet();
}
return parent;
}
void setParent(MReportLineSet lineSet)
{
this.parent = lineSet;
}
private MReportLineSet parent = null;
public boolean isInclInParentCalc()
{
return this.get_ValueAsBoolean("IsInclInParentCalc");
}
public static void checkIncludedReportLineSetCycles(MReportLine line)
{
checkIncludedReportLineSetCycles(line, new TreeSet<Integer>(), new StringBuffer());
}
private static void checkIncludedReportLineSetCycles(MReportLine line, Collection<Integer> trace, StringBuffer traceStr)
|
{
StringBuffer traceStr2 = new StringBuffer(traceStr);
if (traceStr2.length() > 0)
traceStr2.append(" - ");
traceStr2.append(line.getName());
if (trace.contains(line.getPA_ReportLine_ID()))
{
throw new AdempiereException("@PA_ReportLine_ID@ Loop Detected: "+traceStr2.toString()); // TODO: translate
}
Collection<Integer> trace2 = new TreeSet<Integer>(trace);
trace2.add(line.getPA_ReportLine_ID());
if (line.isLineTypeIncluded() && line.getPA_ReportLineSet() != null)
{
MReportLineSet includedSet = line.getIncluded_ReportLineSet();
traceStr2.append("(").append(includedSet.getName()).append(")");
for (MReportLine includedLine : includedSet.getLiness())
{
checkIncludedReportLineSetCycles(includedLine, trace2, traceStr2);
}
}
}
} // MReportLine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportLine.java
| 1
|
请完成以下Java代码
|
public class RateLimiterAspect {
private static final ConcurrentMap<String, com.google.common.util.concurrent.RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();
@Pointcut("@annotation(com.xkcoding.ratelimit.guava.annotation.RateLimiter)")
public void rateLimit() {
}
@Around("rateLimit()")
public Object pointcut(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
// 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
if (rateLimiter != null && rateLimiter.qps() > RateLimiter.NOT_LIMITED) {
|
double qps = rateLimiter.qps();
if (RATE_LIMITER_CACHE.get(method.getName()) == null) {
// 初始化 QPS
RATE_LIMITER_CACHE.put(method.getName(), com.google.common.util.concurrent.RateLimiter.create(qps));
}
log.debug("【{}】的QPS设置为: {}", method.getName(), RATE_LIMITER_CACHE.get(method.getName()).getRate());
// 尝试获取令牌
if (RATE_LIMITER_CACHE.get(method.getName()) != null && !RATE_LIMITER_CACHE.get(method.getName()).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) {
throw new RuntimeException("手速太快了,慢点儿吧~");
}
}
return point.proceed();
}
}
|
repos\spring-boot-demo-master\demo-ratelimit-guava\src\main\java\com\xkcoding\ratelimit\guava\aspect\RateLimiterAspect.java
| 1
|
请完成以下Java代码
|
public class MigrationMerge extends JavaProcess {
private I_AD_Migration migrationFrom;
private I_AD_Migration migrationTo;
/**
*
* Process to merge two migrations together
*
* @author Paul Bowden, Adaxa Pty Ltd
*
*/
@Override
protected String doIt() throws Exception {
if ( migrationFrom == null || migrationFrom.getAD_Migration_ID() <= 0
|| migrationTo == null || migrationTo.getAD_Migration_ID() <= 0
|| migrationFrom.getAD_Migration_ID() == migrationTo.getAD_Migration_ID() )
{
addLog("Two different existing migrations required for merge");
return "@Error@";
}
Services.get(IMigrationBL.class).mergeMigration(migrationTo, migrationFrom);
return "@OK@";
}
@Override
protected void prepare() {
int fromId = 0, toId = 0;
|
ProcessInfoParameter[] params = getParametersAsArray();
for ( ProcessInfoParameter p : params)
{
String para = p.getParameterName();
if ( para.equals("AD_MigrationFrom_ID") )
fromId = p.getParameterAsInt();
else if ( para.equals("AD_MigrationTo_ID") )
toId = p.getParameterAsInt();
}
// launched from migration window
if ( toId == 0 )
toId = getRecord_ID();
migrationTo = InterfaceWrapperHelper.create(getCtx(), toId, I_AD_Migration.class, get_TrxName());
migrationFrom = InterfaceWrapperHelper.create(getCtx(), fromId, I_AD_Migration.class, get_TrxName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationMerge.java
| 1
|
请完成以下Java代码
|
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
final PickingJob pickingJob = getPickingJob(wfProcess);
return computeActivityState(pickingJob);
}
public static WFActivityStatus computeActivityState(final PickingJob pickingJob)
{
return pickingJob.getPickingSlot().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED;
}
@Override
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request)
{
final PickingSlotQRCode pickingSlotQRCode = PickingSlotQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode());
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJob -> pickingJobRestService.allocateAndSetPickingSlot(pickingJob, pickingSlotQRCode)
);
}
@Override
public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(@NonNull GetScannedBarcodeSuggestionsRequest request)
{
final PickingJob pickingJob = getPickingJob(request.getWfProcess());
final PickingSlotSuggestions pickingSlotSuggestions = pickingJobRestService.getPickingSlotsSuggestions(pickingJob);
return toJson(pickingSlotSuggestions);
}
private static JsonScannedBarcodeSuggestions toJson(final PickingSlotSuggestions pickingSlotSuggestions)
{
|
if (pickingSlotSuggestions.isEmpty())
{
return JsonScannedBarcodeSuggestions.EMPTY;
}
return pickingSlotSuggestions.stream()
.map(SetPickingSlotWFActivityHandler::toJson)
.collect(JsonScannedBarcodeSuggestions.collect());
}
private static JsonScannedBarcodeSuggestion toJson(final PickingSlotSuggestion pickingSlotSuggestion)
{
return JsonScannedBarcodeSuggestion.builder()
.caption(pickingSlotSuggestion.getCaption())
.detail(pickingSlotSuggestion.getDeliveryAddress())
.qrCode(pickingSlotSuggestion.getQRCode().toGlobalQRCodeJsonString())
.property1("HU")
.value1(String.valueOf(pickingSlotSuggestion.getCountHUs()))
.additionalProperty("bpartnerLocationId", BPartnerLocationId.toRepoId(pickingSlotSuggestion.getDeliveryBPLocationId())) // for testing
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickingSlotWFActivityHandler.java
| 1
|
请完成以下Java代码
|
public class X_AD_WF_ActivityResult extends org.compiere.model.PO implements I_AD_WF_ActivityResult, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 400558170L;
/** Standard Constructor */
public X_AD_WF_ActivityResult (final Properties ctx, final int AD_WF_ActivityResult_ID, @Nullable final String trxName)
{
super (ctx, AD_WF_ActivityResult_ID, trxName);
}
/** Load Constructor */
public X_AD_WF_ActivityResult (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_WF_Activity_ID (final int AD_WF_Activity_ID)
{
if (AD_WF_Activity_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Activity_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Activity_ID, AD_WF_Activity_ID);
}
@Override
public int getAD_WF_Activity_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Activity_ID);
}
@Override
public void setAD_WF_ActivityResult_ID (final int AD_WF_ActivityResult_ID)
{
if (AD_WF_ActivityResult_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_ActivityResult_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_ActivityResult_ID, AD_WF_ActivityResult_ID);
}
@Override
public int getAD_WF_ActivityResult_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_ActivityResult_ID);
}
|
@Override
public void setAttributeName (final java.lang.String AttributeName)
{
set_Value (COLUMNNAME_AttributeName, AttributeName);
}
@Override
public java.lang.String getAttributeName()
{
return get_ValueAsString(COLUMNNAME_AttributeName);
}
@Override
public void setAttributeValue (final java.lang.String AttributeValue)
{
set_Value (COLUMNNAME_AttributeValue, AttributeValue);
}
@Override
public java.lang.String getAttributeValue()
{
return get_ValueAsString(COLUMNNAME_AttributeValue);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_ActivityResult.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String formatObjectToJsonString() {
try {
User user = new User();
user.setUserName("mrbird");
user.setAge(26);
user.setPassword("123456");
user.setBirthday(new Date());
String jsonStr = mapper.writeValueAsString(user);
return jsonStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("updateuser")
@ResponseBody
|
public int updateUser(@RequestBody List<User> list) {
return list.size();
}
@RequestMapping("customize")
@ResponseBody
public String customize() throws JsonParseException, JsonMappingException, IOException {
String jsonStr = "[{\"userName\":\"mrbird\",\"age\":26},{\"userName\":\"scott\",\"age\":27}]";
JavaType type = mapper.getTypeFactory().constructParametricType(List.class, User.class);
List<User> list = mapper.readValue(jsonStr, type);
String msg = "";
for (User user : list) {
msg += user.getUserName();
}
return msg;
}
}
|
repos\SpringAll-master\18.Spring-Boot-Jackson\src\main\java\com\example\controller\TestJsonController.java
| 2
|
请完成以下Java代码
|
public static String convertPasswordToString(Object passObj) {
Assert.notNull(passObj, "Password object to convert must not be null");
if (passObj instanceof byte[]) {
return Utf8.decode((byte[]) passObj);
}
if (passObj instanceof String) {
return (String) passObj;
}
throw new IllegalArgumentException("Password object was not a String or byte array.");
}
/**
* Works out the root DN for an LDAP URL.
* <p>
* For example, the URL <tt>ldap://monkeymachine:11389/dc=springframework,dc=org</tt>
* has the root DN "dc=springframework,dc=org".
* </p>
* @param url the LDAP URL
* @return the root DN
*/
public static String parseRootDnFromUrl(String url) {
Assert.hasLength(url, "url must have length");
String urlRootDn;
if (url.startsWith("ldap:") || url.startsWith("ldaps:")) {
URI uri = parseLdapUrl(url);
urlRootDn = uri.getRawPath();
}
else {
// Assume it's an embedded server
urlRootDn = url;
}
if (urlRootDn.startsWith("/")) {
urlRootDn = urlRootDn.substring(1);
}
return urlRootDn;
}
|
/**
* Parses the supplied LDAP URL.
* @param url the URL (e.g.
* <tt>ldap://monkeymachine:11389/dc=springframework,dc=org</tt>).
* @return the URI object created from the URL
* @throws IllegalArgumentException if the URL is null, empty or the URI syntax is
* invalid.
*/
private static URI parseLdapUrl(String url) {
Assert.hasLength(url, "url must have length");
try {
return new URI(url);
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException("Unable to parse url: " + url, ex);
}
}
}
|
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\LdapUtils.java
| 1
|
请完成以下Java代码
|
public void setIsBillTo (final boolean IsBillTo)
{
set_Value (COLUMNNAME_IsBillTo, IsBillTo);
}
@Override
public boolean isBillTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsBillTo);
}
@Override
public void setIsFetchedFrom (final boolean IsFetchedFrom)
{
set_Value (COLUMNNAME_IsFetchedFrom, IsFetchedFrom);
}
@Override
public boolean isFetchedFrom()
{
return get_ValueAsBoolean(COLUMNNAME_IsFetchedFrom);
}
@Override
public void setIsPayFrom (final boolean IsPayFrom)
{
set_Value (COLUMNNAME_IsPayFrom, IsPayFrom);
}
@Override
public boolean isPayFrom()
{
return get_ValueAsBoolean(COLUMNNAME_IsPayFrom);
}
@Override
public void setIsRemitTo (final boolean IsRemitTo)
{
set_Value (COLUMNNAME_IsRemitTo, IsRemitTo);
}
@Override
public boolean isRemitTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsRemitTo);
}
@Override
public void setIsShipTo (final boolean IsShipTo)
{
set_Value (COLUMNNAME_IsShipTo, IsShipTo);
}
@Override
public boolean isShipTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsShipTo);
}
@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);
}
/**
* Role AD_Reference_ID=541254
* Reference name: Role
*/
public static final int ROLE_AD_Reference_ID=541254;
/** Main Producer = MP */
public static final String ROLE_MainProducer = "MP";
/** Hostpital = HO */
public static final String ROLE_Hostpital = "HO";
/** Physician Doctor = PD */
public static final String ROLE_PhysicianDoctor = "PD";
/** General Practitioner = GP */
public static final String ROLE_GeneralPractitioner = "GP";
/** Health Insurance = HI */
public static final String ROLE_HealthInsurance = "HI";
/** Nursing Home = NH */
public static final String ROLE_NursingHome = "NH";
/** Caregiver = CG */
public static final String ROLE_Caregiver = "CG";
/** Preferred Pharmacy = PP */
public static final String ROLE_PreferredPharmacy = "PP";
/** Nursing Service = NS */
public static final String ROLE_NursingService = "NS";
/** Payer = PA */
public static final String ROLE_Payer = "PA";
/** Payer = PA */
public static final String ROLE_Pharmacy = "PH";
@Override
public void setRole (final @Nullable java.lang.String Role)
{
set_Value (COLUMNNAME_Role, Role);
}
@Override
public java.lang.String getRole()
{
return get_ValueAsString(COLUMNNAME_Role);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java
| 1
|
请完成以下Java代码
|
public class AuthorizationProperty {
/**
* Enables authorization.
*/
private boolean enabled = Defaults.INSTANCE.isAuthorizationEnabled();
/**
* Enables authorization for custom code.
*/
private boolean enabledForCustomCode = Defaults.INSTANCE.isAuthorizationEnabledForCustomCode();
private String authorizationCheckRevokes = Defaults.INSTANCE.getAuthorizationCheckRevokes();
/**
* If the value of this flag is set <code>true</code> then the process engine
* performs tenant checks to ensure that an authenticated user can only access
* data that belongs to one of his tenants.
*/
private boolean tenantCheckEnabled = true;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabledForCustomCode() {
return enabledForCustomCode;
}
public void setEnabledForCustomCode(boolean enabledForCustomCode) {
this.enabledForCustomCode = enabledForCustomCode;
}
public String getAuthorizationCheckRevokes() {
return authorizationCheckRevokes;
}
|
public void setAuthorizationCheckRevokes(String authorizationCheckRevokes) {
this.authorizationCheckRevokes = authorizationCheckRevokes;
}
public boolean isTenantCheckEnabled() {
return tenantCheckEnabled;
}
public void setTenantCheckEnabled(boolean tenantCheckEnabled) {
this.tenantCheckEnabled = tenantCheckEnabled;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
.add("enabledForCustomCode=" + enabledForCustomCode)
.add("authorizationCheckRevokes=" + authorizationCheckRevokes)
.add("tenantCheckEnabled=" + tenantCheckEnabled)
.toString();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\AuthorizationProperty.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_C_ValidCombination getRealizedLoss_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setRealizedLoss_A(org.compiere.model.I_C_ValidCombination RealizedLoss_A)
{
set_ValueFromPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedLoss_A);
}
/** Set Realisierte Währungsverluste.
@param RealizedLoss_Acct
Konto für realisierte Währungsverluste
*/
@Override
public void setRealizedLoss_Acct (int RealizedLoss_Acct)
{
set_Value (COLUMNNAME_RealizedLoss_Acct, Integer.valueOf(RealizedLoss_Acct));
}
/** Get Realisierte Währungsverluste.
@return Konto für realisierte Währungsverluste
*/
@Override
public int getRealizedLoss_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RealizedLoss_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getUnrealizedGain_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setUnrealizedGain_A(org.compiere.model.I_C_ValidCombination UnrealizedGain_A)
{
set_ValueFromPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedGain_A);
}
/** Set Nicht realisierte Währungsgewinne.
@param UnrealizedGain_Acct
Konto für nicht realisierte Währungsgewinne
*/
@Override
public void setUnrealizedGain_Acct (int UnrealizedGain_Acct)
{
set_Value (COLUMNNAME_UnrealizedGain_Acct, Integer.valueOf(UnrealizedGain_Acct));
}
/** Get Nicht realisierte Währungsgewinne.
@return Konto für nicht realisierte Währungsgewinne
*/
@Override
public int getUnrealizedGain_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedGain_Acct);
if (ii == null)
return 0;
|
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getUnrealizedLoss_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setUnrealizedLoss_A(org.compiere.model.I_C_ValidCombination UnrealizedLoss_A)
{
set_ValueFromPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedLoss_A);
}
/** Set Nicht realisierte Währungsverluste.
@param UnrealizedLoss_Acct
Konto für nicht realisierte Währungsverluste
*/
@Override
public void setUnrealizedLoss_Acct (int UnrealizedLoss_Acct)
{
set_Value (COLUMNNAME_UnrealizedLoss_Acct, Integer.valueOf(UnrealizedLoss_Acct));
}
/** Get Nicht realisierte Währungsverluste.
@return Konto für nicht realisierte Währungsverluste
*/
@Override
public int getUnrealizedLoss_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedLoss_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency_Acct.java
| 1
|
请完成以下Java代码
|
public static class QuantityDeserializer extends StdDeserializer<Quantity>
{
private static final long serialVersionUID = -5406622853902102217L;
public QuantityDeserializer()
{
super(Quantity.class);
}
@Override
public Quantity deserialize(final JsonParser p, final DeserializationContext ctx) throws IOException
{
final JsonNode node = p.getCodec().readTree(p);
final String qtyStr = node.get("qty").asText();
final int uomRepoId = (Integer)node.get("uomId").numberValue();
final String sourceQtyStr;
final int sourceUomRepoId;
if (node.has("sourceQty"))
{
sourceQtyStr = node.get("sourceQty").asText();
sourceUomRepoId = (Integer)node.get("sourceUomId").numberValue();
}
else
{
sourceQtyStr = qtyStr;
sourceUomRepoId = uomRepoId;
}
return Quantitys.of(
new BigDecimal(qtyStr), UomId.ofRepoId(uomRepoId),
new BigDecimal(sourceQtyStr), UomId.ofRepoId(sourceUomRepoId));
}
}
public static class QuantitySerializer extends StdSerializer<Quantity>
{
|
private static final long serialVersionUID = -8292209848527230256L;
public QuantitySerializer()
{
super(Quantity.class);
}
@Override
public void serialize(final Quantity value, final JsonGenerator gen, final SerializerProvider provider) throws IOException
{
gen.writeStartObject();
final String qtyStr = value.toBigDecimal().toString();
final int uomId = value.getUomId().getRepoId();
gen.writeFieldName("qty");
gen.writeString(qtyStr);
gen.writeFieldName("uomId");
gen.writeNumber(uomId);
final String sourceQtyStr = value.getSourceQty().toString();
final int sourceUomId = value.getSourceUomId().getRepoId();
if (!qtyStr.equals(sourceQtyStr) || uomId != sourceUomId)
{
gen.writeFieldName("sourceQty");
gen.writeString(sourceQtyStr);
gen.writeFieldName("sourceUomId");
gen.writeNumber(sourceUomId);
}
gen.writeEndObject();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantitys.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JPAEntityScanner {
public EntityMetaData scanClass(Class<?> clazz) {
EntityMetaData metaData = new EntityMetaData();
// in case with JPA Enhancement method should iterate over superclasses list
// to find @Entity and @Id annotations
while (clazz != null && !clazz.equals(Object.class)) {
// Class should have @Entity annotation
boolean isEntity = isEntityAnnotationPresent(clazz);
if (isEntity) {
metaData.setEntityClass(clazz);
metaData.setJPAEntity(true);
// Try to find a field annotated with @Id
Field idField = getIdField(clazz);
if (idField != null) {
metaData.setIdField(idField);
} else {
// Try to find a method annotated with @Id
Method idMethod = getIdMethod(clazz);
if (idMethod != null) {
metaData.setIdMethod(idMethod);
} else {
throw new FlowableException("Cannot find field or method with annotation @Id on class '" + clazz.getName() + "', only single-valued primary keys are supported on JPA-entities");
}
}
break;
}
clazz = clazz.getSuperclass();
}
return metaData;
}
private Method getIdMethod(Class<?> clazz) {
Method idMethod = null;
// Get all public declared methods on the class. According to spec, @Id should only be
// applied to fields and property get methods
Method[] methods = clazz.getMethods();
Id idAnnotation = null;
for (Method method : methods) {
idAnnotation = method.getAnnotation(Id.class);
if (idAnnotation != null && !method.isBridge()) {
idMethod = method;
break;
}
}
return idMethod;
}
|
private Field getIdField(Class<?> clazz) {
Field idField = null;
Field[] fields = clazz.getDeclaredFields();
Id idAnnotation = null;
for (Field field : fields) {
idAnnotation = field.getAnnotation(Id.class);
if (idAnnotation != null) {
idField = field;
break;
}
}
if (idField == null) {
// Check superClass for fields with @Id, since getDeclaredFields
// does not return superclass-fields.
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !superClass.equals(Object.class)) {
// Recursively go up class hierarchy
idField = getIdField(superClass);
}
}
return idField;
}
private boolean isEntityAnnotationPresent(Class<?> clazz) {
return (clazz.getAnnotation(Entity.class) != null);
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JPAEntityScanner.java
| 2
|
请完成以下Java代码
|
private static final class WebServerSslStoreBundle implements SslStoreBundle {
private final @Nullable KeyStore keyStore;
private final @Nullable KeyStore trustStore;
private final @Nullable String keyStorePassword;
private WebServerSslStoreBundle(@Nullable KeyStore keyStore, @Nullable KeyStore trustStore,
@Nullable String keyStorePassword) {
Assert.state(keyStore != null || trustStore != null,
"SSL is enabled but no trust material is configured for the default host");
this.keyStore = keyStore;
this.trustStore = trustStore;
this.keyStorePassword = keyStorePassword;
}
@Override
public @Nullable KeyStore getKeyStore() {
return this.keyStore;
}
@Override
public @Nullable KeyStore getTrustStore() {
return this.trustStore;
}
@Override
public @Nullable String getKeyStorePassword() {
|
return this.keyStorePassword;
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("keyStore.type", (this.keyStore != null) ? this.keyStore.getType() : "none");
creator.append("keyStorePassword", (this.keyStorePassword != null) ? "******" : null);
creator.append("trustStore.type", (this.trustStore != null) ? this.trustStore.getType() : "none");
return creator.toString();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\WebServerSslBundle.java
| 1
|
请完成以下Java代码
|
public static void dbCreateHistoryLevel(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
HistoryLevel configuredHistoryLevel = processEngineConfiguration.getHistoryLevel();
PropertyEntity property = new PropertyEntity("historyLevel", Integer.toString(configuredHistoryLevel.getId()));
commandContext.getSession(DbEntityManager.class).insert(property);
LOG.creatingHistoryLevelPropertyInDatabase(configuredHistoryLevel);
}
/**
*
* @return Integer value representing the history level or <code>null</code> if none found
*/
public static Integer databaseHistoryLevel(CommandContext commandContext) {
try {
PropertyEntity historyLevelProperty = commandContext.getPropertyManager().findPropertyById("historyLevel");
return historyLevelProperty != null ? Integer.valueOf(historyLevelProperty.getValue()) : null;
}
catch (Exception e) {
LOG.couldNotSelectHistoryLevel(e.getMessage());
return null;
}
}
protected void determineAutoHistoryLevel(ProcessEngineConfigurationImpl engineConfiguration, HistoryLevel databaseHistoryLevel) {
HistoryLevel configuredHistoryLevel = engineConfiguration.getHistoryLevel();
if (configuredHistoryLevel == null
&& ProcessEngineConfiguration.HISTORY_AUTO.equals(engineConfiguration.getHistory())) {
// automatically determine history level or use default AUDIT
if (databaseHistoryLevel != null) {
engineConfiguration.setHistoryLevel(databaseHistoryLevel);
}
else {
engineConfiguration.setHistoryLevel(engineConfiguration.getDefaultHistoryLevel());
|
}
}
}
protected void checkStartupLockExists(CommandContext commandContext) {
PropertyEntity historyStartupProperty = commandContext.getPropertyManager().findPropertyById("startup.lock");
if (historyStartupProperty == null) {
LOG.noStartupLockPropertyFound();
}
}
protected void acquireExclusiveLock(CommandContext commandContext) {
PropertyManager propertyManager = commandContext.getPropertyManager();
//exclusive lock
propertyManager.acquireExclusiveLockForStartup();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoryLevelSetupCommand.java
| 1
|
请完成以下Java代码
|
public int getHR_ListVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
|
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListVersion.java
| 1
|
请完成以下Java代码
|
public boolean isStale()
{
return staled;
}
@Override
public int getNextLineNo()
{
final int lastLineNo = DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setExistingDocumentsSupplier(this::getChangedDocumentOrNull)
.setChangesCollector(NullDocumentChangesCollector.instance)
.retrieveLastLineNo();
final int nextLineNo = lastLineNo / 10 * 10 + 10;
return nextLineNo;
}
//
//
//
@AllArgsConstructor
private final class ActionsContext implements IncludedDocumentsCollectionActionsContext
{
@Override
public boolean isParentDocumentProcessed()
{
return parentDocument.isProcessed();
}
@Override
public boolean isParentDocumentActive()
{
return parentDocument.isActive();
}
@Override
public boolean isParentDocumentNew()
|
{
return parentDocument.isNew();
}
@Override
public boolean isParentDocumentInvalid()
{
return !parentDocument.getValidStatus().isValid();
}
@Override
public Collection<Document> getIncludedDocuments()
{
return getChangedDocuments();
}
@Override
public Evaluatee toEvaluatee()
{
return parentDocument.asEvaluatee();
}
@Override
public void collectAllowNew(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
parentDocument.getChangesCollector().collectAllowNew(parentDocumentPath, detailId, allowNew);
}
@Override
public void collectAllowDelete(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
parentDocument.getChangesCollector().collectAllowDelete(parentDocumentPath, detailId, allowDelete);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadWriteIncludedDocumentsCollection.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
if (PARAM_IsComplete.equals(para.getParameterName()))
{
p_IsComplete = para.getParameterAsBoolean();
}
}
}
@Override
protected String doIt() throws Exception
{
final Iterator<I_M_ReceiptSchedule> schedules = getReceiptSchedules();
if (!schedules.hasNext())
{
throw new AdempiereException("@" + MSG_NO_RECEIPT_SCHEDULES_SELECTED + "@");
}
final InOutGenerateResult result = Services.get(IInOutCandidateBL.class).createEmptyInOutGenerateResult(false); // storeReceipts=false
final IInOutProducer producer = receiptScheduleBL.createInOutProducer(result, p_IsComplete);
receiptScheduleBL.generateInOuts(getCtx(), producer, schedules);
return "@Created@ @M_InOut_ID@: #" + result.getInOutCount();
}
private Iterator<I_M_ReceiptSchedule> getReceiptSchedules()
{
final ProcessInfo processInfo = getProcessInfo();
|
final IQueryBuilder<I_M_ReceiptSchedule> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_M_ReceiptSchedule.class, processInfo);
//
// Only not processed lines
queryBuilder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_Processed, false);
//
// From user selection
queryBuilder.filter(new ProcessInfoSelectionQueryFilter<I_M_ReceiptSchedule>(processInfo));
final IQuery<I_M_ReceiptSchedule> query = queryBuilder.create()
.setClient_ID()
.setOnlyActiveRecords(true)
.setRequiredAccess(Access.WRITE);
return Services.get(IReceiptScheduleDAO.class).retrieve(query);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_GenerateInOutFromSelection.java
| 1
|
请完成以下Java代码
|
public final class StreamUtil {
private static final Logger LOG = LoggerFactory.getLogger(StreamUtil.class);
private StreamUtil() {
}
/**
* 将输入流的内容复制到输出流里
*
* @param in 输入流
* @param out 输出流
* @return 复制的数据字节数
* @throws IOException IO异常
*/
public static int copy(InputStream in, OutputStream out) throws IOException {
BeanUtil.requireNonNull(in, "No InputStream specified");
BeanUtil.requireNonNull(out, "No OutputStream specified");
int byteCount = 0;
byte[] buffer = new byte[4096];
int bytesRead1;
for (; (bytesRead1 = in.read(buffer)) != -1; byteCount += bytesRead1) {
out.write(buffer, 0, bytesRead1);
}
|
out.flush();
return byteCount;
}
/**
* 关闭需要关闭的对象,如果关闭出错,给出警告
*
* @param closeable 需要关闭的对象
*/
public static void closeWithWarn(Closeable closeable) {
if (BeanUtil.nonNull(closeable)) {
try {
closeable.close();
} catch (IOException e) {
LOG.warn("关闭流出错......", e);
}
}
}
}
|
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\utils\StreamUtil.java
| 1
|
请完成以下Java代码
|
private static PricingConditionsBreakChangeRequest createPricingConditionsBreakChangeRequest(final PricingConditionsRow row)
{
if (!row.isEditable())
{
throw new AdempiereException("Saving not editable rows is not allowed")
.setParameter("row", row);
}
final PricingConditionsId pricingConditionsId = row.getPricingConditionsId();
final PricingConditionsBreak pricingConditionsBreak = row.getPricingConditionsBreak();
final PricingConditionsBreakId updateFromPricingConditionsBreakId = row.getCopiedFromPricingConditionsBreakId();
return preparePricingConditionsBreakChangeRequest(pricingConditionsBreak)
.pricingConditionsId(pricingConditionsId)
.updateFromPricingConditionsBreakId(updateFromPricingConditionsBreakId)
.build();
}
|
private static PricingConditionsBreakChangeRequestBuilder preparePricingConditionsBreakChangeRequest(
@NonNull final PricingConditionsBreak pricingConditionsBreak)
{
return PricingConditionsBreakChangeRequest.builder()
.pricingConditionsBreakId(pricingConditionsBreak.getId())
.matchCriteria(pricingConditionsBreak.getMatchCriteria())
.price(pricingConditionsBreak.getPriceSpecification())
.discount(pricingConditionsBreak.getDiscount())
.paymentTermId(Optional.ofNullable(pricingConditionsBreak.getPaymentTermIdOrNull()))
.paymentDiscount(Optional.ofNullable(pricingConditionsBreak.getPaymentDiscountOverrideOrNull()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\PricingConditionsView_SaveEditableRow.java
| 1
|
请完成以下Java代码
|
public void setDataEntry_Tab_ID (final int DataEntry_Tab_ID)
{
if (DataEntry_Tab_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, DataEntry_Tab_ID);
}
@Override
public int getDataEntry_Tab_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_Tab_ID);
}
@Override
public org.compiere.model.I_AD_Window getDataEntry_TargetWindow()
{
return get_ValueAsPO(COLUMNNAME_DataEntry_TargetWindow_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setDataEntry_TargetWindow(final org.compiere.model.I_AD_Window DataEntry_TargetWindow)
{
set_ValueFromPO(COLUMNNAME_DataEntry_TargetWindow_ID, org.compiere.model.I_AD_Window.class, DataEntry_TargetWindow);
}
@Override
public void setDataEntry_TargetWindow_ID (final int DataEntry_TargetWindow_ID)
{
if (DataEntry_TargetWindow_ID < 1)
set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, null);
else
set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, DataEntry_TargetWindow_ID);
}
@Override
public int getDataEntry_TargetWindow_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_TargetWindow_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
|
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTabName (final java.lang.String TabName)
{
set_Value (COLUMNNAME_TabName, TabName);
}
@Override
public java.lang.String getTabName()
{
return get_ValueAsString(COLUMNNAME_TabName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Tab.java
| 1
|
请完成以下Java代码
|
public void syncQtyDeliveredChanged(@NonNull final I_C_CallOrderDetail callOrderDetail)
{
final CallOrderSummaryId callOrderSummaryId = CallOrderSummaryId.ofRepoId(callOrderDetail.getC_CallOrderSummary_ID());
final Quantity qtyDelivered = getQtyDelivered(callOrderDetail);
if (InterfaceWrapperHelper.isNew(callOrderDetail))
{
summaryService.addQtyDelivered(callOrderSummaryId, qtyDelivered);
return;
}
final CallOrderSummary callOrderSummary = summaryService.getById(callOrderSummaryId);
final I_C_CallOrderDetail oldRecord = InterfaceWrapperHelper.createOld(callOrderDetail, I_C_CallOrderDetail.class);
final Quantity oldQtyDelivered = getQtyDelivered(oldRecord);
final Quantity deltaQtyDelivered = conversionBL.computeSum(
UOMConversionContext.of(callOrderSummary.getSummaryData().getProductId()),
ImmutableList.of(oldQtyDelivered.negate(), qtyDelivered),
qtyDelivered.getUomId());
summaryService.addQtyDelivered(callOrderSummaryId, deltaQtyDelivered);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_NEW },
ifColumnsChanged = { I_C_CallOrderDetail.COLUMNNAME_QtyInvoicedInUOM })
public void syncQtyInvoicedChanged(@NonNull final I_C_CallOrderDetail callOrderDetail)
{
final CallOrderSummaryId callOrderSummaryId = CallOrderSummaryId.ofRepoId(callOrderDetail.getC_CallOrderSummary_ID());
final Quantity qtyInvoiced = getQtyInvoiced(callOrderDetail);
|
if (InterfaceWrapperHelper.isNew(callOrderDetail))
{
summaryService.addQtyInvoiced(callOrderSummaryId, qtyInvoiced);
return;
}
final CallOrderSummary callOrderSummary = summaryService.getById(callOrderSummaryId);
final I_C_CallOrderDetail oldRecord = InterfaceWrapperHelper.createOld(callOrderDetail, I_C_CallOrderDetail.class);
final Quantity oldQtyInvoiced = getQtyInvoiced(oldRecord);
final Quantity deltaQtyInvoiced = conversionBL.computeSum(
UOMConversionContext.of(callOrderSummary.getSummaryData().getProductId()),
ImmutableList.of(oldQtyInvoiced.negate(), qtyInvoiced),
qtyInvoiced.getUomId());
summaryService.addQtyInvoiced(callOrderSummaryId, deltaQtyInvoiced);
}
@NonNull
private static Quantity getQtyDelivered(@NonNull final I_C_CallOrderDetail callOrderDetail)
{
return Quantitys.of(callOrderDetail.getQtyDeliveredInUOM(), UomId.ofRepoId(callOrderDetail.getC_UOM_ID()));
}
@NonNull
private static Quantity getQtyInvoiced(@NonNull final I_C_CallOrderDetail callOrderDetail)
{
return Quantitys.of(callOrderDetail.getQtyInvoicedInUOM(), UomId.ofRepoId(callOrderDetail.getC_UOM_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\interceptor\C_CallOrderDetail.java
| 1
|
请完成以下Java代码
|
public void setModerationType (String ModerationType)
{
set_Value (COLUMNNAME_ModerationType, ModerationType);
}
/** Get Moderation Type.
@return Type of moderation
*/
public String getModerationType ()
{
return (String)get_Value(COLUMNNAME_ModerationType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
|
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatType.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8080
spring:
profiles:
default: dev
# 可以被命令行切换
active: dev, main
# 不会被切换
include:
- dev
- main
group:
main:
- main1
- main2
config:
import:
- optional:classpath:/config/app.yml
javastack:
name: Java技术栈
site: www.javastack.cn
author: 栈长
users:
- Jom
- Lucy
- Jack
params:
tel: 18800008888
address: China
security:
# 生成随机 32 位 MD5 字符串
security-key: ${random.value}
security-code: ${random.uuid}
member:
name: Tom
sex: 1
age: ${random.int[18,100]}
birthday: 2000-12-12 12:00:00
---
member:
name: Jack
se
|
x: 1
age: 20
birthday: 2000-01-01 12:00:00
spring:
config:
activate:
on-profile: "dev | test"
---
member:
name: Jack1
spring:
config:
activate:
on-profile: main1
---
member:
name: Jack2
spring:
config:
activate:
on-profile: main2
|
repos\spring-boot-best-practice-master\spring-boot-properties\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class CsvExportUtil {
private static final String CSV_COLUMN_SEPARATOR = ",";
private static final String CSV_ROW_SEPARATOR = "\r\n";
private static final String CSV_TAB = "\t";
public static void doExportByList(List<List<Object>> dataList, List<String> titles, OutputStream os) throws IOException {
StringBuilder buf = new StringBuilder();
if (CollectionUtils.isNotEmpty(titles)) {
for (int i = 0; i < titles.size(); i++) {
String title = titles.get(i);
buf.append(title);
if (i < titles.size() - 1) {
buf.append(CSV_TAB).append(CSV_COLUMN_SEPARATOR);
}
}
buf.append(CSV_ROW_SEPARATOR);
}
if (CollectionUtils.isNotEmpty(dataList)) {
for (List<Object> data : dataList) {
for (int i = 0; i < data.size(); i++) {
buf.append(data.get(i));
if (i < data.size() - 1) {
buf.append(CSV_TAB).append(CSV_COLUMN_SEPARATOR);
}
}
|
buf.append(CSV_ROW_SEPARATOR);
}
}
os.write(buf.toString().getBytes("UTF-8"));
os.flush();
}
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName == null ? sdf.format(new Date()) + ".csv" : fileName + sdf.format(new Date()) + ".csv";
String utf = "UTF-8";
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
response.setHeader(HttpHeaders.TRANSFER_ENCODING, "chunked");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
}
}
|
repos\spring-boot-student-master\spring-boot-student-export\src\main\java\com\xiaolyuh\utils\CsvExportUtil.java
| 1
|
请完成以下Java代码
|
private static ObjectNode mapDependency(Dependency dep) {
ObjectNode node = nodeFactory.objectNode();
node.put("groupId", dep.getGroupId());
node.put("artifactId", dep.getArtifactId());
node.put("scope", dep.getScope());
addIfNotNull(node, "version", dep.getVersion());
addIfNotNull(node, "bom", dep.getBom());
addIfNotNull(node, "repository", dep.getRepository());
return node;
}
private static void addIfNotNull(ObjectNode node, String key, String value) {
if (value != null) {
node.put(key, value);
}
}
private static JsonNode mapRepository(Repository repo) {
ObjectNode node = nodeFactory.objectNode();
node.put("name", repo.getName())
.put("url", (repo.getUrl() != null) ? repo.getUrl().toString() : null)
.put("snapshotEnabled", repo.isSnapshotsEnabled());
return node;
}
private static ObjectNode mapBom(BillOfMaterials bom) {
ObjectNode node = nodeFactory.objectNode();
node.put("groupId", bom.getGroupId());
node.put("artifactId", bom.getArtifactId());
addIfNotNull(node, "version", bom.getVersion());
addArrayIfNotNull(node, bom.getRepositories());
return node;
}
private static void addArrayIfNotNull(ObjectNode node, List<String> values) {
if (!CollectionUtils.isEmpty(values)) {
ArrayNode arrayNode = nodeFactory.arrayNode();
values.forEach(arrayNode::add);
node.set("repositories", arrayNode);
}
}
|
private static ObjectNode mapNode(Map<String, JsonNode> content) {
ObjectNode node = nodeFactory.objectNode();
content.forEach(node::set);
return node;
}
private ObjectNode mapDependencies(Map<String, Dependency> dependencies) {
return mapNode(dependencies.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapDependency(entry.getValue()))));
}
private ObjectNode mapRepositories(Map<String, Repository> repositories) {
return mapNode(repositories.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapRepository(entry.getValue()))));
}
private ObjectNode mapBoms(Map<String, BillOfMaterials> boms) {
return mapNode(boms.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapBom(entry.getValue()))));
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\DependencyMetadataV21JsonMapper.java
| 1
|
请完成以下Java代码
|
public class AD_EventLog_Entry_RepostEvent extends JavaProcess
{
private final IEventBusFactory eventBusFactory = Services.get(IEventBusFactory.class);
private final EventLogService eventLogService = SpringContextHolder.instance.getBean(EventLogService.class);
@Override
protected String doIt() throws Exception
{
final I_AD_EventLog_Entry eventLogEntryRecord = getRecord(I_AD_EventLog_Entry.class);
final I_AD_EventLog eventLogRecord = eventLogEntryRecord.getAD_EventLog();
Check.assumeNotNull(eventLogRecord.getEventTopicName(), "EventTopicName is null");
Check.assumeNotNull(eventLogRecord.getEventTypeName(), "EventTypeName is null");
final Topic topic = Topic.builder()
.name(eventLogRecord.getEventTopicName())
.type(Type.valueOf(eventLogRecord.getEventTypeName()))
.build();
final boolean typeMismatchBetweenTopicAndBus = !Type.valueOf(eventLogRecord.getEventTypeName()).equals(topic.getType());
if (typeMismatchBetweenTopicAndBus)
|
{
addLog("The given event log record has a different topic than the event bus!");
}
final IEventBus eventBus = eventBusFactory.getEventBus(topic);
final ImmutableList<String> handlerToIgnore = ImmutableList.of(eventLogEntryRecord.getClassname());
final Event event = eventLogService.loadEventForReposting(
EventLogId.ofRepoId(eventLogRecord.getAD_EventLog_ID()),
handlerToIgnore);
eventBus.enqueueEvent(event);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\process\AD_EventLog_Entry_RepostEvent.java
| 1
|
请完成以下Java代码
|
private void closeConnections(HikariDataSource dataSource, Duration shutdownTimeout) {
logger.info("Evicting Hikari connections");
dataSource.getHikariPoolMXBean().softEvictConnections();
logger.debug(LogMessage.format("Waiting %d seconds for Hikari connections to be closed",
shutdownTimeout.toSeconds()));
CompletableFuture<Void> allConnectionsClosed = CompletableFuture
.runAsync(() -> this.waitForConnectionsToClose(dataSource));
try {
allConnectionsClosed.get(shutdownTimeout.toMillis(), TimeUnit.MILLISECONDS);
logger.debug("Hikari connections closed");
}
catch (InterruptedException ex) {
logger.warn("Interrupted while waiting for connections to be closed", ex);
Thread.currentThread().interrupt();
}
catch (TimeoutException ex) {
logger.warn(LogMessage.format("Hikari connections could not be closed within %s", shutdownTimeout), ex);
}
catch (ExecutionException ex) {
throw new RuntimeException("Failed to close Hikari connections", ex);
}
}
private void waitForConnectionsToClose(HikariDataSource dataSource) {
while (this.hasOpenConnections.apply((HikariPool) dataSource.getHikariPoolMXBean())) {
try {
|
TimeUnit.MILLISECONDS.sleep(50);
}
catch (InterruptedException ex) {
logger.error("Interrupted while waiting for datasource connections to be closed", ex);
Thread.currentThread().interrupt();
}
}
}
@Override
public boolean isRunning() {
return this.dataSource != null && this.dataSource.isRunning();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\HikariCheckpointRestoreLifecycle.java
| 1
|
请完成以下Java代码
|
public String getTreatment() {
if (treatment == null) {
return "ambulatory";
} else {
return treatment;
}
}
/**
* Sets the value of the treatment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTreatment(String value) {
this.treatment = value;
}
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReason(String value) {
this.reason = value;
}
/**
* Gets the value of the apid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getApid() {
return apid;
}
/**
* Sets the value of the apid property.
*
* @param value
* allowed object is
|
* {@link String }
*
*/
public void setApid(String value) {
this.apid = value;
}
/**
* Gets the value of the acid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAcid() {
return acid;
}
/**
* Sets the value of the acid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcid(String value) {
this.acid = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\TreatmentType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getAmountTypeCode() {
return amountTypeCode;
}
/**
* Sets the value of the amountTypeCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAmountTypeCode(String value) {
this.amountTypeCode = value;
}
/**
* Gets the value of the amount property.
*
* @return
|
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getAmount() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmount(BigDecimal value) {
this.amount = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\MonetaryAmountType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ImmutableAttributeSet getImmutableAttributeSet(final AttributeSetInstanceId asiId)
{
return asiBL.getImmutableAttributeSetById(asiId);
}
public Optional<HuId> getHuIdByQRCodeIfExists(@NonNull final HUQRCode qrCode)
{
return huQRCodeService.getHuIdByQRCodeIfExists(qrCode);
}
public void assignQRCodeForReceiptHU(@NonNull final HUQRCode qrCode, @NonNull final HuId huId)
{
final boolean ensureSingleAssignment = true;
huQRCodeService.assign(qrCode, huId, ensureSingleAssignment);
}
public HUQRCode getFirstQRCodeByHuId(@NonNull final HuId huId)
{
return huQRCodeService.getFirstQRCodeByHuId(huId);
}
public Quantity getHUCapacity(
@NonNull final HuId huId,
@NonNull final ProductId productId,
@NonNull final I_C_UOM uom)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
return handlingUnitsBL
.getStorageFactory()
.getStorage(hu)
.getQuantity(productId, uom);
}
@NonNull
public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId)
{
final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId)
.stream()
.map(locatorId -> {
final String caption = getLocatorName(locatorId);
|
return LocatorInfo.builder()
.id(locatorId)
.caption(caption)
.qrCode(LocatorQRCode.builder()
.locatorId(locatorId)
.caption(caption)
.build())
.build();
})
.collect(ImmutableList.toImmutableList());
return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList);
}
@NonNull
public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId)
{
return productBL.getCatchUOMId(productId);
}
@NonNull
private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId)
{
final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId);
return handlingUnitsBL.getLocatorIds(huIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java
| 2
|
请完成以下Java代码
|
public class MBPGroup extends X_C_BP_Group
{
public MBPGroup(Properties ctx, int C_BP_Group_ID, String trxName)
{
super(ctx, C_BP_Group_ID, trxName);
if (C_BP_Group_ID == 0)
{
// setValue (null);
// setName (null);
setIsConfidentialInfo(false); // N
setIsDefault(false);
setPriorityBase(PRIORITYBASE_Same);
}
}
public MBPGroup(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
|
}
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (newRecord && success)
return insert_Accounting("C_BP_Group_Acct", "C_AcctSchema_Default", null);
return success;
}
@Override
protected boolean beforeDelete()
{
return delete_Accounting("C_BP_Group_Acct");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MBPGroup.java
| 1
|
请完成以下Java代码
|
public int getLaneId()
{
return laneId;
}
private List<Integer> getCardIds()
{
return cardIds;
}
public void addCardIdAtPosition(final int cardId, final int position)
{
Preconditions.checkArgument(cardId > 0, "cardId > 0");
if (position < 0)
{
cardIds.remove((Object)cardId);
cardIds.add(cardId);
}
else if (position == Integer.MAX_VALUE || position > cardIds.size() - 1)
{
cardIds.remove((Object)cardId);
cardIds.add(cardId);
}
|
else
{
cardIds.remove((Object)cardId);
cardIds.add(position, cardId);
}
}
public void removeCardId(final int cardId)
{
Preconditions.checkArgument(cardId > 0, "cardId > 0");
cardIds.remove((Object)cardId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\BoardDescriptorRepository.java
| 1
|
请完成以下Java代码
|
public void setC_DocLine_Sort(org.compiere.model.I_C_DocLine_Sort C_DocLine_Sort)
{
set_ValueFromPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class, C_DocLine_Sort);
}
/** Set Document Line Sorting Preferences.
@param C_DocLine_Sort_ID Document Line Sorting Preferences */
@Override
public void setC_DocLine_Sort_ID (int C_DocLine_Sort_ID)
{
if (C_DocLine_Sort_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, Integer.valueOf(C_DocLine_Sort_ID));
}
/** Get Document Line Sorting Preferences.
@return Document Line Sorting Preferences */
@Override
public int getC_DocLine_Sort_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document Line Sorting Preferences Item.
@param C_DocLine_Sort_Item_ID Document Line Sorting Preferences Item */
@Override
public void setC_DocLine_Sort_Item_ID (int C_DocLine_Sort_Item_ID)
{
if (C_DocLine_Sort_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_Item_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_Item_ID, Integer.valueOf(C_DocLine_Sort_Item_ID));
}
/** Get Document Line Sorting Preferences Item.
@return Document Line Sorting Preferences Item */
@Override
public int getC_DocLine_Sort_Item_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_Item_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
|
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocLine_Sort_Item.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getResourceLocation() {
return resourceLocation;
}
public void setResourceLocation(String resourceLocation) {
this.resourceLocation = resourceLocation;
}
public List<String> getResourceSuffixes() {
return resourceSuffixes;
}
public void setResourceSuffixes(List<String> resourceSuffixes) {
this.resourceSuffixes = resourceSuffixes;
}
|
public boolean isDeployResources() {
return deployResources;
}
public void setDeployResources(boolean deployResources) {
this.deployResources = deployResources;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\app\FlowableAppProperties.java
| 2
|
请完成以下Java代码
|
public class ScopedAssociation {
@Inject
private RuntimeService runtimeService;
@Inject
private TaskService taskService;
protected VariableMap cachedVariables = new VariableMapImpl();
protected VariableMap cachedVariablesLocal = new VariableMapImpl();
protected Execution execution;
protected Task task;
public Execution getExecution() {
return execution;
}
public void setExecution(Execution execution) {
this.execution = execution;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
@SuppressWarnings("unchecked")
public <T extends TypedValue> T getVariable(String variableName) {
TypedValue value = cachedVariables.getValueTyped(variableName);
if(value == null) {
if(execution != null) {
value = runtimeService.getVariableTyped(execution.getId(), variableName);
cachedVariables.put(variableName, value);
}
}
return (T) value;
}
public void setVariable(String variableName, Object value) {
cachedVariables.put(variableName, value);
}
public VariableMap getCachedVariables() {
return cachedVariables;
}
@SuppressWarnings("unchecked")
public <T extends TypedValue> T getVariableLocal(String variableName) {
TypedValue value = cachedVariablesLocal.getValueTyped(variableName);
if (value == null) {
if (task != null) {
value = taskService.getVariableLocalTyped(task.getId(), variableName);
cachedVariablesLocal.put(variableName, value);
} else if (execution != null) {
value = runtimeService.getVariableLocalTyped(execution.getId(), variableName);
cachedVariablesLocal.put(variableName, value);
}
}
|
return (T) value;
}
public void setVariableLocal(String variableName, Object value) {
if (execution == null && task == null) {
throw new ProcessEngineCdiException("Cannot set a local cached variable: neither a Task nor an Execution is associated.");
}
cachedVariablesLocal.put(variableName, value);
}
public VariableMap getCachedVariablesLocal() {
return cachedVariablesLocal;
}
public void flushVariableCache() {
if(task != null) {
taskService.setVariablesLocal(task.getId(), cachedVariablesLocal);
taskService.setVariables(task.getId(), cachedVariables);
} else if(execution != null) {
runtimeService.setVariablesLocal(execution.getId(), cachedVariablesLocal);
runtimeService.setVariables(execution.getId(), cachedVariables);
} else {
throw new ProcessEngineCdiException("Cannot flush variable cache: neither a Task nor an Execution is associated.");
}
// clear variable cache after flush
cachedVariables.clear();
cachedVariablesLocal.clear();
}
}
|
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\ScopedAssociation.java
| 1
|
请完成以下Java代码
|
public void setSorting(List<SortingDto> sorting) {
this.sortings = sorting;
}
public List<SortingDto> getSorting() {
return sortings;
}
protected abstract boolean isValidSortByValue(String value);
protected boolean sortOptionsValid() {
return (sortBy != null && sortOrder != null) || (sortBy == null && sortOrder == null);
}
public T toQuery(ProcessEngine engine) {
T query = createNewQuery(engine);
applyFilters(query);
if (!sortOptionsValid()) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Only a single sorting parameter specified. sortBy and sortOrder required");
}
applySortingOptions(query, engine);
return query;
}
protected abstract T createNewQuery(ProcessEngine engine);
protected abstract void applyFilters(T query);
protected void applySortingOptions(T query, ProcessEngine engine) {
if (sortBy != null) {
applySortBy(query, sortBy, null, engine);
}
if (sortOrder != null) {
applySortOrder(query, sortOrder);
}
if (sortings != null) {
|
for (SortingDto sorting : sortings) {
String sortingOrder = sorting.getSortOrder();
String sortingBy = sorting.getSortBy();
if (sortingBy != null) {
applySortBy(query, sortingBy, sorting.getParameters(), engine);
}
if (sortingOrder != null) {
applySortOrder(query, sortingOrder);
}
}
}
}
protected abstract void applySortBy(T query, String sortBy, Map<String, Object> parameters, ProcessEngine engine);
protected void applySortOrder(T query, String sortOrder) {
if (sortOrder != null) {
if (sortOrder.equals(SORT_ORDER_ASC_VALUE)) {
query.asc();
} else if (sortOrder.equals(SORT_ORDER_DESC_VALUE)) {
query.desc();
}
}
}
public static String sortOrderValueForDirection(Direction direction) {
if (Direction.ASCENDING.equals(direction)) {
return SORT_ORDER_ASC_VALUE;
}
else if (Direction.DESCENDING.equals(direction)) {
return SORT_ORDER_DESC_VALUE;
}
else {
throw new RestException("Unknown query sorting direction " + direction);
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AbstractQueryDto.java
| 1
|
请完成以下Java代码
|
public class ProcessDefinitionCache extends ResourceDefinitionCache<ProcessDefinitionEntity> {
public ProcessDefinitionCache(CacheFactory factory, int cacheCapacity, CacheDeployer cacheDeployer) {
super(factory, cacheCapacity, cacheDeployer);
}
@Override
protected AbstractResourceDefinitionManager<ProcessDefinitionEntity> getManager() {
return Context.getCommandContext().getProcessDefinitionManager();
}
@Override
protected void checkInvalidDefinitionId(String definitionId) {
ensureNotNull("Invalid process definition id", "processDefinitionId", definitionId);
}
@Override
protected void checkDefinitionFound(String definitionId, ProcessDefinitionEntity definition) {
ensureNotNull(NotFoundException.class, "no deployed process definition found with id '" + definitionId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKey(String definitionKey, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key '" + definitionKey + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key '" + definitionKey + "' and tenant-id '" + tenantId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key = '" + definitionKey + "', version = '" + definitionVersion
+ "' and tenant-id = '" + tenantId + "'", "processDefinition", definition);
}
|
@Override
protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId,
ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key = '" + definitionKey + "', versionTag = '" + definitionVersionTag
+ "' and tenant-id = '" + tenantId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key = '" + definitionKey + "' in deployment = '" + deploymentId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, ProcessDefinitionEntity definition) {
ensureNotNull("deployment '" + deploymentId + "' didn't put process definition '" + definitionId + "' in the cache", "cachedProcessDefinition", definition);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\ProcessDefinitionCache.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalSystemWooCommerceConfigId implements IExternalSystemChildConfigId
{
int repoId;
@JsonCreator
@NonNull
public static ExternalSystemWooCommerceConfigId ofRepoId(final int repoId)
{
return new ExternalSystemWooCommerceConfigId(repoId);
}
@Nullable
public static ExternalSystemWooCommerceConfigId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ExternalSystemWooCommerceConfigId(repoId) : null;
}
public static ExternalSystemWooCommerceConfigId cast(@NonNull final IExternalSystemChildConfigId id)
{
return (ExternalSystemWooCommerceConfigId)id;
}
@JsonValue
public int toJson()
|
{
return getRepoId();
}
private ExternalSystemWooCommerceConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_Config_WooCommerce_ID");
}
@Override
public ExternalSystemType getType()
{
return ExternalSystemType.WOO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\woocommerce\ExternalSystemWooCommerceConfigId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class TestController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private TestService testService;
@GetMapping("async")
public String testAsync() throws Exception {
long start = System.currentTimeMillis();
logger.info("异步方法开始");
Future<String> stringFuture = testService.asyncMethod();
String result = stringFuture.get(60, TimeUnit.SECONDS);
logger.info("异步方法返回值:{}", result);
logger.info("异步方法结束");
long end = System.currentTimeMillis();
|
logger.info("总耗时:{} ms", end - start);
return stringFuture.get();
}
@GetMapping("sync")
public void testSync() {
long start = System.currentTimeMillis();
logger.info("同步方法开始");
testService.syncMethod();
logger.info("同步方法结束");
long end = System.currentTimeMillis();
logger.info("总耗时:{} ms", end - start);
}
}
|
repos\SpringAll-master\49.Spring-Boot-Async\src\main\java\com\example\demo\controller\TestController.java
| 2
|
请完成以下Java代码
|
private static ByteArray generate() throws IOException
{
int preType = 5;
int preChar = 0;
List<int[]> typeList = new LinkedList<int[]>();
for (int i = 0; i <= Character.MAX_VALUE; ++i)
{
int type = TextUtility.charType((char) i);
// System.out.printf("%d %d\n", i, TextUtility.charType((char) i));
if (type != preType)
{
int[] array = new int[3];
array[0] = preChar;
array[1] = i - 1;
array[2] = preType;
typeList.add(array);
// System.out.printf("%d %d %d\n", array[0], array[1], array[2]);
preChar = i;
}
preType = type;
}
{
int[] array = new int[3];
array[0] = preChar;
array[1] = (int) Character.MAX_VALUE;
array[2] = preType;
typeList.add(array);
}
// System.out.print("int[" + typeList.size() + "][3] array = \n");
DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(HanLP.Config.CharTypePath));
for (int[] array : typeList)
{
// System.out.printf("%d %d %d\n", array[0], array[1], array[2]);
out.writeChar(array[0]);
out.writeChar(array[1]);
out.writeByte(array[2]);
}
out.close();
ByteArray byteArray = ByteArray.createByteArray(HanLP.Config.CharTypePath);
return byteArray;
}
/**
* 获取字符的类型
|
*
* @param c
* @return
*/
public static byte get(char c)
{
return type[(int) c];
}
/**
* 设置字符类型
*
* @param c 字符
* @param t 类型
*/
public static void set(char c, byte t)
{
type[c] = t;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\other\CharType.java
| 1
|
请完成以下Java代码
|
private static RelatedProcessDescriptor replacingWindowIdIfNeeded(
@NonNull final RelatedProcessDescriptor descriptor,
@NonNull final AdWindowId windowId)
{
if (descriptor.getWindowId() == null)
{
return descriptor;
}
else if (AdWindowId.equals(descriptor.getWindowId(), windowId))
{
return descriptor;
}
else
{
return descriptor.toBuilder().windowId(windowId).tabId(null).build();
}
}
/**
* Create a document specific process with a specific workflow for the given document. Link the process to the document
*/
public I_AD_Process createAndLinkDocumentSpecificProcess(@NonNull final I_AD_Table document)
{
// Workflow
final I_AD_Workflow adWorkflow = workflowBL.createWorkflowForDocument(document);
// Process
final I_AD_Process adProcess = InterfaceWrapperHelper.newInstance(I_AD_Process.class);
adProcess.setAD_Workflow_ID(adWorkflow.getAD_Workflow_ID());
adProcess.setValue(adWorkflow.getValue());
adProcess.setName(adWorkflow.getName());
adProcess.setEntityType(adWorkflow.getEntityType());
adProcess.setAccessLevel(adWorkflow.getAccessLevel());
adProcess.setType(X_AD_Process.TYPE_Java);
adProcess.setIsReport(false);
adProcess.setIsUseBPartnerLanguage(true);
InterfaceWrapperHelper.save(adProcess);
//
linkProcessWithDocument(document, adProcess);
return adProcess;
}
private void linkProcessWithDocument(@NonNull final I_AD_Table document, @NonNull final I_AD_Process documentSpecificProcess)
{
final I_AD_Column processingColumn = getColumnForDocument(document, DocumentTableFields.COLUMNNAME_Processing);
linkProcessingColumnWithProcess(documentSpecificProcess, processingColumn);
final I_AD_Column docActionColumn = getColumnForDocument(document, DocumentTableFields.COLUMNNAME_DocAction);
linkProcessingColumnWithProcess(documentSpecificProcess, docActionColumn);
|
}
private void linkProcessingColumnWithProcess(final I_AD_Process documentSpecificProcess, final I_AD_Column processingColumn)
{
if (processingColumn == null)
{
// nothing to do if the column does not exist for the document table
return;
}
processingColumn.setAD_Process(documentSpecificProcess);
InterfaceWrapperHelper.save(processingColumn);
}
private I_AD_Column getColumnForDocument(@NonNull final I_AD_Table document, @NonNull final String columnName)
{
final String tableName = adTableDAO.retrieveTableName(document.getAD_Table_ID());
return adTableDAO.retrieveColumn(tableName, columnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ADProcessService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PurchaseCandidateDimensionFactory implements DimensionFactory<I_C_PurchaseCandidate>
{
@Override
public String getHandledTableName()
{
return I_C_PurchaseCandidate.Table_Name;
}
@Override
public void updateRecord(final I_C_PurchaseCandidate record, final Dimension from)
{
record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId()));
record.setC_Campaign_ID(from.getCampaignId());
record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId()));
record.setC_OrderSO_ID(OrderId.toRepoId(from.getSalesOrderId()));
record.setUserElementString1(from.getUserElementString1());
record.setUserElementString2(from.getUserElementString2());
record.setUserElementString3(from.getUserElementString3());
record.setUserElementString4(from.getUserElementString4());
record.setUserElementString5(from.getUserElementString5());
record.setUserElementString6(from.getUserElementString6());
record.setUserElementString7(from.getUserElementString7());
}
@NonNull
@Override
|
public Dimension getFromRecord(@NonNull final I_C_PurchaseCandidate record)
{
return Dimension.builder()
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.campaignId(record.getC_Campaign_ID())
.activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID()))
.userElementString1(record.getUserElementString1())
.userElementString2(record.getUserElementString2())
.userElementString3(record.getUserElementString3())
.userElementString4(record.getUserElementString4())
.userElementString5(record.getUserElementString5())
.userElementString6(record.getUserElementString6())
.userElementString7(record.getUserElementString7())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\document\dimension\PurchaseCandidateDimensionFactory.java
| 2
|
请完成以下Java代码
|
public static final class Builder {
private final String rolePrefix;
private final Map<String, Set<GrantedAuthority>> hierarchy;
private Builder(String rolePrefix) {
this.rolePrefix = rolePrefix;
this.hierarchy = new LinkedHashMap<>();
}
/**
* Creates a new hierarchy branch to define a role and its child roles.
* @param role the highest role in this branch
* @return a {@link ImpliedRoles} to define the child roles for the
* <code>role</code>
*/
public ImpliedRoles role(String role) {
Assert.hasText(role, "role must not be empty");
return new ImpliedRoles(role);
}
/**
* Builds and returns a {@link RoleHierarchyImpl} describing the defined role
* hierarchy.
* @return a {@link RoleHierarchyImpl}
*/
public RoleHierarchyImpl build() {
return new RoleHierarchyImpl(this.hierarchy);
}
private Builder addHierarchy(String role, String... impliedRoles) {
Set<GrantedAuthority> withPrefix = this.hierarchy.computeIfAbsent(this.rolePrefix.concat(role),
(r) -> new HashSet<>());
for (String impliedRole : impliedRoles) {
withPrefix.add(new SimpleGrantedAuthority(this.rolePrefix.concat(impliedRole)));
}
return this;
}
/**
* Builder class for constructing child roles within a role hierarchy branch.
*/
public final class ImpliedRoles {
private final String role;
private ImpliedRoles(String role) {
|
this.role = role;
}
/**
* Specifies implied role(s) for the current role in the hierarchy.
* @param impliedRoles role name(s) implied by the role.
* @return the same {@link Builder} instance
* @throws IllegalArgumentException if <code>impliedRoles</code> is null,
* empty or contains any null element.
*/
public Builder implies(String... impliedRoles) {
Assert.notEmpty(impliedRoles, "at least one implied role must be provided");
Assert.noNullElements(impliedRoles, "implied role name(s) cannot be empty");
return Builder.this.addHierarchy(this.role, impliedRoles);
}
}
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\access\hierarchicalroles\RoleHierarchyImpl.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://172.17.0.9:3306/JForum?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = jishimen.2018
spring.redis.host=172.17.0.10
spring.redis.port=6379
spring.redis.timeout=60000
## Dubbo 服务提供者配置
spring.dubbo.application.name=redis-provider
s
|
pring.dubbo.registry.address=zookeeper://172.17.0.2:2181
spring.dubbo.protocol.name=dubbo
spring.dubbo.protocol.port=20880
spring.dubbo.scan=com.gaoxi.redis.service
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Redis\src\main\resources\application-test.properties
| 2
|
请完成以下Java代码
|
protected boolean afterSave(boolean newRecord, boolean success)
{
//metas start: cg task us025b
if (success)
{
updateAmounts();
}
return success;
//metas end: cg task us025b
}
@Override
protected boolean afterDelete(boolean success)
{
//metas start: cg task us025b
if (success)
{
updateAmounts();
}
return success;
//metas end: cg task us025b
}
|
/**
* metas cg task us025b
* method for updating amounts in payment
*/
private void updateAmounts()
{
String updateSQL = "UPDATE C_Payment "
+ " set PayAmt = (SELECT SUM(Amount) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " DiscountAmt = (SELECT SUM(DiscountAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " WriteOffAmt = (SELECT SUM(WriteOffAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " OverUnderAmt = (SELECT SUM(OverUnderAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " IsOverUnderPayment = (SELECT CASE WHEN sum(OverUnderAmt)!=0 THEN 'Y' ELSE 'N' END FROM C_PaymentAllocate WHERE C_Payment_ID=?) "
+ " WHERE C_Payment_ID=?";
DB.executeUpdateAndIgnoreErrorOnFail(updateSQL, new Object[] { getC_Payment_ID(), getC_Payment_ID(), getC_Payment_ID(),
getC_Payment_ID(), getC_Payment_ID(), getC_Payment_ID() },
false, get_TrxName());
}
} // MPaymentAllocate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MPaymentAllocate.java
| 1
|
请完成以下Java代码
|
public class Player {
private String firstName;
private String lastName;
private String position;
public Player() {
}
public Player(String firstName, String lastName, String position) {
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, position);
}
@Override
public boolean equals(Object obj) {
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Player other = (Player) obj;
if (firstName == null) {
if (other.firstName != null) {
return false;
}
} else if (!firstName.equals(other.firstName)) {
return false;
}
if (lastName == null) {
if (other.lastName != null) {
return false;
}
} else if (!lastName.equals(other.lastName)) {
return false;
}
if (position == null) {
if (other.position != null) {
return false;
}
} else if (!position.equals(other.position)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-3\src\main\java\com\baeldung\hash\Player.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DroolsConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DroolsConfig.class);
private KieServices kieServices = KieServices.Factory.get();
@Bean
public KieSession getKieSession() throws IOException {
LOGGER.info("Session created...");
KieSession kieSession = getKieContainer().newKieSession();
kieSession.setGlobal("showResults", new OutputDisplay());
kieSession.setGlobal("sh", new OutputDisplay());
kieSession.addEventListener(new RuleRuntimeEventListener() {
@Override
public void objectInserted(ObjectInsertedEvent event) {
System.out.println("Object inserted \n "
+ event.getObject().toString());
}
@Override
public void objectUpdated(ObjectUpdatedEvent event) {
System.out.println("Object was updated \n"
+ "New Content \n"
+ event.getObject().toString());
}
@Override
public void objectDeleted(ObjectDeletedEvent event) {
System.out.println("Object retracted \n"
+ event.getOldObject().toString());
}
});
return kieSession;
}
@Bean
public KieContainer getKieContainer() throws IOException {
LOGGER.info("Container created...");
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
kb.buildAll();
KieModule kieModule = kb.getKieModule();
|
return kieServices.newKieContainer(kieModule.getReleaseId());
}
private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
@Override
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
}
private KieFileSystem getKieFileSystem() throws IOException {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("order.drl"));
return kieFileSystem;
}
}
|
repos\springboot-demo-master\drools\src\main\java\com\et\drools\DroolsConfig.java
| 2
|
请完成以下Java代码
|
public int getAD_Client_ID() {
return m_AD_Client_ID;
}
@Override
public void initialize(ModelValidationEngine engine, MClient client) {
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
engine.addDocValidate(I_C_Order.Table_Name, this);
engine.addModelChange(I_C_OrderLine.Table_Name, this);
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) {
return null;
}
@Override
public String modelChange(PO po, int type) throws Exception {
if (po instanceof MOrderLine) {
|
if (type == TYPE_AFTER_DELETE) {
MOrderLine ol = (MOrderLine) po;
MOrder order = ol.getParent();
String promotionCode = (String)order.get_Value("PromotionCode");
if (ol.getC_Charge_ID() > 0) {
Integer promotionID = (Integer) ol.get_Value("M_Promotion_ID");
if (promotionID != null && promotionID.intValue() > 0) {
int M_PromotionPreCondition_ID = findPromotionPreConditionId(
order, promotionCode, promotionID);
if (M_PromotionPreCondition_ID > 0) {
String update = "UPDATE M_PromotionPreCondition SET PromotionCounter = PromotionCounter - 1 WHERE M_PromotionPreCondition_ID = ?";
DB.executeUpdateAndSaveErrorOnFail(update, M_PromotionPreCondition_ID, order.get_TrxName());
}
}
}
}
}
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\model\PromotionValidator.java
| 1
|
请完成以下Java代码
|
private final I_M_Material_Tracking_Ref createMaterialTrackingRef(@NonNull final MTLinkRequest request)
{
final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class);
final I_M_Material_Tracking_Ref refNew = materialTrackingDAO.createMaterialTrackingRefNoSave(request.getMaterialTrackingRecord(), request.getModel());
if (request.getQtyIssued() != null)
{
refNew.setQtyIssued(request.getQtyIssued());
}
final String msg = ": Linking model with M_Material_Tracking_ID=" + refNew.getM_Material_Tracking_ID();
logRequest(request, msg);
listeners.beforeModelLinked(request, refNew);
InterfaceWrapperHelper.save(refNew);
listeners.afterModelLinked(request);
return refNew;
}
private void logRequest(final MTLinkRequest request, final String msgSuffix)
{
logger.debug(request + msgSuffix); // log the request
Loggables.addLog(request.getModel() + msgSuffix); // don't be too verbose in the user/admin output; keep it readable.
}
@Override
public boolean unlinkModelFromMaterialTrackings(final Object model)
{
final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class);
final List<I_M_Material_Tracking_Ref> existingRefs = materialTrackingDAO.retrieveMaterialTrackingRefsForModel(model);
for (final I_M_Material_Tracking_Ref exitingRef : existingRefs)
{
unlinkModelFromMaterialTracking(model, exitingRef);
}
return true;
}
@Override
public boolean unlinkModelFromMaterialTrackings(final Object model, @NonNull final I_M_Material_Tracking materialTracking)
{
final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class);
final List<I_M_Material_Tracking_Ref> existingRefs = materialTrackingDAO.retrieveMaterialTrackingRefsForModel(model);
if (existingRefs.isEmpty())
{
|
return false;
}
boolean atLeastOneUnlinked = false;
for (final I_M_Material_Tracking_Ref exitingRef : existingRefs)
{
if (exitingRef.getM_Material_Tracking_ID() != materialTracking.getM_Material_Tracking_ID())
{
continue;
}
unlinkModelFromMaterialTracking(model, exitingRef);
atLeastOneUnlinked = true;
}
return atLeastOneUnlinked;
}
private final void unlinkModelFromMaterialTracking(final Object model, final I_M_Material_Tracking_Ref ref)
{
final I_M_Material_Tracking materialTrackingOld = ref.getM_Material_Tracking();
InterfaceWrapperHelper.delete(ref);
listeners.afterModelUnlinked(model, materialTrackingOld);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingBL.java
| 1
|
请完成以下Java代码
|
public void setOperation(final OPERATION operation) {
this.operation = operation.getValue();
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(final long timestamp) {
this.timestamp = timestamp;
}
public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(final long createdDate) {
this.createdDate = createdDate;
}
public long getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(final long modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(final String modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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 Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
|
}
@PrePersist
public void onPrePersist() {
logger.info("@PrePersist");
audit(OPERATION.INSERT);
}
@PreUpdate
public void onPreUpdate() {
logger.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
logger.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
public enum OPERATION {
INSERT, UPDATE, DELETE;
private String value;
OPERATION() {
value = toString();
}
public static OPERATION parse(final String value) {
OPERATION operation = null;
for (final OPERATION op : OPERATION.values()) {
if (op.getValue().equals(value)) {
operation = op;
break;
}
}
return operation;
}
public String getValue() {
return value;
}
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Bar.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Server {
private final ServerRequests requests = new ServerRequests();
public ServerRequests getRequests() {
return this.requests;
}
public static class ServerRequests {
/**
* Name of the observation for server requests.
*/
private String name = "http.server.requests";
|
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationProperties.java
| 2
|
请完成以下Java代码
|
public class JavaInfo {
private final String version;
private final JavaVendorInfo vendor;
private final JavaRuntimeEnvironmentInfo runtime;
private final JavaVirtualMachineInfo jvm;
public JavaInfo() {
this.version = System.getProperty("java.version");
this.vendor = new JavaVendorInfo();
this.runtime = new JavaRuntimeEnvironmentInfo();
this.jvm = new JavaVirtualMachineInfo();
}
public String getVersion() {
return this.version;
}
public JavaVendorInfo getVendor() {
return this.vendor;
}
public JavaRuntimeEnvironmentInfo getRuntime() {
return this.runtime;
}
public JavaVirtualMachineInfo getJvm() {
return this.jvm;
}
/**
* Information about the Java Vendor of the Java Runtime the application is running
* in.
*
* @since 2.7.0
*/
public static class JavaVendorInfo {
private final String name;
private final String version;
public JavaVendorInfo() {
this.name = System.getProperty("java.vendor");
this.version = System.getProperty("java.vendor.version");
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
}
/**
* Information about the Java Runtime Environment the application is running in.
*/
|
public static class JavaRuntimeEnvironmentInfo {
private final String name;
private final String version;
public JavaRuntimeEnvironmentInfo() {
this.name = System.getProperty("java.runtime.name");
this.version = System.getProperty("java.runtime.version");
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
}
/**
* Information about the Java Virtual Machine the application is running in.
*/
public static class JavaVirtualMachineInfo {
private final String name;
private final String vendor;
private final String version;
public JavaVirtualMachineInfo() {
this.name = System.getProperty("java.vm.name");
this.vendor = System.getProperty("java.vm.vendor");
this.version = System.getProperty("java.vm.version");
}
public String getName() {
return this.name;
}
public String getVendor() {
return this.vendor;
}
public String getVersion() {
return this.version;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\JavaInfo.java
| 1
|
请完成以下Java代码
|
protected boolean isValidTime(Date newTimer) {
BusinessCalendar businessCalendar = Context
.getProcessEngineConfiguration()
.getBusinessCalendarManager()
.getBusinessCalendar(getBusinessCalendarName(TimerEventHandler.geCalendarNameFromConfiguration(jobHandlerConfiguration)));
return businessCalendar.validateDuedate(repeat, maxIterations, endDate, newTimer);
}
protected int calculateRepeatValue() {
int times = -1;
List<String> expression = Arrays.asList(repeat.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 void setNewRepeat(int newRepeatValue) {
List<String> expression = Arrays.asList(repeat.split("/"));
expression = expression.subList(1, expression.size());
StringBuilder repeatBuilder = new StringBuilder("R");
repeatBuilder.append(newRepeatValue);
for (String value : expression) {
repeatBuilder.append("/");
repeatBuilder.append(value);
}
repeat = repeatBuilder.toString();
}
protected Date calculateNextTimer() {
BusinessCalendar businessCalendar = Context
.getProcessEngineConfiguration()
|
.getBusinessCalendarManager()
.getBusinessCalendar(getBusinessCalendarName(TimerEventHandler.geCalendarNameFromConfiguration(jobHandlerConfiguration)));
return businessCalendar.resolveDuedate(repeat, maxIterations);
}
protected String getBusinessCalendarName(String calendarName) {
String businessCalendarName = CycleBusinessCalendar.NAME;
if (StringUtils.isNotEmpty(calendarName)) {
VariableScope execution = NoExecutionVariableScope.getSharedInstance();
if (StringUtils.isNotEmpty(this.executionId)) {
execution = Context.getCommandContext().getExecutionEntityManager().findExecutionById(this.executionId);
}
businessCalendarName = (String) Context.getProcessEngineConfiguration().getExpressionManager().createExpression(calendarName).getValue(execution);
}
return businessCalendarName;
}
public String getLockOwner() {
return null;
}
public void setLockOwner(String lockOwner) {
// Nothing to do
}
public Date getLockExpirationTime() {
return null;
}
public void setLockExpirationTime(Date lockExpirationTime) {
// Nothing to do
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
sysFormFileService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "表单评论文件-批量删除")
@Operation(summary = "表单评论文件-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysFormFileService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "表单评论文件-通过id查询")
@Operation(summary = "表单评论文件-通过id查询")
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysFormFile sysFormFile = sysFormFileService.getById(id);
return Result.OK(sysFormFile);
}
/**
|
* 导出excel
*
* @param request
* @param sysFormFile
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysFormFile sysFormFile) {
return super.exportXls(request, sysFormFile, SysFormFile.class, "表单评论文件");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysFormFile.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysFormFileController.java
| 2
|
请完成以下Java代码
|
public class X_M_DiscountSchemaBreak_V extends org.compiere.model.PO implements I_M_DiscountSchemaBreak_V, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1372859297L;
/** Standard Constructor */
public X_M_DiscountSchemaBreak_V (final Properties ctx, final int M_DiscountSchemaBreak_V_ID, @Nullable final String trxName)
{
super (ctx, M_DiscountSchemaBreak_V_ID, trxName);
}
/** Load Constructor */
public X_M_DiscountSchemaBreak_V (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_M_DiscountSchema getM_DiscountSchema()
{
return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class);
}
@Override
public void setM_DiscountSchema(final org.compiere.model.I_M_DiscountSchema M_DiscountSchema)
{
set_ValueFromPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class, M_DiscountSchema);
}
@Override
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID)
{
if (M_DiscountSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID);
}
@Override
public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setM_DiscountSchemaBreak_V_ID (final int M_DiscountSchemaBreak_V_ID)
{
if (M_DiscountSchemaBreak_V_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, M_DiscountSchemaBreak_V_ID);
}
@Override
public int getM_DiscountSchemaBreak_V_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchemaBreak_V_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak_V.java
| 1
|
请完成以下Java代码
|
public String getDeleteReason() {
return deleteReason;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getTenantId() {
return tenantId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getRestartedProcessInstanceId() {
return restartedProcessInstanceId;
}
public void setRestartedProcessInstanceId(String restartedProcessInstanceId) {
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
public static HistoricProcessInstanceDto fromHistoricProcessInstance(HistoricProcessInstance historicProcessInstance) {
|
HistoricProcessInstanceDto dto = new HistoricProcessInstanceDto();
dto.id = historicProcessInstance.getId();
dto.businessKey = historicProcessInstance.getBusinessKey();
dto.processDefinitionId = historicProcessInstance.getProcessDefinitionId();
dto.processDefinitionKey = historicProcessInstance.getProcessDefinitionKey();
dto.processDefinitionName = historicProcessInstance.getProcessDefinitionName();
dto.processDefinitionVersion = historicProcessInstance.getProcessDefinitionVersion();
dto.startTime = historicProcessInstance.getStartTime();
dto.endTime = historicProcessInstance.getEndTime();
dto.removalTime = historicProcessInstance.getRemovalTime();
dto.durationInMillis = historicProcessInstance.getDurationInMillis();
dto.startUserId = historicProcessInstance.getStartUserId();
dto.startActivityId = historicProcessInstance.getStartActivityId();
dto.deleteReason = historicProcessInstance.getDeleteReason();
dto.rootProcessInstanceId = historicProcessInstance.getRootProcessInstanceId();
dto.superProcessInstanceId = historicProcessInstance.getSuperProcessInstanceId();
dto.superCaseInstanceId = historicProcessInstance.getSuperCaseInstanceId();
dto.caseInstanceId = historicProcessInstance.getCaseInstanceId();
dto.tenantId = historicProcessInstance.getTenantId();
dto.state = historicProcessInstance.getState();
dto.restartedProcessInstanceId = historicProcessInstance.getRestartedProcessInstanceId();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricProcessInstanceDto.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.