instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class AnnotatedJXTable extends JXTable
{
private static final long serialVersionUID = 1L;
private Function<Integer, Integer> convertRowIndexToModelFunction;
AnnotatedJXTable()
{
super();
}
@Override
protected final JComponent createDefaultColumnControl()
{
return new AnnotatedColumnControlButton(this);
}
public final Function<Integer, Integer> getConvertRowIndexToModelFunction()
|
{
if (convertRowIndexToModelFunction == null)
{
convertRowIndexToModelFunction = new Function<Integer, Integer>()
{
@Override
public Integer apply(final Integer viewRowIndex)
{
return convertRowIndexToModel(viewRowIndex);
}
};
}
return convertRowIndexToModelFunction;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedJXTable.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long getLoadPollInterval() {
return this.loadPollInterval;
}
public void setLoadPollInterval(long loadPollInterval) {
this.loadPollInterval = loadPollInterval;
}
public int getMaxConnections() {
return this.maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public int getMaxMessageCount() {
return this.maxMessageCount;
}
public void setMaxMessageCount(int maxMessageCount) {
this.maxMessageCount = maxMessageCount;
}
public int getMaxThreads() {
return this.maxThreads;
}
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
public int getMaxTimeBetweenPings() {
return this.maxTimeBetweenPings;
}
public void setMaxTimeBetweenPings(int maxTimeBetweenPings) {
this.maxTimeBetweenPings = maxTimeBetweenPings;
}
public int getMessageTimeToLive() {
return this.messageTimeToLive;
}
public void setMessageTimeToLive(int messageTimeToLive) {
this.messageTimeToLive = messageTimeToLive;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public int getSocketBufferSize() {
return this.socketBufferSize;
}
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public int getSubscriptionCapacity() {
|
return this.subscriptionCapacity;
}
public void setSubscriptionCapacity(int subscriptionCapacity) {
this.subscriptionCapacity = subscriptionCapacity;
}
public String getSubscriptionDiskStoreName() {
return this.subscriptionDiskStoreName;
}
public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) {
this.subscriptionDiskStoreName = subscriptionDiskStoreName;
}
public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() {
return this.subscriptionEvictionPolicy;
}
public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) {
this.subscriptionEvictionPolicy = subscriptionEvictionPolicy;
}
public boolean isTcpNoDelay() {
return this.tcpNoDelay;
}
public void setTcpNoDelay(boolean tcpNoDelay) {
this.tcpNoDelay = tcpNoDelay;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java
| 2
|
请完成以下Java代码
|
public void setProductValue (final java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM()
{
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
|
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static private ImmutableMultimap<BPartnerId, InvoiceProcessingServiceCompanyConfigBPartnerDetails> getBPartnerDetailsForCompany(
@NonNull final ImmutableListMultimap<InvoiceProcessingServiceCompanyConfigId, InvoiceProcessingServiceCompanyConfigBPartnerDetails> bpartnerDetailsByCompanyConfig,
@NonNull final InvoiceProcessingServiceCompanyConfigId companyConfigId)
{
return bpartnerDetailsByCompanyConfig.get(companyConfigId)
.stream()
.collect(GuavaCollectors.toImmutableListMultimap(InvoiceProcessingServiceCompanyConfigBPartnerDetails::getBpartnerId));
}
private ImmutableListMultimap<InvoiceProcessingServiceCompanyConfigId, InvoiceProcessingServiceCompanyConfigBPartnerDetails> retrieveAllBPartnerDetailsMappedByConfigId()
{
return queryBL.createQueryBuilder(I_InvoiceProcessingServiceCompany_BPartnerAssignment.class)
.create()
.iterateAndStream()
.map(bpartnerDetailsToMapEntry())
.collect(GuavaCollectors.toImmutableListMultimap());
}
|
@NonNull
private static Function<I_InvoiceProcessingServiceCompany_BPartnerAssignment, ImmutableMapEntry<InvoiceProcessingServiceCompanyConfigId, InvoiceProcessingServiceCompanyConfigBPartnerDetails>> bpartnerDetailsToMapEntry()
{
return recordBP -> {
final InvoiceProcessingServiceCompanyConfigBPartnerDetails partnerDetails = InvoiceProcessingServiceCompanyConfigBPartnerDetails.builder()
.bpartnerId(BPartnerId.ofRepoId(recordBP.getC_BPartner_ID()))
.docTypeId(DocTypeId.ofRepoIdOrNull(recordBP.getC_DocType_ID()))
.percent(Percent.of(recordBP.getFeePercentageOfGrandTotal()))
.isActive(recordBP.isActive())
.build();
final InvoiceProcessingServiceCompanyConfigId companyConfigId = InvoiceProcessingServiceCompanyConfigId.ofRepoId(recordBP.getInvoiceProcessingServiceCompany_ID());
return ImmutableMapEntry.of(companyConfigId, partnerDetails);
};
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\invoiceProcessingServiceCompany\InvoiceProcessingServiceCompanyConfigRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static GlobalQRCode toGlobalQRCode(@NonNull final ExternalSystemConfigQRCode qrCode)
{
return GlobalQRCode.of(ExternalSystemConfigQRCodeJsonConverter.GLOBAL_QRCODE_TYPE, GLOBAL_QRCODE_VERSION, toJson(qrCode));
}
private static JsonPayload toJson(@NonNull final ExternalSystemConfigQRCode qrCode)
{
final IExternalSystemChildConfigId childConfigId = qrCode.getChildConfigId();
return JsonPayload.builder()
.externalSystemType(childConfigId.getType().getValue())
.childConfigId(childConfigId.getRepoId())
.build();
}
public static ExternalSystemConfigQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
Check.assumeEquals(globalQRCode.getVersion(), GLOBAL_QRCODE_VERSION, "QR Code version");
final JsonPayload payload = globalQRCode.getPayloadAs(JsonPayload.class);
return fromJson(payload);
}
private static ExternalSystemConfigQRCode fromJson(@NonNull final JsonPayload json)
{
final ExternalSystemType externalSystemType = ExternalSystemType.ofValue(json.getExternalSystemType());
final int repoId = json.getChildConfigId();
return ExternalSystemConfigQRCode.builder()
.childConfigId(toExternalSystemChildConfigId(externalSystemType, repoId))
.build();
}
private static IExternalSystemChildConfigId toExternalSystemChildConfigId(final ExternalSystemType externalSystemType, final int repoId)
{
if (externalSystemType.isAlberta())
{
return ExternalSystemAlbertaConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isShopware6())
{
return ExternalSystemShopware6ConfigId.ofRepoId(repoId);
}
// else if (externalSystemType.isOther())
|
// {
// return ExternalSystemOtherConfigId.ofRepoId(repoId);
// }
else if (externalSystemType.isRabbitMQ())
{
return ExternalSystemRabbitMQConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isWOO())
{
return ExternalSystemWooCommerceConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isGRSSignum())
{
return ExternalSystemGRSSignumConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isLeichUndMehl())
{
return ExternalSystemLeichMehlConfigId.ofRepoId(repoId);
}
throw new AdempiereException("Unsupported externalSystemType: " + externalSystemType);
}
//
//
//
@Value
@Builder
@Jacksonized
public static class JsonPayload
{
@NonNull String externalSystemType;
int childConfigId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\config\qrcode\v1\JsonConverterV1.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MonetaryAmountType {
@XmlElement(name = "AmountTypeCode")
protected String amountTypeCode;
@XmlElement(name = "Amount", required = true)
protected BigDecimal amount;
/**
* Gets the value of the amountTypeCode property.
*
* @return
* possible object is
* {@link String }
*
*/
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
|
请完成以下Java代码
|
public static boolean writeIOParameters(String elementName, List<IOParameter> parameterList, boolean didWriteParameterStartElement, XMLStreamWriter xtw) throws Exception {
if (parameterList == null || parameterList.isEmpty()) {
return didWriteParameterStartElement;
}
for (IOParameter ioParameter : parameterList) {
if (!didWriteParameterStartElement) {
xtw.writeStartElement(ELEMENT_EXTENSION_ELEMENTS);
didWriteParameterStartElement = true;
}
xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, elementName, FLOWABLE_EXTENSIONS_NAMESPACE);
if (StringUtils.isNotEmpty(ioParameter.getSource())) {
xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_SOURCE, ioParameter.getSource());
}
if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) {
|
xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION, ioParameter.getSourceExpression());
}
if (StringUtils.isNotEmpty(ioParameter.getTarget())) {
xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_TARGET, ioParameter.getTarget());
}
if (StringUtils.isNotEmpty(ioParameter.getTargetExpression())) {
xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_TARGET_EXPRESSION, ioParameter.getTargetExpression());
}
xtw.writeEndElement();
}
return didWriteParameterStartElement;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\util\CmmnXmlUtil.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* ArticleUnit AD_Reference_ID=541280
* Reference name: ArticleUnit
*/
public static final int ARTICLEUNIT_AD_Reference_ID=541280;
/** PCE = Stk */
public static final String ARTICLEUNIT_PCE = "Stk";
/** BOX = Ktn */
public static final String ARTICLEUNIT_BOX = "Ktn";
@Override
public void setArticleUnit (final String ArticleUnit)
{
set_Value (COLUMNNAME_ArticleUnit, ArticleUnit);
}
@Override
public String getArticleUnit()
{
return get_ValueAsString(COLUMNNAME_ArticleUnit);
}
@Override
public void setM_Product_AlbertaPackagingUnit_ID (final int M_Product_AlbertaPackagingUnit_ID)
{
if (M_Product_AlbertaPackagingUnit_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, M_Product_AlbertaPackagingUnit_ID);
}
@Override
public int getM_Product_AlbertaPackagingUnit_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaPackagingUnit_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);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaPackagingUnit.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Employee)) {
return false;
} else {
Employee other = (Employee) o;
if (!other.canEqual(this)) {
return false;
} else if (this.getId() != other.getId()) {
return false;
} else if (this.getAge() != other.getAge()) {
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name == null) {
return true;
}
} else if (this$name.equals(other$name)) {
return true;
|
}
return false;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Employee;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getId();
result = result * PRIME + this.getAge();
Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
return result;
}
}
|
repos\tutorials-master\lombok-modules\lombok\src\main\java\com\baeldung\lombok\equalsandhashcode\EmployeeDelomboked.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class CommissionStagingRecords
{
final static CommissionStagingRecords EMPTY = CommissionStagingRecords.builder().build();
ImmutableMap<CommissionTriggerDocumentId, I_C_Commission_Instance> documentIdToInstanceRecords;
ImmutableMap<Integer, I_C_Commission_Instance> instanceRecordIdToInstance;
@Getter(AccessLevel.NONE)
ImmutableListMultimap<Integer, I_C_Commission_Share> instanceRecordIdToShareRecords;
@Getter(AccessLevel.NONE)
ImmutableListMultimap<Integer, I_C_Commission_Fact> shareRecordIdToSalesFactRecords;
@Builder
private CommissionStagingRecords(
@Nullable final ImmutableMap<CommissionTriggerDocumentId, I_C_Commission_Instance> documentIdToInstanceRecords,
@Nullable final ImmutableMap<Integer, I_C_Commission_Instance> instanceRecordIdToInstance,
@Nullable final ImmutableListMultimap<Integer, I_C_Commission_Share> instanceRecordIdToShareRecords,
|
@Nullable final ImmutableListMultimap<Integer, I_C_Commission_Fact> shareRecordIdToFactRecords)
{
this.documentIdToInstanceRecords = coalesce(documentIdToInstanceRecords, ImmutableMap.of());
this.instanceRecordIdToInstance = coalesce(instanceRecordIdToInstance, ImmutableMap.of());
this.instanceRecordIdToShareRecords = coalesce(instanceRecordIdToShareRecords, ImmutableListMultimap.of());
this.shareRecordIdToSalesFactRecords = coalesce(shareRecordIdToFactRecords, ImmutableListMultimap.of());
}
ImmutableList<I_C_Commission_Share> getShareRecordsForInstanceRecordId(@NonNull final CommissionInstanceId commissionInstanceId)
{
return instanceRecordIdToShareRecords.get(commissionInstanceId.getRepoId());
}
ImmutableList<I_C_Commission_Fact> getSalesFactRecordsForShareRecordId(final int commissionShareRecordId)
{
return shareRecordIdToSalesFactRecords.get(commissionShareRecordId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\repos\CommissionRecordStagingService.java
| 2
|
请完成以下Java代码
|
public void execute(Job job, String configuration, ExecutionEntity execution, CommandContext commandContext) {
String nestedActivityId = TimerEventHandler.getActivityIdFromConfiguration(configuration);
ActivityImpl intermediateEventActivity = execution.getProcessDefinition().findActivity(nestedActivityId);
if (intermediateEventActivity == null) {
throw new ActivitiException("Error while firing timer: intermediate event activity " + nestedActivityId + " not found");
}
try {
if (commandContext.getEventDispatcher().isEnabled()) {
commandContext.getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TIMER_FIRED, job),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
if (!execution.getActivity().getId().equals(intermediateEventActivity.getId())) {
execution.setActivity(intermediateEventActivity);
|
}
execution.signal(null, null);
} catch (RuntimeException e) {
LogMDC.putMDCExecution(execution);
LOGGER.error("exception during timer execution", e);
LogMDC.clear();
throw e;
} catch (Exception e) {
LogMDC.putMDCExecution(execution);
LOGGER.error("exception during timer execution", e);
LogMDC.clear();
throw new ActivitiException("exception during timer execution: " + e.getMessage(), e);
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerCatchIntermediateEventJobHandler.java
| 1
|
请完成以下Java代码
|
private JsonPackageDimensions toJsonPackageDimensions(final PackageDimensions dims)
{
if (dims == null) {return JsonPackageDimensions.builder().lengthInCM(0).widthInCM(0).heightInCM(0).build();}
return JsonPackageDimensions.builder()
.lengthInCM(dims.getLengthInCM())
.widthInCM(dims.getWidthInCM())
.heightInCM(dims.getHeightInCM())
.build();
}
@NonNull
private JsonMappingConfigList toJsonMappingConfigList(@NonNull final ShipperMappingConfigList configs)
{
if (configs == ShipperMappingConfigList.EMPTY)
{
return JsonMappingConfigList.EMPTY;
}
return JsonMappingConfigList.ofList(
StreamSupport.stream(configs.spliterator(), false)
.map(this::toJsonMappingConfig)
.collect(ImmutableList.toImmutableList()));
|
}
@NonNull
private JsonMappingConfig toJsonMappingConfig(@NonNull final ShipperMappingConfig config)
{
final CarrierProduct carrierProduct = config.getCarrierProductId() != null ? carrierProductRepository.getCachedShipperProductById(config.getCarrierProductId()) : null;
return JsonMappingConfig.builder()
.seqNo(config.getSeqNo().toInt())
.shipperProductExternalId(carrierProduct != null ? carrierProduct.getCode() : null)
.attributeType(config.getAttributeType().getCode())
.groupKey(config.getGroupKey())
.attributeKey(config.getAttributeKey())
.attributeValue(config.getAttributeValue().getCode())
.mappingRule(config.getMappingRule() != null ? config.getMappingRule().getCode() : null)
.mappingRuleValue(config.getMappingRuleValue())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\converters\v1\JsonShipperConverter.java
| 1
|
请完成以下Java代码
|
public Optional<NotificationGroupName> getNameById(@NonNull final NotificationGroupId notificationGroupId) {return getMap().getNameById(notificationGroupId);}
@Override
public Optional<NotificationGroupId> getNotificationGroupId(final NotificationGroupName notificationGroupName) {return getMap().getIdByName(notificationGroupName);}
@Override
public Optional<NotificationGroup> getNotificationGroupByName(final NotificationGroupName notificationGroupName) {return getMap().getByName(notificationGroupName);}
@Override
public Set<NotificationGroupName> getActiveNames() {return getMap().getNames();}
private NotificationGroupMap getMap() {return notificationGroupNames.getOrLoad(0, this::retrieveMap);}
private NotificationGroupMap retrieveMap()
{
final Map<NotificationGroupId, NotificationGroupCCs> ccsByGroupId = queryBL.createQueryBuilderOutOfTrx(I_AD_NotificationGroup_CC.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.collect(Collectors.groupingBy(
record -> NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID()),
Collectors.mapping(NotificationGroupRepository::extractRecipient, NotificationGroupCCs.collect())
));
return queryBL.createQueryBuilderOutOfTrx(I_AD_NotificationGroup.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
|
.map(record -> toNotificationGroup(record, ccsByGroupId))
.collect(NotificationGroupMap.collect());
}
private static Recipient extractRecipient(final I_AD_NotificationGroup_CC record)
{
return Recipient.user(UserId.ofRepoId(record.getAD_User_ID()));
}
private static NotificationGroup toNotificationGroup(final I_AD_NotificationGroup record, Map<NotificationGroupId, NotificationGroupCCs> ccsById)
{
final NotificationGroupId id = NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID());
return NotificationGroup.builder()
.id(id)
.name(NotificationGroupName.of(record.getInternalName()))
.ccs(ccsById.getOrDefault(id, NotificationGroupCCs.EMPTY))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationGroupRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public LocalDate getDateStart()
{
return DateUtils.toLocalDate(dateStart);
}
public void setDateStart(final LocalDate dateStart)
{
this.dateStart = DateUtils.toSqlDate(dateStart);
}
public LocalDate getDateEnd()
{
return DateUtils.toLocalDate(dateEnd);
}
public void setDateEnd(final LocalDate dateEnd)
{
this.dateEnd = DateUtils.toSqlDate(dateEnd);
}
public Long getBpartnerId()
{
return getBpartner().getId();
}
public LocalDate getDateClose()
{
return DateUtils.toLocalDate(dateClose);
}
public void setDateClose(final LocalDate dateClose)
{
this.dateClose = DateUtils.toSqlDate(dateClose);
}
public List<RfqQty> getQuantities()
{
return quantities;
}
public ImmutableSet<LocalDate> generateAllDaysSet()
{
final ArrayList<LocalDate> dates = DateUtils.getDaysList(getDateStart(), getDateEnd());
dates.addAll(quantities
.stream()
.map(RfqQty::getDatePromised)
.collect(ImmutableSet.toImmutableSet()));
dates.sort(LocalDate::compareTo);
return ImmutableSet.copyOf(dates);
}
public void setPricePromisedUserEntered(@NonNull final BigDecimal pricePromisedUserEntered)
{
this.pricePromisedUserEntered = pricePromisedUserEntered;
}
public BigDecimal getQtyPromisedUserEntered()
{
return quantities.stream()
.map(RfqQty::getQtyPromisedUserEntered)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public void setQtyPromised(@NonNull final LocalDate date, @NonNull final BigDecimal qtyPromised)
{
final RfqQty rfqQty = getOrCreateQty(date);
rfqQty.setQtyPromisedUserEntered(qtyPromised);
updateConfirmedByUser();
}
private RfqQty getOrCreateQty(@NonNull final LocalDate date)
{
final RfqQty existingRfqQty = getRfqQtyByDate(date);
if (existingRfqQty != null)
{
return existingRfqQty;
}
|
else
{
final RfqQty rfqQty = RfqQty.builder()
.rfq(this)
.datePromised(date)
.build();
addRfqQty(rfqQty);
return rfqQty;
}
}
private void addRfqQty(final RfqQty rfqQty)
{
rfqQty.setRfq(this);
quantities.add(rfqQty);
}
@Nullable
public RfqQty getRfqQtyByDate(@NonNull final LocalDate date)
{
for (final RfqQty rfqQty : quantities)
{
if (date.equals(rfqQty.getDatePromised()))
{
return rfqQty;
}
}
return null;
}
private void updateConfirmedByUser()
{
this.confirmedByUser = computeConfirmedByUser();
}
private boolean computeConfirmedByUser()
{
if (pricePromised.compareTo(pricePromisedUserEntered) != 0)
{
return false;
}
for (final RfqQty rfqQty : quantities)
{
if (!rfqQty.isConfirmedByUser())
{
return false;
}
}
return true;
}
public void closeIt()
{
this.closed = true;
}
public void confirmByUser()
{
this.pricePromised = getPricePromisedUserEntered();
quantities.forEach(RfqQty::confirmByUser);
updateConfirmedByUser();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
| 2
|
请完成以下Java代码
|
private void save(final IQualityInspectionLine qiLine)
{
Check.assumeNotNull(qiLine, "qiLine not null");
final I_PP_Order ppOrder = getPP_Order();
final int seqNo = _seqNoNext;
BigDecimal qty = qiLine.getQty();
if (qty != null && qiLine.isNegateQtyInReport())
{
qty = qty.negate();
}
//
// Create report line
final I_PP_Order_Report reportLine = InterfaceWrapperHelper.newInstance(I_PP_Order_Report.class, getContext());
reportLine.setPP_Order(ppOrder);
reportLine.setAD_Org_ID(ppOrder.getAD_Org_ID());
reportLine.setSeqNo(seqNo);
reportLine.setIsActive(true);
// reportLine.setQualityInspectionLineType(qiLine.getQualityInspectionLineType());
reportLine.setProductionMaterialType(qiLine.getProductionMaterialType());
|
reportLine.setM_Product(qiLine.getM_Product());
reportLine.setName(qiLine.getName());
reportLine.setQty(qty);
reportLine.setC_UOM(qiLine.getC_UOM());
reportLine.setPercentage(qiLine.getPercentage());
reportLine.setQtyProjected(qiLine.getQtyProjected());
reportLine.setComponentType(qiLine.getComponentType());
reportLine.setVariantGroup(qiLine.getVariantGroup());
//
// Save report line
InterfaceWrapperHelper.save(reportLine);
_createdReportLines.add(reportLine);
_seqNoNext += 10;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderReportWriter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static <T> Result<T> newFailureResult(){
Result<T> result = new Result<>();
result.isSuccess = false;
result.errorCode = ExpCodeEnum.UNKNOW_ERROR.getCode();
result.message = ExpCodeEnum.UNKNOW_ERROR.getMessage();
return result;
}
/**
* 返回失败的结果
* @param commonBizException 异常
* @param <T>
* @return
*/
public static <T> Result<T> newFailureResult(CommonBizException commonBizException){
Result<T> result = new Result<>();
result.isSuccess = false;
result.errorCode = commonBizException.getCodeEnum().getCode();
result.message = commonBizException.getCodeEnum().getMessage();
return result;
}
/**
* 返回失败的结果
* @param commonBizException 异常
* @param data 需返回的数据
* @param <T>
* @return
*/
public static <T> Result<T> newFailureResult(CommonBizException commonBizException, T data){
Result<T> result = new Result<>();
result.isSuccess = false;
result.errorCode = commonBizException.getCodeEnum().getCode();
result.message = commonBizException.getCodeEnum().getMessage();
result.data = data;
return result;
}
public boolean isSuccess() {
return isSuccess;
}
|
public void setSuccess(boolean success) {
isSuccess = success;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"isSuccess=" + isSuccess +
", errorCode=" + errorCode +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\rsp\Result.java
| 2
|
请完成以下Java代码
|
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public void setHistoryTimeToLive(Integer historyTimeToLive) {
this.historyTimeToLive = historyTimeToLive;
}
public long getFinishedCaseInstanceCount() {
return finishedCaseInstanceCount;
}
public void setFinishedCaseInstanceCount(long finishedCaseInstanceCount) {
this.finishedCaseInstanceCount = finishedCaseInstanceCount;
}
public long getCleanableCaseInstanceCount() {
return cleanableCaseInstanceCount;
}
public void setCleanableCaseInstanceCount(long cleanableCaseInstanceCount) {
this.cleanableCaseInstanceCount = cleanableCaseInstanceCount;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public static List<CleanableHistoricCaseInstanceReportResultDto> convert(List<CleanableHistoricCaseInstanceReportResult> reportResult) {
|
List<CleanableHistoricCaseInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricCaseInstanceReportResultDto>();
for (CleanableHistoricCaseInstanceReportResult current : reportResult) {
CleanableHistoricCaseInstanceReportResultDto dto = new CleanableHistoricCaseInstanceReportResultDto();
dto.setCaseDefinitionId(current.getCaseDefinitionId());
dto.setCaseDefinitionKey(current.getCaseDefinitionKey());
dto.setCaseDefinitionName(current.getCaseDefinitionName());
dto.setCaseDefinitionVersion(current.getCaseDefinitionVersion());
dto.setHistoryTimeToLive(current.getHistoryTimeToLive());
dto.setFinishedCaseInstanceCount(current.getFinishedCaseInstanceCount());
dto.setCleanableCaseInstanceCount(current.getCleanableCaseInstanceCount());
dto.setTenantId(current.getTenantId());
dtos.add(dto);
}
return dtos;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricCaseInstanceReportResultDto.java
| 1
|
请完成以下Java代码
|
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Integer getTime() {
return time;
}
public void setTime(Integer time) {
this.time = time;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getParams() {
|
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
|
repos\SpringAll-master\07.Spring-Boot-AOP-Log\src\main\java\com\springboot\domain\SysLog.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Sniffer getSniffer() {
return this.sniffer;
}
public Ssl getSsl() {
return this.ssl;
}
public static class Sniffer {
/**
* Whether the sniffer is enabled.
*/
private boolean enabled;
/**
* Interval between consecutive ordinary sniff executions.
*/
private Duration interval = Duration.ofMinutes(5);
/**
* Delay of a sniff execution scheduled after a failure.
*/
private Duration delayAfterFailure = Duration.ofMinutes(1);
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getInterval() {
return this.interval;
}
public void setInterval(Duration interval) {
this.interval = interval;
}
public Duration getDelayAfterFailure() {
return this.delayAfterFailure;
}
public void setDelayAfterFailure(Duration delayAfterFailure) {
this.delayAfterFailure = delayAfterFailure;
}
|
}
public static class Ssl {
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java
| 2
|
请完成以下Java代码
|
public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) {
Heap<E> result = new Heap<>();
for (E element : elements) {
result.add(element);
}
return result;
}
public void add(E e) {
elements.add(e);
int elementIndex = elements.size() - 1;
while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) {
int parentIndex = parentIndex(elementIndex);
swap(elementIndex, parentIndex);
elementIndex = parentIndex;
}
}
public E pop() {
if (isEmpty()) {
throw new IllegalStateException("You cannot pop from an empty heap");
}
E result = elementAt(0);
int lasElementIndex = elements.size() - 1;
swap(0, lasElementIndex);
elements.remove(lasElementIndex);
int elementIndex = 0;
while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) {
int smallerChildIndex = smallerChildIndex(elementIndex);
swap(elementIndex, smallerChildIndex);
elementIndex = smallerChildIndex;
}
return result;
}
public boolean isEmpty() {
return elements.isEmpty();
}
private boolean isRoot(int index) {
return index == 0;
}
private int smallerChildIndex(int index) {
int leftChildIndex = leftChildIndex(index);
int rightChildIndex = rightChildIndex(index);
if (!isValidIndex(rightChildIndex)) {
return leftChildIndex;
}
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
return leftChildIndex;
}
return rightChildIndex;
}
|
private boolean isLeaf(int index) {
return !isValidIndex(leftChildIndex(index));
}
private boolean isCorrectParent(int index) {
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
}
private boolean isCorrectChild(int index) {
return isCorrect(parentIndex(index), index);
}
private boolean isCorrect(int parentIndex, int childIndex) {
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
return true;
}
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
}
private boolean isValidIndex(int index) {
return index < elements.size();
}
private void swap(int index1, int index2) {
E element1 = elementAt(index1);
E element2 = elementAt(index2);
elements.set(index1, element2);
elements.set(index2, element1);
}
private E elementAt(int index) {
return elements.get(index);
}
private int parentIndex(int index) {
return (index - 1) / 2;
}
private int leftChildIndex(int index) {
return 2 * index + 1;
}
private int rightChildIndex(int index) {
return 2 * index + 2;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\heapsort\Heap.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Buyer buyer = (Buyer)o;
return Objects.equals(this.taxAddress, buyer.taxAddress) &&
Objects.equals(this.taxIdentifier, buyer.taxIdentifier) &&
Objects.equals(this.username, buyer.username);
}
@Override
public int hashCode()
{
return Objects.hash(taxAddress, taxIdentifier, username);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Buyer {\n");
sb.append(" taxAddress: ").append(toIndentedString(taxAddress)).append("\n");
sb.append(" taxIdentifier: ").append(toIndentedString(taxIdentifier)).append("\n");
|
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Buyer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode() {
return Objects.hash(_id, name, patientId, therapyId, therapyTypeId, archived, createdBy, updatedBy, createdAt, updatedAt);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Document {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n");
sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n");
sb.append(" updatedBy: ").append(toIndentedString(updatedBy)).append("\n");
|
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Document.java
| 2
|
请完成以下Java代码
|
public static String decrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptFrom = parseHexStr2Byte(content);
byte[] result = cipher.doFinal(decryptFrom);
return new String(result);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
|
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String[] args) {
String content = "test";
String password = "12345678";
// 加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
// 解密
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom, password);
System.out.println("解密后:" + new String(decryptResult));
String enStr = encryptString("123", "@#&^%-$#@Coupon#$%^&@*");
System.out.println(enStr);
System.out.println(decrypt("2DA4A4EEA4777CB2CC342815FC84B539", "@#&^%-$#@Coupon#$%^&@*"));
}
}
|
repos\spring-boot-student-master\spring-boot-student-encode\src\main\java\com\xiaolyuh\utils\AESUtil.java
| 1
|
请完成以下Java代码
|
private void unlock0(final int huId, final LockOwner lockOwner)
{
Services.get(ILockManager.class)
.unlock()
.setOwner(lockOwner)
.setRecordByTableRecordId(I_M_HU.Table_Name, huId)
.release();
}
@Override
public void unlockAll(final Collection<I_M_HU> hus, final LockOwner lockOwner)
{
if (hus.isEmpty())
{
return;
}
Preconditions.checkNotNull(lockOwner, "lockOwner is null");
Preconditions.checkArgument(!lockOwner.isAnyOwner(), "{} not allowed", lockOwner);
Services.get(ILockManager.class)
.unlock()
.setOwner(lockOwner)
.setRecordsByModels(hus)
.release();
if (isUseVirtualColumn())
|
{
InterfaceWrapperHelper.refresh(hus);
}
}
@Override
public IQueryFilter<I_M_HU> isLockedFilter()
{
return Services.get(ILockManager.class).getLockedByFilter(I_M_HU.class, LockOwner.ANY);
}
@Override
public IQueryFilter<I_M_HU> isNotLockedFilter()
{
return Services.get(ILockManager.class).getNotLockedFilter(I_M_HU.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HULockBL.java
| 1
|
请完成以下Java代码
|
public class EscalationEndEventActivityBehavior extends FlowNodeActivityBehavior {
private static final long serialVersionUID = 1L;
protected EscalationEventDefinition escalationEventDefinition;
protected Escalation escalation;
public EscalationEndEventActivityBehavior(EscalationEventDefinition escalationEventDefinition, Escalation escalation) {
this.escalationEventDefinition = escalationEventDefinition;
this.escalation = escalation;
}
@Override
public void execute(DelegateExecution execution) {
if (escalation != null) {
EscalationPropagation.propagateEscalation(escalation, execution);
} else {
EscalationPropagation.propagateEscalation(escalationEventDefinition.getEscalationCode(),
escalationEventDefinition.getEscalationCode(), execution);
}
|
CommandContextUtil.getAgenda().planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) execution, true);
}
public EscalationEventDefinition getEscalationEventDefinition() {
return escalationEventDefinition;
}
public void setEscalationEventDefinition(EscalationEventDefinition escalationEventDefinition) {
this.escalationEventDefinition = escalationEventDefinition;
}
public Escalation getEscalation() {
return escalation;
}
public void setEscalation(Escalation escalation) {
this.escalation = escalation;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\EscalationEndEventActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class ServiceLevelObjectiveBoundary {
private final MeterValue value;
ServiceLevelObjectiveBoundary(MeterValue value) {
this.value = value;
}
/**
* Return the underlying value of the SLO in form suitable to apply to the given meter
* type.
* @param meterType the meter type
* @return the value or {@code null} if the value cannot be applied
*/
public @Nullable Double getValue(Meter.Type meterType) {
return this.value.getValue(meterType);
}
/**
* Return a new {@link ServiceLevelObjectiveBoundary} instance for the given double
* value.
* @param value the source value
* @return a {@link ServiceLevelObjectiveBoundary} instance
*/
|
public static ServiceLevelObjectiveBoundary valueOf(double value) {
return new ServiceLevelObjectiveBoundary(MeterValue.valueOf(value));
}
/**
* Return a new {@link ServiceLevelObjectiveBoundary} instance for the given String
* value.
* @param value the source value
* @return a {@link ServiceLevelObjectiveBoundary} instance
*/
public static ServiceLevelObjectiveBoundary valueOf(String value) {
return new ServiceLevelObjectiveBoundary(MeterValue.valueOf(value));
}
static class ServiceLevelObjectiveBoundaryHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection().registerType(ServiceLevelObjectiveBoundary.class, MemberCategory.INVOKE_PUBLIC_METHODS);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\ServiceLevelObjectiveBoundary.java
| 2
|
请完成以下Java代码
|
class NotificationItem
{
public static final Builder builder()
{
return new Builder();
}
private final String summary;
private final String detail;
private final String senderName;
private NotificationItem(final Builder builder)
{
super();
summary = builder.summary;
detail = builder.detail;
senderName = builder.senderName;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
/** @return summary HTML */
public String getSummary()
{
return summary;
}
/** @return detail HTML */
public String getDetail()
{
return detail;
}
public String getSenderName()
{
return senderName;
}
public static final class Builder
{
|
private String summary;
private String detail;
private String senderName;
private Builder()
{
super();
}
public NotificationItem build()
{
return new NotificationItem(this);
}
/**
* @param summary detail HTML text
*/
public Builder setSummary(final String summary)
{
this.summary = summary;
return this;
}
/**
* @param detail detail HTML text
*/
public Builder setDetail(String detail)
{
this.detail = detail;
return this;
}
public Builder setSenderName(String senderName)
{
this.senderName = senderName;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\NotificationItem.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public de.metas.payment.sumup.repository.model.I_SUMUP_Config getSUMUP_Config()
{
return get_ValueAsPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class);
}
@Override
public void setSUMUP_Config(final de.metas.payment.sumup.repository.model.I_SUMUP_Config SUMUP_Config)
{
set_ValueFromPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class, SUMUP_Config);
}
@Override
public void setSUMUP_Config_ID (final int SUMUP_Config_ID)
{
if (SUMUP_Config_ID < 1)
set_Value (COLUMNNAME_SUMUP_Config_ID, null);
else
set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
}
@Override
public int getSUMUP_Config_ID()
{
|
return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID);
}
@Override
public void setSUMUP_merchant_code (final @Nullable java.lang.String SUMUP_merchant_code)
{
set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code);
}
@Override
public java.lang.String getSUMUP_merchant_code()
{
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_API_Log.java
| 2
|
请完成以下Java代码
|
public I_LeichMehl_PluFile_ConfigGroup getLeichMehl_PluFile_ConfigGroup()
{
return get_ValueAsPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class);
}
@Override
public void setLeichMehl_PluFile_ConfigGroup(final I_LeichMehl_PluFile_ConfigGroup LeichMehl_PluFile_ConfigGroup)
{
set_ValueFromPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class, LeichMehl_PluFile_ConfigGroup);
}
@Override
public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID)
{
if (LeichMehl_PluFile_ConfigGroup_ID < 1)
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null);
else
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID);
}
@Override
public int getLeichMehl_PluFile_ConfigGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_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);
}
@Override
public void setPLU_File (final String PLU_File)
{
set_Value (COLUMNNAME_PLU_File, PLU_File);
}
@Override
public String getPLU_File()
{
return get_ValueAsString(COLUMNNAME_PLU_File);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
| 1
|
请完成以下Java代码
|
public class MetricsAggregatedResultDto {
protected String metric;
protected Long sum;
protected Integer subscriptionYear;
protected Integer subscriptionMonth;
public String getMetric() {
return metric;
}
public void setMetric(String metric) {
this.metric = metric;
}
public Long getSum() {
return sum;
}
public void setSum(Long sum) {
this.sum = sum;
}
|
public Integer getSubscriptionYear() {
return subscriptionYear;
}
public void setSubscriptionYear(Integer subscriptionYear) {
this.subscriptionYear = subscriptionYear;
}
public Integer getSubscriptionMonth() {
return subscriptionMonth;
}
public void setSubscriptionMonth(Integer subscriptionMonth) {
this.subscriptionMonth = subscriptionMonth;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\plugin\base\dto\MetricsAggregatedResultDto.java
| 1
|
请完成以下Java代码
|
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setPackageInfoCount (int PackageInfoCount)
{
throw new IllegalArgumentException ("PackageInfoCount is virtual column"); }
@Override
public int getPackageInfoCount()
{
return get_ValueAsInt(COLUMNNAME_PackageInfoCount);
}
@Override
public void setPageCount (int PageCount)
{
set_Value (COLUMNNAME_PageCount, Integer.valueOf(PageCount));
}
|
@Override
public int getPageCount()
{
return get_ValueAsInt(COLUMNNAME_PageCount);
}
@Override
public void setTransactionID (java.lang.String TransactionID)
{
set_Value (COLUMNNAME_TransactionID, TransactionID);
}
@Override
public java.lang.String getTransactionID()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Package.java
| 1
|
请完成以下Java代码
|
public void afterMobileApplicationTrlChanged(final I_Mobile_Application_Trl mobileApplicationTrl)
{
final MobileApplicationRepoId mobileApplicationRepoId = MobileApplicationRepoId.ofRepoId(mobileApplicationTrl.getMobile_Application_ID());
final String adLanguage = mobileApplicationTrl.getAD_Language();
mobileApplicationInfoRepository.updateMobileApplicationTrl(mobileApplicationRepoId, adLanguage);
}
private static void assertNotChangingRegularAndCustomizationFields(final I_Mobile_Application_Trl mobileApplicationTrl)
{
final Set<String> changedRegularFields = new HashSet<>();
final Set<String> changedCustomizationFields = new HashSet<>();
if (isValueChanged(mobileApplicationTrl, I_Mobile_Application_Trl.COLUMNNAME_IsUseCustomization))
{
changedCustomizationFields.add(I_Mobile_Application_Trl.COLUMNNAME_IsUseCustomization);
}
//
for (final MobileApplicationTranslatedColumn field : MobileApplicationTranslatedColumn.values())
{
if (field.hasCustomizedField() && isValueChanged(mobileApplicationTrl, field.getCustomizationColumnName()))
{
changedCustomizationFields.add(field.getCustomizationColumnName());
}
if (isValueChanged(mobileApplicationTrl, field.getColumnName()))
{
changedRegularFields.add(field.getColumnName());
}
}
//
if (!changedRegularFields.isEmpty() && !changedCustomizationFields.isEmpty())
{
throw new AdempiereException("Changing regular fields and customization fields is not allowed."
+ "\n Regular fields changed: " + changedRegularFields
+ "\n Customization fields changed: " + changedCustomizationFields)
.markAsUserValidationError();
}
}
private static boolean isValueChanged(final I_Mobile_Application_Trl mobileApplicationTrl, final String columnName)
{
return InterfaceWrapperHelper.isValueChanged(mobileApplicationTrl, columnName);
|
}
private enum MobileApplicationTranslatedColumn
{
Name(I_Mobile_Application_Trl.COLUMNNAME_Name, I_Mobile_Application_Trl.COLUMNNAME_Name_Customized), //
Description(I_Mobile_Application_Trl.COLUMNNAME_Description, I_Mobile_Application_Trl.COLUMNNAME_Description_Customized), //
;
@Getter
private final String columnName;
@Getter
private final String customizationColumnName;
MobileApplicationTranslatedColumn(
@NonNull final String columnName,
@Nullable final String customizationColumnName)
{
this.columnName = columnName;
this.customizationColumnName = customizationColumnName;
}
public boolean hasCustomizedField()
{
return getCustomizationColumnName() != null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\translation\interceptor\Mobile_Application_Trl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PageResult<DictDto> queryAll(DictQueryCriteria dict, Pageable pageable){
Page<Dict> page = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable);
return PageUtil.toPage(page.map(dictMapper::toDto));
}
@Override
public List<DictDto> queryAll(DictQueryCriteria dict) {
List<Dict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb));
return dictMapper.toDto(list);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Dict resources) {
dictRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Dict resources) {
// 清理缓存
delCaches(resources);
Dict dict = dictRepository.findById(resources.getId()).orElseGet(Dict::new);
ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId());
dict.setName(resources.getName());
dict.setDescription(resources.getDescription());
dictRepository.save(dict);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
// 清理缓存
List<Dict> dicts = dictRepository.findByIdIn(ids);
for (Dict dict : dicts) {
delCaches(dict);
}
dictRepository.deleteByIdIn(ids);
}
@Override
public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DictDto dictDTO : dictDtos) {
if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){
for (DictDetailDto dictDetail : dictDTO.getDictDetails()) {
Map<String,Object> map = new LinkedHashMap<>();
|
map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", dictDetail.getLabel());
map.put("字典值", dictDetail.getValue());
map.put("创建日期", dictDetail.getCreateTime());
list.add(map);
}
} else {
Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", null);
map.put("字典值", null);
map.put("创建日期", dictDTO.getCreateTime());
list.add(map);
}
}
FileUtil.downloadExcel(list, response);
}
public void delCaches(Dict dict){
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictServiceImpl.java
| 2
|
请完成以下Java代码
|
private void generateOutboundDocument(
@NonNull final Object record,
@Nullable final UserId userId)
{
final boolean isInvoiceEmailEnabledEffective = computeInvoiceEmailEnabledFromRecord(record);
final ArchiveResult archiveResult = DefaultModelArchiver.builder()
.record(record)
.flavor(isInvoiceEmailEnabledEffective ? DocumentReportFlavor.EMAIL : DocumentReportFlavor.PRINT)
.reportProcessId(getReportProcessIdToUse(record))
.build()
.archive();
if (archiveResult.isNoArchive())
{
Loggables.addLog("Created *no* AD_Archive for record={}", record);
}
else
{
Loggables.addLog("Created AD_Archive_ID={} for record={}", archiveResult.getArchiveRecord().getAD_Archive_ID(), record);
archiveEventManager.firePdfUpdate(archiveResult.getArchiveRecord(), userId);
}
}
@Nullable
private AdProcessId getReportProcessIdToUse(final Object record)
{
if (InterfaceWrapperHelper.isInstanceOf(record, I_C_Letter.class))
{
final I_C_Letter letter = InterfaceWrapperHelper.create(record, I_C_Letter.class);
final BoilerPlateId boilderPlateId = BoilerPlateId.ofRepoIdOrNull(letter.getAD_BoilerPlate_ID());
if (boilderPlateId != null)
{
|
return TextTemplateBL.getJasperProcessId(boilderPlateId).orElse(null);
}
}
// fallback
return null;
}
private boolean computeInvoiceEmailEnabledFromRecord(@NonNull final Object record)
{
final TableRecordReference recordRef = TableRecordReference.of(record);
return docOutboundLogMailRecipientRegistry
.getRecipient(
DocOutboundLogMailRecipientRequest.builder()
.recordRef(recordRef)
.clientId(InterfaceWrapperHelper.getClientId(record).orElseThrow(() -> new AdempiereException("Cannot get AD_Client_ID from " + record)))
.orgId(InterfaceWrapperHelper.getOrgId(record).orElseThrow(() -> new AdempiereException("Cannot get AD_Org_ID from " + record)))
.docTypeId(documentBL.getDocTypeId(record).orElse(null))
.build())
.map(DocOutBoundRecipients::isInvoiceAsEmail)
.orElse(false);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\async\spi\impl\DocOutboundWorkpackageProcessor.java
| 1
|
请完成以下Java代码
|
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
|
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[" +
"count=" + count +
", processDefinitionKey='" + processDefinitionKey + '\'' +
", processDefinitionId='" + processDefinitionId + '\'' +
", processDefinitionName='" + processDefinitionName + '\'' +
", taskName='" + taskName + '\'' +
", tenantId='" + tenantId + '\'' +
']';
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskReportResultEntity.java
| 1
|
请完成以下Java代码
|
public static FormRepositoryService getFormRepositoryService(ProcessEngineConfiguration processEngineConfiguration) {
FormRepositoryService formRepositoryService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(processEngineConfiguration);
if (formEngineConfiguration != null) {
formRepositoryService = formEngineConfiguration.getFormRepositoryService();
}
return formRepositoryService;
}
public static FormService getFormService(AbstractEngineConfiguration engineConfiguration) {
FormService formService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(engineConfiguration);
if (formEngineConfiguration != null) {
formService = formEngineConfiguration.getFormService();
}
return formService;
}
public static FormManagementService getFormManagementService(AbstractEngineConfiguration engineConfiguration) {
FormManagementService formManagementService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(engineConfiguration);
if (formEngineConfiguration != null) {
formManagementService = formEngineConfiguration.getFormManagementService();
}
return formManagementService;
}
// CONTENT ENGINE
|
public static ContentEngineConfigurationApi getContentEngineConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (ContentEngineConfigurationApi) engineConfiguration.getEngineConfigurations().get(EngineConfigurationConstants.KEY_CONTENT_ENGINE_CONFIG);
}
public static ContentService getContentService(AbstractEngineConfiguration engineConfiguration) {
ContentService contentService = null;
ContentEngineConfigurationApi contentEngineConfiguration = getContentEngineConfiguration(engineConfiguration);
if (contentEngineConfiguration != null) {
contentService = contentEngineConfiguration.getContentService();
}
return contentService;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\EngineServiceUtil.java
| 1
|
请完成以下Java代码
|
public void setup() throws IOException {
for (int i = 0; i < 1500; i++) {
File targetFile = new File(FILE_NAME + i);
FileUtils.writeStringToFile(targetFile, "Test", "UTF8");
}
}
@TearDown(Level.Trial)
public void tearDown() {
for (int i = 0; i < 1500; i++) {
File fileToDelete = new File(FILE_NAME + i);
fileToDelete.delete();
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
public static void textFileSearchSequential() throws IOException {
Files.walk(Paths.get("src/main/resources/")).map(Path::normalize).filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt")).collect(Collectors.toList());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void textFileSearchParallel() throws IOException {
Files.walk(Paths.get("src/main/resources/")).parallel().map(Path::normalize).filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt")).collect(Collectors.toList());
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\parallel\FileSearchCost.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public TopicBuilder replicas(int replicaCount) {
this.replicas = Optional.of((short) replicaCount);
return this;
}
/**
* Set the replica assignments.
* @param replicaAssignments the assignments.
* @return the builder.
* @see NewTopic#replicasAssignments()
*/
public TopicBuilder replicasAssignments(Map<Integer, List<Integer>> replicaAssignments) {
replicaAssignments.forEach((part, list) -> assignReplicas(part, list));
return this;
}
/**
* Add an individual replica assignment.
* @param partition the partition.
* @param replicaList the replicas.
* @return the builder.
* @see NewTopic#replicasAssignments()
*/
public TopicBuilder assignReplicas(int partition, List<Integer> replicaList) {
if (this.replicasAssignments == null) {
this.replicasAssignments = new HashMap<>();
}
this.replicasAssignments.put(partition, new ArrayList<>(replicaList));
return this;
}
/**
* Set the configs.
* @param configProps the configs.
* @return the builder.
* @see NewTopic#configs()
*/
public TopicBuilder configs(Map<String, String> configProps) {
this.configs.putAll(configProps);
return this;
}
/**
* Set a configuration option.
* @param configName the name.
* @param configValue the value.
* @return the builder
* @see TopicConfig
*/
public TopicBuilder config(String configName, String configValue) {
this.configs.put(configName, configValue);
return this;
|
}
/**
* Set the {@link TopicConfig#CLEANUP_POLICY_CONFIG} to
* {@link TopicConfig#CLEANUP_POLICY_COMPACT}.
* @return the builder.
*/
public TopicBuilder compact() {
this.configs.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
return this;
}
public NewTopic build() {
NewTopic topic = this.replicasAssignments == null
? new NewTopic(this.name, this.partitions, this.replicas)
: new NewTopic(this.name, this.replicasAssignments);
if (!this.configs.isEmpty()) {
topic.configs(this.configs);
}
return topic;
}
/**
* Create a TopicBuilder with the supplied name.
* @param name the name.
* @return the builder.
*/
public static TopicBuilder name(String name) {
return new TopicBuilder(name);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\TopicBuilder.java
| 2
|
请完成以下Java代码
|
public MealAsSingleEntity getMeal() {
return meal;
}
public void setMeal(MealAsSingleEntity meal) {
this.meal = meal;
}
public boolean isPeanuts() {
return peanuts;
}
public void setPeanuts(boolean peanuts) {
this.peanuts = peanuts;
}
public boolean isCelery() {
return celery;
}
public void setCelery(boolean celery) {
|
this.celery = celery;
}
public boolean isSesameSeeds() {
return sesameSeeds;
}
public void setSesameSeeds(boolean sesameSeeds) {
this.sesameSeeds = sesameSeeds;
}
@Override
public String toString() {
return "AllergensAsEntity [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]";
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\multipletables\multipleentities\AllergensAsEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DefaultTbResourceDataCache implements TbResourceDataCache {
private final ResourceService resourceService;
private final JpaExecutorService executorService;
@Value("${cache.tbResourceData.maxSize:100000}")
private int cacheMaxSize;
@Value("${cache.tbResourceData.timeToLiveInMinutes:44640}")
private int cacheValueTtl;
private AsyncLoadingCache<ResourceDataKey, TbResourceDataInfo> cache;
@PostConstruct
private void init() {
cache = Caffeine.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterAccess(cacheValueTtl, TimeUnit.MINUTES)
.executor(executorService)
.buildAsync((key, executor) -> CompletableFuture.supplyAsync(() -> resourceService.getResourceDataInfo(key.tenantId(), key.resourceId()), executor));
}
|
@Override
public FluentFuture<TbResourceDataInfo> getResourceDataInfoAsync(TenantId tenantId, TbResourceId resourceId) {
log.trace("Retrieving resource data info by id [{}], tenant id [{}] from cache", resourceId, tenantId);
return DonAsynchron.toFluentFuture(cache.get(new ResourceDataKey(tenantId, resourceId)));
}
@Override
public void evictResourceData(TenantId tenantId, TbResourceId resourceId) {
cache.asMap().remove(new ResourceDataKey(tenantId, resourceId));
log.trace("Evicted resource data info with id [{}], tenant id [{}]", resourceId, tenantId);
}
record ResourceDataKey (TenantId tenantId, TbResourceId resourceId) {}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\resource\DefaultTbResourceDataCache.java
| 2
|
请完成以下Java代码
|
public int getMobileUI_HUManager_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_ID);
}
@Override
public void setMobileUI_HUManager_LayoutSection_ID (final int MobileUI_HUManager_LayoutSection_ID)
{
if (MobileUI_HUManager_LayoutSection_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_LayoutSection_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_LayoutSection_ID, MobileUI_HUManager_LayoutSection_ID);
}
@Override
public int getMobileUI_HUManager_LayoutSection_ID()
|
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_LayoutSection_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_HUManager_LayoutSection.java
| 1
|
请完成以下Java代码
|
public class InstructionType {
@XmlAttribute(name = "token", required = true)
protected String token;
@XmlAttribute(name = "value", required = true)
protected String value;
/**
* Gets the value of the token property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getToken() {
return token;
}
/**
* Sets the value of the token property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setToken(String value) {
this.token = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = 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\InstructionType.java
| 1
|
请完成以下Java代码
|
public boolean hasTaskOwnerChanged() {
return hasStringFieldChanged(TaskInfo::getOwner);
}
public boolean hasTaskPriorityChanged() {
return hasIntegerFieldChanged(TaskInfo::getPriority);
}
public boolean hasTaskCategoryChanged() {
return hasStringFieldChanged(TaskInfo::getCategory);
}
public boolean hasTaskFormKeyChanged() {
return hasStringFieldChanged(TaskInfo::getFormKey);
}
public boolean hasTaskParentIdChanged() {
return hasStringFieldChanged(TaskInfo::getParentTaskId);
}
private boolean hasStringFieldChanged(Function<TaskInfo, String> comparableTaskGetter) {
if (originalTask != null && updatedTask != null) {
return !StringUtils.equals(
comparableTaskGetter.apply(originalTask),
comparableTaskGetter.apply(updatedTask)
);
}
return false;
}
private boolean hasIntegerFieldChanged(Function<TaskInfo, Integer> comparableTaskGetter) {
if (originalTask != null && updatedTask != null) {
return !Objects.equals(comparableTaskGetter.apply(originalTask), comparableTaskGetter.apply(updatedTask));
}
return false;
}
private boolean hasDateFieldChanged(Function<TaskInfo, Date> comparableTaskGetter) {
if (originalTask != null && updatedTask != null) {
Date originalDate = comparableTaskGetter.apply(originalTask);
Date newDate = comparableTaskGetter.apply(updatedTask);
return (
(originalDate == null && newDate != null) ||
(originalDate != null && newDate == null) ||
(originalDate != null && !originalDate.equals(newDate))
);
}
|
return false;
}
private TaskInfo copyInformationFromTaskInfo(TaskInfo task) {
if (task != null) {
TaskEntityImpl duplicatedTask = new TaskEntityImpl();
duplicatedTask.setName(task.getName());
duplicatedTask.setDueDate(task.getDueDate());
duplicatedTask.setDescription(task.getDescription());
duplicatedTask.setId(task.getId());
duplicatedTask.setOwner(task.getOwner());
duplicatedTask.setPriority(task.getPriority());
duplicatedTask.setCategory(task.getCategory());
duplicatedTask.setFormKey(task.getFormKey());
duplicatedTask.setAssignee(task.getAssignee());
duplicatedTask.setTaskDefinitionKey(task.getTaskDefinitionKey());
duplicatedTask.setParentTaskId(task.getParentTaskId());
return duplicatedTask;
}
throw new IllegalArgumentException("task must be non-null");
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\task\TaskComparatorImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<DDOrderLineId, List<DDOrderMoveSchedule>> getSchedulesByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds)
{
if (ddOrderLineIds.isEmpty()) {return ImmutableMap.of();}
final Map<DDOrderLineId, List<DDOrderMoveSchedule>> map = ddOrderMoveScheduleService.getByDDOrderLineIds(ddOrderLineIds)
.stream()
.collect(Collectors.groupingBy(DDOrderMoveSchedule::getDdOrderLineId, Collectors.toList()));
return CollectionUtils.fillMissingKeys(map, ddOrderLineIds, ImmutableList.of());
}
public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId)
{
return ddOrderMoveScheduleService.hasInTransitSchedules(inTransitLocatorId);
}
public ZoneId getTimeZone(final OrgId orgId)
{
return orgDAO.getTimeZone(orgId);
}
public HUInfo getHUInfo(final HuId huId) {return huService.getHUInfoById(huId);}
|
@Nullable
public SalesOrderRef getSalesOderRef(@NonNull final I_DD_Order ddOrder)
{
final OrderId salesOrderId = OrderId.ofRepoIdOrNull(ddOrder.getC_Order_ID());
return salesOrderId != null ? sourceDocService.getSalesOderRef(salesOrderId) : null;
}
@Nullable
public ManufacturingOrderRef getManufacturingOrderRef(@NonNull final I_DD_Order ddOrder)
{
final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID());
return ppOrderId != null ? sourceDocService.getManufacturingOrderRef(ppOrderId) : null;
}
@NonNull
public PlantInfo getPlantInfo(@NonNull final ResourceId plantId)
{
return sourceDocService.getPlantInfo(plantId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoaderSupportingServices.java
| 2
|
请完成以下Java代码
|
public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) {
}
@Override
public void disconnected(ExecutorDriver driver) {
}
@Override
public void launchTask(ExecutorDriver driver, TaskInfo task) {
Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_RUNNING).build();
driver.sendStatusUpdate(status);
String myStatus = "Hello Framework";
driver.sendFrameworkMessage(myStatus.getBytes());
System.out.println("Hello World!!!");
status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_FINISHED).build();
driver.sendStatusUpdate(status);
}
|
@Override
public void killTask(ExecutorDriver driver, Protos.TaskID taskId) {
}
@Override
public void frameworkMessage(ExecutorDriver driver, byte[] data) {
}
@Override
public void shutdown(ExecutorDriver driver) {
}
@Override
public void error(ExecutorDriver driver, String message) {
}
public static void main(String[] args) {
MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor());
System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1);
}
}
|
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\mesos\executors\HelloWorldExecutor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
void setRequestFactoryBuilder(@Nullable ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder) {
this.requestFactoryBuilder = requestFactoryBuilder;
}
void setClientSettings(@Nullable HttpClientSettings clientSettings) {
this.clientSettings = clientSettings;
}
void setHttpMessageConvertersCustomizers(
@Nullable List<ClientHttpMessageConvertersCustomizer> httpMessageConvertersCustomizers) {
this.httpMessageConvertersCustomizers = httpMessageConvertersCustomizers;
}
void setRestTemplateCustomizers(@Nullable List<RestTemplateCustomizer> restTemplateCustomizers) {
this.restTemplateCustomizers = restTemplateCustomizers;
}
void setRestTemplateRequestCustomizers(
@Nullable List<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers) {
this.restTemplateRequestCustomizers = restTemplateRequestCustomizers;
}
/**
* Configure the specified {@link RestTemplateBuilder}. The builder can be further
* tuned and default settings can be overridden.
* @param builder the {@link RestTemplateBuilder} instance to configure
* @return the configured builder
*/
public RestTemplateBuilder configure(RestTemplateBuilder builder) {
if (this.requestFactoryBuilder != null) {
builder = builder.requestFactoryBuilder(this.requestFactoryBuilder);
}
if (this.clientSettings != null) {
builder = builder.clientSettings(this.clientSettings);
}
if (this.httpMessageConvertersCustomizers != null) {
ClientBuilder clientBuilder = HttpMessageConverters.forClient();
|
this.httpMessageConvertersCustomizers.forEach((customizer) -> customizer.customize(clientBuilder));
builder = builder.messageConverters(clientBuilder.build());
}
builder = addCustomizers(builder, this.restTemplateCustomizers, RestTemplateBuilder::customizers);
builder = addCustomizers(builder, this.restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);
return builder;
}
private <T> RestTemplateBuilder addCustomizers(RestTemplateBuilder builder, @Nullable List<T> customizers,
BiFunction<RestTemplateBuilder, Collection<T>, RestTemplateBuilder> method) {
if (!ObjectUtils.isEmpty(customizers)) {
return method.apply(builder, customizers);
}
return builder;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\RestTemplateBuilderConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getScopeId() {
return this.scopeId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return this.scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
|
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
if (userId != null) {
sb.append(", userId=").append(userId);
}
if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefId != null) {
sb.append(", processDefId=").append(processDefId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\IdentityLinkEntityImpl.java
| 2
|
请完成以下Java代码
|
public class SumUpTransactionStatus
{
public static final SumUpTransactionStatus SUCCESSFUL = new SumUpTransactionStatus("SUCCESSFUL");
public static final SumUpTransactionStatus CANCELLED = new SumUpTransactionStatus("CANCELLED");
public static final SumUpTransactionStatus FAILED = new SumUpTransactionStatus("FAILED");
public static final SumUpTransactionStatus PENDING = new SumUpTransactionStatus("PENDING");
@NonNull private static final ConcurrentHashMap<String, SumUpTransactionStatus> intern = new ConcurrentHashMap<>();
static
{
Arrays.asList(SUCCESSFUL, CANCELLED, FAILED, PENDING)
.forEach(status -> intern.put(status.getCode(), status));
}
@NonNull private final String code;
private SumUpTransactionStatus(@NonNull final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
if (codeNorm == null)
{
throw new AdempiereException("Invalid status: " + code);
}
this.code = codeNorm;
}
|
@JsonCreator
@NonNull
public static SumUpTransactionStatus ofString(@NonNull final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
if (codeNorm == null)
{
throw new AdempiereException("Invalid status: " + code);
}
return intern.computeIfAbsent(codeNorm, SumUpTransactionStatus::new);
}
@Override
@Deprecated
public String toString() {return getCode();}
@JsonValue
@NonNull
public String getCode() {return code;}
public static boolean equals(@Nullable final SumUpTransactionStatus status1, @Nullable final SumUpTransactionStatus status2) {return Objects.equals(status1, status2);}
public boolean isPending() {return this.equals(PENDING);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransactionStatus.java
| 1
|
请完成以下Java代码
|
public static boolean verify(byte[] messageBytes, String signingAlgorithm, PublicKey publicKey, byte[] signedData) {
try {
Signature signature = Signature.getInstance(signingAlgorithm);
signature.initVerify(publicKey);
signature.update(messageBytes);
return signature.verify(signedData);
} catch (GeneralSecurityException exp) {
throw new SecurityException("Error during verifying", exp);
}
}
public static byte[] signWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PrivateKey privateKey) {
try {
MessageDigest md = MessageDigest.getInstance(hashingAlgorithm);
byte[] messageHash = md.digest(messageBytes);
DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder();
AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm);
DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, messageHash);
byte[] hashToEncrypt = digestInfo.getEncoded();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(hashToEncrypt);
} catch (GeneralSecurityException | IOException exp) {
throw new SecurityException("Error during signature generation", exp);
}
}
public static boolean verifyWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PublicKey publicKey, byte[] encryptedMessageHash) {
try {
|
MessageDigest md = MessageDigest.getInstance(hashingAlgorithm);
byte[] newMessageHash = md.digest(messageBytes);
DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder();
AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm);
DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, newMessageHash);
byte[] hashToEncrypt = digestInfo.getEncoded();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decryptedMessageHash = cipher.doFinal(encryptedMessageHash);
return Arrays.equals(decryptedMessageHash, hashToEncrypt);
} catch (GeneralSecurityException | IOException exp) {
throw new SecurityException("Error during verifying", exp);
}
}
}
|
repos\tutorials-master\libraries-security\src\main\java\com\baeldung\digitalsignature\DigitalSignatureUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer getOrSaveKeyId(String strKey) {
Integer cached = keyDictionaryMap.get(strKey);
if (cached != null) {
return cached;
}
var compositeKey = new KeyDictionaryCompositeKey(strKey);
Optional<Integer> existingId = keyDictionaryRepository.findById(compositeKey).map(KeyDictionaryEntry::getKeyId);
if (existingId.isPresent()) {
return cacheAndReturn(strKey, existingId.get());
}
creationLock.lock();
try {
Integer fromCache = keyDictionaryMap.get(strKey);
if (fromCache != null) {
return fromCache;
}
Integer keyId = keyDictionaryRepository.upsertAndGetKeyId(strKey);
if (keyId != null) {
return cacheAndReturn(strKey, keyId);
}
log.warn("upsertAndGetKeyId returned: [{}] for key: [{}], falling back to findById", keyId, strKey);
keyId = keyDictionaryRepository.findById(compositeKey)
.map(KeyDictionaryEntry::getKeyId)
.orElseThrow(() -> new IllegalStateException(
|
"Failed to resolve keyId for string key: " + strKey + " after fallback."));
return cacheAndReturn(strKey, keyId);
} finally {
creationLock.unlock();
}
}
@Override
public String getKey(Integer keyId) {
Optional<KeyDictionaryEntry> byKeyId = keyDictionaryRepository.findByKeyId(keyId);
return byKeyId.map(KeyDictionaryEntry::getKey).orElse(null);
}
@Override
public PageData<KeyDictionaryEntry> findAll(PageLink pageLink) {
return DaoUtil.pageToPageData(keyDictionaryRepository.findAll(DaoUtil.toPageable(pageLink)));
}
private Integer cacheAndReturn(String key, Integer keyId) {
keyDictionaryMap.put(key, keyId);
return keyId;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\dictionary\JpaKeyDictionaryDao.java
| 2
|
请完成以下Java代码
|
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.math.BigDecimal Version)
{
|
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.math.BigDecimal getVersion ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RideProcessingWorkflow implements Workflow {
@Override
public WorkflowStub create() {
return context -> {
String instanceId = context.getInstanceId();
context.getLogger()
.info("Starting ride processing workflow: {}", instanceId);
RideWorkflowRequest request = context.getInput(RideWorkflowRequest.class);
WorkflowTaskOptions options = taskOptions();
context.getLogger()
.info("Step 1: Validating driver {}", request.getDriverId());
boolean isValid = context.callActivity(ValidateDriverActivity.class.getName(), request, options, boolean.class)
.await();
if (!isValid) {
context.complete(new RideWorkflowStatus(request.getRideId(), "FAILED", "Driver validation failed"));
return;
}
context.getLogger()
.info("Step 2: Calculating fare");
double fare = context.callActivity(CalculateFareActivity.class.getName(), request, options, double.class)
.await();
context.getLogger()
.info("Step 3: Notifying passenger");
NotificationInput notificationInput = new NotificationInput(request, fare);
String notification = context.callActivity(NotifyPassengerActivity.class.getName(), notificationInput, options, String.class)
.await();
|
context.getLogger()
.info("Step 4: Waiting for passenger confirmation");
String confirmation = context.waitForExternalEvent("passenger-confirmation", Duration.ofMinutes(5), String.class)
.await();
if (!"confirmed".equalsIgnoreCase(confirmation)) {
context.complete(new RideWorkflowStatus(request.getRideId(), "CANCELLED", "Passenger did not confirm the ride within the timeout period"));
return;
}
String message = String.format("Ride confirmed and processed successfully. Fare: $%.2f. %s", fare, notification);
RideWorkflowStatus status = new RideWorkflowStatus(request.getRideId(), "COMPLETED", message);
context.getLogger()
.info("Workflow completed: {}", message);
context.complete(status);
};
}
private WorkflowTaskOptions taskOptions() {
int maxRetries = 3;
Duration backoffTimeout = Duration.ofSeconds(1);
double backoffCoefficient = 1.5;
Duration maxRetryInterval = Duration.ofSeconds(5);
Duration maxTimeout = Duration.ofSeconds(10);
WorkflowTaskRetryPolicy retryPolicy = new WorkflowTaskRetryPolicy(maxRetries, backoffTimeout, backoffCoefficient, maxRetryInterval, maxTimeout);
return new WorkflowTaskOptions(retryPolicy);
}
}
|
repos\tutorials-master\messaging-modules\dapr\dapr-workflows\src\main\java\com\baeldung\dapr\workflow\RideProcessingWorkflow.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ImportIssuesRequest
{
@NonNull
String oAuthToken;
@NonNull
ExternalProjectReferenceId externalProjectReferenceId;
@NonNull
String repoId;
@NonNull
String repoOwner;
@NonNull
ExternalProjectType externalProjectType;
@NonNull
OrgId orgId;
|
@Nullable
ProjectId projectId;
@Nullable
GithubIssueLinkMatcher githubIssueLinkMatcher;
@Nullable
LocalDate dateFrom;
@Nullable
ImmutableList<String> issueNoList;
public boolean importByIds()
{
return !Check.isEmpty(issueNoList);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\importer\info\ImportIssuesRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Car {
@Id
@GeneratedValue
private int id;
private Integer power;
private String model;
public Car() {
}
public Car(int power, String model) {
this.power = power;
this.model = model;
}
public Integer getPower() {
return power;
}
public void setPower(Integer power) {
|
this.power = power;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getId() {
return id;
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\boot\domain\Car.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* Gets the value of the baseQuantity property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getBaseQuantity() {
return baseQuantity;
}
/**
* Sets the value of the baseQuantity property.
*
* @param value
* allowed object is
|
* {@link BigDecimal }
*
*/
public void setBaseQuantity(BigDecimal value) {
this.baseQuantity = value;
}
/**
* Gets the value of the priceType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPriceType() {
return priceType;
}
/**
* Sets the value of the priceType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPriceType(String value) {
this.priceType = 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\UnitPriceExtType.java
| 2
|
请完成以下Java代码
|
HttpEntity<String> post(@RequestBody UserPayload user) {
return ResponseEntity
.ok(String.format("Received firstname: %s, lastname: %s", user.getFirstname(), user.getLastname()));
}
/**
* Returns a simple JSON payload.
*
* @return
*/
@GetMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
Map<String, Object> getJson() {
Map<String, Object> result = new HashMap<>();
result.put("firstname", "Dave");
result.put("lastname", "Matthews");
return result;
}
/**
* Returns the payload of {@link #getJson()} wrapped into another element to simulate a change in the representation.
*
* @return
*/
@GetMapping(path = "/changed", produces = MediaType.APPLICATION_JSON_VALUE)
Map<String, Object> getChangedJson() {
return Collections.singletonMap("user", getJson());
}
/**
* Returns a simple XML payload.
*
* @return
*/
@GetMapping(path = "/", produces = MediaType.APPLICATION_XML_VALUE)
String getXml() {
|
return "<user>".concat(XML_PAYLOAD).concat("</user>");
}
/**
* Returns the payload of {@link #getXml()} wrapped into another XML element to simulate a change in the
* representation structure.
*
* @return
*/
@GetMapping(path = "/changed", produces = MediaType.APPLICATION_XML_VALUE)
String getChangedXml() {
return "<user><username>".concat(XML_PAYLOAD).concat("</username></user>");
}
/**
* The projection interface using XPath and JSON Path expression to selectively pick elements from the payload.
*
* @author Oliver Gierke
*/
@ProjectedPayload
public interface UserPayload {
@XBRead("//firstname")
@JsonPath("$..firstname")
String getFirstname();
@XBRead("//lastname")
@JsonPath("$..lastname")
String getLastname();
}
}
|
repos\spring-data-examples-main\web\projection\src\main\java\example\users\UserController.java
| 1
|
请完成以下Java代码
|
private SqlAndParamsExtractor<ImpDataLine> createInsertIntoImportTableSql()
{
final String tableName = importTableDescriptor.getTableName();
final String keyColumnName = importTableDescriptor.getKeyColumnName();
final StringBuilder sqlColumns = new StringBuilder();
final StringBuilder sqlValues = new StringBuilder();
final List<ParametersExtractor<ImpDataLine>> sqlParamsExtractors = new ArrayList<>();
sqlColumns.append(keyColumnName);
sqlValues.append(DB.TO_TABLESEQUENCE_NEXTVAL(tableName));
//
// Standard fields
sqlColumns.append(", AD_Client_ID");
sqlValues.append(", ").append(clientId.getRepoId());
//
sqlColumns.append(", AD_Org_ID");
sqlValues.append(", ").append(orgId.getRepoId());
//
sqlColumns.append(", Created,CreatedBy,Updated,UpdatedBy,IsActive");
sqlValues.append(", now(),").append(userId.getRepoId()).append(",now(),").append(userId.getRepoId()).append(",'Y'");
//
sqlColumns.append(", Processed, I_IsImported");
sqlValues.append(", 'N', 'N'");
//
// I_LineNo
if (importTableDescriptor.getImportLineNoColumnName() != null)
{
sqlColumns.append(", ").append(importTableDescriptor.getImportLineNoColumnName());
sqlValues.append(", ?");
sqlParamsExtractors.add(dataLine -> ImmutableList.of(dataLine.getFileLineNo()));
}
//
// I_LineContext
if (importTableDescriptor.getImportLineNoColumnName() != null)
{
sqlColumns.append(", ").append(importTableDescriptor.getImportLineContentColumnName());
sqlValues.append(", ?");
sqlParamsExtractors.add(dataLine -> Collections.singletonList(dataLine.getLineString()));
}
//
// C_DataImport_Run_ID
{
Check.assumeNotNull(dataImportRunId, "dataImportRunId is not null");
sqlColumns.append(", ").append(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID);
sqlValues.append(", ").append(dataImportRunId.getRepoId());
}
//
// C_DataImport_ID
if (importTableDescriptor.getDataImportConfigIdColumnName() != null && dataImportConfigId != null)
{
sqlColumns.append(", ").append(importTableDescriptor.getDataImportConfigIdColumnName());
sqlValues.append(", ").append(dataImportConfigId.getRepoId());
}
|
//
// I_ErrorMsg
{
final int errorMaxLength = importTableDescriptor.getErrorMsgMaxLength();
sqlColumns.append(", ").append(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg);
sqlValues.append(", ?");
sqlParamsExtractors.add(dataLine -> Collections.singletonList(dataLine.getErrorMessageAsStringOrNull(errorMaxLength)));
}
//
// Values
{
for (final ImpFormatColumn column : columns)
{
sqlColumns.append(", ").append(column.getColumnName());
sqlValues.append(", ?");
}
sqlParamsExtractors.add(dataLine -> dataLine.getJdbcValues(columns));
}
return SqlAndParamsExtractor.<ImpDataLine> builder()
.sql("INSERT INTO " + tableName + "(" + sqlColumns + ") VALUES (" + sqlValues + ")")
.parametersExtractors(sqlParamsExtractors)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\SqlInsertIntoImportTableCommand.java
| 1
|
请完成以下Java代码
|
public void beforeSave(final I_GL_Distribution glDistribution)
{
//
// Update segment matcher values
if (glDistribution.isAnyAcct() && glDistribution.getAccount_ID() > 0)
{
glDistribution.setAccount(null);
}
if (glDistribution.isAnyActivity() && glDistribution.getC_Activity_ID() > 0)
{
glDistribution.setC_Activity_ID(-1);
}
if (glDistribution.isAnyBPartner() && glDistribution.getC_BPartner_ID() > 0)
{
glDistribution.setC_BPartner_ID(-1);
}
if (glDistribution.isAnyCampaign() && glDistribution.getC_Campaign_ID() > 0)
{
glDistribution.setC_Campaign(null);
}
if (glDistribution.isAnyLocFrom() && glDistribution.getC_LocFrom_ID() > 0)
{
glDistribution.setC_LocFrom(null);
}
if (glDistribution.isAnyLocTo() && glDistribution.getC_LocTo_ID() > 0)
{
glDistribution.setC_LocTo(null);
}
if (glDistribution.isAnyOrg() && glDistribution.getOrg_ID() > 0)
{
glDistribution.setOrg_ID(-1);
}
if (glDistribution.isAnyOrgTrx() && glDistribution.getAD_OrgTrx_ID() > 0)
{
glDistribution.setAD_OrgTrx_ID(-1);
}
if (glDistribution.isAnyProduct() && glDistribution.getM_Product_ID() > 0)
{
glDistribution.setM_Product_ID(-1);
|
}
if (glDistribution.isAnyProject() && glDistribution.getC_Project_ID() > 0)
{
glDistribution.setC_Project_ID(-1);
}
if (glDistribution.isAnySalesRegion() && glDistribution.getC_SalesRegion_ID() > 0)
{
glDistribution.setC_SalesRegion(null);
}
if (glDistribution.isAnyUser1() && glDistribution.getUser1_ID() > 0)
{
glDistribution.setUser1(null);
}
if (glDistribution.isAnyUser2() && glDistribution.getUser2_ID() > 0)
{
glDistribution.setUser2(null);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\GL_Distribution.java
| 1
|
请完成以下Java代码
|
public final void flush()
{
final String trxName = Services.get(ITrxManager.class).getThreadInheritedTrxName();
//
// Save HU Storages
for (final Map<Object, I_M_HU_Storage> huStorages : _hu2storage.values())
{
for (final I_M_HU_Storage huStorage : huStorages.values())
{
saveToDatabase(huStorage, trxName);
}
}
//
// Save HU Item Storages
for (final Map<Object, I_M_HU_Item_Storage> huItemStorages : _item2itemStorage.values())
|
{
for (final I_M_HU_Item_Storage huItemStorage : huItemStorages.values())
{
saveToDatabase(huItemStorage, trxName);
}
}
}
private final void saveToDatabase(final Object model, final String trxName)
{
InterfaceWrapperHelper.setSaveDeleteDisabled(model, false);
InterfaceWrapperHelper.save(model, trxName);
// InterfaceWrapperHelper.setSaveDeleteDisabled(model, true); // not sure if is necessary
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\SaveDecoupledHUStorageDAO.java
| 1
|
请完成以下Java代码
|
String getWhereClause()
{
return whereClause;
}
public ProcessDialogBuilder setTableAndRecord(final int AD_Table_ID, final int Record_ID)
{
this.AD_Table_ID = AD_Table_ID;
this.Record_ID = Record_ID;
return this;
}
int getAD_Table_ID()
{
return AD_Table_ID;
}
int getRecord_ID()
{
return Record_ID;
}
/**
* @param showHelp
* @see X_AD_Process#SHOWHELP_AD_Reference_ID
*/
public ProcessDialogBuilder setShowHelp(final String showHelp)
{
this.showHelp = showHelp;
return this;
}
String getShowHelp(final Supplier<String> defaultValueSupplier)
{
return showHelp != null ? showHelp : defaultValueSupplier.get();
}
ProcessDialogBuilder skipResultsPanel()
{
skipResultsPanel = true;
return this;
}
boolean isSkipResultsPanel()
{
return skipResultsPanel;
}
public ProcessDialogBuilder setAllowProcessReRun(final Boolean allowProcessReRun)
{
this.allowProcessReRun = allowProcessReRun;
return this;
}
boolean isAllowProcessReRun(final Supplier<Boolean> defaultValueSupplier)
{
return allowProcessReRun != null ? allowProcessReRun : defaultValueSupplier.get();
}
public ProcessDialogBuilder setFromGridTab(GridTab gridTab)
{
final int windowNo = gridTab.getWindowNo();
final int tabNo = gridTab.getTabNo();
setWindowAndTabNo(windowNo, tabNo);
setAdWindowId(gridTab.getAdWindowId());
|
setIsSOTrx(Env.isSOTrx(gridTab.getCtx(), windowNo));
setTableAndRecord(gridTab.getAD_Table_ID(), gridTab.getRecord_ID());
setWhereClause(gridTab.getTableModel().getSelectWhereClauseFinal());
skipResultsPanel();
return this;
}
public ProcessDialogBuilder setProcessExecutionListener(final IProcessExecutionListener processExecutionListener)
{
this.processExecutionListener = processExecutionListener;
return this;
}
IProcessExecutionListener getProcessExecutionListener()
{
return processExecutionListener;
}
public ProcessDialogBuilder setPrintPreview(final boolean printPreview)
{
this._printPreview = printPreview;
return this;
}
boolean isPrintPreview()
{
if (_printPreview != null)
{
return _printPreview;
}
return Ini.isPropertyBool(Ini.P_PRINTPREVIEW);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessDialogBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ServerProperties {
private Map<String, String> application;
private Map<String, List<String>> config;
private Map<String, Credential> users;
public Map<String, String> getApplication() {
return application;
}
public void setApplication(Map<String, String> application) {
this.application = application;
}
public Map<String, List<String>> getConfig() {
return config;
}
public void setConfig(Map<String, List<String>> config) {
this.config = config;
}
public Map<String, Credential> getUsers() {
return users;
}
public void setUsers(Map<String, Credential> users) {
this.users = users;
|
}
public static class Credential {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-properties-2\src\main\java\com\baeldung\properties\yamlmap\pojo\ServerProperties.java
| 2
|
请完成以下Java代码
|
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public org.compiere.model.I_S_ResourceType getS_ResourceType()
{
return get_ValueAsPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class);
}
@Override
public void setS_ResourceType(final org.compiere.model.I_S_ResourceType S_ResourceType)
{
set_ValueFromPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class, S_ResourceType);
}
@Override
public void setS_ResourceType_ID (final int S_ResourceType_ID)
{
if (S_ResourceType_ID < 1)
set_Value (COLUMNNAME_S_ResourceType_ID, null);
else
set_Value (COLUMNNAME_S_ResourceType_ID, S_ResourceType_ID);
}
@Override
public int getS_ResourceType_ID()
{
return get_ValueAsInt(COLUMNNAME_S_ResourceType_ID);
}
|
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final @Nullable BigDecimal WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public BigDecimal getWaitingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WaitingTime);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Resource.java
| 1
|
请完成以下Java代码
|
public void considerPPOrderAsNotClosed(final I_PP_Order ppOrder)
{
Check.assumeNotNull(ppOrder, "Param 'ppOrder is not null");
ppOrdersToBeConsideredNotClosed.add(ppOrder.getPP_Order_ID());
}
@Override
public Collection<I_M_PriceList_Version> getPriceListVersions()
{
return getPricingInfo().getPriceListVersions();
}
@Override
public IVendorInvoicingInfo getVendorInvoicingInfoForPLV(final I_M_PriceList_Version plv)
{
final MaterialTrackingAsVendorInvoicingInfo materialTrackingAsVendorInvoicingInfo = new MaterialTrackingAsVendorInvoicingInfo(getM_Material_Tracking());
materialTrackingAsVendorInvoicingInfo.setM_PriceList_Version(plv);
return materialTrackingAsVendorInvoicingInfo;
}
private MaterialTrackingDocumentsPricingInfo getPricingInfo()
{
if (pricingInfo == null)
{
final I_M_Material_Tracking materialTracking = getM_Material_Tracking();
final I_C_Flatrate_Term flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID());
final I_M_PricingSystem pricingSystem = priceListsRepo.getPricingSystemById(PricingSystemId.ofRepoIdOrNull(flatrateTerm
.getC_Flatrate_Conditions()
.getM_PricingSystem_ID()));
pricingInfo = MaterialTrackingDocumentsPricingInfo
.builder()
.setM_Material_Tracking(materialTracking)
// note that we give to the builder also those that were already processed into invoice candidates,
// because it needs that information to distinguish InOutLines that were not yet issued
// from those that were issued and whose issue-PP_Order already have IsInvoiceCanidate='Y'
.setAllProductionOrders(getAllProductionOrders())
.setNotYetInvoicedProductionOrders(getNotInvoicedProductionOrders())
.setM_PricingSystem(pricingSystem)
.build();
}
return pricingInfo;
}
@Override
public List<IQualityInspectionOrder> getProductionOrdersForPLV(final I_M_PriceList_Version plv)
{
return getPricingInfo().getQualityInspectionOrdersForPLV(plv);
}
@Override
|
public IVendorReceipt<I_M_InOutLine> getVendorReceiptForPLV(final I_M_PriceList_Version plv)
{
return getPricingInfo().getVendorReceiptForPLV(plv);
}
@Override
public IQualityInspectionOrder getQualityInspectionOrderOrNull()
{
final List<IQualityInspectionOrder> qualityInspectionOrders = getQualityInspectionOrders();
if (qualityInspectionOrders.isEmpty())
{
return null;
}
// as of now, return the last one
// TODO: consider returning an aggregated/averaged one
return qualityInspectionOrders.get(qualityInspectionOrders.size() - 1);
}
@Override
public void linkModelToMaterialTracking(final Object model)
{
final I_M_Material_Tracking materialTracking = getM_Material_Tracking();
materialTrackingBL.linkModelToMaterialTracking(
MTLinkRequest.builder()
.model(model)
.materialTrackingRecord(materialTracking)
.build());
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingDocuments.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BooleanDataEntry)) return false;
if (!super.equals(o)) return false;
BooleanDataEntry that = (BooleanDataEntry) o;
return Objects.equals(value, that.value);
}
@Override
public Object getValue() {
return value;
}
@Override
public int hashCode() {
|
return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "BooleanDataEntry{" +
"value=" + value +
"} " + super.toString();
}
@Override
public String getValueAsString() {
return Boolean.toString(value);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BooleanDataEntry.java
| 1
|
请完成以下Java代码
|
public boolean supports(Class<?> authentication) {
return OAuth2PushedAuthorizationRequestAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* Sets the {@code Consumer} providing access to the
* {@link OAuth2AuthorizationCodeRequestAuthenticationContext} and is responsible for
* validating specific OAuth 2.0 Pushed Authorization Request parameters associated in
* the {@link OAuth2AuthorizationCodeRequestAuthenticationToken}. The default
* authentication validator is
* {@link OAuth2AuthorizationCodeRequestAuthenticationValidator}.
*
* <p>
* <b>NOTE:</b> The authentication validator MUST throw
* {@link OAuth2AuthorizationCodeRequestAuthenticationException} if validation fails.
* @param authenticationValidator the {@code Consumer} providing access to the
* {@link OAuth2AuthorizationCodeRequestAuthenticationContext} and is responsible for
* validating specific OAuth 2.0 Pushed Authorization Request parameters
*/
public void setAuthenticationValidator(
|
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator) {
Assert.notNull(authenticationValidator, "authenticationValidator cannot be null");
this.authenticationValidator = authenticationValidator;
}
private static OAuth2AuthorizationCodeRequestAuthenticationToken toAuthorizationCodeRequestAuthentication(
OAuth2PushedAuthorizationRequestAuthenticationToken pushedAuthorizationCodeRequestAuthentication) {
return new OAuth2AuthorizationCodeRequestAuthenticationToken(
pushedAuthorizationCodeRequestAuthentication.getAuthorizationUri(),
pushedAuthorizationCodeRequestAuthentication.getClientId(),
(Authentication) pushedAuthorizationCodeRequestAuthentication.getPrincipal(),
pushedAuthorizationCodeRequestAuthentication.getRedirectUri(),
pushedAuthorizationCodeRequestAuthentication.getState(),
pushedAuthorizationCodeRequestAuthentication.getScopes(),
pushedAuthorizationCodeRequestAuthentication.getAdditionalParameters());
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2PushedAuthorizationRequestAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public boolean isHighVolume()
{
return true;
}
@Override
public LookupSource getLookupSourceType()
{
return LookupSource.lookup;
}
@Override
public boolean hasParameters()
{
return true;
}
@Override
|
public boolean isNumericKey()
{
return true;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return null;
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
@Override
public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression()
{
return sqlLookupDescriptor != null ? sqlLookupDescriptor.getSqlForFetchingLookupByIdExpression() : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptor.java
| 1
|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_Comment_ID()));
}
public I_K_Entry getK_Entry() throws RuntimeException
{
return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name)
.getPO(getK_Entry_ID(), get_TrxName()); }
/** Set Entry.
@param K_Entry_ID
Knowledge Entry
*/
public void setK_Entry_ID (int K_Entry_ID)
{
if (K_Entry_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID));
}
/** Get Entry.
@return Knowledge Entry
*/
public int getK_Entry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Comment.java
| 1
|
请完成以下Java代码
|
public <ID extends RepoIdAware> ImmutableSet<ID> toIdsFromInt(@NonNull final IntFunction<ID> idMapper)
{
return toSet(documentId -> idMapper.apply(documentId.toInt()));
}
/**
* Similar to {@link #toIds(Function)} but this returns a list, so it preserves the order
*/
public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper)
{
return toImmutableList(idMapper.compose(DocumentId::toInt));
}
public Set<String> toJsonSet()
{
if (all)
{
return ALL_StringSet;
}
return toSet(DocumentId::toJson);
}
public SelectionSize toSelectionSize()
{
if (isAll())
{
return SelectionSize.ofAll();
}
return SelectionSize.ofSize(size());
}
public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection)
{
if (this.isEmpty())
{
|
return documentIdsSelection;
}
else if (documentIdsSelection.isEmpty())
{
return this;
}
if (this.all)
{
return this;
}
else if (documentIdsSelection.all)
{
return documentIdsSelection;
}
final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet());
final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds);
if (this.equals(result))
{
return this;
}
else if (documentIdsSelection.equals(result))
{
return documentIdsSelection;
}
else
{
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RabbitMQConfig {
/**
* 创建 Direct 模式队列
* @return
*/
@Bean
public Queue testDirectQueue() {
return new Queue("test-direct-queue");
}
/**
* 创建 Direct 模式交换器
* @return
*/
@Bean
|
public DirectExchange TestDirectExchange() {
return new DirectExchange("test-direct-exchange");
}
/**
* 创建 Direct 队列与交换器绑定
* @param testDirectQueue
* @return
*/
@Bean
public Binding testDirectBinding(Queue testDirectQueue) {
return BindingBuilder.bind(testDirectQueue)
.to(TestDirectExchange()).with("test-direct-routing-key");
}
}
|
repos\spring-boot-best-practice-master\spring-boot-rabbitmq\src\main\java\cn\javastack\springboot\rabbitmq\RabbitMQConfig.java
| 2
|
请完成以下Java代码
|
private static ImmutableSet<CacheLabel> parseLabels(final String labels)
{
final String labelsNorm = StringUtils.trimBlankToNull(labels);
if (labelsNorm == null)
{
return ImmutableSet.of();
}
return Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToStream(labelsNorm)
.map(CacheLabel::ofTableName)
.collect(ImmutableSet.toImmutableSet());
}
@Override
public boolean test(@NonNull final CCacheStats stats)
{
if (cacheNameContainsLC != null && !stats.getName().toLowerCase().contains(cacheNameContainsLC))
|
{
return false;
}
if (minSize > 0 && stats.getSize() < minSize)
{
return false;
}
if (!labels.isEmpty() && !stats.getLabels().containsAll(labels))
{
return false;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCacheStatsPredicate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<AuthorityRuleEntity> apiAddAuthorityRule(@RequestBody AuthorityRuleEntity entity) {
Result<AuthorityRuleEntity> checkResult = checkEntityInternal(entity);
if (checkResult != null) {
return checkResult;
}
entity.setId(null);
Date date = new Date();
entity.setGmtCreate(date);
entity.setGmtModified(date);
try {
entity = repository.save(entity);
publishRules(entity.getApp());
} catch (Throwable throwable) {
logger.error("Failed to add authority rule", throwable);
return Result.ofThrowable(-1, throwable);
}
return Result.ofSuccess(entity);
}
@PutMapping("/rule/{id}")
@AuthAction(PrivilegeType.WRITE_RULE)
public Result<AuthorityRuleEntity> apiUpdateParamFlowRule(@PathVariable("id") Long id,
@RequestBody AuthorityRuleEntity entity) {
if (id == null || id <= 0) {
return Result.ofFail(-1, "Invalid id");
}
Result<AuthorityRuleEntity> checkResult = checkEntityInternal(entity);
if (checkResult != null) {
return checkResult;
}
entity.setId(id);
Date date = new Date();
entity.setGmtCreate(null);
entity.setGmtModified(date);
try {
entity = repository.save(entity);
if (entity == null) {
return Result.ofFail(-1, "Failed to save authority rule");
}
publishRules(entity.getApp());
} catch (Throwable throwable) {
logger.error("Failed to save authority rule", throwable);
return Result.ofThrowable(-1, throwable);
}
return Result.ofSuccess(entity);
}
@DeleteMapping("/rule/{id}")
@AuthAction(PrivilegeType.DELETE_RULE)
|
public Result<Long> apiDeleteRule(@PathVariable("id") Long id) {
if (id == null) {
return Result.ofFail(-1, "id cannot be null");
}
AuthorityRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
publishRules(oldEntity.getApp());
} catch (Exception e) {
return Result.ofFail(-1, e.getMessage());
}
return Result.ofSuccess(id);
}
private void publishRules(String app) throws Exception {
List<AuthorityRuleEntity> rules = repository.findAllByApp(app);
rulePublisher.publish(app, rules);
//延迟加载
delayTime();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\AuthorityRuleController.java
| 2
|
请完成以下Java代码
|
public CaseExecutionEntity findSubCaseInstanceBySuperExecutionId(String superExecutionId) {
return (CaseExecutionEntity) getDbEntityManager().selectOne("selectSubCaseInstanceBySuperExecutionId", superExecutionId);
}
public long findCaseExecutionCountByQueryCriteria(CaseExecutionQueryImpl caseExecutionQuery) {
configureTenantCheck(caseExecutionQuery);
return (Long) getDbEntityManager().selectOne("selectCaseExecutionCountByQueryCriteria", caseExecutionQuery);
}
@SuppressWarnings("unchecked")
public List<CaseExecution> findCaseExecutionsByQueryCriteria(CaseExecutionQueryImpl caseExecutionQuery, Page page) {
configureTenantCheck(caseExecutionQuery);
return getDbEntityManager().selectList("selectCaseExecutionsByQueryCriteria", caseExecutionQuery, page);
}
public long findCaseInstanceCountByQueryCriteria(CaseInstanceQueryImpl caseInstanceQuery) {
configureTenantCheck(caseInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectCaseInstanceCountByQueryCriteria", caseInstanceQuery);
}
@SuppressWarnings("unchecked")
public List<CaseInstance> findCaseInstanceByQueryCriteria(CaseInstanceQueryImpl caseInstanceQuery, Page page) {
configureTenantCheck(caseInstanceQuery);
|
return getDbEntityManager().selectList("selectCaseInstanceByQueryCriteria", caseInstanceQuery, page);
}
@SuppressWarnings("unchecked")
public List<CaseExecutionEntity> findChildCaseExecutionsByParentCaseExecutionId(String parentCaseExecutionId) {
return getDbEntityManager().selectList("selectCaseExecutionsByParentCaseExecutionId", parentCaseExecutionId);
}
@SuppressWarnings("unchecked")
public List<CaseExecutionEntity> findChildCaseExecutionsByCaseInstanceId(String caseInstanceId) {
return getDbEntityManager().selectList("selectCaseExecutionsByCaseInstanceId", caseInstanceId);
}
protected void configureTenantCheck(AbstractQuery<?, ?> query) {
getTenantManager().configureQuery(query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionManager.java
| 1
|
请完成以下Java代码
|
public ProcessDefinitionBuilder property(String name, Object value) {
processElement.setProperty(name, value);
return this;
}
public PvmProcessDefinition buildProcessDefinition() {
for (Object[] unresolvedTransition: unresolvedTransitions) {
TransitionImpl transition = (TransitionImpl) unresolvedTransition[0];
String destinationActivityName = (String) unresolvedTransition[1];
ActivityImpl destination = processDefinition.findActivity(destinationActivityName);
if (destination == null) {
throw new RuntimeException("destination '"+destinationActivityName+"' not found. (referenced from transition in '"+transition.getSource().getId()+"')");
}
transition.setDestination(destination);
}
return processDefinition;
}
protected ActivityImpl getActivity() {
return (ActivityImpl) scopeStack.peek();
}
public ProcessDefinitionBuilder scope() {
getActivity().setScope(true);
|
return this;
}
public ProcessDefinitionBuilder executionListener(ExecutionListener executionListener) {
if (transition!=null) {
transition.addExecutionListener(executionListener);
} else {
throw new PvmException("not in a transition scope");
}
return this;
}
public ProcessDefinitionBuilder executionListener(String eventName, ExecutionListener executionListener) {
if (transition==null) {
scopeStack.peek().addExecutionListener(eventName, executionListener);
} else {
transition.addExecutionListener(executionListener);
}
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\ProcessDefinitionBuilder.java
| 1
|
请完成以下Java代码
|
public String toString() {return toGlobalQRCodeJsonString();}
@JsonValue
public String toGlobalQRCodeJsonString() {return LocatorQRCodeJsonConverter.toGlobalQRCodeJsonString(this);}
@JsonCreator
public static LocatorQRCode ofGlobalQRCodeJsonString(final String json) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(json);}
public static LocatorQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);}
@JsonCreator
public static LocatorQRCode ofScannedCode(final ScannedCode scannedCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(scannedCode.getAsString());}
public static LocatorQRCode ofLocator(@NonNull final I_M_Locator locator)
{
return builder()
.locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID()))
.caption(locator.getValue())
.build();
}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
|
.qrCode(toGlobalQRCodeJsonString())
.bottomText(caption)
.build();
}
public GlobalQRCode toGlobalQRCode()
{
return LocatorQRCodeJsonConverter.toGlobalQRCode(this);
}
public ScannedCode toScannedCode()
{
return ScannedCode.ofString(toGlobalQRCodeJsonString());
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return LocatorQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCode.java
| 1
|
请完成以下Java代码
|
public void setC_BP_BankAccount_ID (final int C_BP_BankAccount_ID)
{
if (C_BP_BankAccount_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_ID, C_BP_BankAccount_ID);
}
@Override
public int getC_BP_BankAccount_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_ID);
}
@Override
public void setC_BP_BankAccount_InvoiceAutoAllocateRule_ID (final int C_BP_BankAccount_InvoiceAutoAllocateRule_ID)
{
if (C_BP_BankAccount_InvoiceAutoAllocateRule_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_InvoiceAutoAllocateRule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_InvoiceAutoAllocateRule_ID, C_BP_BankAccount_InvoiceAutoAllocateRule_ID);
}
@Override
|
public int getC_BP_BankAccount_InvoiceAutoAllocateRule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_InvoiceAutoAllocateRule_ID);
}
@Override
public void setC_DocTypeInvoice_ID (final int C_DocTypeInvoice_ID)
{
if (C_DocTypeInvoice_ID < 1)
set_Value (COLUMNNAME_C_DocTypeInvoice_ID, null);
else
set_Value (COLUMNNAME_C_DocTypeInvoice_ID, C_DocTypeInvoice_ID);
}
@Override
public int getC_DocTypeInvoice_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocTypeInvoice_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_InvoiceAutoAllocateRule.java
| 1
|
请完成以下Java代码
|
private I_AD_Note createOrderCompleteErrorNote(final String errorMsg)
{
final org.compiere.model.I_AD_User user = userDAO.getById(userInChargeId);
final String candidateIdsAsString = candidates.stream()
.map(OLCand::getId)
.map(String::valueOf)
.collect(Collectors.joining(", "));
final Language adLanguage = userBL.getUserLanguage(user);
final MNote note = new MNote(ctx, IOLCandBL.MSG_OL_CAND_PROCESSOR_PROCESSING_ERROR_0P, userInChargeId.getRepoId(), ITrx.TRXNAME_None);
note.setClientOrg(user.getAD_Client_ID(), user.getAD_Org_ID());
note.setReference(errorMsg);
note.setTextMsg(msgBL.getMsg(adLanguage.getAD_Language(), MSG_OL_CAND_PROCESSOR_PROCESSING_ERROR_DESC_1P, new Object[] { candidateIdsAsString }));
save(note);
return note;
}
private void validateCandidateOutOfTrx(@NonNull final I_C_OLCand candidate)
{
olCandValidatorService.setValidationProcessInProgress(true);
try
{
final I_C_OLCand validatedOlCand = trxManager.callInNewTrx(() -> {
final I_C_OLCand cand = olCandValidatorService.validate(candidate);
saveRecord(cand);
return cand;
});
if (validatedOlCand.isError())
{
throw new AdempiereException("Fail to validate candidate.")
.appendParametersToMessage()
.setParameter("C_OLCand_ID", candidate.getC_OLCand_ID());
}
}
finally
{
olCandValidatorService.setValidationProcessInProgress(false);
}
}
@Nullable
|
@VisibleForTesting
I_C_Order getOrder()
{
return order;
}
private void setBPSalesRepIdToOrder(@NonNull final I_C_Order order, @NonNull final OLCand olCand)
{
switch (olCand.getAssignSalesRepRule())
{
case Candidate:
order.setC_BPartner_SalesRep_ID(BPartnerId.toRepoId(olCand.getSalesRepId()));
break;
case BPartner:
order.setC_BPartner_SalesRep_ID(BPartnerId.toRepoId(olCand.getSalesRepInternalId()));
break;
case CandidateFirst:
final int salesRepInt = Optional.ofNullable(olCand.getSalesRepId())
.map(BPartnerId::getRepoId)
.orElseGet(() -> BPartnerId.toRepoId(olCand.getSalesRepInternalId()));
order.setC_BPartner_SalesRep_ID(salesRepInt);
break;
default:
throw new AdempiereException("Unsupported SalesRepFrom type")
.appendParametersToMessage()
.setParameter("salesRepFrom", olCand.getAssignSalesRepRule());
}
}
private void setExternalBPartnerInfo(@NonNull final I_C_OrderLine orderLine, @NonNull final OLCand candidate)
{
orderLine.setExternalSeqNo(candidate.getLine());
final I_C_OLCand olCand = candidate.unbox();
orderLine.setBPartner_QtyItemCapacity(olCand.getQtyItemCapacity());
final UomId uomId = UomId.ofRepoIdOrNull(olCand.getC_UOM_ID());
if (uomId != null)
{
orderLine.setC_UOM_BPartner_ID(uomId.getRepoId());
orderLine.setQtyEnteredInBPartnerUOM(olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandOrderFactory.java
| 1
|
请完成以下Java代码
|
public int getUser2_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getUser2_ID();
}
/**
* Get Attribute Set Instance
*
* @return ASI if based on shipment line and 0 for charge based
*/
public int getM_AttributeSetInstance_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getM_AttributeSetInstance_ID();
}
/**
* Get Locator
*
* @return locator if based on shipment line and 0 for charge based
*/
public int getM_Locator_ID()
{
if (m_ioLine == null)
{
|
return 0;
}
return m_ioLine.getM_Locator_ID();
}
/**
* Get Tax
*
* @return Tax based on Invoice/Order line and Tax exempt for charge based
*/
public int getC_Tax_ID()
{
return taxId;
}
} // MRMALine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMALine.java
| 1
|
请完成以下Java代码
|
public int getMaxResults() {
return maxResults;
}
public Object getParameter() {
return parameter;
}
public void setFirstResult(int firstResult) {
this.firstResult = firstResult;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
public void setParameter(Object parameter) {
this.parameter = parameter;
}
|
public String getOrderBy() {
// the default order column
return "RES.ID_ asc";
}
public String getOrderByColumns() {
return getOrderBy();
}
public void setDatabaseType(String databaseType) {
this.databaseType = databaseType;
}
public String getDatabaseType() {
return databaseType;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\ListQueryParameterObject.java
| 1
|
请完成以下Java代码
|
public void setProxyLogon (java.lang.String ProxyLogon)
{
set_Value (COLUMNNAME_ProxyLogon, ProxyLogon);
}
/** Get Proxy logon.
@return Logon of your proxy server
*/
@Override
public java.lang.String getProxyLogon ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProxyLogon);
}
/** Set Proxy-Passwort.
@param ProxyPassword
Password of your proxy server
*/
@Override
public void setProxyPassword (java.lang.String ProxyPassword)
{
set_Value (COLUMNNAME_ProxyPassword, ProxyPassword);
}
/** Get Proxy-Passwort.
@return Password of your proxy server
*/
@Override
public java.lang.String getProxyPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProxyPassword);
}
/** Set Proxy port.
@param ProxyPort
Port of your proxy server
*/
@Override
public void setProxyPort (int ProxyPort)
{
set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort));
}
/** Get Proxy port.
@return Port of your proxy server
*/
@Override
public int getProxyPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Require CreditCard Verification Code.
@param RequireVV
Require 3/4 digit Credit Verification Code
*/
@Override
public void setRequireVV (boolean RequireVV)
{
set_Value (COLUMNNAME_RequireVV, Boolean.valueOf(RequireVV));
}
/** Get Require CreditCard Verification Code.
|
@return Require 3/4 digit Credit Verification Code
*/
@Override
public boolean isRequireVV ()
{
Object oo = get_Value(COLUMNNAME_RequireVV);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set User ID.
@param UserID
User ID or account number
*/
@Override
public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
/** Set Vendor ID.
@param VendorID
Vendor ID for the Payment Processor
*/
@Override
public void setVendorID (java.lang.String VendorID)
{
set_Value (COLUMNNAME_VendorID, VendorID);
}
/** Get Vendor ID.
@return Vendor ID for the Payment Processor
*/
@Override
public java.lang.String getVendorID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VendorID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java
| 1
|
请完成以下Java代码
|
public SqlDocumentOrderByBuilder beforeOrderBy(@Nullable final String beforeOrderBy)
{
if (beforeOrderBy != null)
{
beforeOrderBy(SqlAndParams.of(beforeOrderBy));
}
return this;
}
/**
* @return SQL order by (e.g. Column1 ASC, Column2 DESC)
*/
public Optional<SqlAndParamsExpression> buildSqlOrderBy(final DocumentQueryOrderByList orderBys)
{
if (orderBys.isEmpty())
{
return Optional.empty();
}
final SqlAndParamsExpression.Builder result = SqlAndParamsExpression.builder();
//
// First ORDER BYs
if (beforeOrderBys != null && !beforeOrderBys.isEmpty())
{
for (final SqlAndParams beforeOrderBy : beforeOrderBys)
{
if (!result.isEmpty())
{
result.append(", ");
}
result.append(beforeOrderBy);
}
}
//
// Actual ORDER BY columns
{
final IStringExpression orderBysExpression = orderBys
.stream()
.map(this::buildSqlOrderBy)
.filter(sql -> sql != null && !sql.isNullExpression())
.collect(IStringExpression.collectJoining(", "));
if (orderBysExpression != null && !orderBysExpression.isNullExpression())
{
if (!result.isEmpty())
{
result.append(", ");
}
result.append(orderBysExpression);
}
|
}
return !result.isEmpty()
? Optional.of(result.build())
: Optional.empty();
}
private IStringExpression buildSqlOrderBy(final DocumentQueryOrderBy orderBy)
{
final String fieldName = orderBy.getFieldName();
final SqlOrderByValue sqlExpression = bindings.getFieldOrderBy(fieldName);
return buildSqlOrderBy(sqlExpression, orderBy.isAscending(), orderBy.isNullsLast());
}
private IStringExpression buildSqlOrderBy(
final SqlOrderByValue orderBy,
final boolean ascending,
final boolean nullsLast)
{
if (orderBy.isNull())
{
return IStringExpression.NULL;
}
final CompositeStringExpression.Builder sql = IStringExpression.composer();
if (useColumnNameAlias)
{
sql.append(orderBy.withJoinOnTableNameOrAlias(joinOnTableNameOrAlias).toSqlUsingColumnNameAlias());
}
else
{
sql.append("(").append(orderBy.withJoinOnTableNameOrAlias(joinOnTableNameOrAlias).toSourceSqlExpression()).append(")");
}
return sql.append(ascending ? " ASC" : " DESC")
.append(nullsLast ? " NULLS LAST" : " NULLS FIRST")
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentOrderByBuilder.java
| 1
|
请完成以下Java代码
|
public class CassandraConnector {
private static final Logger LOG = LoggerFactory.getLogger(CassandraConnector.class);
private Cluster cluster;
private Session session;
public void connect(final String node, final Integer port) {
Builder b = Cluster.builder().addContactPoint(node);
if (port != null) {
b.withPort(port);
}
cluster = b.build();
Metadata metadata = cluster.getMetadata();
LOG.info("Cluster name: " + metadata.getClusterName());
|
for (Host host : metadata.getAllHosts()) {
LOG.info("Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: " + host.getRack());
}
session = cluster.connect();
}
public Session getSession() {
return this.session;
}
public void close() {
session.close();
cluster.close();
}
}
|
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\java\client\CassandraConnector.java
| 1
|
请完成以下Java代码
|
public PriceListVersion createPriceListVersion(@NonNull final CreatePriceListVersionRequest request)
{
final I_M_PriceList_Version record = prepareNewPriceListVersionRecord(request);
saveRecord(record);
return toPriceListVersion(record);
}
@NonNull
public PriceListVersion getPriceListVersionById(@NonNull final PriceListVersionId priceListVersionId)
{
final I_M_PriceList_Version priceListVersionRecord = queryBL.createQueryBuilder(I_M_PriceList_Version.class)
.addEqualsFilter(I_M_PriceList_Version.COLUMNNAME_M_PriceList_Version_ID, priceListVersionId.getRepoId())
.create()
.firstOnlyNotNull(I_M_PriceList_Version.class);
return toPriceListVersion(priceListVersionRecord);
}
@NonNull
public PriceListVersion savePriceListVersion(@NonNull final PriceListVersion request)
{
final I_M_PriceList_Version record = toPriceListVersionRecord(request);
saveRecord(record);
return toPriceListVersion(record);
}
@NonNull
private I_M_PriceList_Version prepareNewPriceListVersionRecord(@NonNull final CreatePriceListVersionRequest request)
{
final I_M_PriceList_Version record = InterfaceWrapperHelper.newInstance(I_M_PriceList_Version.class);
record.setAD_Org_ID(request.getOrgId().getRepoId());
record.setM_PriceList_ID(request.getPriceListId().getRepoId());
record.setValidFrom(TimeUtil.asTimestamp(request.getValidFrom()));
if (request.getIsActive() != null)
{
record.setIsActive(request.getIsActive());
}
|
record.setDescription(request.getDescription());
return record;
}
@NonNull
private I_M_PriceList_Version toPriceListVersionRecord(@NonNull final PriceListVersion request)
{
final I_M_PriceList_Version existingRecord = getRecordById(request.getPriceListVersionId());
existingRecord.setAD_Org_ID(request.getOrgId().getRepoId());
existingRecord.setM_PriceList_ID(request.getPriceListId().getRepoId());
existingRecord.setValidFrom(TimeUtil.asTimestamp(request.getValidFrom()));
existingRecord.setIsActive(request.getIsActive());
existingRecord.setDescription(request.getDescription());
return existingRecord;
}
@NonNull
private I_M_PriceList_Version getRecordById(@NonNull final PriceListVersionId priceListVersionId)
{
return queryBL.createQueryBuilder(I_M_PriceList_Version.class)
.addEqualsFilter(I_M_PriceList_Version.COLUMNNAME_M_PriceList_Version_ID, priceListVersionId.getRepoId())
.create()
.firstOnlyNotNull(I_M_PriceList_Version.class);
}
@NonNull
private PriceListVersion toPriceListVersion(@NonNull final I_M_PriceList_Version record)
{
return PriceListVersion.builder()
.priceListVersionId(PriceListVersionId.ofRepoId(record.getM_PriceList_Version_ID()))
.priceListId(PriceListId.ofRepoId(record.getM_PriceList_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.description(record.getDescription())
.validFrom(TimeUtil.asInstant(record.getValidFrom()))
.isActive(record.isActive())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\pricelist\PriceListVersionRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DefaultDatasourceConfiguration extends AbstractCamundaConfiguration implements CamundaDatasourceConfiguration {
@Autowired
protected PlatformTransactionManager transactionManager;
@Autowired(required = false)
@Qualifier("camundaBpmTransactionManager")
protected PlatformTransactionManager camundaTransactionManager;
@Autowired
protected DataSource dataSource;
@Autowired(required = false)
@Qualifier("camundaBpmDataSource")
protected DataSource camundaDataSource;
@Override
public void preInit(SpringProcessEngineConfiguration configuration) {
final DatabaseProperty database = camundaBpmProperties.getDatabase();
if (camundaTransactionManager == null) {
configuration.setTransactionManager(transactionManager);
} else {
configuration.setTransactionManager(camundaTransactionManager);
}
if (camundaDataSource == null) {
configuration.setDataSource(dataSource);
} else {
configuration.setDataSource(camundaDataSource);
}
configuration.setDatabaseType(database.getType());
configuration.setDatabaseSchemaUpdate(database.getSchemaUpdate());
if (!StringUtils.isEmpty(database.getTablePrefix())) {
configuration.setDatabaseTablePrefix(database.getTablePrefix());
}
if(!StringUtils.isEmpty(database.getSchemaName())) {
|
configuration.setDatabaseSchema(database.getSchemaName());
}
configuration.setJdbcBatchProcessing(database.isJdbcBatchProcessing());
}
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public PlatformTransactionManager getCamundaTransactionManager() {
return camundaTransactionManager;
}
public void setCamundaTransactionManager(PlatformTransactionManager camundaTransactionManager) {
this.camundaTransactionManager = camundaTransactionManager;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getCamundaDataSource() {
return camundaDataSource;
}
public void setCamundaDataSource(DataSource camundaDataSource) {
this.camundaDataSource = camundaDataSource;
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\DefaultDatasourceConfiguration.java
| 2
|
请完成以下Java代码
|
protected void notifyWeakPropertyChangeListenerCreated(PropertyChangeListener listener, Boolean weak, WeakListenerCreationScope scope)
{
// nothing at this level
}
@Override
public final void addPropertyChangeListener(final PropertyChangeListener listener)
{
addPropertyChangeListener(listener, WEAK_AUTO);
}
public void addPropertyChangeListener(final PropertyChangeListener listener, final Boolean weak)
{
final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, weak, WeakListenerCreationScope.ForAdding);
super.addPropertyChangeListener(weakListener);
}
@Override
public final void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener)
{
addPropertyChangeListener(propertyName, listener, WEAK_AUTO);
}
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener, final Boolean weak)
{
final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, weak, WeakListenerCreationScope.ForAdding);
super.addPropertyChangeListener(propertyName, weakListener);
}
@Override
public void removePropertyChangeListener(final PropertyChangeListener listener)
{
|
super.removePropertyChangeListener(listener);
final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, true, WeakListenerCreationScope.ForRemoving);
super.removePropertyChangeListener(weakListener);
}
@Override
public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener)
{
super.removePropertyChangeListener(propertyName, listener);
final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, true, WeakListenerCreationScope.ForRemoving);
super.removePropertyChangeListener(propertyName, weakListener);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
// it's dangerous to output the source, because sometimes the source also holds a reference to this listener, and if it also has this listener in its toString(), then we get a StackOverflow
// .add("source (weakly referenced)", debugSourceBeanRef.get()) // debugSourceBeanRef can't be null, otherwise the constructor would have failed
.add("listeners", getPropertyChangeListeners()) // i know there should be no method but only fields in toString(), but don't see how else to output this
.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\WeakPropertyChangeSupport.java
| 1
|
请完成以下Java代码
|
public CamundaList newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaListImpl(instanceContext);
}
});
typeBuilder.build();
}
public CamundaListImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
@SuppressWarnings("unchecked")
public <T extends BpmnModelElementInstance> Collection<T> getValues() {
return new Collection<T>() {
protected Collection<T> getElements() {
return ModelUtil.getModelElementCollection(getDomElement().getChildElements(), getModelInstance());
}
public int size() {
return getElements().size();
}
public boolean isEmpty() {
return getElements().isEmpty();
}
public boolean contains(Object o) {
return getElements().contains(o);
}
public Iterator<T> iterator() {
return (Iterator<T>) getElements().iterator();
}
public Object[] toArray() {
return getElements().toArray();
}
public <T1> T1[] toArray(T1[] a) {
return getElements().toArray(a);
}
public boolean add(T t) {
getDomElement().appendChild(t.getDomElement());
return true;
}
public boolean remove(Object o) {
ModelUtil.ensureInstanceOf(o, BpmnModelElementInstance.class);
return getDomElement().removeChild(((BpmnModelElementInstance) o).getDomElement());
}
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false;
}
}
return true;
}
|
public boolean addAll(Collection<? extends T> c) {
for (T element : c) {
add(element);
}
return true;
}
public boolean removeAll(Collection<?> c) {
boolean result = false;
for (Object o : c) {
result |= remove(o);
}
return result;
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
DomElement domElement = getDomElement();
List<DomElement> childElements = domElement.getChildElements();
for (DomElement childElement : childElements) {
domElement.removeChild(childElement);
}
}
};
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaListImpl.java
| 1
|
请完成以下Java代码
|
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setURL2 (final @Nullable java.lang.String URL2)
{
set_Value (COLUMNNAME_URL2, URL2);
}
@Override
public java.lang.String getURL2()
{
return get_ValueAsString(COLUMNNAME_URL2);
}
@Override
public void setURL3 (final @Nullable java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3);
}
@Override
public java.lang.String getURL3()
{
return get_ValueAsString(COLUMNNAME_URL3);
}
@Override
public void setValue (final java.lang.String Value)
{
|
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getPollInterval() {
return this.pollInterval;
}
public void setPollInterval(Duration pollInterval) {
this.pollInterval = pollInterval;
}
public Duration getQuietPeriod() {
return this.quietPeriod;
}
public void setQuietPeriod(Duration quietPeriod) {
this.quietPeriod = quietPeriod;
}
public @Nullable String getTriggerFile() {
return this.triggerFile;
}
public void setTriggerFile(@Nullable String triggerFile) {
this.triggerFile = triggerFile;
}
public List<File> getAdditionalPaths() {
return this.additionalPaths;
}
public void setAdditionalPaths(List<File> additionalPaths) {
this.additionalPaths = additionalPaths;
}
public boolean isLogConditionEvaluationDelta() {
return this.logConditionEvaluationDelta;
}
public void setLogConditionEvaluationDelta(boolean logConditionEvaluationDelta) {
this.logConditionEvaluationDelta = logConditionEvaluationDelta;
}
}
/**
* LiveReload properties.
*/
public static class Livereload {
/**
|
* Whether to enable a livereload.com-compatible server.
*/
private boolean enabled;
/**
* Server port.
*/
private int port = 35729;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
| 2
|
请完成以下Java代码
|
protected BusinessProcessEvent createEvent(DelegateTask task) {
ExecutionContext executionContext = Context.getExecutionContext();
ProcessDefinitionEntity processDefinition = null;
if (executionContext != null) {
processDefinition = executionContext.getProcessDefinition();
}
// map type
String eventName = task.getEventName();
BusinessProcessEventType type = null;
if (TaskListener.EVENTNAME_CREATE.equals(eventName)) {
type = BusinessProcessEventType.CREATE_TASK;
} else if (TaskListener.EVENTNAME_ASSIGNMENT.equals(eventName)) {
type = BusinessProcessEventType.ASSIGN_TASK;
} else if (TaskListener.EVENTNAME_COMPLETE.equals(eventName)) {
type = BusinessProcessEventType.COMPLETE_TASK;
} else if (TaskListener.EVENTNAME_UPDATE.equals(eventName)) {
type = BusinessProcessEventType.UPDATE_TASK;
} else if (TaskListener.EVENTNAME_DELETE.equals(eventName)) {
type = BusinessProcessEventType.DELETE_TASK;
}
return new CdiBusinessProcessEvent(task, processDefinition, type, ClockUtil.getCurrentTime());
}
protected Annotation[] getQualifiers(BusinessProcessEvent event) {
ProcessDefinition processDefinition = event.getProcessDefinition();
List<Annotation> annotations = new ArrayList<Annotation>();
if (processDefinition != null) {
annotations.add(new BusinessProcessDefinitionLiteral(processDefinition.getKey()));
}
if (event.getType() == BusinessProcessEventType.TAKE) {
|
annotations.add(new TakeTransitionLiteral(event.getTransitionName()));
} else if (event.getType() == BusinessProcessEventType.START_ACTIVITY) {
annotations.add(new StartActivityLiteral(event.getActivityId()));
} else if (event.getType() == BusinessProcessEventType.END_ACTIVITY) {
annotations.add(new EndActivityLiteral(event.getActivityId()));
} else if (event.getType() == BusinessProcessEventType.CREATE_TASK) {
annotations.add(new CreateTaskLiteral(event.getTaskDefinitionKey()));
} else if (event.getType() == BusinessProcessEventType.ASSIGN_TASK) {
annotations.add(new AssignTaskLiteral(event.getTaskDefinitionKey()));
} else if (event.getType() == BusinessProcessEventType.COMPLETE_TASK) {
annotations.add(new CompleteTaskLiteral(event.getTaskDefinitionKey()));
} else if (event.getType() == BusinessProcessEventType.DELETE_TASK) {
annotations.add(new DeleteTaskLiteral(event.getTaskDefinitionKey()));
}
return annotations.toArray(new Annotation[annotations.size()]);
}
}
|
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\event\AbstractCdiEventListener.java
| 1
|
请完成以下Java代码
|
protected void preHandle(OrderProcessContext orderProcessContext) {
super.preHandle(orderProcessContext);
// 插入物流单号
insertExpressNo(orderProcessContext);
}
/**
* 插入物流单号
* @param orderProcessContext
*/
private void insertExpressNo(OrderProcessContext orderProcessContext) {
// 获取物流单号
String expressNo = (String) orderProcessContext.getOrderProcessReq().getReqData();
// 获取订单ID
String orderId = orderProcessContext.getOrderProcessReq().getOrderId();
// 构造插入请求
|
OrdersEntity ordersEntity = new OrdersEntity();
ordersEntity.setId(orderId);
ordersEntity.setExpressNo(expressNo);
// 插入物流单号
orderDAO.updateOrder(ordersEntity);
}
@Override
public void setTargetOrderState() {
this.targetOrderState = OrderStateEnum.BUYER_RECEIVING;
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\changestate\BuyerReceivingChangeStateComponent.java
| 1
|
请完成以下Java代码
|
public void close() throws IOException {
doOnResponseCommitted();
this.delegate.close();
}
@Override
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public void print(boolean b) throws IOException {
trackContentLength(b);
this.delegate.print(b);
}
@Override
public void print(char c) throws IOException {
trackContentLength(c);
this.delegate.print(c);
}
@Override
public void print(double d) throws IOException {
trackContentLength(d);
this.delegate.print(d);
}
@Override
public void print(float f) throws IOException {
trackContentLength(f);
this.delegate.print(f);
}
@Override
public void print(int i) throws IOException {
trackContentLength(i);
this.delegate.print(i);
}
@Override
public void print(long l) throws IOException {
trackContentLength(l);
this.delegate.print(l);
}
@Override
public void print(String s) throws IOException {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void println() throws IOException {
trackContentLengthLn();
this.delegate.println();
}
@Override
public void println(boolean b) throws IOException {
trackContentLength(b);
trackContentLengthLn();
this.delegate.println(b);
}
@Override
public void println(char c) throws IOException {
trackContentLength(c);
trackContentLengthLn();
this.delegate.println(c);
}
|
@Override
public void println(double d) throws IOException {
trackContentLength(d);
trackContentLengthLn();
this.delegate.println(d);
}
@Override
public void println(float f) throws IOException {
trackContentLength(f);
trackContentLengthLn();
this.delegate.println(f);
}
@Override
public void println(int i) throws IOException {
trackContentLength(i);
trackContentLengthLn();
this.delegate.println(i);
}
@Override
public void println(long l) throws IOException {
trackContentLength(l);
trackContentLengthLn();
this.delegate.println(l);
}
@Override
public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\OnCommittedResponseWrapper.java
| 1
|
请完成以下Java代码
|
public String getSummary()
{
return getDescription();
}
@Override
public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getMovementDate());
}
@Override
public String getProcessMsg()
{
return null;
}
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
}
@Override
public int getC_Currency_ID()
{
return 0; // N/A
}
@Override
public BigDecimal getApprovalAmt()
{
return BigDecimal.ZERO; // N/A
|
}
@Override
public File createPDF()
{
throw new UnsupportedOperationException(); // N/A
}
@Override
public String getDocumentInfo()
{
final I_C_DocType dt = MDocType.get(getCtx(), getC_DocType_ID());
return dt.getName() + " " + getDocumentNo();
}
private PPOrderRouting getOrderRouting()
{
final IPPOrderRoutingRepository orderRoutingsRepo = Services.get(IPPOrderRoutingRepository.class);
final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID());
return orderRoutingsRepo.getByOrderId(orderId);
}
private PPOrderRoutingActivityId getActivityId()
{
final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID());
return PPOrderRoutingActivityId.ofRepoId(orderId, getPP_Order_Node_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPCostCollector.java
| 1
|
请完成以下Java代码
|
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public String getImplementationType() {
return implementationTypeAttribute.getValue(this);
}
public void setImplementationType(String implementationType) {
implementationTypeAttribute.setValue(this, implementationType);
}
public Collection<InputProcessParameter> getInputs() {
return inputCollection.get(this);
}
public Collection<OutputProcessParameter> getOutputs() {
return outputCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Process.class, CMMN_ELEMENT_PROCESS)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Process>() {
|
public Process newInstance(ModelTypeInstanceContext instanceContext) {
return new ProcessImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE)
.defaultValue("http://www.omg.org/spec/CMMN/ProcessType/Unspecified")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputCollection = sequenceBuilder.elementCollection(InputProcessParameter.class)
.build();
outputCollection = sequenceBuilder.elementCollection(OutputProcessParameter.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessImpl.java
| 1
|
请完成以下Java代码
|
public void createTrainer() {
CARTRegressionTrainer subsamplingTree = new CARTRegressionTrainer(Integer.MAX_VALUE, AbstractCARTTrainer.MIN_EXAMPLES, 0.001f, 0.7f,
new MeanSquaredError(), Trainer.DEFAULT_SEED);
trainer = new RandomForestTrainer<>(subsamplingTree, new AveragingCombiner(), 10);
model = trainer.train(trainSet);
}
public void createDatasets() throws Exception {
RegressionFactory regressionFactory = new RegressionFactory();
CSVLoader<Regressor> csvLoader = new CSVLoader<>(';', CSVIterator.QUOTE, regressionFactory);
DataSource<Regressor> dataSource = csvLoader.loadDataSource(Paths.get(DATASET_PATH), "quality");
TrainTestSplitter<Regressor> dataSplitter = new TrainTestSplitter<>(dataSource, 0.7, 1L);
trainSet = new MutableDataset<>(dataSplitter.getTrain());
log.info(String.format("Train set size = %d, num of features = %d", trainSet.size(), trainSet.getFeatureMap()
.size()));
testSet = new MutableDataset<>(dataSplitter.getTest());
log.info(String.format("Test set size = %d, num of features = %d", testSet.size(), testSet.getFeatureMap()
.size()));
}
public void evaluateModels() throws Exception {
log.info("Training model");
evaluate(model, "trainSet", trainSet);
log.info("Testing model");
evaluate(model, "testSet", testSet);
|
log.info("Dataset Provenance: --------------------");
log.info(ProvenanceUtil.formattedProvenanceString(model.getProvenance()
.getDatasetProvenance()));
log.info("Trainer Provenance: --------------------");
log.info(ProvenanceUtil.formattedProvenanceString(model.getProvenance()
.getTrainerProvenance()));
}
public void evaluate(Model<Regressor> model, String datasetName, Dataset<Regressor> dataset) {
log.info("Results for " + datasetName + "---------------------");
RegressionEvaluator evaluator = new RegressionEvaluator();
RegressionEvaluation evaluation = evaluator.evaluate(model, dataset);
Regressor dimension0 = new Regressor("DIM-0", Double.NaN);
log.info("MAE: " + evaluation.mae(dimension0));
log.info("RMSE: " + evaluation.rmse(dimension0));
log.info("R^2: " + evaluation.r2(dimension0));
}
public void saveModel() throws Exception {
File modelFile = new File(MODEL_PATH);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(modelFile))) {
objectOutputStream.writeObject(model);
}
}
}
|
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\tribuo\WineQualityRegression.java
| 1
|
请完成以下Java代码
|
public boolean isPassive ()
{
Object oo = get_Value(COLUMNNAME_IsPassive);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Password.
@param Password
Password of any length (case sensitive)
*/
public void setPassword (String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Password.
@return Password of any length (case sensitive)
*/
public String getPassword ()
{
return (String)get_Value(COLUMNNAME_Password);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
|
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
public void setUserName (String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
public String getUserName ()
{
return (String)get_Value(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
CaseDefinition newCaseDefinition;
if (builder.hasNewCaseDefinitionId()) {
newCaseDefinition = getCaseDefinitionById(builder.getNewCaseDefinitionId(), commandContext);
} else {
// no explicit case definition provided, so use latest one
CaseDefinition caseDefinition = getCaseDefinitionById(builder.getCaseDefinitionId(), commandContext);
newCaseDefinition = getLatestCaseDefinitionByKey(caseDefinition.getKey(), caseDefinition.getTenantId(), commandContext);
}
if (newCaseDefinition == null) {
throw new FlowableIllegalArgumentException("Cannot find case definition with id " + (builder.hasNewCaseDefinitionId() ?
builder.getNewCaseDefinitionId() :
builder.getCaseDefinitionId()));
}
Case caze = getCase(newCaseDefinition.getId(), commandContext);
|
String eventDefinitionKey = caze.getStartEventType();
String startCorrelationConfiguration = getStartCorrelationConfiguration(newCaseDefinition.getId(), commandContext);
if (eventDefinitionKey != null && Objects.equals(startCorrelationConfiguration, CmmnXmlConstants.START_EVENT_CORRELATION_MANUAL)) {
String correlationKey = null;
if (builder.hasCorrelationParameterValues()) {
correlationKey = generateCorrelationConfiguration(eventDefinitionKey, builder.getTenantId(),
builder.getCorrelationParameterValues(), commandContext);
}
getEventSubscriptionService(commandContext).updateEventSubscriptionScopeDefinitionId(builder.getCaseDefinitionId(), newCaseDefinition.getId(),
eventDefinitionKey, null, correlationKey);
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\ModifyCaseInstanceStartEventSubscriptionCmd.java
| 1
|
请完成以下Java代码
|
public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) {
return super.getEventSubscriptionRestService(engineName);
}
@Override
@Path("/{name}" + TelemetryRestService.PATH)
public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) {
return super.getTelemetryRestService(engineName);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<ProcessEngineDto> getProcessEngineNames() {
ProcessEngineProvider provider = getProcessEngineProvider();
Set<String> engineNames = provider.getProcessEngineNames();
List<ProcessEngineDto> results = new ArrayList<ProcessEngineDto>();
|
for (String engineName : engineNames) {
ProcessEngineDto dto = new ProcessEngineDto();
dto.setName(engineName);
results.add(dto);
}
return results;
}
@Override
protected URI getRelativeEngineUri(String engineName) {
return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\NamedProcessEngineRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public Boolean getActive() {
return active;
}
public Boolean getCompleted() {
return completed;
}
public Boolean getTerminated() {
return terminated;
}
public static HistoricCaseActivityInstanceDto fromHistoricCaseActivityInstance(HistoricCaseActivityInstance historicCaseActivityInstance) {
HistoricCaseActivityInstanceDto dto = new HistoricCaseActivityInstanceDto();
dto.id = historicCaseActivityInstance.getId();
dto.parentCaseActivityInstanceId = historicCaseActivityInstance.getParentCaseActivityInstanceId();
dto.caseActivityId = historicCaseActivityInstance.getCaseActivityId();
dto.caseActivityName = historicCaseActivityInstance.getCaseActivityName();
dto.caseActivityType = historicCaseActivityInstance.getCaseActivityType();
dto.caseDefinitionId = historicCaseActivityInstance.getCaseDefinitionId();
|
dto.caseInstanceId = historicCaseActivityInstance.getCaseInstanceId();
dto.caseExecutionId = historicCaseActivityInstance.getCaseExecutionId();
dto.taskId = historicCaseActivityInstance.getTaskId();
dto.calledProcessInstanceId = historicCaseActivityInstance.getCalledProcessInstanceId();
dto.calledCaseInstanceId = historicCaseActivityInstance.getCalledCaseInstanceId();
dto.tenantId = historicCaseActivityInstance.getTenantId();
dto.createTime = historicCaseActivityInstance.getCreateTime();
dto.endTime = historicCaseActivityInstance.getEndTime();
dto.durationInMillis = historicCaseActivityInstance.getDurationInMillis();
dto.required = historicCaseActivityInstance.isRequired();
dto.available = historicCaseActivityInstance.isAvailable();
dto.enabled = historicCaseActivityInstance.isEnabled();
dto.disabled = historicCaseActivityInstance.isDisabled();
dto.active = historicCaseActivityInstance.isActive();
dto.completed = historicCaseActivityInstance.isCompleted();
dto.terminated = historicCaseActivityInstance.isTerminated();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseActivityInstanceDto.java
| 1
|
请完成以下Java代码
|
public void deleteAttachmentsByProcessInstanceIds(List<String> processInstanceIds) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("processInstanceIds", processInstanceIds);
deleteAttachments(parameters);
}
public void deleteAttachmentsByTaskProcessInstanceIds(List<String> processInstanceIds) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("taskProcessInstanceIds", processInstanceIds);
deleteAttachments(parameters);
}
public void deleteAttachmentsByTaskCaseInstanceIds(List<String> caseInstanceIds) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("caseInstanceIds", caseInstanceIds);
deleteAttachments(parameters);
}
protected void deleteAttachments(Map<String, Object> parameters) {
getDbEntityManager().deletePreserveOrder(ByteArrayEntity.class, "deleteAttachmentByteArraysByIds", parameters);
getDbEntityManager().deletePreserveOrder(AttachmentEntity.class, "deleteAttachmentByIds", parameters);
}
public Attachment findAttachmentByTaskIdAndAttachmentId(String taskId, String attachmentId) {
checkHistoryEnabled();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("taskId", taskId);
parameters.put("id", attachmentId);
return (AttachmentEntity) getDbEntityManager().selectOne("selectAttachmentByTaskIdAndAttachmentId", parameters);
|
}
public DbOperation deleteAttachmentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(AttachmentEntity.class, "deleteAttachmentsByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentManager.java
| 1
|
请完成以下Java代码
|
public class UserDao implements Dao<User> {
private List<User> users = new ArrayList<>();
public UserDao() {
users.add(new User("John", "john@domain.com"));
users.add(new User("Susan", "susan@domain.com"));
}
@Override
public Optional<User> get(long id) {
return Optional.ofNullable(users.get((int) id));
}
@Override
public List<User> getAll() {
return users;
}
@Override
|
public void save(User user) {
users.add(user);
}
@Override
public void update(User user, String[] params) {
user.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null"));
users.add(user);
}
@Override
public void delete(User user) {
users.remove(user);
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\daos\UserDao.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule()
{
return get_ValueAsPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class);
}
@Override
public void setAD_Val_Rule(final org.compiere.model.I_AD_Val_Rule AD_Val_Rule)
{
set_ValueFromPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, AD_Val_Rule);
}
@Override
public void setAD_Val_Rule_ID (final int AD_Val_Rule_ID)
{
if (AD_Val_Rule_ID < 1)
set_Value (COLUMNNAME_AD_Val_Rule_ID, null);
else
set_Value (COLUMNNAME_AD_Val_Rule_ID, AD_Val_Rule_ID);
}
@Override
|
public int getAD_Val_Rule_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Val_Rule_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setWEBUI_Board_ID (final int WEBUI_Board_ID)
{
if (WEBUI_Board_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID);
}
@Override
public int getWEBUI_Board_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.