instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | ArtemisConnectionDetails artemisConnectionDetails(ArtemisProperties properties) {
return new PropertiesArtemisConnectionDetails(properties);
}
/**
* Adapts {@link ArtemisProperties} to {@link ArtemisConnectionDetails}.
*/
static class PropertiesArtemisConnectionDetails implements ArtemisConnectionDetails {
private final ArtemisProperties properties;
PropertiesArtemisConnectionDetails(ArtemisProperties properties) {
this.properties = properties;
}
@Override
public @Nullable ArtemisMode getMode() {
return this.properties.getMode();
}
@Override | public @Nullable String getBrokerUrl() {
return this.properties.getBrokerUrl();
}
@Override
public @Nullable String getUser() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisAutoConfiguration.java | 2 |
请完成以下Java代码 | public @Nullable String getDriverClassName() {
return this.driverClassName;
}
/**
* Return the XA driver source class name.
* @return the class name or {@code null}
*/
public @Nullable String getXaDataSourceClassName() {
return this.xaDataSourceClassName;
}
/**
* Return the validation query.
* @return the validation query or {@code null}
*/
public @Nullable String getValidationQuery() {
return this.validationQuery;
}
/**
* Find a {@link DatabaseDriver} for the given URL.
* @param url the JDBC URL
* @return the database driver or {@link #UNKNOWN} if not found
*/
public static DatabaseDriver fromJdbcUrl(@Nullable String url) {
if (StringUtils.hasLength(url)) {
Assert.isTrue(url.startsWith("jdbc"), "'url' must start with \"jdbc\"");
String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH);
for (DatabaseDriver driver : values()) {
for (String urlPrefix : driver.getUrlPrefixes()) {
String prefix = ":" + urlPrefix + ":";
if (driver != UNKNOWN && urlWithoutPrefix.startsWith(prefix)) {
return driver;
} | }
}
}
return UNKNOWN;
}
/**
* Find a {@link DatabaseDriver} for the given product name.
* @param productName product name
* @return the database driver or {@link #UNKNOWN} if not found
*/
public static DatabaseDriver fromProductName(@Nullable String productName) {
if (StringUtils.hasLength(productName)) {
for (DatabaseDriver candidate : values()) {
if (candidate.matchProductName(productName)) {
return candidate;
}
}
}
return UNKNOWN;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\DatabaseDriver.java | 1 |
请完成以下Java代码 | private Quantity getQtyToIssueForOneFinishedGood()
{
return _qtyToIssueForOneFinishedGood == null
? _qtyToIssueForOneFinishedGood = computeQtyToIssueForOneFinishedGood()
: _qtyToIssueForOneFinishedGood;
}
@NonNull
private Quantity computeQtyToIssueForOneFinishedGood()
{
return ppOrderBOMBL.getQtyCalculationsBOM(getPPOrderRecord())
.getLineByOrderBOMLineId(request.getPpOrderBOMLineId())
.computeQtyRequired(Quantity.of(1, uomDAO.getById(UomId.EACH)));
}
private List<I_M_HU> splitToOneItemPerHU(final I_PP_Order_Qty finishedGoodsReceiveCandidate)
{
final ProductId finishedGoodProductId = ProductId.ofRepoId(finishedGoodsReceiveCandidate.getM_Product_ID());
final HuId huId = HuId.ofRepoId(finishedGoodsReceiveCandidate.getM_HU_ID());
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory huStorageFactory = huContext.getHUStorageFactory();
final int huQty = huStorageFactory.getStorage(hu)
.getQuantity(finishedGoodProductId, uomEach)
.intValueExact();
if (huQty <= 0)
{
// shall not happen but we can live with it
return ImmutableList.of();
}
else if (huQty == 1)
{
// Our HU is in desired shape, i.e. one item per HU
return ImmutableList.of(hu);
}
else // huQty > 1
{
final ArrayList<I_M_HU> singleItemHUs = new ArrayList<>(); | final CreateReceiptCandidateRequest.CreateReceiptCandidateRequestBuilder createReceiptCandidateRequestTemplate = CreateReceiptCandidateRequest.builder()
.orderId(PPOrderId.ofRepoId(finishedGoodsReceiveCandidate.getPP_Order_ID()))
.orgId(OrgId.ofRepoId(finishedGoodsReceiveCandidate.getAD_Org_ID()))
.date(date)
.locatorId(IHandlingUnitsBL.extractLocatorId(hu))
.productId(finishedGoodProductId)
.qtyToReceive(Quantity.of(1, uomEach))
//.topLevelHUId(...)
;
// Extract CUs of 1 item each.
// The original HU will also be replaced.
for (int i = 1; i <= huQty; i++)
{
final I_M_HU extractedHU = HUTransformService.newInstance(huContext)
.husToNewCUs(HUTransformService.HUsToNewCUsRequest.builder()
.sourceHU(hu)
.productId(finishedGoodProductId)
.qtyCU(Quantity.of(1, uomEach))
.build())
.singleCU();
singleItemHUs.add(extractedHU);
ppOrderQtyDAO.save(createReceiptCandidateRequestTemplate
.topLevelHUId(HuId.ofRepoId(extractedHU.getM_HU_ID()))
.build());
}
// delete the original candidate, we no longer need it
// NOTE: we have to delete it first and then create the new link because of the unique constraint on (PP_Order_ID, M_HU_ID).
ppOrderQtyDAO.delete(finishedGoodsReceiveCandidate);
return singleItemHUs;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderIssueServiceProductCommand.java | 1 |
请完成以下Java代码 | public BigDecimal encrypt(BigDecimal value)
{
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear text values
*
* @param value encrypted value
* @return decrypted String
*/
@Override
public BigDecimal decrypt(BigDecimal value)
{
return value;
} // decrypt
/**
* Encryption.
* The methods must recognize clear text values
*
* @param value clear value
* @return encrypted String
*/
@Override
public Timestamp encrypt(Timestamp value)
{
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear text values
*
* @param value encrypted value
* @return decrypted String
*/
@Override
public Timestamp decrypt(Timestamp value)
{
return value;
} // decrypt
/**
* Convert String to Digest.
* JavaScript version see - http://pajhome.org.uk/crypt/md5/index.html
*
* @param value message
* @return HexString of message (length = 32 characters)
*/
@Override
public String getDigest(String value)
{
if (m_md == null)
{
try
{
m_md = MessageDigest.getInstance("MD5");
// m_md = MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException nsae)
{
nsae.printStackTrace(); | }
}
// Reset MessageDigest object
m_md.reset();
// Convert String to array of bytes
byte[] input = value.getBytes(StandardCharsets.UTF_8);
// feed this array of bytes to the MessageDigest object
m_md.update(input);
// Get the resulting bytes after the encryption process
byte[] output = m_md.digest();
m_md.reset();
//
return convertToHexString(output);
} // getDigest
/**
* Checks, if value is a valid digest
*
* @param value digest string
* @return true if valid digest
*/
@Override
public boolean isDigest(String value)
{
if (value == null || value.length() != 32)
return false;
// needs to be a hex string, so try to convert it
return (convertHexString(value) != null);
} // isDigest
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("cipher", m_cipher)
.toString();
}
} // Secure | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Secure.java | 1 |
请完成以下Java代码 | public Percent getQualityDiscountPercent()
{
final StockQtyAndUOMQty qtyTotalExact = getQtyTotal();
final StockQtyAndUOMQty qtyWithIssuesExact = getQtyWithIssuesExact();
if (qtyTotalExact.signum() == 0)
{
if (qtyWithIssuesExact.signum() == 0)
{
return Percent.ZERO;
}
// Case: qtyTotal is ZERO but we have qtyWithIssues.
// => this could be an issue
else
{
final AdempiereException ex = new AdempiereException("We are asked to calculate QualityDiscountPercent when QtyTotal=0 and QtyWithIssues>0."
+ "\nThis could be an error but we are returning ZERO by now."
+ "\nQtyAndQuality: " + this);
// just log it for now
logger.warn(ex.getLocalizedMessage(), ex);
return Percent.ZERO;
}
}
final BigDecimal qtyWithIssuesExactBD;
final BigDecimal qtyTotalExactBD;
if (catchUomId != null)
{
qtyWithIssuesExactBD = qtyWithIssuesExact.getUOMQtyNotNull().toBigDecimal();
qtyTotalExactBD = qtyTotalExact.getUOMQtyNotNull().toBigDecimal();
}
else
{
qtyWithIssuesExactBD = qtyWithIssuesExact.getStockQty().toBigDecimal();
qtyTotalExactBD = qtyTotalExact.getStockQty().toBigDecimal();
}
if (qtyWithIssuesExactBD.signum() == 0 || qtyTotalExact.signum() == 0)
{
return Percent.ZERO;
}
final BigDecimal qualityDiscountPercent = Env.ONEHUNDRED
.multiply(qtyWithIssuesExactBD) | .divide(qtyTotalExactBD,
QualityDiscountPercent_Precision,
QualityDiscountPercent_RoundingMode);
return Percent.of(qualityDiscountPercent);
}
/**
* @return quantity with issues (precise, high scale value)
*/
public StockQtyAndUOMQty getQtyWithIssuesExact()
{
return qtyWithIssues;
}
/**
* @return quantity without issues; i.e. QtyTotal - QtyWithIssues
*/
public StockQtyAndUOMQty getQtyWithoutIssues()
{
return qtyTotal.subtract(qtyWithIssues);
}
public void addQualityNotices(final QualityNoticesCollection qualityNoticesToAdd)
{
this.qualityNotices.addQualityNotices(qualityNoticesToAdd);
}
/**
* @return quality notices; never null
*/
public QualityNoticesCollection getQualityNotices()
{
// always return a copy, because qualityNotices is not immutable
return qualityNotices.copy();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\ReceiptQty.java | 1 |
请完成以下Java代码 | public boolean isExistingLU()
{
return luId != null;
}
public boolean isNewLU()
{
return luId == null && luPIId != null;
}
public HuPackingInstructionsId getLuPIIdNotNull()
{
return Check.assumeNotNull(luPIId, "LU PI shall be set for {}", this);
}
public HuId getLuIdNotNull()
{
return Check.assumeNotNull(luId, "LU shall be set for {}", this);
}
public interface CaseConsumer
{
void noLU();
void newLU(final HuPackingInstructionsId luPackingInstructionsId);
void existingLU(final HuId luId, final HUQRCode luQRCode);
}
public interface CaseMapper<T>
{
T noLU();
T newLU(final HuPackingInstructionsId luPackingInstructionsId);
T existingLU(final HuId luId, final HUQRCode luQRCode);
}
public static void apply(@Nullable final LUPickingTarget target, @NonNull final CaseConsumer consumer)
{
if (target == null)
{
consumer.noLU();
}
else if (target.isNewLU())
{
consumer.newLU(target.getLuPIIdNotNull());
}
else if (target.isExistingLU())
{
consumer.existingLU(target.getLuIdNotNull(), target.getLuQRCode());
} | else
{
throw new AdempiereException("Unsupported target type: " + target);
}
}
public static <T> T apply(@Nullable final LUPickingTarget target, @NonNull final CaseMapper<T> mapper)
{
if (target == null)
{
return mapper.noLU();
}
else if (target.isNewLU())
{
return mapper.newLU(target.getLuPIIdNotNull());
}
else if (target.isExistingLU())
{
return mapper.existingLU(target.getLuIdNotNull(), target.getLuQRCode());
}
else
{
throw new AdempiereException("Unsupported target type: " + target);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\LUPickingTarget.java | 1 |
请完成以下Java代码 | public String nextWord() throws IOException
{
return null;
}
@Override
public int readWordIndex() throws IOException
{
int id = nextId();
while (id == -4)
{
id = nextId();
}
return id;
}
private int nextId() throws IOException
{ | if (raf.length() - raf.getFilePointer() >= 4)
{
int id = raf.readInt();
return id < 0 ? id : table[id];
}
return -2;
}
@Override
public void rewind(int numThreads, int id) throws IOException
{
super.rewind(numThreads, id);
raf.seek(raf.length() / 4 / numThreads * id * 4); // spilt by id, not by bytes
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\CacheCorpus.java | 1 |
请完成以下Java代码 | private final void updateDeliveryDayWhenAllocationChanged(final I_M_DeliveryDay deliveryDay,
final I_M_DeliveryDay_Alloc deliveryDayAllocNew,
final I_M_DeliveryDay_Alloc deliveryDayAllocOld)
{
final boolean deliveryDayProcessed = deliveryDay.isProcessed();
//
// Call handlers to update the delivery day record
Services.get(IDeliveryDayBL.class)
.getDeliveryDayHandlers()
.updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
//
// Prohibit changing delivery day if it was processed
if (deliveryDayProcessed)
{
if (InterfaceWrapperHelper.hasChanges(deliveryDay)) | {
throw new AdempiereException("Cannot change a delivery day which was already processed"
+ "\n @M_DeliveryDay_ID@: " + deliveryDay
+ "\n @M_DeliveryDay_Alloc_ID@ @New@: " + deliveryDayAllocNew
+ "\n @M_DeliveryDay_Alloc_ID@ @Old@: " + deliveryDayAllocOld);
}
// return it because there is no need to save the changes
return;
}
//
// Save delivery day changes
InterfaceWrapperHelper.save(deliveryDay);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\M_DeliveryDay_Alloc.java | 1 |
请完成以下Java代码 | private Map<HuId, I_PP_Order_SourceHU> retrieveRecordsIfExist(
final @NonNull PPOrderId ppOrderId,
final @NonNull Set<HuId> huIds)
{
return queryBL.createQueryBuilder(I_PP_Order_SourceHU.class)
//.addOnlyActiveRecordsFilter() // all
.addEqualsFilter(I_PP_Order_SourceHU.COLUMNNAME_PP_Order_ID, ppOrderId)
.addInArrayFilter(I_PP_Order_SourceHU.COLUMNNAME_M_HU_ID, huIds)
.create()
.stream()
.collect(ImmutableMap.toImmutableMap(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID()),
Function.identity()));
}
@NonNull
public ImmutableSet<HuId> getSourceHUIds(final PPOrderId ppOrderId)
{
final List<HuId> huIds = queryBL.createQueryBuilder(I_PP_Order_SourceHU.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_Order_SourceHU.COLUMNNAME_PP_Order_ID, ppOrderId) | .create()
.listDistinct(I_PP_Order_SourceHU.COLUMNNAME_M_HU_ID, HuId.class);
return ImmutableSet.copyOf(huIds);
}
@NonNull
private I_PP_Order_SourceHU initRecord(@NonNull final HuId huId, @NonNull final PPOrderId ppOrderId)
{
final I_PP_Order_SourceHU record = InterfaceWrapperHelper.newInstance(I_PP_Order_SourceHU.class);
record.setPP_Order_ID(ppOrderId.getRepoId());
record.setM_HU_ID(huId.getRepoId());
return record;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHURepository.java | 1 |
请完成以下Java代码 | static class Person {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
UUID id;
@JsonProperty(access = JsonProperty.Access.READ_WRITE, required = true)
String name;
@JsonProperty(access = JsonProperty.Access.READ_WRITE, required = true)
String surname;
@JsonProperty(access = JsonProperty.Access.READ_WRITE, required = true)
Address address;
@JsonIgnore
String fullName;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
Date createdAt;
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
List<Person> friends; | }
static class Address {
@JsonProperty()
String street;
@JsonProperty(required = true)
String city;
@JsonProperty(required = true)
String country;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\modules\JacksonModuleSchemaGenerator.java | 1 |
请完成以下Java代码 | public EsrAddressType getBank() {
return bank;
}
/**
* Sets the value of the bank property.
*
* @param value
* allowed object is
* {@link EsrAddressType }
*
*/
public void setBank(EsrAddressType value) {
this.bank = value;
}
/**
* Gets the value of the creditor property.
*
* @return
* possible object is
* {@link EsrAddressType }
*
*/
public EsrAddressType getCreditor() {
return creditor;
}
/**
* Sets the value of the creditor property.
*
* @param value
* allowed object is
* {@link EsrAddressType }
*
*/
public void setCreditor(EsrAddressType value) {
this.creditor = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "16or27";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the participantNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getParticipantNumber() {
return participantNumber;
}
/**
* Sets the value of the participantNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParticipantNumber(String value) { | this.participantNumber = value;
}
/**
* Gets the value of the referenceNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the codingLine property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodingLine() {
return codingLine;
}
/**
* Sets the value of the codingLine property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine(String value) {
this.codingLine = 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\Esr9Type.java | 1 |
请完成以下Java代码 | private final int getContextAsInt(final String columnName)
{
return Env.getContextAsInt(ctx, windowNo, tabNo, columnName);
}
@Override
public final int getWindowNo()
{
return windowNo;
}
@Override
public final int getTabNo()
{
return tabNo;
}
@Override
public BPartnerId getBpartnerId()
{
return BPartnerId.ofRepoIdOrNull(getContextAsInt("C_BPartner_ID"));
}
@Override
public ProductId getProductId()
{
return ProductId.ofRepoIdOrNull(getContextAsInt("M_Product_ID"));
}
@Override
public boolean isSOTrx()
{
return SOTrx.toBoolean(getSoTrx());
}
@Override
public SOTrx getSoTrx() | {
final Boolean soTrx = Env.getSOTrxOrNull(ctx, windowNo);
return SOTrx.ofBoolean(soTrx);
}
@Override
public WarehouseId getWarehouseId()
{
return WarehouseId.ofRepoIdOrNull(getContextAsInt("M_Warehouse_ID"));
}
@Override
public int getM_Locator_ID()
{
return getContextAsInt("M_Locator_ID");
}
@Override
public DocTypeId getDocTypeId()
{
return DocTypeId.ofRepoIdOrNull(getContextAsInt("C_DocType_ID"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VPAttributeWindowContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public TimePeriod getPeriod() { | return period;
}
public void setPeriod(TimePeriod period) {
this.period = period;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
} | repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\domain\Item.java | 2 |
请完成以下Java代码 | public InterestType1Code getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link InterestType1Code }
*
*/
public void setCd(InterestType1Code value) {
this.cd = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\InterestType1Choice.java | 1 |
请完成以下Java代码 | public static StorageServer[] getStoreStorages(String groupName)
throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getStoreStorages(trackerServer, groupName);
}
public static ServerInfo[] getFetchStorages(String groupName,
String remoteFileName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
}
public static String getTrackerUrl() throws IOException { | return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
}
private static StorageClient getStorageClient() throws IOException {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = new StorageClient(trackerServer, null);
return storageClient;
}
private static TrackerServer getTrackerServer() throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerServer;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\fastdfs\FastDFSClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Duration getAsyncJobsGlobalLockWaitTime() {
return asyncJobsGlobalLockWaitTime;
}
public void setAsyncJobsGlobalLockWaitTime(Duration asyncJobsGlobalLockWaitTime) {
this.asyncJobsGlobalLockWaitTime = asyncJobsGlobalLockWaitTime;
}
public Duration getAsyncJobsGlobalLockPollRate() {
return asyncJobsGlobalLockPollRate;
}
public void setAsyncJobsGlobalLockPollRate(Duration asyncJobsGlobalLockPollRate) {
this.asyncJobsGlobalLockPollRate = asyncJobsGlobalLockPollRate;
}
public Duration getAsyncJobsGlobalLockForceAcquireAfter() {
return asyncJobsGlobalLockForceAcquireAfter;
}
public void setAsyncJobsGlobalLockForceAcquireAfter(Duration asyncJobsGlobalLockForceAcquireAfter) {
this.asyncJobsGlobalLockForceAcquireAfter = asyncJobsGlobalLockForceAcquireAfter;
}
public Duration getTimerLockWaitTime() {
return timerLockWaitTime;
}
public void setTimerLockWaitTime(Duration timerLockWaitTime) {
this.timerLockWaitTime = timerLockWaitTime;
}
public Duration getTimerLockPollRate() {
return timerLockPollRate;
}
public void setTimerLockPollRate(Duration timerLockPollRate) {
this.timerLockPollRate = timerLockPollRate;
}
public Duration getTimerLockForceAcquireAfter() {
return timerLockForceAcquireAfter;
}
public void setTimerLockForceAcquireAfter(Duration timerLockForceAcquireAfter) {
this.timerLockForceAcquireAfter = timerLockForceAcquireAfter;
}
public Duration getResetExpiredJobsInterval() {
return resetExpiredJobsInterval; | }
public void setResetExpiredJobsInterval(Duration resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobExecutorConfiguration.java | 2 |
请完成以下Java代码 | private MSV3ClientFactory getClientFactory(final Version version)
{
final MSV3ClientFactory clientFactory = clientFactoriesByVersion.get(version.getId());
if (clientFactory == null)
{
throw new AdempiereException("No MSV3 client factory found for version " + version + "."
+ " Available factories are: " + clientFactoriesByVersion);
}
return clientFactory;
}
@Override
public String testConnection(final int configRepoId)
{
final MSV3ClientConfigId configId = MSV3ClientConfigId.ofRepoId(configRepoId);
final MSV3ClientConfig config = configRepo.getById(configId);
return getClientFactory(config.getVersion())
.newTestConnectionClient(config)
.testConnection();
}
@Override
public boolean isProvidedForVendor(final int vendorRepoId)
{
final BPartnerId vendorId = BPartnerId.ofRepoId(vendorRepoId);
return configRepo.hasConfigForVendor(vendorId);
}
@Override
public AvailabilityResponse retrieveAvailability(@NonNull final AvailabilityRequest request)
{
final BPartnerId vendorId = BPartnerId.ofRepoId(request.getVendorId());
final MSV3ClientConfig config = configRepo.getByVendorId(vendorId);
final MSV3AvailiabilityClient client = getClientFactory(config.getVersion())
.newAvailabilityClient(config);
return client.retrieveAvailability(request);
}
@Override
public RemotePurchaseOrderCreated placePurchaseOrder(@NonNull final PurchaseOrderRequest request)
{
final BPartnerId vendorId = BPartnerId.ofRepoId(request.getVendorId());
final MSV3ClientConfig config = configRepo.getByVendorId(vendorId);
final MSV3PurchaseOrderClient client = getClientFactory(config.getVersion()) | .newPurchaseOrderClient(config);
return client.prepare(request).placeOrder();
}
@Override
public void associateLocalWithRemotePurchaseOrderId(
@NonNull final LocalPurchaseOrderForRemoteOrderCreated localPurchaseOrderForRemoteOrderCreated)
{
final RemotePurchaseOrderCreatedItem item = localPurchaseOrderForRemoteOrderCreated.getRemotePurchaseOrderCreatedItem();
final I_MSV3_BestellungAnteil anteilRecord = Services.get(IQueryBL.class).createQueryBuilder(I_MSV3_BestellungAnteil.class)
.addEqualsFilter(I_MSV3_BestellungAnteil.COLUMN_MSV3_BestellungAnteil_ID, item.getInternalItemId())
.create()
.firstOnlyNotNull(I_MSV3_BestellungAnteil.class);
anteilRecord.setC_OrderLinePO_ID(localPurchaseOrderForRemoteOrderCreated.getPurchaseOrderLineId());
save(anteilRecord);
final I_MSV3_BestellungAntwortAuftrag bestellungAntwortAuftrag = anteilRecord
.getMSV3_BestellungAntwortPosition()
.getMSV3_BestellungAntwortAuftrag();
bestellungAntwortAuftrag.setC_OrderPO_ID(localPurchaseOrderForRemoteOrderCreated.getPurchaseOrderId());
save(bestellungAntwortAuftrag);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3VendorGatewayService.java | 1 |
请完成以下Java代码 | public static String getSummary(String document, int max_length)
{
return getSummary(document, max_length, default_sentence_separator);
}
/**
* 一句话调用接口
*
* @param document 目标文档
* @param max_length 需要摘要的长度
* @param sentence_separator 句子分隔符,正则格式, 如:[。??!!;;]
* @return 摘要文本
*/
public static String getSummary(String document, int max_length, String sentence_separator)
{
List<String> sentenceList = splitSentence(document, sentence_separator);
int sentence_count = sentenceList.size();
int document_length = document.length();
int sentence_length_avg = document_length / sentence_count;
int size = max_length / sentence_length_avg + 1;
List<List<String>> docs = convertSentenceListToDocument(sentenceList);
TextRankSentence textRank = new TextRankSentence(docs);
int[] topSentence = textRank.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
resultList = permutation(resultList, sentenceList);
resultList = pick_sentences(resultList, max_length);
return TextUtility.join("。", resultList);
}
private static List<String> permutation(List<String> resultList, final List<String> sentenceList)
{
Collections.sort(resultList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) { | Integer num1 = sentenceList.indexOf(o1);
Integer num2 = sentenceList.indexOf(o2);
return num1.compareTo(num2);
}
});
return resultList;
}
private static List<String> pick_sentences(List<String> resultList, int max_length)
{
List<String> summary = new ArrayList<String>();
int count = 0;
for (String result : resultList) {
if (count + result.length() <= max_length) {
summary.add(result);
count += result.length();
}
}
return summary;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\summary\TextRankSentence.java | 1 |
请完成以下Java代码 | public MultiPolygon createMulPolygonByPolygon(Polygon[] polygons) throws ParseException{
return geometryFactory.createMultiPolygon(polygons);
}
/**
* 4.1 根据几何对象数组,创建几何对象集合:【GeometryCollection】
* @return
* @throws ParseException
*/
public GeometryCollection createGeoCollect(Geometry[] geoArray) throws ParseException{
return geometryFactory.createGeometryCollection(geoArray);
}
/**
* 5.1 根据圆点以及半径创建几何对象:特殊的多边形--圆 【Polygon】
* @param x 圆点x坐标
* @param y 圆点y坐标
* @param radius 半径
* @return
*/
public Polygon createCircle(double x, double y, final double radius){
//圆上面的点个数
final int sides = 32;
Coordinate[] coords = new Coordinate[sides+1];
for( int i = 0; i < sides; i++){
double angle = ((double) i / (double) sides) * Math.PI * 2.0;
double dx = Math.cos( angle ) * radius;
double dy = Math.sin( angle ) * radius;
coords[i] = new Coordinate( (double) x + dx, (double) y + dy );
}
coords[sides] = coords[0];
//线性环
LinearRing ring = geometryFactory.createLinearRing(coords);
return geometryFactory.createPolygon(ring, null);
}
/**
* 6.1 根据WKT创建环
* @param ringWKT | * @return
* @throws ParseException
*/
public LinearRing createLinearRingByWKT(String ringWKT) throws ParseException{
WKTReader reader = new WKTReader( geometryFactory );
return (LinearRing) reader.read(ringWKT);
}
/**
* 几何对象转GeoJson对象
* @param geometry
* @return
* @throws Exception
*/
public static String geometryToGeoJson(Geometry geometry) throws Exception {
if (geometry == null) {
return null;
}
StringWriter writer = new StringWriter();
geometryJson.write(geometry, writer);
String geojson = writer.toString();
writer.close();
return geojson;
}
/**
* GeoJson转几何对象
* @param geojson
* @return
* @throws Exception
*/
public static Geometry geoJsonToGeometry(String geojson) throws Exception {
return geometryJson.read(new StringReader(geojson));
}
} | repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\geotools\GeometryCreator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(value = "For a single resource contains the actual URL to use for retrieving the binary resource", example = "http://localhost:8081/flowable-rest/service/app-repository/deployments/10/resources/oneApp.app")
public String getUrl() {
return url;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
@ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/app-repository/deployments/10/resourcedata/oneApp.app")
public String getContentUrl() {
return contentUrl;
}
public void setMediaType(String mimeType) {
this.mediaType = mimeType;
} | @ApiModelProperty(example = "text/xml", value = "Contains the media-type the resource has. This is resolved using a (pluggable) MediaTypeResolver and contains, by default, a limited number of mime-type mappings.")
public String getMediaType() {
return mediaType;
}
public void setType(String type) {
this.type = type;
}
@ApiModelProperty(example = "appDefinition", value = "Type of resource", allowableValues = "resource,appDefinition")
public String getType() {
return type;
}
} | repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDeploymentResourceResponse.java | 2 |
请完成以下Java代码 | public JavaRuntimeEnvironmentInfo getRuntime() {
return this.runtime;
}
public JavaVirtualMachineInfo getJvm() {
return this.jvm;
}
/**
* Information about the Java Vendor of the Java Runtime the application is running
* in.
*
* @since 2.7.0
*/
public static class JavaVendorInfo {
private final String name;
private final String version;
public JavaVendorInfo() {
this.name = System.getProperty("java.vendor");
this.version = System.getProperty("java.vendor.version");
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
}
/**
* Information about the Java Runtime Environment the application is running in.
*/
public static class JavaRuntimeEnvironmentInfo {
private final String name;
private final String version;
public JavaRuntimeEnvironmentInfo() {
this.name = System.getProperty("java.runtime.name");
this.version = System.getProperty("java.runtime.version");
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
} | /**
* Information about the Java Virtual Machine the application is running in.
*/
public static class JavaVirtualMachineInfo {
private final String name;
private final String vendor;
private final String version;
public JavaVirtualMachineInfo() {
this.name = System.getProperty("java.vm.name");
this.vendor = System.getProperty("java.vm.vendor");
this.version = System.getProperty("java.vm.version");
}
public String getName() {
return this.name;
}
public String getVendor() {
return this.vendor;
}
public String getVersion() {
return this.version;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\JavaInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void reportFailure(HousekeeperTaskType taskType, ToHousekeeperServiceMsg msg) {
HousekeeperStats stats = this.stats.get(taskType);
if (msg.getTask().getErrorsCount() == 0) {
stats.getFailedProcessingCounter().increment();
} else {
stats.getFailedReprocessingCounter().increment();
}
}
@Getter
static class HousekeeperStats {
private final HousekeeperTaskType taskType;
private final List<StatsCounter> counters = new ArrayList<>();
private final StatsCounter processedCounter;
private final StatsCounter failedProcessingCounter;
private final StatsCounter reprocessedCounter;
private final StatsCounter failedReprocessingCounter;
private final StatsTimer processingTimer;
public HousekeeperStats(HousekeeperTaskType taskType, StatsFactory statsFactory) { | this.taskType = taskType;
this.processedCounter = register("processed", statsFactory);
this.failedProcessingCounter = register("failedProcessing", statsFactory);
this.reprocessedCounter = register("reprocessed", statsFactory);
this.failedReprocessingCounter = register("failedReprocessing", statsFactory);
this.processingTimer = statsFactory.createStatsTimer(StatsType.HOUSEKEEPER.getName(), "processingTime", "taskType", taskType.name());
}
private StatsCounter register(String statsName, StatsFactory statsFactory) {
StatsCounter counter = statsFactory.createStatsCounter(StatsType.HOUSEKEEPER.getName(), statsName, "taskType", taskType.name());
counters.add(counter);
return counter;
}
public void reset() {
counters.forEach(DefaultCounter::clear);
processingTimer.reset();
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\housekeeper\stats\HousekeeperStatsService.java | 2 |
请完成以下Java代码 | public void created(CmmnActivityExecution execution) {
// TODO: implement this:
// (1) in case of a UserEventListener there is nothing to do!
// (2) in case of TimerEventListener we have to check
// whether the timer must be triggered, when a transition
// on another plan item or case file item happens!
}
protected String getTypeName() {
return "event listener";
}
protected boolean isAtLeastOneEntryCriterionSatisfied(CmmnActivityExecution execution) {
return false;
} | public void fireEntryCriteria(CmmnActivityExecution execution) {
throw LOG.criteriaNotAllowedForEventListenerException("entry", execution.getId());
}
public void repeat(CmmnActivityExecution execution) {
// It is not possible to repeat a event listener
}
protected boolean evaluateRepetitionRule(CmmnActivityExecution execution) {
// It is not possible to define a repetition rule on an event listener
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerActivityBehavior.java | 1 |
请完成以下Java代码 | public String getFailedActivityId() {
return failedActivityId;
}
public String getCauseIncidentId() {
return causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getTenantId() {
return tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public Boolean isOpen() {
return open;
}
public Boolean isDeleted() {
return deleted;
}
public Boolean isResolved() {
return resolved;
} | public String getAnnotation() {
return annotation;
}
public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) {
HistoricIncidentDto dto = new HistoricIncidentDto();
dto.id = historicIncident.getId();
dto.processDefinitionKey = historicIncident.getProcessDefinitionKey();
dto.processDefinitionId = historicIncident.getProcessDefinitionId();
dto.processInstanceId = historicIncident.getProcessInstanceId();
dto.executionId = historicIncident.getExecutionId();
dto.createTime = historicIncident.getCreateTime();
dto.endTime = historicIncident.getEndTime();
dto.incidentType = historicIncident.getIncidentType();
dto.failedActivityId = historicIncident.getFailedActivityId();
dto.activityId = historicIncident.getActivityId();
dto.causeIncidentId = historicIncident.getCauseIncidentId();
dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId();
dto.configuration = historicIncident.getConfiguration();
dto.historyConfiguration = historicIncident.getHistoryConfiguration();
dto.incidentMessage = historicIncident.getIncidentMessage();
dto.open = historicIncident.isOpen();
dto.deleted = historicIncident.isDeleted();
dto.resolved = historicIncident.isResolved();
dto.tenantId = historicIncident.getTenantId();
dto.jobDefinitionId = historicIncident.getJobDefinitionId();
dto.removalTime = historicIncident.getRemovalTime();
dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId();
dto.annotation = historicIncident.getAnnotation();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentDto.java | 1 |
请完成以下Java代码 | private static class Column
{
private final String columnName;
private final String sourceColumnName;
private final Object constantValue;
public Column(String columnName, String sourceColumnName, Object constantValue)
{
super();
this.columnName = columnName;
this.sourceColumnName = sourceColumnName;
this.constantValue = constantValue;
}
public String getColumnName()
{
return columnName;
}
public String getSourceColumnName()
{
return sourceColumnName;
}
public Object getConstantValue()
{
return constantValue;
}
}
private final String tableName;
private final Map<String, Column> fields = new LinkedHashMap<String, Column>();
public JdbcTableExportDataDestination(final String tableName)
{
super();
this.tableName = tableName;
}
@Override
public void appendLine(List<Object> values) throws IOException
{
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void close() throws IOException
{
// nothing
}
public void append(final JdbcExportDataSource source)
{
final StringBuilder sqlInsert = new StringBuilder();
final StringBuilder sqlSelect = new StringBuilder();
final List<Object> sqlSelectParams = new ArrayList<Object>();
for (final Column field : fields.values())
{
final String columnName = field.getColumnName();
//
// INSERT part
if (sqlInsert.length() > 0) | {
sqlInsert.append(", ");
}
sqlInsert.append(columnName);
if (sqlSelect.length() > 0)
{
sqlSelect.append("\n, ");
}
//
// SELECT part
final String sourceColumnName = field.getSourceColumnName();
if (!Check.isEmpty(sourceColumnName))
{
sqlSelect.append(sourceColumnName).append(" AS ").append(columnName);
}
// Constant
else
{
sqlSelect.append("? AS ").append(columnName);
sqlSelectParams.add(field.getConstantValue());
}
}
final String sql = new StringBuilder()
.append("INSERT INTO ").append(tableName).append(" (").append(sqlInsert).append(")")
.append("\nSELECT ").append(sqlSelect)
.append("\nFROM (").append(source.getSqlSelect()).append(") t")
.toString();
final List<Object> sqlParams = new ArrayList<Object>();
sqlParams.addAll(sqlSelectParams);
sqlParams.addAll(source.getSqlParams());
final String trxName = Trx.TRXNAME_None;
final int count = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), trxName);
logger.info("Inserted {} records into {} from {}", new Object[] { count, tableName, source });
}
public void addField(final String fieldName, final String sourceFieldName)
{
final Column field = new Column(fieldName, sourceFieldName, null);
fields.put(fieldName, field);
}
public void addConstant(final String fieldName, final Object value)
{
final Column field = new Column(fieldName, null, value);
fields.put(fieldName, field);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcTableExportDataDestination.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class IndexController {
private final static Logger LOGGER = Logger.getLogger(IndexController.class.getName());
@GetMapping("/")
public String greeting(Device device) {
String deviceType = "browser";
String platform = "browser";
String viewName = "index";
if (device.isNormal()) {
deviceType = "browser";
} else if (device.isMobile()) {
deviceType = "mobile";
viewName = "mobile/index"; | } else if (device.isTablet()) {
deviceType = "tablet";
viewName = "tablet/index";
}
platform = device.getDevicePlatform().name();
if (platform.equalsIgnoreCase("UNKNOWN")) {
platform = "browser";
}
LOGGER.info("Client Device Type: " + deviceType + ", Platform: " + platform);
return viewName;
}
} | repos\springboot-demo-master\SpringMobile\src\main\java\com\et\springmobile\controller\IndexController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean containsValue(Object value) {
return this.loaded.containsValue(value);
}
@Override
public Collection<V> values() {
return this.loaded.values();
}
@Override
public Set<Entry<K, V>> entrySet() {
return this.loaded.entrySet();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true; | }
if (o == null || getClass() != o.getClass()) {
return false;
}
LoadingMap<?, ?> that = (LoadingMap<?, ?>) o;
return this.loaded.equals(that.loaded);
}
@Override
public int hashCode() {
return this.loaded.hashCode();
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java | 2 |
请完成以下Java代码 | public int getCaretPosition()
{
return m_textPane.getCaretPosition();
}
/**
* Set Editable
* @param edit editable
*/
public void setEditable (boolean edit)
{
m_textPane.setEditable(edit);
}
/**
* Editable
* @return true if editable
*/
public boolean isEditable()
{
return m_textPane.isEditable();
}
/**
* Set Text Margin
* @param m insets
*/
public void setMargin (Insets m)
{
if (m_textPane != null)
m_textPane.setMargin(m);
} // setMargin
/**
* Set Opaque
* @param isOpaque opaque
*/
@Override
public void setOpaque (boolean isOpaque)
{
// JScrollPane & Viewport is always not Opaque
if (m_textPane == null) // during init of JScrollPane
super.setOpaque(isOpaque);
else
m_textPane.setOpaque(isOpaque);
} // setOpaque
/**
* Add Focus Listener
* @param l listener
*/
@Override
public void addFocusListener (FocusListener l)
{
if (m_textPane == null) // during init
super.addFocusListener(l);
else
m_textPane.addFocusListener(l);
}
/**
* Add Mouse Listener
* @param l listner
*/
@Override
public void addMouseListener (MouseListener l)
{
m_textPane.addMouseListener(l);
}
/**
* Add Key Listener
* @param l listner
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textPane.addKeyListener(l);
} | /**
* Add Input Method Listener
* @param l listener
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textPane.addInputMethodListener(l);
}
/**
* Get Input Method Requests
* @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textPane.getInputMethodRequests();
}
/**
* Set Input Verifier
* @param l verifyer
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textPane.setInputVerifier(l);
}
// metas: begin
public String getContentType()
{
if (m_textPane != null)
return m_textPane.getContentType();
return null;
}
private void setHyperlinkListener()
{
if (hyperlinkListenerClass == null)
{
return;
}
try
{
final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance();
m_textPane.addHyperlinkListener(listener);
}
catch (Exception e)
{
log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e);
}
}
private static Class<?> hyperlinkListenerClass;
static
{
final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler";
try
{
hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname);
}
catch (Exception e)
{
log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e);
}
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
// metas: end
} // CTextPane | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("bpartnerIds", bpartnerIds)
.add("locatorIds", locatorIds)
.add("productIdsRO", productIdsRO)
.add("huId", huId)
.add("hasQtyOnHandChanges", hasQtyOnHandChanges)
.toString();
}
@Override
public Set<Integer> getProductIds()
{
if (productIdsRO != null)
{
return productIdsRO;
}
//
// Extract affected products
final List<Integer> productIdsList = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_Storage.class, Env.getCtx(), ITrx.TRXNAME_None)
.addEqualsFilter(I_M_HU_Storage.COLUMNNAME_M_HU_ID, huId)
.andCollect(I_M_HU_Storage.COLUMNNAME_M_Product_ID, I_M_Product.class)
.create()
.listIds();
productIdsRO = Collections.unmodifiableSet(new HashSet<>(productIdsList));
return productIdsRO;
}
@Override
public Set<Integer> getBpartnerIds()
{
return bpartnersIdsRO;
} | @Override
public Set<Integer> getLocatorIds()
{
return locatorsIdsRO;
}
public boolean hasQtyOnHandChanges()
{
return hasQtyOnHandChanges;
}
@Override
public Set<Integer> getBillBPartnerIds()
{
return ImmutableSet.of();
}
@Override
public Set<ShipmentScheduleAttributeSegment> getAttributes()
{
return ImmutableSet.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\segments\ShipmentScheduleSegmentFromHU.java | 1 |
请完成以下Java代码 | public abstract class BaseChildElementParser implements DmnXMLConstants {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseChildElementParser.class);
public abstract String getElementName();
public abstract void parseChildElement(XMLStreamReader xtr, DmnElement parentElement, Decision decision) throws Exception;
protected void parseChildElements(XMLStreamReader xtr, DmnElement parentElement, Decision decision, BaseChildElementParser parser) throws Exception {
boolean readyWithChildElements = false;
while (!readyWithChildElements && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (parser.getElementName().equals(xtr.getLocalName())) {
parser.parseChildElement(xtr, parentElement, decision);
}
} else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
}
public boolean accepts(DmnElement element) {
return element != null;
}
public List<Object> splitAndFormatInputOutputValues(String valuesText) {
if (StringUtils.isEmpty(valuesText)) {
return Collections.emptyList();
}
List<Object> result = new ArrayList<>();
int start = 0;
int subStart, subEnd;
boolean inQuotes = false;
for (int current = 0; current < valuesText.length(); current++) {
if (valuesText.charAt(current) == '\"') {
inQuotes = !inQuotes;
} else if (valuesText.charAt(current) == ',' && !inQuotes) {
subStart = getSubStringStartPos(start, valuesText);
subEnd = getSubStringEndPos(current, valuesText);
result.add(valuesText.substring(subStart, subEnd));
start = current + 1;
if (valuesText.charAt(start) == ' ') {
start++; | }
}
}
subStart = getSubStringStartPos(start, valuesText);
subEnd = getSubStringEndPos(valuesText.length(), valuesText);
result.add(valuesText.substring(subStart, subEnd));
return result;
}
protected int getSubStringStartPos(int initialStart, String searchString) {
if (searchString.charAt(initialStart) == '\"') {
return initialStart + 1;
}
return initialStart;
}
protected int getSubStringEndPos(int initialEnd, String searchString) {
if (searchString.charAt(initialEnd - 1) == '\"') {
return initialEnd - 1;
}
return initialEnd;
}
} | repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\converter\child\BaseChildElementParser.java | 1 |
请完成以下Java代码 | public Optional<Workplace> getWorkplaceByUserId(@NonNull final UserId userId)
{
return workplaceUserAssignRepository.getWorkplaceIdByUserId(userId)
.map(workplaceRepository::getById);
}
public List<Workplace> getAllActive() {return workplaceRepository.getAllActive();}
public Optional<WarehouseId> getWarehouseIdByUserId(@NonNull final UserId userId)
{
return getWorkplaceByUserId(userId).map(Workplace::getWarehouseId);
}
public void assignWorkplace(@NonNull UserId userId, @NonNull WorkplaceId workplaceId)
{
workplaceUserAssignRepository.create(WorkplaceAssignmentCreateRequest.builder().userId(userId).workplaceId(workplaceId).build());
}
public void assignWorkplace(@NonNull final WorkplaceAssignmentCreateRequest request)
{
workplaceUserAssignRepository.create(request);
}
public boolean isUserAssigned(@NonNull final UserId userId, @NonNull final WorkplaceId expectedWorkplaceId)
{
final WorkplaceId workplaceId = workplaceUserAssignRepository.getWorkplaceIdByUserId(userId).orElse(null);
return WorkplaceId.equals(workplaceId, expectedWorkplaceId);
}
public boolean isAnyWorkplaceActive() | {
return workplaceRepository.isAnyWorkplaceActive();
}
public Set<LocatorId> getPickFromLocatorIds(final Workplace workplace)
{
if (workplace.getPickFromLocatorId() != null)
{
return ImmutableSet.of(workplace.getPickFromLocatorId());
}
else
{
return warehouseBL.getLocatorIdsByWarehouseId(workplace.getWarehouseId());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Autowired(required = false)
void setAuthenticationManagerPostProcessor(
Map<String, ObjectPostProcessor<ReactiveAuthenticationManager>> postProcessors) {
if (postProcessors.size() == 1) {
this.postProcessor = postProcessors.values().iterator().next();
}
this.postProcessor = postProcessors.get("rSocketAuthenticationManagerPostProcessor");
}
@Bean(name = RSOCKET_SECURITY_BEAN_NAME)
@Scope("prototype")
RSocketSecurity rsocketSecurity(ApplicationContext context) {
RSocketSecurity security = new RSocketSecurity().authenticationManager(authenticationManager());
security.setApplicationContext(context); | return security;
}
private ReactiveAuthenticationManager authenticationManager() {
if (this.authenticationManager != null) {
return this.authenticationManager;
}
if (this.reactiveUserDetailsService != null) {
UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(
this.reactiveUserDetailsService);
if (this.passwordEncoder != null) {
manager.setPasswordEncoder(this.passwordEncoder);
}
return this.postProcessor.postProcess(manager);
}
return null;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurityConfiguration.java | 2 |
请完成以下Java代码 | public void ignoringNonExecutableProcess(String elementId) {
logInfo("002", "Ignoring non-executable process with id '{}'. Set the attribute isExecutable=\"true\" to deploy " +
"this process.", elementId);
}
public void missingIsExecutableAttribute(String elementId) {
logInfo("003", "Process with id '{}' has no attribute isExecutable. Better set the attribute explicitly, " +
"especially to be compatible with future engine versions which might change the default behavior.", elementId);
}
public void parsingFailure(Throwable cause) {
logError("004", "Unexpected Exception with message: {} ", cause.getMessage());
}
public void intermediateCatchTimerEventWithTimeCycleNotRecommended(String definitionKey, String elementId) {
logInfo("005", "definitionKey: {}; It is not recommended to use an intermediate catch timer event with a time cycle, " +
"element with id '{}'.", definitionKey, elementId);
}
// EXCEPTIONS
public ProcessEngineException parsingProcessException(Exception cause) {
return new ProcessEngineException(exceptionMessage("009", "Error while parsing process. {}.", cause.getMessage()), cause); | }
public void exceptionWhileGeneratingProcessDiagram(Throwable t) {
logError(
"010",
"Error while generating process diagram, image will not be stored in repository", t);
}
public ProcessEngineException messageEventSubscriptionWithSameNameExists(String resourceName, String eventName) {
throw new ProcessEngineException(exceptionMessage(
"011",
"Cannot deploy process definition '{}': there already is a message event subscription for the message with name '{}'.", resourceName, eventName));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\BpmnParseLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonOrderPaymentCreateRequest
{
@JsonProperty("orgCode")
@NonNull
String orgCode;
@JsonProperty("bpartnerIdentifier")
@NonNull
String bpartnerIdentifier;
@JsonProperty("orderIdentifier")
@NonNull
String orderIdentifier;
@JsonProperty("currencyCode")
@NonNull
String currencyCode;
@JsonProperty("amount")
@NonNull
BigDecimal amount;
@JsonProperty("externalPaymentId")
@Nullable
String externalPaymentId;
@JsonProperty("writeOffAmt")
@Nullable
BigDecimal writeOffAmt;
@JsonProperty("discountAmt") | @Nullable
BigDecimal discountAmt;
@JsonProperty("docBaseType")
@Nullable
BigDecimal docBaseType;
@JsonProperty("docSubType")
@Nullable
String docSubType;
@JsonProperty("targetIBAN")
@Nullable
String targetIBAN;
@JsonProperty("transactionDate")
@Nullable
LocalDate transactionDate;
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\order\JsonOrderPaymentCreateRequest.java | 2 |
请完成以下Java代码 | public class SchemaLogQueryDto extends AbstractQueryDto<SchemaLogQuery>{
private static final String SORT_BY_TIMESTAMP_VALUE = "timestamp";
private static final List<String> VALID_SORT_BY_VALUES;
static {
VALID_SORT_BY_VALUES = new ArrayList<String>();
VALID_SORT_BY_VALUES.add(SORT_BY_TIMESTAMP_VALUE);
}
String version;
public SchemaLogQueryDto() {
}
public SchemaLogQueryDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) {
super(objectMapper, queryParameters);
}
public String getVersion() {
return version;
}
@CamundaQueryParam("version")
public void setVersion(String version) {
this.version = version;
} | @Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected SchemaLogQuery createNewQuery(ProcessEngine engine) {
return engine.getManagementService().createSchemaLogQuery();
}
@Override
protected void applyFilters(SchemaLogQuery query) {
if(this.version != null) {
query.version(this.version);
}
}
@Override
protected void applySortBy(SchemaLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if(sortBy.equals(SORT_BY_TIMESTAMP_VALUE)) {
query.orderByTimestamp();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\SchemaLogQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String genre;
private int age;
private String email;
private String address;
private String rating;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + ", email="
+ email + ", address=" + address + ", rating=" + rating + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDynamicProjection\src\main\java\com\bookstore\entity\Author.java | 2 |
请完成以下Java代码 | public static String toLowerCamel(String str) {
if (str == null || str.trim().isEmpty()) {
return str;
}
StringBuilder result = new StringBuilder();
char pre = '\0';
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '-' || ch == '—' || ch == '_') {
ch = '_';
pre = ch;
continue;
}
char ch2 = ch;
if (pre == '_') {
ch2 = Character.toUpperCase(ch); | pre = ch2;
} else if (pre >= 'A' && pre <= 'Z') {
pre = ch;
ch2 = Character.toLowerCase(ch);
} else {
pre = ch;
}
result.append(ch2);
}
return lowerCaseFirst(result.toString());
}
public static boolean isNotNull(String str) {
return org.apache.commons.lang3.StringUtils.isNotEmpty(str);
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\util\StringUtilsPlus.java | 1 |
请完成以下Java代码 | public List<RelatedDocumentsCandidateGroup> retrieveRelatedDocumentsCandidates(
@NonNull final IZoomSource fromDocument,
@Nullable final AdWindowId targetWindowId)
{
if (!fromDocument.isSingleKeyRecord())
{
return ImmutableList.of();
}
final AdWindowId logsWindowId = RecordWindowFinder.findAdWindowId(I_Document_Acct_Log.Table_Name).orElse(null);
if (logsWindowId == null)
{
return ImmutableList.of();
}
if (targetWindowId != null && !AdWindowId.equals(targetWindowId, logsWindowId))
{
return ImmutableList.of();
}
if (!isAccountableDocument(fromDocument))
{
return ImmutableList.of();
}
final DocumentAcctLogsQuerySupplier querySupplier = createQuerySupplier(fromDocument);
return ImmutableList.of(
RelatedDocumentsCandidateGroup.of(
RelatedDocumentsCandidate.builder()
.id(RelatedDocumentsId.ofString(I_Document_Acct_Log.Table_Name))
.internalName(I_Document_Acct_Log.Table_Name)
.targetWindow(RelatedDocumentsTargetWindow.ofAdWindowId(logsWindowId))
.windowCaption(adWindowDAO.retrieveWindowName(logsWindowId))
.priority(relatedDocumentsPriority)
.querySupplier(querySupplier) | .documentsCountSupplier(querySupplier)
.build()));
}
private boolean isAccountableDocument(final @NonNull IZoomSource fromDocument)
{
return acctDocRegistry.isAccountingTable(fromDocument.getTableName());
}
private DocumentAcctLogsQuerySupplier createQuerySupplier(final @NonNull IZoomSource fromDocument)
{
return DocumentAcctLogsQuerySupplier.builder()
.queryBL(queryBL)
.adTableId(fromDocument.getAD_Table_ID())
.recordId(fromDocument.getRecord_ID())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\related_documents\DocumentAcctLogsRelatedDocumentsProvider.java | 1 |
请完成以下Java代码 | public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setPIName (final @Nullable java.lang.String PIName)
{
set_ValueNoCheck (COLUMNNAME_PIName, PIName);
}
@Override
public java.lang.String getPIName()
{
return get_ValueAsString(COLUMNNAME_PIName);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{ | return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_ValueNoCheck (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Instance_Properties_v.java | 1 |
请完成以下Java代码 | public java.lang.String getawb()
{
return get_ValueAsString(COLUMNNAME_awb);
}
@Override
public void setCarrier_ShipmentOrder_ID (final int Carrier_ShipmentOrder_ID)
{
if (Carrier_ShipmentOrder_ID < 1)
set_Value (COLUMNNAME_Carrier_ShipmentOrder_ID, null);
else
set_Value (COLUMNNAME_Carrier_ShipmentOrder_ID, Carrier_ShipmentOrder_ID);
}
@Override
public int getCarrier_ShipmentOrder_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_ID);
}
@Override
public void setCarrier_ShipmentOrder_Parcel_ID (final int Carrier_ShipmentOrder_Parcel_ID)
{
if (Carrier_ShipmentOrder_Parcel_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID, Carrier_ShipmentOrder_Parcel_ID);
}
@Override
public int getCarrier_ShipmentOrder_Parcel_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID);
}
@Override
public void setHeightInCm (final int HeightInCm)
{
set_Value (COLUMNNAME_HeightInCm, HeightInCm);
}
@Override
public int getHeightInCm()
{
return get_ValueAsInt(COLUMNNAME_HeightInCm);
}
@Override
public void setLengthInCm (final int LengthInCm)
{
set_Value (COLUMNNAME_LengthInCm, LengthInCm);
}
@Override
public int getLengthInCm()
{
return get_ValueAsInt(COLUMNNAME_LengthInCm);
}
@Override
public void setM_Package_ID (final int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, M_Package_ID);
}
@Override
public int getM_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_ID); | }
@Override
public void setPackageDescription (final @Nullable java.lang.String PackageDescription)
{
set_Value (COLUMNNAME_PackageDescription, PackageDescription);
}
@Override
public java.lang.String getPackageDescription()
{
return get_ValueAsString(COLUMNNAME_PackageDescription);
}
@Override
public void setPdfLabelData (final @Nullable byte[] PdfLabelData)
{
set_Value (COLUMNNAME_PdfLabelData, PdfLabelData);
}
@Override
public byte[] getPdfLabelData()
{
return (byte[])get_Value(COLUMNNAME_PdfLabelData);
}
@Override
public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@Override
public void setWeightInKg (final BigDecimal WeightInKg)
{
set_Value (COLUMNNAME_WeightInKg, WeightInKg);
}
@Override
public BigDecimal getWeightInKg()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java | 1 |
请完成以下Java代码 | public class AddIdentityLinkForProcessInstanceCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String processInstanceId;
protected String userId;
protected String groupId;
protected String type;
public AddIdentityLinkForProcessInstanceCmd(String processInstanceId, String userId, String groupId, String type) {
validateParams(processInstanceId, userId, groupId, type);
this.processInstanceId = processInstanceId;
this.userId = userId;
this.groupId = groupId;
this.type = type;
}
protected void validateParams(String processInstanceId, String userId, String groupId, String type) {
if (processInstanceId == null) {
throw new ActivitiIllegalArgumentException("processInstanceId is null");
}
if (type == null) {
throw new ActivitiIllegalArgumentException("type is required when adding a new process instance identity link");
}
if (userId == null && groupId == null) {
throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null");
} | }
@Override
public Void execute(CommandContext commandContext) {
ExecutionEntity processInstance = commandContext.getExecutionEntityManager().findExecutionById(processInstanceId);
if (processInstance == null) {
throw new ActivitiObjectNotFoundException("Cannot find process instance with id " + processInstanceId, ExecutionEntity.class);
}
processInstance.addIdentityLink(userId, groupId, type);
commandContext.getHistoryManager().createProcessInstanceIdentityLinkComment(processInstanceId, userId, groupId, type, true);
return null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\AddIdentityLinkForProcessInstanceCmd.java | 1 |
请完成以下Java代码 | public String getMethodCallSyntax(String obj, String method, String... arguments) {
throw new UnsupportedOperationException("Method getMethodCallSyntax is not supported");
}
public List<String> getMimeTypes() {
return mimeTypes;
}
public List<String> getNames() {
return names;
}
public String getOutputStatement(String toDisplay) {
// We will use out:print function to output statements
StringBuilder stringBuffer = new StringBuilder();
stringBuffer.append("out:print(\"");
int length = toDisplay.length();
for (int i = 0; i < length; i++) {
char c = toDisplay.charAt(i);
switch (c) {
case '"':
stringBuffer.append("\\\"");
break;
case '\\':
stringBuffer.append("\\\\");
break;
default:
stringBuffer.append(c);
break;
}
}
stringBuffer.append("\")");
return stringBuffer.toString();
}
public String getParameter(String key) {
if (key.equals(ScriptEngine.NAME)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.ENGINE)) {
return getEngineName();
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return getEngineVersion();
} else if (key.equals(ScriptEngine.LANGUAGE)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return getLanguageVersion();
} else if (key.equals("THREADING")) {
return "MULTITHREADED"; | } else {
return null;
}
}
public String getProgram(String... statements) {
// Each statement is wrapped in '${}' to comply with EL
StringBuilder buf = new StringBuilder();
if (statements.length != 0) {
for (int i = 0; i < statements.length; i++) {
buf.append("${");
buf.append(statements[i]);
buf.append("} ");
}
}
return buf.toString();
}
public ScriptEngine getScriptEngine() {
return new JuelScriptEngine(this);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngineFactory.java | 1 |
请完成以下Java代码 | public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setDeliveredData(ic);
}
@Override
public void invalidateCandidatesFor(final Object model)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(model);
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
final List<IInvoiceCandidateHandler> handlersForTable = retrieveImplementationsForTable(ctx, tableName);
for (final IInvoiceCandidateHandler handler : handlersForTable)
{
final OnInvalidateForModelAction onInvalidateForModelAction = handler.getOnInvalidateForModelAction();
switch (onInvalidateForModelAction)
{
case RECREATE_ASYNC:
scheduleCreateMissingCandidatesFor(model, handler);
break;
case REVALIDATE:
handler.invalidateCandidatesFor(model);
break;
default:
// nothing
logger.warn("Got no OnInvalidateForModelAction for " + model + ". Doing nothing.");
break;
}
}
}
@Override
public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
return handler.calculatePriceAndTax(ic);
} | @Override
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setBPartnerData(ic);
}
@Override
public void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate icRecord)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(icRecord);
handler.setInvoiceScheduleAndDateToInvoice(icRecord);
}
@Override
public void setPickedData(final I_C_Invoice_Candidate ic)
{
final InvoiceCandidateRecordService invoiceCandidateRecordService = SpringContextHolder.instance.getBean(InvoiceCandidateRecordService.class);
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setShipmentSchedule(ic);
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(ic.getM_ShipmentSchedule_ID());
if (shipmentScheduleId == null)
{
return;
}
final StockQtyAndUOMQty qtysPicked = invoiceCandidateRecordService.ofRecord(ic).computeQtysPicked();
ic.setQtyPicked(qtysPicked.getStockQty().toBigDecimal());
ic.setQtyPickedInUOM(qtysPicked.getUOMQtyNotNull().toBigDecimal());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateHandlerBL.java | 1 |
请完成以下Java代码 | public Class<AuthorRecord> getRecordType() {
return AuthorRecord.class;
}
/**
* The column <code>public.author.id</code>.
*/
public final TableField<AuthorRecord, Integer> ID = createField(DSL.name("id"), org.jooq.impl.SQLDataType.INTEGER.nullable(false), AUTHOR, "");
/**
* The column <code>public.author.first_name</code>.
*/
public final TableField<AuthorRecord, String> FIRST_NAME = createField(DSL.name("first_name"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
/**
* The column <code>public.author.last_name</code>.
*/
public final TableField<AuthorRecord, String> LAST_NAME = createField(DSL.name("last_name"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
/**
* The column <code>public.author.age</code>.
*/
public final TableField<AuthorRecord, Integer> AGE = createField(DSL.name("age"), org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>public.author</code> table reference
*/
public Author() {
this(DSL.name("author"), null);
}
/**
* Create an aliased <code>public.author</code> table reference
*/
public Author(String alias) {
this(DSL.name(alias), AUTHOR);
}
/**
* Create an aliased <code>public.author</code> table reference
*/
public Author(Name alias) {
this(alias, AUTHOR);
}
private Author(Name alias, Table<AuthorRecord> aliased) {
this(alias, aliased, null);
}
private Author(Name alias, Table<AuthorRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table());
}
public <O extends Record> Author(Table<O> child, ForeignKey<O, AuthorRecord> key) {
super(child, key, AUTHOR);
} | @Override
public Schema getSchema() {
return Public.PUBLIC;
}
@Override
public UniqueKey<AuthorRecord> getPrimaryKey() {
return Keys.AUTHOR_PKEY;
}
@Override
public List<UniqueKey<AuthorRecord>> getKeys() {
return Arrays.<UniqueKey<AuthorRecord>>asList(Keys.AUTHOR_PKEY);
}
@Override
public Author as(String alias) {
return new Author(DSL.name(alias), this);
}
@Override
public Author as(Name alias) {
return new Author(alias, this);
}
/**
* Rename this table
*/
@Override
public Author rename(String name) {
return new Author(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Author rename(Name name) {
return new Author(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Author.java | 1 |
请完成以下Java代码 | public int getService_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_BPartner_ID);
}
@Override
public void setServiceFeeAmount (final @Nullable BigDecimal ServiceFeeAmount)
{
set_Value (COLUMNNAME_ServiceFeeAmount, ServiceFeeAmount);
}
@Override
public BigDecimal getServiceFeeAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_Invoice getService_Fee_Invoice()
{
return get_ValueAsPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
@Override
public void setService_Fee_Invoice(final org.compiere.model.I_C_Invoice Service_Fee_Invoice)
{
set_ValueFromPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class, Service_Fee_Invoice);
}
@Override
public void setService_Fee_Invoice_ID (final int Service_Fee_Invoice_ID)
{
if (Service_Fee_Invoice_ID < 1)
set_Value (COLUMNNAME_Service_Fee_Invoice_ID, null);
else
set_Value (COLUMNNAME_Service_Fee_Invoice_ID, Service_Fee_Invoice_ID);
}
@Override
public int getService_Fee_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID);
} | @Override
public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate)
{
set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate);
}
@Override
public BigDecimal getServiceFeeVatRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setService_Product_ID (final int Service_Product_ID)
{
if (Service_Product_ID < 1)
set_Value (COLUMNNAME_Service_Product_ID, null);
else
set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID);
}
@Override
public int getService_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Product_ID);
}
@Override
public void setService_Tax_ID (final int Service_Tax_ID)
{
if (Service_Tax_ID < 1)
set_Value (COLUMNNAME_Service_Tax_ID, null);
else
set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID);
}
@Override
public int getService_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Tax_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public boolean isOverrideId() {
return overrideId;
} | public void setOverrideId(boolean overrideId) {
this.overrideId = overrideId;
}
public String getPlaceholder() {
return placeholder;
}
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public LayoutDefinition getLayout() {
return layout;
}
public void setLayout(LayoutDefinition layout) {
this.layout = layout;
}
@JsonInclude(Include.NON_EMPTY)
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
@JsonIgnore
public Object getParam(String name) {
if (params != null) {
return params.get(name);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-form-model\src\main\java\org\flowable\form\model\FormField.java | 1 |
请完成以下Java代码 | public boolean exists(String key)
{
return d.containsKey(key);
}
public int getsum()
{
return total;
}
Integer get(String key)
{
return d.get(key);
}
public int get(char[]... keyArray)
{
Integer f = get(convert(keyArray));
if (f == null) return 0;
return f;
}
public int get(char... key)
{
Integer f = d.get(key);
if (f == null) return 0;
return f;
}
public double freq(String key)
{
Integer f = get(key);
if (f == null) f = 0;
return f / (double) total;
}
public double freq(char[]... keyArray)
{
return freq(convert(keyArray));
}
public double freq(char... keyArray)
{
Integer f = d.get(keyArray);
if (f == null) f = 0;
return f / (double) total;
}
public Set<String> samples()
{
return d.keySet();
}
void add(String key, int value)
{
Integer f = get(key);
if (f == null) f = 0;
f += value;
d.put(key, f);
total += value;
}
void add(int value, char... key)
{
Integer f = d.get(key);
if (f == null) f = 0;
f += value;
d.put(key, f);
total += value;
}
public void add(int value, char[]... keyArray)
{
add(convert(keyArray), value); | }
public void add(int value, Collection<char[]> keyArray)
{
add(convert(keyArray), value);
}
private String convert(Collection<char[]> keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.size() * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
static private String convert(char[]... keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.length * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
@Override
public void save(DataOutputStream out) throws Exception
{
out.writeInt(total);
Integer[] valueArray = d.getValueArray(new Integer[0]);
out.writeInt(valueArray.length);
for (Integer v : valueArray)
{
out.writeInt(v);
}
d.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
total = byteArray.nextInt();
int size = byteArray.nextInt();
Integer[] valueArray = new Integer[size];
for (int i = 0; i < valueArray.length; ++i)
{
valueArray[i] = byteArray.nextInt();
}
d.load(byteArray, valueArray);
return true;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\frequency\Probability.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AppDefinitionResponse {
protected String id;
protected String url;
protected String category;
protected String name;
protected String key;
protected String description;
protected int version;
protected String resourceName;
protected String deploymentId;
protected String tenantId;
public AppDefinitionResponse(AppDefinition appDefinition) {
setId(appDefinition.getId());
setCategory(appDefinition.getCategory());
setName(appDefinition.getName());
setKey(appDefinition.getKey());
setDescription(appDefinition.getDescription());
setVersion(appDefinition.getVersion());
setResourceName(appDefinition.getResourceName());
setDeploymentId(appDefinition.getDeploymentId());
setTenantId(appDefinition.getTenantId());
}
@ApiModelProperty(example = "10")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "http://localhost:8182/app-repository/app-definitions/simpleApp")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "Examples")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@ApiModelProperty(example = "Simple App")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "simpleApp")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
} | @ApiModelProperty(example = "This is an app for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@ApiModelProperty(example = "1")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@ApiModelProperty(example = "SimpleSourceName")
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@ApiModelProperty(example = "818e4703-f1d2-11e6-8549-acde48001121")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDefinitionResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void deleteHistoricIdentityLink(String id) {
getHistoricIdentityLinkEntityManager().delete(id);
}
@Override
public void deleteHistoricIdentityLink(HistoricIdentityLinkEntity identityLink) {
getHistoricIdentityLinkEntityManager().delete(identityLink);
}
@Override
public void deleteHistoricIdentityLinksByProcessInstanceId(String processInstanceId) {
getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByProcInstance(processInstanceId);
}
@Override
public void deleteHistoricIdentityLinksByTaskId(String taskId) {
getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByTaskId(taskId);
}
@Override
public void deleteHistoricIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByScopeIdAndScopeType(scopeId, scopeType);
}
@Override
public void bulkDeleteHistoricIdentityLinksForProcessInstanceIds(Collection<String> processInstanceIds) {
getHistoricIdentityLinkEntityManager().bulkDeleteHistoricIdentityLinksForProcessInstanceIds(processInstanceIds);
}
@Override | public void bulkDeleteHistoricIdentityLinksForTaskIds(Collection<String> taskIds) {
getHistoricIdentityLinkEntityManager().bulkDeleteHistoricIdentityLinksForTaskIds(taskIds);
}
@Override
public void bulkDeleteHistoricIdentityLinksByScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
getHistoricIdentityLinkEntityManager().bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType);
}
@Override
public void deleteHistoricProcessIdentityLinksForNonExistingInstances() {
getHistoricIdentityLinkEntityManager().deleteHistoricProcessIdentityLinksForNonExistingInstances();
}
@Override
public void deleteHistoricCaseIdentityLinksForNonExistingInstances() {
getHistoricIdentityLinkEntityManager().deleteHistoricCaseIdentityLinksForNonExistingInstances();
}
@Override
public void deleteHistoricTaskIdentityLinksForNonExistingInstances() {
getHistoricIdentityLinkEntityManager().deleteHistoricTaskIdentityLinksForNonExistingInstances();
}
public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return configuration.getHistoricIdentityLinkEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\HistoricIdentityLinkServiceImpl.java | 2 |
请完成以下Java代码 | public MailTextBuilder adLanguage(final String adLanguage)
{
_adLanguage = adLanguage;
invalidateCache();
return this;
}
private void invalidateCache()
{
_adLanguageEffective = null;
_text2parsedText.clear();
}
public MailTextBuilder record(final Object record)
{
_record = record;
invalidateCache();
return this;
}
public MailTextBuilder recordAndUpdateBPartnerAndContact(final Object record)
{
record(record);
if (record != null)
{
updateBPartnerAndContactFromRecord(record);
}
return this;
}
private void updateBPartnerAndContactFromRecord(@NonNull final Object record)
{
final BPartnerId bpartnerId = extractBPartnerId(record);
if (bpartnerId != null)
{
bpartner(bpartnerId);
}
final UserId bpartnerContactId = extractBPartnerContactId(record);
if (bpartnerContactId != null)
{
bpartnerContact(bpartnerContactId);
}
}
private BPartnerId extractBPartnerId(final Object record)
{ | final Object bpartnerIdObj = InterfaceWrapperHelper.getValueOrNull(record, "C_BPartner_ID");
if (!(bpartnerIdObj instanceof Integer))
{
return null;
}
final int bpartnerRepoId = (Integer)bpartnerIdObj;
return BPartnerId.ofRepoIdOrNull(bpartnerRepoId);
}
private UserId extractBPartnerContactId(final Object record)
{
final Integer userIdObj = InterfaceWrapperHelper.getValueOrNull(record, "AD_User_ID");
if (!(userIdObj instanceof Integer))
{
return null;
}
final int userRepoId = userIdObj.intValue();
return UserId.ofRepoIdOrNull(userRepoId);
}
private Object getRecord()
{
return _record;
}
public MailTextBuilder customVariable(@NonNull final String name, @Nullable final String value)
{
return customVariable(name, TranslatableStrings.anyLanguage(value));
}
public MailTextBuilder customVariable(@NonNull final String name, @NonNull final ITranslatableString value)
{
_customVariables.put(name, value);
invalidateCache();
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTextBuilder.java | 1 |
请完成以下Java代码 | public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setIsDefaultESR (final boolean IsDefaultESR)
{
set_Value (COLUMNNAME_IsDefaultESR, IsDefaultESR);
}
@Override
public boolean isDefaultESR()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefaultESR);
}
@Override
public void setIsEsrAccount (final boolean IsEsrAccount)
{
set_Value (COLUMNNAME_IsEsrAccount, IsEsrAccount);
}
@Override
public boolean isEsrAccount()
{
return get_ValueAsBoolean(COLUMNNAME_IsEsrAccount);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQR_IBAN (final @Nullable java.lang.String QR_IBAN)
{
set_Value (COLUMNNAME_QR_IBAN, QR_IBAN);
}
@Override
public java.lang.String getQR_IBAN()
{
return get_ValueAsString(COLUMNNAME_QR_IBAN);
}
/**
* R_AvsAddr AD_Reference_ID=213
* Reference name: C_Payment AVS
*/
public static final int R_AVSADDR_AD_Reference_ID=213;
/** Match = Y */
public static final String R_AVSADDR_Match = "Y";
/** NoMatch = N */
public static final String R_AVSADDR_NoMatch = "N";
/** Unavailable = X */
public static final String R_AVSADDR_Unavailable = "X";
@Override
public void setR_AvsAddr (final @Nullable java.lang.String R_AvsAddr)
{
set_ValueNoCheck (COLUMNNAME_R_AvsAddr, R_AvsAddr);
}
@Override
public java.lang.String getR_AvsAddr()
{
return get_ValueAsString(COLUMNNAME_R_AvsAddr);
}
/**
* R_AvsZip AD_Reference_ID=213
* Reference name: C_Payment AVS
*/
public static final int R_AVSZIP_AD_Reference_ID=213;
/** Match = Y */
public static final String R_AVSZIP_Match = "Y";
/** NoMatch = N */
public static final String R_AVSZIP_NoMatch = "N"; | /** Unavailable = X */
public static final String R_AVSZIP_Unavailable = "X";
@Override
public void setR_AvsZip (final @Nullable java.lang.String R_AvsZip)
{
set_ValueNoCheck (COLUMNNAME_R_AvsZip, R_AvsZip);
}
@Override
public java.lang.String getR_AvsZip()
{
return get_ValueAsString(COLUMNNAME_R_AvsZip);
}
@Override
public void setRoutingNo (final @Nullable java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setSEPA_CreditorIdentifier (final @Nullable java.lang.String SEPA_CreditorIdentifier)
{
set_Value (COLUMNNAME_SEPA_CreditorIdentifier, SEPA_CreditorIdentifier);
}
@Override
public java.lang.String getSEPA_CreditorIdentifier()
{
return get_ValueAsString(COLUMNNAME_SEPA_CreditorIdentifier);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount.java | 1 |
请完成以下Java代码 | public <ImportRecordType> ImportProcessDescriptor register(
@NonNull final Class<ImportRecordType> modelImportClass,
@NonNull final Class<? extends IImportProcess<ImportRecordType>> importProcessClass)
{
final String importTableName = InterfaceWrapperHelper.getTableName(modelImportClass);
final ImportProcessDescriptor descriptor = ImportProcessDescriptor.builder()
.modelImportClass(ClassReference.of(modelImportClass))
.importTableName(importTableName)
.importProcessClass(ClassReference.of(importProcessClass))
.build();
descriptorsByImportTableName.put(importTableName, descriptor);
return descriptor;
} | public Class<? extends IImportProcess<?>> getImportProcessClassByModelImportClassOrNull(@NonNull final Class<?> modelImportClass)
{
final String importTableName = InterfaceWrapperHelper.getTableName(modelImportClass);
return getImportProcessClassByImportTableNameOrNull(importTableName);
}
public Class<? extends IImportProcess<?>> getImportProcessClassByImportTableNameOrNull(@NonNull final String importTableName)
{
final ImportProcessDescriptor descriptor = descriptorsByImportTableName.get(importTableName);
if (descriptor == null)
{
return null;
}
return descriptor.getImportProcessClass().getReferencedClass();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportProcessDescriptorsMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
} | public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java | 2 |
请完成以下Java代码 | 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代码 | private static Marshaller getContextMarshaller(Class clazz) {
Marshaller marshaller = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("jaxb.fragment", Boolean.TRUE);
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
return marshaller;
}
public static void example() {
try {
XMLExample xml = (XMLExample) JAXBHelper.getContextUnmarshaller(XMLExample.class).unmarshal(new File(XML_FILE_IN));
JAXBHelper.print(xml.toString());
ExampleHTML html = new ExampleHTML();
Body body = new Body();
CustomElement customElement = new CustomElement(); | NestedElement nested = new NestedElement();
CustomElement child = new CustomElement();
customElement.setValue("descendantOne: " + xml.getAncestor().getDescendantOne().getValue());
child.setValue("descendantThree: " + xml.getAncestor().getDescendantTwo().getDescendantThree().getValue());
nested.setCustomElement(child);
body.setCustomElement(customElement);
body.setNestedElement(nested);
Meta meta = new Meta();
meta.setTitle("example");
html.getHead().add(meta);
html.setBody(body);
JAXBHelper.getContextMarshaller(ExampleHTML.class).marshal(html, new File(JAXB_FILE_OUT));
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
}
} | repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xmlhtml\helpers\jaxb\JAXBHelper.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_Region getC_Region() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Region_ID, org.compiere.model.I_C_Region.class);
}
@Override
public void setC_Region(org.compiere.model.I_C_Region C_Region)
{
set_ValueFromPO(COLUMNNAME_C_Region_ID, org.compiere.model.I_C_Region.class, C_Region);
}
/** Set Region.
@param C_Region_ID
Identifies a geographical Region
*/
@Override
public void setC_Region_ID (int C_Region_ID)
{
if (C_Region_ID < 1)
set_Value (COLUMNNAME_C_Region_ID, null);
else
set_Value (COLUMNNAME_C_Region_ID, Integer.valueOf(C_Region_ID));
}
/** Get Region.
@return Identifies a geographical Region
*/
@Override
public int getC_Region_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Coordinates.
@param Coordinates
Location coordinate
*/
@Override
public void setCoordinates (java.lang.String Coordinates)
{
set_Value (COLUMNNAME_Coordinates, Coordinates);
}
/** Get Coordinates.
@return Location coordinate
*/
@Override
public java.lang.String getCoordinates ()
{
return (java.lang.String)get_Value(COLUMNNAME_Coordinates);
}
/** Set Locode.
@param Locode
Location code - UN/LOCODE
*/
@Override
public void setLocode (java.lang.String Locode)
{
set_Value (COLUMNNAME_Locode, Locode);
}
/** Get Locode.
@return Location code - UN/LOCODE
*/ | @Override
public java.lang.String getLocode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Locode);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set PLZ.
@param Postal
Postal code
*/
@Override
public void setPostal (java.lang.String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
/** Get PLZ.
@return Postal code
*/
@Override
public java.lang.String getPostal ()
{
return (java.lang.String)get_Value(COLUMNNAME_Postal);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_City.java | 1 |
请完成以下Java代码 | private <T> Optional<T> getModel(
@NonNull final PPOrderLineRow ppOrderLineRow,
@NonNull final Class<T> modelClass)
{
if (I_PP_Order.class.isAssignableFrom(modelClass))
{
if (ppOrderLineRow.getOrderId() == null)
{
return Optional.empty();
}
else
{
final I_PP_Order order = Services.get(IPPOrderDAO.class).getById(ppOrderLineRow.getOrderId());
return Optional.of(InterfaceWrapperHelper.create(order, modelClass));
}
}
else if (I_PP_Order_BOMLine.class.isAssignableFrom(modelClass))
{
if (ppOrderLineRow.getOrderBOMLineId() == null)
{
return Optional.empty();
}
else
{
final I_PP_Order_BOMLine orderBOMLine = Services.get(IPPOrderBOMDAO.class).getOrderBOMLineById(ppOrderLineRow.getOrderBOMLineId());
return Optional.of(InterfaceWrapperHelper.create(orderBOMLine, modelClass));
}
}
else
{
return Optional.empty();
}
}
@Override
public Stream<PPOrderLineRow> streamByIds(final DocumentIdsSelection documentIds)
{
return getData().streamByIds(documentIds);
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO: notifyRecordsChanged: identify the sub-trees which could be affected and invalidate only those
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() | {
if (docStatus.isCompleted())
{
return additionalRelatedProcessDescriptors;
}
else
{
return ImmutableList.of();
}
}
@Override
public void invalidateAll()
{
invalidateAllNoNotify();
ViewChangesCollector.getCurrentOrAutoflush()
.collectFullyChanged(this);
}
private void invalidateAllNoNotify()
{
dataSupplier.invalidate();
}
private PPOrderLinesViewData getData()
{
return dataSupplier.getData();
}
@Override
public boolean isConsiderTableRelatedProcessDescriptors(@NonNull final ProcessHandlerType processHandlerType, final @NonNull DocumentIdsSelection selectedRowIds)
{
return ProcessHandlerType.equals(processHandlerType, HUReportProcessInstancesRepository.PROCESS_HANDLER_TYPE);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UomId implements RepoIdAware
{
public static final UomId EACH = new UomId(100);
@JsonCreator
public static UomId ofRepoId(final int repoId)
{
if (repoId == EACH.repoId)
{
return EACH;
}
else
{
return new UomId(repoId);
}
}
@Nullable
public static UomId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final UomId uomId)
{
return uomId != null ? uomId.getRepoId() : -1;
}
public static Optional<UomId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
int repoId;
private UomId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_UOM_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final UomId id1, @Nullable final UomId id2)
{
return Objects.equals(id1, id2);
}
@NonNull
@SafeVarargs
public static <T> UomId getCommonUomIdOfAll(
@NonNull final Function<T, UomId> getUomId,
@NonNull final String name,
@Nullable final T... objects)
{
if (objects == null || objects.length == 0)
{
throw new AdempiereException("No " + name + " provided");
}
else if (objects.length == 1 && objects[0] != null)
{
return getUomId.apply(objects[0]);
} | else
{
UomId commonUomId = null;
for (final T object : objects)
{
if (object == null)
{
continue;
}
final UomId uomId = getUomId.apply(object);
if (commonUomId == null)
{
commonUomId = uomId;
}
else if (!UomId.equals(commonUomId, uomId))
{
throw new AdempiereException("All given " + name + "(s) shall have the same UOM: " + Arrays.asList(objects));
}
}
if (commonUomId == null)
{
throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects));
}
return commonUomId;
}
}
public boolean isEach() {return EACH.equals(this);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UomId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void updateIntegration(Long id, Integer integration) {
UmsMember record=new UmsMember();
record.setId(id);
record.setIntegration(integration);
memberMapper.updateByPrimaryKeySelective(record);
memberCacheService.delMember(id);
}
@Override
public UserDetails loadUserByUsername(String username) {
UmsMember member = getByUsername(username);
if(member!=null){
return new MemberDetails(member);
}
throw new UsernameNotFoundException("用户名或密码错误");
}
@Override
public String login(String username, String password) {
String token = null;
//密码需要客户端加密后传递
try {
UserDetails userDetails = loadUserByUsername(username);
if(!passwordEncoder.matches(password,userDetails.getPassword())){
throw new BadCredentialsException("密码不正确");
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
token = jwtTokenUtil.generateToken(userDetails);
} catch (AuthenticationException e) {
LOGGER.warn("登录异常:{}", e.getMessage());
} | return token;
}
@Override
public String refreshToken(String token) {
return jwtTokenUtil.refreshHeadToken(token);
}
//对输入的验证码进行校验
private boolean verifyAuthCode(String authCode, String telephone){
if(StrUtil.isEmpty(authCode)){
return false;
}
String realAuthCode = memberCacheService.getAuthCode(telephone);
return authCode.equals(realAuthCode);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberServiceImpl.java | 2 |
请完成以下Java代码 | public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
super.init(ctx);
this.config = TbNodeUtils.convert(configuration, TbSnsNodeConfiguration.class);
AWSCredentials awsCredentials = new BasicAWSCredentials(this.config.getAccessKeyId(), this.config.getSecretAccessKey());
AWSStaticCredentialsProvider credProvider = new AWSStaticCredentialsProvider(awsCredentials);
try {
this.snsClient = AmazonSNSClient.builder()
.withCredentials(credProvider)
.withRegion(this.config.getRegion())
.withClientConfiguration(new ClientConfiguration()
.withConnectionTimeout(10000)
.withRequestTimeout(5000))
.build();
} catch (Exception e) {
throw new TbNodeException(e);
}
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
var tbMsg = ackIfNeeded(ctx, msg);
withCallback(publishMessageAsync(ctx, tbMsg),
m -> tellSuccess(ctx, m),
t -> tellFailure(ctx, processException(tbMsg, t), t));
}
private ListenableFuture<TbMsg> publishMessageAsync(TbContext ctx, TbMsg msg) {
return ctx.getExternalCallExecutor().executeAsync(() -> publishMessage(msg));
}
private TbMsg publishMessage(TbMsg msg) {
String topicArn = TbNodeUtils.processPattern(this.config.getTopicArnPattern(), msg);
PublishRequest publishRequest = new PublishRequest()
.withTopicArn(topicArn)
.withMessage(msg.getData());
PublishResult result = this.snsClient.publish(publishRequest);
return processPublishResult(msg, result);
}
private TbMsg processPublishResult(TbMsg origMsg, PublishResult result) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(MESSAGE_ID, result.getMessageId());
metaData.putValue(REQUEST_ID, result.getSdkResponseMetadata().getRequestId());
return origMsg.transform()
.metaData(metaData)
.build();
} | private TbMsg processException(TbMsg origMsg, Throwable t) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage());
return origMsg.transform()
.metaData(metaData)
.build();
}
@Override
public void destroy() {
if (this.snsClient != null) {
try {
this.snsClient.shutdown();
} catch (Exception e) {
log.error("Failed to shutdown SNS client during destroy()", e);
}
}
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\sns\TbSnsNode.java | 1 |
请完成以下Java代码 | public void setC_OrgAssignment_ID (int C_OrgAssignment_ID)
{
if (C_OrgAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrgAssignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrgAssignment_ID, Integer.valueOf(C_OrgAssignment_ID));
}
/** Get Org Assignment.
@return Assigment to (transaction) Organization
*/
public int getC_OrgAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_OrgAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
} | /** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrgAssignment.java | 1 |
请完成以下Java代码 | public String getPassword() {
return user.getPassword();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.<GrantedAuthority>singletonList(new SimpleGrantedAuthority("User"));
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true; | }
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public AppUser getAppUser() {
return user;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\security\AppUserPrincipal.java | 1 |
请完成以下Java代码 | public void setM_AttributeSearch_ID (int M_AttributeSearch_ID)
{
if (M_AttributeSearch_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, Integer.valueOf(M_AttributeSearch_ID));
}
/** Get Attribute Search.
@return Common Search Attribute
*/
public int getM_AttributeSearch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSearch_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name) | {
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSearch.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InfoUpdateTrigger extends AbstractEventHandler<InstanceEvent> {
private static final Logger log = LoggerFactory.getLogger(InfoUpdateTrigger.class);
private final InfoUpdater infoUpdater;
private final IntervalCheck intervalCheck;
public InfoUpdateTrigger(InfoUpdater infoUpdater, Publisher<InstanceEvent> publisher, Duration updateInterval,
Duration infoLifetime, Duration maxBackoff) {
super(publisher, InstanceEvent.class);
this.infoUpdater = infoUpdater;
this.intervalCheck = new IntervalCheck("info", this::updateInfo, updateInterval, infoLifetime, maxBackoff);
}
@Override
protected Publisher<Void> handle(Flux<InstanceEvent> publisher) {
return publisher
.filter((event) -> event instanceof InstanceEndpointsDetectedEvent
|| event instanceof InstanceStatusChangedEvent || event instanceof InstanceRegistrationUpdatedEvent)
.flatMap((event) -> this.updateInfo(event.getInstance()));
}
protected Mono<Void> updateInfo(InstanceId instanceId) {
return this.infoUpdater.updateInfo(instanceId).onErrorResume((e) -> {
log.warn("Unexpected error while updating info for {}", instanceId, e);
return Mono.empty();
}).doFinally((s) -> this.intervalCheck.markAsChecked(instanceId));
}
@Override
public void start() { | super.start();
this.intervalCheck.start();
}
@Override
public void stop() {
super.stop();
this.intervalCheck.stop();
}
public void setInterval(Duration updateInterval) {
this.intervalCheck.setInterval(updateInterval);
}
public void setLifetime(Duration infoLifetime) {
this.intervalCheck.setMinRetention(infoLifetime);
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\InfoUpdateTrigger.java | 2 |
请完成以下Java代码 | public Workplace getById(final WorkplaceId id)
{
final Workplace workplace = byId.get(id);
if (workplace == null)
{
throw new AdempiereException("No workplace found for " + id);
}
return workplace;
}
public Collection<Workplace> getByIds(final Collection<WorkplaceId> ids)
{
if (ids.isEmpty())
{
return ImmutableList.of();
}
return ids.stream()
.map(this::getById) | .collect(ImmutableList.toImmutableList());
}
public boolean isEmpty()
{
return byId.isEmpty();
}
public SeqNo getNextSeqNo()
{
final Workplace workplace = getAllActive().stream().max(Comparator.comparing(v -> v.getSeqNo().toInt())).orElse(null);
return workplace != null ? workplace.getSeqNo().next() : SeqNo.ofInt(10);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceRepository.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 3000
spring:
cloud:
gateway:
routes:
- id: greeting-service
uri: http://localhost:4000/
predicates:
- Path=/**
filters | :
- RewritePath=//?(?<segment>.*), /v1.0/invoke/greeting/method/$\{segment} | repos\tutorials-master\spring-cloud-modules\spring-cloud-dapr\spring-cloud-dapr-gateway\src\main\resources\application-with-dapr.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public SaveMode getSaveMode() {
return this.saveMode;
}
public SessionIdGenerator getSessionIdGenerator() {
return this.sessionIdGenerator;
}
public RedisSerializer<Object> getDefaultRedisSerializer() {
return this.defaultRedisSerializer;
}
@Autowired
public void setRedisConnectionFactory(
@SpringSessionRedisConnectionFactory ObjectProvider<ReactiveRedisConnectionFactory> springSessionRedisConnectionFactory,
ObjectProvider<ReactiveRedisConnectionFactory> redisConnectionFactory) {
ReactiveRedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory
.getIfAvailable();
if (redisConnectionFactoryToUse == null) {
redisConnectionFactoryToUse = redisConnectionFactory.getObject();
}
this.redisConnectionFactory = redisConnectionFactoryToUse;
}
@Autowired(required = false)
@Qualifier("springSessionDefaultRedisSerializer")
public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) {
this.defaultRedisSerializer = defaultRedisSerializer;
}
@Autowired(required = false)
public void setSessionRepositoryCustomizer(
ObjectProvider<ReactiveSessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) {
this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList());
}
protected List<ReactiveSessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() {
return this.sessionRepositoryCustomizers;
} | protected ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() {
RedisSerializer<String> keySerializer = RedisSerializer.string();
RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer
: new JdkSerializationRedisSerializer();
RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(defaultSerializer)
.key(keySerializer)
.hashKey(keySerializer)
.build();
return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext);
}
public ReactiveRedisConnectionFactory getRedisConnectionFactory() {
return this.redisConnectionFactory;
}
@Autowired(required = false)
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\AbstractRedisWebSessionConfiguration.java | 2 |
请完成以下Java代码 | public class ConcatenatePdfs extends JavaProcess
{
private int printJobID;
private File outputFile = null;
private static final String SYSCONFIG_PdfDownloadPath = "de.metas.printing.process.ConcatenatePdfs.OutputDir";
@Override
protected void prepare()
{
if (I_C_Print_Job.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
printJobID = getRecord_ID();
}
}
@Override
protected String doIt() throws IOException, DocumentException
{
final Properties ctx = Env.getCtx();
final String trxName = ITrx.TRXNAME_None;
final String outputDir = Services.get(ISysConfigBL.class).getValue(SYSCONFIG_PdfDownloadPath);
final String fileName = "printjobs_" + getPinstanceId().getRepoId();
final I_C_Print_Job job = InterfaceWrapperHelper.create(ctx, printJobID, I_C_Print_Job.class, trxName);
final Iterator<I_C_Print_Job_Line> jobLines = Services.get(IPrintingDAO.class).retrievePrintJobLines(job);
if (!jobLines.hasNext())
{
return "No print job lines found. Pdf not generated.";
}
final File file;
if (Check.isEmpty(outputDir, true))
{
file = File.createTempFile(fileName, ".pdf");
}
else
{
file = new File(outputDir, fileName + ".pdf");
}
final Document document = new Document();
final FileOutputStream fos = new FileOutputStream(file, false); | final PdfCopy copy = new PdfCopy(document, fos);
document.open();
for (final I_C_Print_Job_Line jobLine : IteratorUtils.asIterable(jobLines))
{
final I_C_Printing_Queue queue = jobLine.getC_Printing_Queue();
Check.assume(queue != null, jobLine + " references a C_Printing_Queue");
final I_AD_Archive archive = queue.getAD_Archive();
Check.assume(archive != null, queue + " references an AD_Archive record");
final byte[] data = Services.get(IArchiveBL.class).getBinaryData(archive);
final PdfReader reader = new PdfReader(data);
for (int page = 0; page < reader.getNumberOfPages();)
{
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}
document.close();
fos.close();
outputFile = new File(outputDir);
return "@Created@ " + fileName + ".pdf" + " in " + outputDir;
}
public File getOutputFile()
{
return outputFile;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\ConcatenatePdfs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OxidAdaptor
{
private final static String SYS_CONFIG_OXID_USER_ID = "de.metas.rest_api.v2.shipping.c_olcand.OxidUserId";
private final IOLCandDAO olCandDAO = Services.get(IOLCandDAO.class);
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
public boolean isOxidOrder(@NonNull final OrderAndLineId orderAndLineId)
{
final int oxidUserId = sysConfigBL.getIntValue(SYS_CONFIG_OXID_USER_ID, -1);
if (oxidUserId <= 0)
{
return false;
}
final List<I_C_OLCand> olCands = olCandDAO.retrieveOLCands(orderAndLineId.getOrderLineId(), I_C_OLCand.class);
return olCands.size() > 0
&& olCands.get(0).getCreatedBy() == oxidUserId;
} | @Nullable
public String getContactEmail(@NonNull final ShipmentSchedule shipmentSchedule, @NonNull final BPartnerComposite composite)
{
if (shipmentSchedule.getBillContactId() == null)
{
return null;
}
final BPartnerContact contact = composite.extractContact(shipmentSchedule.getBillContactId())
.orElseThrow(() -> new AdempiereException("Unable to get the contact info from bPartnerComposite!")
.appendParametersToMessage()
.setParameter("composite.C_BPartner_ID", composite.getBpartner().getId())
.setParameter("AD_User_ID", shipmentSchedule.getBillContactId()));
return contact.getEmail();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\custom\OxidAdaptor.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Pet> getPets() {
return pets;
}
public void setPets(List<Pet> pets) {
this.pets = pets;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", pets=" + pets + "]";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-4\src\main\java\com\baeldung\mongodb\dbref\model\Person.java | 1 |
请完成以下Java代码 | public class Address {
private String locality;
private String city;
private String zip;
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZip() {
return zip;
} | public void setZip(String zip) {
this.zip = zip;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Address [locality=").append(locality).append(", city=").append(city).append(", zip=").append(zip).append("]");
return builder.toString();
}
public Address(String locality, String city, String zip) {
super();
this.locality = locality;
this.city = city;
this.zip = zip;
}
} | repos\tutorials-master\libraries-apache-commons-collections\src\main\java\com\baeldung\commons\collections\collectionutils\Address.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProcessDefinitionActionRequest extends RestActionRequest {
public static final String ACTION_SUSPEND = "suspend";
public static final String ACTION_ACTIVATE = "activate";
private boolean includeProcessInstances;
private Date date;
private String category;
public void setIncludeProcessInstances(boolean includeProcessInstances) {
this.includeProcessInstances = includeProcessInstances;
}
@ApiModelProperty(value = "Whether or not to suspend/activate running process-instances for this process-definition. If omitted, the process-instances are left in the state they are")
public boolean isIncludeProcessInstances() {
return includeProcessInstances;
}
public void setDate(Date date) {
this.date = date;
}
@ApiModelProperty(value = "Date (ISO-8601) when the suspension/activation should be executed. If omitted, the suspend/activation is effective immediately.") | public Date getDate() {
return date;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
@Override
@ApiModelProperty(value = "Action to perform: Either activate or suspend", example = "activate", required = true)
public String getAction() {
return super.getAction();
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionActionRequest.java | 2 |
请完成以下Java代码 | public class ValRuleAutoApplier
{
// services
private final IADTableDAO adTableDAO;
private final ADReferenceService adReferenceService;
@Getter private final String tableName;
private final ImmutableList<MinimalColumnInfo> columns;
@Builder
private ValRuleAutoApplier(
@NonNull final ADReferenceService adReferenceService,
@NonNull final IADTableDAO adTableDAO,
@NonNull final String tableName,
@NonNull final Collection<MinimalColumnInfo> columns)
{
this.adReferenceService = adReferenceService;
this.adTableDAO = adTableDAO;
this.tableName = tableName;
this.columns = ImmutableList.copyOf(columns);
}
/**
* @param recordModel the record in question; generally not yet be persisted in DB.
*/
public void handleRecord(@NonNull final Object recordModel)
{
columns.forEach((column) -> handleColumn(recordModel, column));
}
private void handleColumn(
@NonNull final Object recordModel,
@NonNull final MinimalColumnInfo column)
{
if (!InterfaceWrapperHelper.isNullOrEmpty(recordModel, column.getColumnName()))
{
return;
}
final int resultId = retrieveFirstValRuleResultId(recordModel, column, adReferenceService);
final int firstValidId = InterfaceWrapperHelper.getFirstValidIdByColumnName(column.getColumnName());
if (resultId >= firstValidId)
{
InterfaceWrapperHelper.setValue(recordModel, column.getColumnName(), resultId);
}
}
private static int retrieveFirstValRuleResultId(
@NonNull final Object recordModel,
@NonNull final MinimalColumnInfo column,
@NonNull final ADReferenceService adReferenceService)
{
final ADRefTable tableRefInfo = extractTableRefInfo(column, adReferenceService);
final IQueryBuilder<Object> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(tableRefInfo.getTableName());
final AdValRuleId adValRuleId = column.getAdValRuleId(); | if (adValRuleId != null)
{
final ValidationRuleQueryFilter<Object> validationRuleQueryFilter = new ValidationRuleQueryFilter<>(recordModel, adValRuleId);
queryBuilder.filter(validationRuleQueryFilter);
}
final IQuery<Object> query = queryBuilder
.create()
.setRequiredAccess(Access.READ);
final String orderByClause = tableRefInfo.getOrderByClause();
if (query instanceof TypedSqlQuery && !Check.isEmpty(orderByClause, true))
{
@SuppressWarnings("rawtypes") final TypedSqlQuery sqlQuery = (TypedSqlQuery)query;
sqlQuery.setOrderBy(orderByClause);
}
return query.firstId();
}
private static ADRefTable extractTableRefInfo(@NonNull final MinimalColumnInfo column, @NonNull final ADReferenceService adReferenceService)
{
final ReferenceId adReferenceValueId = column.getAdReferenceValueId();
return adReferenceValueId != null
? adReferenceService.retrieveTableRefInfo(adReferenceValueId)
: adReferenceService.getTableDirectRefInfo(column.getColumnName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\ValRuleAutoApplier.java | 1 |
请完成以下Java代码 | public boolean isShowInactiveValues ()
{
Object oo = get_Value(COLUMNNAME_ShowInactiveValues);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause | */
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_Table.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class IdmEngineResource {
@Autowired(required=false)
protected IdmRestApiInterceptor restApiInterceptor;
@ApiOperation(value = "Get IDM engine info", tags = { "Engine" }, notes = "Returns a read-only view of the engine that is used in this REST-service.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the engine info is returned."),
})
@GetMapping(value = "/idm-management/engine", produces = "application/json")
public EngineInfoResponse getEngineInfo() {
if (restApiInterceptor != null) {
restApiInterceptor.accessIdmManagementInfo();
}
EngineInfoResponse response = new EngineInfoResponse();
try {
IdmEngine idmEngine = IdmEngines.getDefaultIdmEngine(); | EngineInfo idmEngineInfo = IdmEngines.getIdmEngineInfo(idmEngine.getName());
if (idmEngineInfo != null) {
response.setName(idmEngineInfo.getName());
response.setResourceUrl(idmEngineInfo.getResourceUrl());
response.setException(idmEngineInfo.getException());
} else {
response.setName(idmEngine.getName());
}
} catch (Exception e) {
throw new FlowableException("Error retrieving idm engine info", e);
}
response.setVersion(IdmEngine.class.getPackage().getImplementationVersion());
return response;
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\management\IdmEngineResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION; | }
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java | 2 |
请完成以下Java代码 | public class SysUploadController {
@Autowired
private IOssFileService ossFileService;
/**
* 上传
* @param request
*/
@PostMapping(value = "/uploadMinio")
public Result<?> uploadMinio(HttpServletRequest request) throws Exception {
Result<?> result = new Result<>();
// 获取业务路径
String bizPath = request.getParameter("biz");
// 获取上传文件对象
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
// 文件安全校验,防止上传漏洞文件
SsrfFileTypeFilter.checkUploadFileType(file, bizPath);
if(oConvertUtils.isEmpty(bizPath)){
bizPath = "";
}
// 获取文件名
String orgName = file.getOriginalFilename(); | orgName = CommonUtils.getFileName(orgName);
String fileUrl = MinioUtil.upload(file,bizPath);
if(oConvertUtils.isEmpty(fileUrl)){
return Result.error("上传失败,请检查配置信息是否正确!");
}
//保存文件信息
OssFile minioFile = new OssFile();
minioFile.setFileName(orgName);
minioFile.setUrl(fileUrl);
ossFileService.save(minioFile);
result.setMessage(fileUrl);
result.setSuccess(true);
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysUploadController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Date orderDate;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
} | public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\java\com\baeldung\spring\data\jpa\nestedobject\Order.java | 2 |
请完成以下Java代码 | protected String doIt()
{
streamChangedRows()
.forEach(this::save);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
invalidateView();
}
private boolean hasChangedRows()
{
return streamChangedRows()
.findAny()
.isPresent();
}
private Stream<ProductsProposalRow> streamChangedRows()
{
return getSelectedRows()
.stream()
.filter(ProductsProposalRow::isChanged);
}
private void save(final ProductsProposalRow row)
{
if (!row.isChanged())
{
return;
}
final BigDecimal userEnteredPriceValue = row.getPrice().getUserEnteredPriceValue();
final ProductPriceId productPriceId;
//
// Update existing product price | if (row.getProductPriceId() != null)
{
productPriceId = row.getProductPriceId();
pricesListsRepo.updateProductPrice(UpdateProductPriceRequest.builder()
.productPriceId(productPriceId)
.priceStd(userEnteredPriceValue)
.build());
}
//
// Save a new product price which was copied from some other price list version
else if (row.getCopiedFromProductPriceId() != null)
{
productPriceId = pricesListsRepo.copyProductPrice(CopyProductPriceRequest.builder()
.copyFromProductPriceId(row.getCopiedFromProductPriceId())
.copyToPriceListVersionId(getPriceListVersionId())
.priceStd(userEnteredPriceValue)
.build());
}
else
{
throw new AdempiereException("Cannot save row: " + row);
}
//
// Refresh row
getView().patchViewRow(row.getId(), RowSaved.builder()
.productPriceId(productPriceId)
.price(row.getPrice().withPriceListPriceValue(userEnteredPriceValue))
.build());
}
private PriceListVersionId getPriceListVersionId()
{
return getView()
.getSinglePriceListVersionId()
.orElseThrow(() -> new AdempiereException("@NotFound@ @M_PriceList_Version_ID@"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\process\WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean shouldDeployResource(Resource newResource, Resource existingResource) {
return resourcesDiffer(newResource, existingResource);
}
@Override
public String determineDuplicateDeployment(CandidateDeployment candidateDeployment) {
return Context.getCommandContext()
.getDeploymentManager()
.findLatestDeploymentByName(candidateDeployment.getName())
.getId();
}
@Override
public Set<String> determineDeploymentsToResumeByProcessDefinitionKey(
String[] processDefinitionKeys) {
Set<String> deploymentIds = new HashSet<>();
List<ProcessDefinition> processDefinitions = Context.getCommandContext().getProcessDefinitionManager()
.findProcessDefinitionsByKeyIn(processDefinitionKeys);
for (ProcessDefinition processDefinition : processDefinitions) {
deploymentIds.add(processDefinition.getDeploymentId());
}
return deploymentIds;
}
@Override
public Set<String> determineDeploymentsToResumeByDeploymentName(CandidateDeployment candidateDeployment) {
List<Deployment> previousDeployments = processEngine.getRepositoryService()
.createDeploymentQuery()
.deploymentName(candidateDeployment.getName())
.list(); | Set<String> deploymentIds = new HashSet<>();
for (Deployment deployment : previousDeployments) {
deploymentIds.add(deployment.getId());
}
return deploymentIds;
}
protected boolean resourcesDiffer(Resource resource, Resource existing) {
byte[] bytes = resource.getBytes();
byte[] savedBytes = existing.getBytes();
return !Arrays.equals(bytes, savedBytes);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DefaultDeploymentHandler.java | 2 |
请完成以下Java代码 | private String buildTextSearchQuery(SqlQueryContext ctx, List<EntityKey> selectionMapping, String searchText) {
if (!StringUtils.isEmpty(searchText) && selectionMapping != null && !selectionMapping.isEmpty()) {
String lowerSearchText = searchText.toLowerCase() + "%";
List<String> searchPredicates = selectionMapping.stream()
.map(mapping -> alarmFieldColumnMap.get(mapping.getKey()))
.filter(Objects::nonNull)
.map(mapping -> {
String paramName = mapping + "_lowerSearchText";
ctx.addStringParameter(paramName, lowerSearchText);
return String.format("cast(%s as varchar) ILIKE concat('%%', :%s, '%%')", mapping, paramName);
}
).collect(Collectors.toList());
return String.format("%s", String.join(" or ", searchPredicates));
} else {
return "";
} | }
private String buildPermissionsQuery(TenantId tenantId, SqlQueryContext ctx) {
StringBuilder permissionsQuery = new StringBuilder();
ctx.addUuidParameter("permissions_tenant_id", tenantId.getId());
permissionsQuery.append(" a.tenant_id = :permissions_tenant_id and ea.tenant_id = :permissions_tenant_id ");
return permissionsQuery.toString();
}
private void addAndIfNeeded(StringBuilder wherePart, boolean addAnd) {
if (addAnd) {
wherePart.append(" and ");
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\DefaultAlarmQueryRepository.java | 1 |
请完成以下Java代码 | public void setPrimaryChange(final DocumentPath documentPath)
{
// do nothing
}
@Override
public Stream<DocumentChanges> streamOrderedDocumentChanges()
{
return Stream.empty();
}
@Override
public void collectValueChanged(final IDocumentFieldView documentField, final ReasonSupplier reason)
{
// do nothing
}
@Override
public void collectValueIfChanged(final IDocumentFieldView documentField, final Object valueOld, final ReasonSupplier reason)
{
// do nothing
}
@Override
public void collectReadonlyIfChanged(final IDocumentFieldView documentField, final LogicExpressionResult valueOld, final ReasonSupplier reason)
{
// do nothing
}
@Override
public void collectMandatoryIfChanged(final IDocumentFieldView documentField, final LogicExpressionResult valueOld, final ReasonSupplier reason)
{
// do nothing
}
@Override
public void collectDisplayedIfChanged(final IDocumentFieldView documentField, final LogicExpressionResult valueOld, final ReasonSupplier reason)
{
// do nothing
}
@Override
public void collectLookupValuesStaled(final IDocumentFieldView documentField, final ReasonSupplier reason)
{
// do nothing
}
@Override
public void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning)
{
// do nothing
}
@Override
public void collectFrom(final IDocumentChangesCollector fromCollector)
{
// do nothing
}
@Override | public Set<String> collectFrom(final Document document, final ReasonSupplier reason)
{
return ImmutableSet.of(); // nothing collected
}
@Override
public void collectDocumentValidStatusChanged(final DocumentPath documentPath, final DocumentValidStatus documentValidStatus)
{
// do nothing
}
@Override
public void collectValidStatus(final IDocumentFieldView documentField)
{
// do nothing
}
@Override
public void collectDocumentSaveStatusChanged(final DocumentPath documentPath, final DocumentSaveStatus documentSaveStatus)
{
// do nothing
}
@Override
public void collectDeleted(final DocumentPath documentPath)
{
// do nothing
}
@Override
public void collectStaleDetailId(final DocumentPath rootDocumentPath, final DetailId detailId)
{
// do nothing
}
@Override
public void collectAllowNew(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
// do nothing
}
@Override
public void collectAllowDelete(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
// do nothing
}
@Override
public void collectEvent(final IDocumentFieldChangedEvent event)
{
// do nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\NullDocumentChangesCollector.java | 1 |
请完成以下Java代码 | protected ProcessApplicationScriptEnvironment getProcessApplicationScriptEnvironment() {
if (processApplicationScriptEnvironment == null) {
synchronized (this) {
if (processApplicationScriptEnvironment == null) {
processApplicationScriptEnvironment = new ProcessApplicationScriptEnvironment(this);
}
}
}
return processApplicationScriptEnvironment;
}
public VariableSerializers getVariableSerializers() {
return variableSerializers;
}
public void setVariableSerializers(VariableSerializers variableSerializers) {
this.variableSerializers = variableSerializers;
}
/**
* <p>Provides the default Process Engine name to deploy to, if no Process Engine
* was defined in <code>processes.xml</code>.</p>
*
* @return the default deploy-to Process Engine name. | * The default value is "default".
*/
public String getDefaultDeployToEngineName() {
return defaultDeployToEngineName;
}
/**
* <p>Programmatically set the name of the Process Engine to deploy to if no Process Engine
* is defined in <code>processes.xml</code>. This allows to circumvent the "default" Process
* Engine name and set a custom one.</p>
*
* @param defaultDeployToEngineName
*/
protected void setDefaultDeployToEngineName(String defaultDeployToEngineName) {
this.defaultDeployToEngineName = defaultDeployToEngineName;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\AbstractProcessApplication.java | 1 |
请完成以下Java代码 | public class KerberosUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken
implements KerberosAuthentication {
private static final long serialVersionUID = 6327699460703504153L;
private final JaasSubjectHolder jaasSubjectHolder;
/**
* <p>
* Creates an authentication token that holds the username and password, and the
* Subject that the user will need to create new authentication tokens against other
* services.
* </p>
* @param principal
* @param credentials | * @param authorities
* @param subjectHolder
*/
public KerberosUsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities, JaasSubjectHolder subjectHolder) {
super(principal, credentials, authorities);
this.jaasSubjectHolder = subjectHolder;
}
@Override
public JaasSubjectHolder getJaasSubjectHolder() {
return this.jaasSubjectHolder;
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosUsernamePasswordAuthenticationToken.java | 1 |
请完成以下Java代码 | public Optional<BPartnerId> getBPartnerIdForModel(@NonNull final Object model)
{
return bpartnerBL.getBPartnerIdForModel(model);
}
public I_C_BPartner getBPartnerById(@NonNull final BPartnerId bpartnerId)
{
return bpartnerBL.getById(bpartnerId);
}
@Nullable
public BPartnerLocationId getBPartnerLocationId(@Nullable final BPartnerId bPartnerId, @NonNull final Object model)
{
final Integer locationId = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_C_BPartner_Location_ID);
return BPartnerLocationId.ofRepoIdOrNull(bPartnerId, locationId);
}
public Optional<Language> getBPartnerLanguage(@NonNull final I_C_BPartner bpartner)
{
return bpartnerBL.getLanguage(bpartner);
}
public BPartnerPrintFormatMap getBPartnerPrintFormats(final BPartnerId bpartnerId)
{
return bpartnerBL.getPrintFormats(bpartnerId);
}
@NonNull
public DefaultPrintFormats getDefaultPrintFormats(@NonNull final ClientId clientId)
{
return defaultPrintFormatsRepository.getByClientId(clientId);
}
@NonNull
public AdProcessId getReportProcessIdByPrintFormatId(@NonNull final PrintFormatId printFormatId)
{
return getReportProcessIdByPrintFormatIdIfExists(printFormatId).get();
}
@NonNull
public ExplainedOptional<AdProcessId> getReportProcessIdByPrintFormatIdIfExists(@NonNull final PrintFormatId printFormatId)
{
final PrintFormat printFormat = printFormatRepository.getById(printFormatId);
final AdProcessId reportProcessId = printFormat.getReportProcessId();
return reportProcessId != null
? ExplainedOptional.of(reportProcessId)
: ExplainedOptional.emptyBecause("No report process defined by " + printFormat);
} | @NonNull
public I_C_DocType getDocTypeById(@NonNull final DocTypeId docTypeId)
{
return docTypeDAO.getById(docTypeId);
}
public PrintCopies getDocumentCopies(
@Nullable final I_C_DocType docType,
@Nullable final BPPrintFormatQuery bpPrintFormatQuery)
{
final BPPrintFormat bpPrintFormat = bpPrintFormatQuery == null ? null : bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery);
if(bpPrintFormat == null)
{
return getDocumentCopies(docType);
}
return bpPrintFormat.getPrintCopies();
}
private static PrintCopies getDocumentCopies(@Nullable final I_C_DocType docType)
{
return docType != null && !InterfaceWrapperHelper.isNull(docType, I_C_DocType.COLUMNNAME_DocumentCopies)
? PrintCopies.ofInt(docType.getDocumentCopies())
: PrintCopies.ONE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportAdvisorUtil.java | 1 |
请完成以下Spring Boot application配置 | spring.application.name=nacos-provider
spring.cloud.nacos.discovery.server-addr=localhost:8848
#nacos.discovery.server-addr=localhost:8848
#spring.main.allow-bean-definition-overriding=true
dubbo.scan.base-packages=com.quick.nacos
dubbo.registry.address=spring-cloud://localhost:8848
dubbo.protocol.id=dubbo
dubbo.registry.id=nacos
dubbo.protocol.name=dubbo
dubbo.protocol.port=-1
dubbo.consumer.check=false
dubbo.application.id= | dubbo-nacos-provider
dubbo.application.name=dubbo-nacos-provider
dubbo.cloud.subscribed-services=nacos-provider
logging.level.root=info
service.version=1.0.0
service.name=helloService | repos\spring-boot-quick-master\quick-dubbo-nacos\service\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setCreatedby_Print_Job_Instructions (int Createdby_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Createdby_Print_Job_Instructions, Integer.valueOf(Createdby_Print_Job_Instructions));
}
@Override
public int getCreatedby_Print_Job_Instructions()
{
return get_ValueAsInt(COLUMNNAME_Createdby_Print_Job_Instructions);
}
@Override
public void setCreated_Print_Job_Instructions (java.sql.Timestamp Created_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Created_Print_Job_Instructions, Created_Print_Job_Instructions);
}
@Override
public java.sql.Timestamp getCreated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Created_Print_Job_Instructions);
}
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName);
}
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setPrintServiceTray (java.lang.String PrintServiceTray)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray);
}
@Override
public java.lang.String getPrintServiceTray()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override | public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setUpdatedby_Print_Job_Instructions (int Updatedby_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updatedby_Print_Job_Instructions, Integer.valueOf(Updatedby_Print_Job_Instructions));
}
@Override
public int getUpdatedby_Print_Job_Instructions()
{
return get_ValueAsInt(COLUMNNAME_Updatedby_Print_Job_Instructions);
}
@Override
public void setUpdated_Print_Job_Instructions (java.sql.Timestamp Updated_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updated_Print_Job_Instructions, Updated_Print_Job_Instructions);
}
@Override
public java.sql.Timestamp getUpdated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Updated_Print_Job_Instructions);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_PrintInfo_v.java | 1 |
请完成以下Java代码 | public void execute() {
commandExecutor.execute(new RestartProcessInstancesCmd(commandExecutor, this));
}
public Batch executeAsync() {
return commandExecutor.execute(new RestartProcessInstancesBatchCmd(commandExecutor, this));
}
public List<AbstractProcessInstanceModificationCommand> getInstructions() {
return instructions;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
@Override
public RestartProcessInstanceBuilder processInstanceIds(String... processInstanceIds) {
this.processInstanceIds.addAll(Arrays.asList(processInstanceIds));
return this;
}
@Override
public RestartProcessInstanceBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery query) {
this.query = query;
return this;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return query;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
this.instructions = instructions;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public RestartProcessInstanceBuilder processInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds.addAll(processInstanceIds);
return this;
}
@Override
public RestartProcessInstanceBuilder initialSetOfVariables() {
this.initialVariables = true;
return this;
}
public boolean isInitialVariables() {
return initialVariables;
} | @Override
public RestartProcessInstanceBuilder skipCustomListeners() {
this.skipCustomListeners = true;
return this;
}
@Override
public RestartProcessInstanceBuilder skipIoMappings() {
this.skipIoMappings = true;
return this;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
@Override
public RestartProcessInstanceBuilder withoutBusinessKey() {
withoutBusinessKey = true;
return this;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstanceBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class OpenTelemetryPropagationConfigurations {
/**
* Propagates traces but no baggage.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(name = "management.tracing.baggage.enabled", havingValue = false)
@EnableConfigurationProperties(TracingProperties.class)
static class PropagationWithoutBaggage {
@Bean
@ConditionalOnEnabledTracingExport
TextMapPropagator textMapPropagator(TracingProperties properties) {
return CompositeTextMapPropagator.create(properties.getPropagation(), null);
}
}
/**
* Propagates traces and baggage.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(name = "management.tracing.baggage.enabled", matchIfMissing = true)
@EnableConfigurationProperties(TracingProperties.class)
static class PropagationWithBaggage {
private final TracingProperties tracingProperties;
PropagationWithBaggage(TracingProperties tracingProperties) {
this.tracingProperties = tracingProperties;
}
@Bean
@ConditionalOnEnabledTracingExport
TextMapPropagator textMapPropagatorWithBaggage(OtelCurrentTraceContext otelCurrentTraceContext) { | List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields();
List<String> tagFields = this.tracingProperties.getBaggage().getTagFields();
BaggageTextMapPropagator baggagePropagator = new BaggageTextMapPropagator(remoteFields,
new OtelBaggageManager(otelCurrentTraceContext, remoteFields, tagFields));
return CompositeTextMapPropagator.create(this.tracingProperties.getPropagation(), baggagePropagator);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBooleanProperty(name = "management.tracing.baggage.correlation.enabled", matchIfMissing = true)
Slf4JBaggageEventListener otelSlf4JBaggageEventListener() {
return new Slf4JBaggageEventListener(this.tracingProperties.getBaggage().getCorrelation().getFields());
}
}
/**
* Propagates neither traces nor baggage.
*/
@Configuration(proxyBeanMethods = false)
static class NoPropagation {
@Bean
@ConditionalOnMissingBean
TextMapPropagator noopTextMapPropagator() {
return TextMapPropagator.noop();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryPropagationConfigurations.java | 2 |
请完成以下Java代码 | public String getTimerElementKey() {
return timerElementKey;
}
public void setTimerElementKey(String timerElementKey) {
this.timerElementKey = timerElementKey;
}
public boolean isFollowUpJobCreated() {
return followUpJobCreated;
}
public void setFollowUpJobCreated(boolean followUpJobCreated) {
this.followUpJobCreated = followUpJobCreated;
}
public String getTimerElementSecondaryKey() {
return timerElementSecondaryKey;
}
public void setTimerElementSecondaryKey(String timerElementSecondaryKey) {
this.timerElementSecondaryKey = timerElementSecondaryKey;
}
@Override
public String toCanonicalString() {
String canonicalString = timerElementKey;
if (timerElementSecondaryKey != null) {
canonicalString += JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_TASK_LISTENER_PREFIX + timerElementSecondaryKey; | }
if (followUpJobCreated) {
canonicalString += JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_PROPERTY_FOLLOW_UP_JOB_CREATED;
}
return canonicalString;
}
}
public void onDelete(TimerJobConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerEventJobHandler.java | 1 |
请完成以下Java代码 | public ProcessEngineException multipleTenantsForCamundaFormDefinitionKeyException(String camundaFormDefinitionKey) {
return new ProcessEngineException(exceptionMessage(
"109",
"Cannot resolve a unique Camunda Form definition for key '{}' because it exists for multiple tenants.",
camundaFormDefinitionKey
));
}
public void concurrentModificationFailureIgnored(DbOperation operation) {
logDebug(
"110",
"An OptimisticLockingListener attempted to ignore a failure of: {}. "
+ "Since the database aborted the transaction, ignoring the failure "
+ "is not possible and an exception is thrown instead.",
operation
);
}
// exception code 110 is already taken. See requiredCamundaAdminOrPermissionException() for details.
public static List<SQLException> findRelatedSqlExceptions(Throwable exception) {
List<SQLException> sqlExceptionList = new ArrayList<>();
Throwable cause = exception;
do {
if (cause instanceof SQLException) {
SQLException sqlEx = (SQLException) cause;
sqlExceptionList.add(sqlEx);
while (sqlEx.getNextException() != null) {
sqlExceptionList.add(sqlEx.getNextException());
sqlEx = sqlEx.getNextException();
}
}
cause = cause.getCause();
} while (cause != null);
return sqlExceptionList;
}
public static String collectExceptionMessages(Throwable cause) {
StringBuilder message = new StringBuilder(cause.getMessage()); | //collect real SQL exception messages in case of batch processing
Throwable exCause = cause;
do {
if (exCause instanceof BatchExecutorException) {
final List<SQLException> relatedSqlExceptions = findRelatedSqlExceptions(exCause);
StringBuilder sb = new StringBuilder();
for (SQLException sqlException : relatedSqlExceptions) {
sb.append(sqlException).append("\n");
}
message.append("\n").append(sb);
}
exCause = exCause.getCause();
} while (exCause != null);
return message.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\EnginePersistenceLogger.java | 1 |
请完成以下Java代码 | public List<FeelCustomFunctionProvider> getFeelCustomFunctionProviders() {
return feelCustomFunctionProviders;
}
/**
* Set a list of FEEL Custom Function Providers.
*
* @param feelCustomFunctionProviders a list of FEEL Custom Function Providers
*/
public void setFeelCustomFunctionProviders(List<FeelCustomFunctionProvider> feelCustomFunctionProviders) {
this.feelCustomFunctionProviders = feelCustomFunctionProviders;
}
/**
* Set a list of FEEL Custom Function Providers.
*
* @param feelCustomFunctionProviders a list of FEEL Custom Function Providers
* @return this
*/
public DefaultDmnEngineConfiguration feelCustomFunctionProviders(List<FeelCustomFunctionProvider> feelCustomFunctionProviders) {
setFeelCustomFunctionProviders(feelCustomFunctionProviders);
return this;
}
/**
* @return whether FEEL legacy behavior is enabled or not
*/
public boolean isEnableFeelLegacyBehavior() {
return enableFeelLegacyBehavior;
}
/**
* Controls whether the FEEL legacy behavior is enabled or not
*
* @param enableFeelLegacyBehavior the FEEL legacy behavior | */
public void setEnableFeelLegacyBehavior(boolean enableFeelLegacyBehavior) {
this.enableFeelLegacyBehavior = enableFeelLegacyBehavior;
}
/**
* Controls whether the FEEL legacy behavior is enabled or not
*
* @param enableFeelLegacyBehavior the FEEL legacy behavior
* @return this
*/
public DefaultDmnEngineConfiguration enableFeelLegacyBehavior(boolean enableFeelLegacyBehavior) {
setEnableFeelLegacyBehavior(enableFeelLegacyBehavior);
return this;
}
/**
* @return whether blank table outputs are swallowed or returned as {@code null}.
*/
public boolean isReturnBlankTableOutputAsNull() {
return returnBlankTableOutputAsNull;
}
/**
* Controls whether blank table outputs are swallowed or returned as {@code null}.
*
* @param returnBlankTableOutputAsNull toggles whether blank table outputs are swallowed or returned as {@code null}.
* @return this
*/
public DefaultDmnEngineConfiguration setReturnBlankTableOutputAsNull(boolean returnBlankTableOutputAsNull) {
this.returnBlankTableOutputAsNull = returnBlankTableOutputAsNull;
return this;
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnEngineConfiguration.java | 1 |
请完成以下Java代码 | public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
/** Get Warehouse.
@return Storage Warehouse and Service Point
*/
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Promotion Code.
@param PromotionCode
User entered promotion code at sales time
*/
public void setPromotionCode (String PromotionCode)
{
set_Value (COLUMNNAME_PromotionCode, PromotionCode);
}
/** Get Promotion Code.
@return User entered promotion code at sales time
*/
public String getPromotionCode ()
{
return (String)get_Value(COLUMNNAME_PromotionCode);
}
/** Set Usage Counter.
@param PromotionCounter
Usage counter
*/
public void setPromotionCounter (int PromotionCounter)
{
set_ValueNoCheck (COLUMNNAME_PromotionCounter, Integer.valueOf(PromotionCounter));
}
/** Get Usage Counter.
@return Usage counter
*/
public int getPromotionCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionCounter);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usage Limit.
@param PromotionUsageLimit
Maximum usage limit
*/
public void setPromotionUsageLimit (int PromotionUsageLimit)
{
set_Value (COLUMNNAME_PromotionUsageLimit, Integer.valueOf(PromotionUsageLimit));
}
/** Get Usage Limit.
@return Maximum usage limit
*/
public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first | */
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请完成以下Java代码 | public void setProductName (java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
/** Get Produktname.
@return Name des Produktes
*/
@Override
public java.lang.String getProductName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductName);
}
/** Set Produktschlüssel.
@param ProductValue
Schlüssel des Produktes
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{
throw new IllegalArgumentException ("ProductValue is virtual column"); }
/** Get Produktschlüssel.
@return Schlüssel des Produktes
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab. | @param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Product.java | 1 |
请完成以下Java代码 | public void setTradDt(XMLGregorianCalendar value) {
this.tradDt = value;
}
/**
* Gets the value of the intrBkSttlmDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getIntrBkSttlmDt() {
return intrBkSttlmDt;
}
/**
* Sets the value of the intrBkSttlmDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setIntrBkSttlmDt(XMLGregorianCalendar value) {
this.intrBkSttlmDt = value;
}
/**
* Gets the value of the startDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartDt() {
return startDt;
}
/**
* Sets the value of the startDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartDt(XMLGregorianCalendar value) {
this.startDt = value;
}
/**
* Gets the value of the endDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndDt() {
return endDt;
}
/**
* Sets the value of the endDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndDt(XMLGregorianCalendar value) {
this.endDt = value;
}
/**
* Gets the value of the txDtTm property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTxDtTm() {
return txDtTm;
} | /**
* Sets the value of the txDtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTxDtTm(XMLGregorianCalendar value) {
this.txDtTm = value;
}
/**
* Gets the value of the prtry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryDate2 }
*
*
*/
public List<ProprietaryDate2> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryDate2>();
}
return this.prtry;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionDates2.java | 1 |
请完成以下Java代码 | public void setM_Ingredients_ID (final int M_Ingredients_ID)
{
if (M_Ingredients_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Ingredients_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Ingredients_ID, M_Ingredients_ID);
}
@Override
public int getM_Ingredients_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Ingredients_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_Product_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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Ingredients.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ITemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() { | final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
final List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Bean(name = "multipartResolver")
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\spring\web\config\WebConfig.java | 2 |
请完成以下Java代码 | public class OfficeUtils {
private static final Logger logger = LoggerFactory.getLogger(OfficeUtils.class);
private static final String POI_INVALID_PASSWORD_MSG = "password";
/**
* 判断office(word,excel,ppt)文件是否受密码保护
*
* @param path office文件路径
* @return 是否受密码保护
*/
public static boolean isPwdProtected(String path) {
InputStream propStream = null;
try {
propStream = Files.newInputStream(Paths.get(path));
ExtractorFactory.createExtractor(propStream);
} catch (IOException | EncryptedDocumentException e) {
if (e.getMessage().toLowerCase().contains(POI_INVALID_PASSWORD_MSG)) {
return true;
}
} catch (Exception e) {
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
for (Throwable throwable : throwableArray) {
if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) {
if (e.getMessage().toLowerCase().contains(POI_INVALID_PASSWORD_MSG)) {
return true;
}
}
}
}finally {
if(propStream!=null) {//如果文件输入流不是null
try {
propStream.close();//关闭文件输入流
} catch (IOException e) {
logger.error("Failed to close input stream for file: {}", path, e);
}
}
}
return false;
}
/**
* 判断office文件是否可打开(兼容)
* | * @param path office文件路径
* @param password 文件密码
* @return 是否可打开(兼容)
*/
public static synchronized boolean isCompatible(String path, String password) {
InputStream propStream = null;
try {
propStream = Files.newInputStream(Paths.get(path));
Biff8EncryptionKey.setCurrentUserPassword(password);
ExtractorFactory.createExtractor(propStream);
} catch (Exception e) {
return false;
} finally {
Biff8EncryptionKey.setCurrentUserPassword(null);
if(propStream!=null) {//如果文件输入流不是null
try {
propStream.close();//关闭文件输入流
} catch (IOException e) {
logger.error("Failed to close input stream for file: {}", path, e);
}
}
}
return true;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\utils\OfficeUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addUnpackedItem(@NonNull final IPackingItem item)
{
addItem(PackingSlot.UNPACKED, item);
}
public void addUnpackedItems(final Collection<? extends IPackingItem> items)
{
addItems(PackingSlot.UNPACKED, items);
}
public void addItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem item)
{
items.put(slot, item);
}
public void addItems(@NonNull final PackingSlot slot, @NonNull final Collection<? extends IPackingItem> items)
{
this.items.putAll(slot, items);
}
public PackingItemsMap copy()
{
return new PackingItemsMap(this);
}
public List<IPackingItem> removeBySlot(@NonNull final PackingSlot slot)
{
return items.removeAll(slot);
}
public void removeUnpackedItem(@NonNull final IPackingItem itemToRemove)
{
final boolean removed = items.remove(PackingSlot.UNPACKED, itemToRemove);
if (!removed)
{
throw new AdempiereException("Unpacked item " + itemToRemove + " was not found in: " + items.get(PackingSlot.UNPACKED));
}
}
/**
* Append given <code>itemPacked</code> to existing packed items
*
* @param slot
* @param packedItem
*/
public void appendPackedItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem packedItem)
{
for (final IPackingItem item : items.get(slot))
{
// add new item into the list only if is a real new item
// NOTE: should be only one item with same grouping key
if (PackingItemGroupingKey.equals(item.getGroupingKey(), packedItem.getGroupingKey()))
{
item.addParts(packedItem);
return;
}
}
//
// No matching existing packed item where our item could be added was found | // => add it here as a new item
addItem(slot, packedItem);
}
/**
*
* @return true if there exists at least one packed item
*/
public boolean hasPackedItems()
{
return streamPackedItems().findAny().isPresent();
}
public boolean hasPackedItemsMatching(@NonNull final Predicate<IPackingItem> predicate)
{
return streamPackedItems().anyMatch(predicate);
}
public Stream<IPackingItem> streamPackedItems()
{
return items
.entries()
.stream()
.filter(e -> !e.getKey().isUnpacked())
.map(e -> e.getValue());
}
/**
*
* @return true if there exists at least one unpacked item
*/
public boolean hasUnpackedItems()
{
return !items.get(PackingSlot.UNPACKED).isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemsMap.java | 2 |
请完成以下Java代码 | public static OrgId ofRepoIdOrNull(final int repoId)
{
if (repoId == ANY.repoId)
{
return ANY;
}
else if (repoId == MAIN.repoId)
{
return MAIN;
}
else if (repoId < 0)
{
return null;
}
else
{
return new OrgId(repoId);
}
}
/**
* @return {@link #ANY} even if the given {@code repoId} is less than zero.
*/
public static OrgId ofRepoIdOrAny(final int repoId)
{
final OrgId orgId = ofRepoIdOrNull(repoId);
return orgId != null ? orgId : ANY;
}
public static Optional<OrgId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : -1;
}
public static int toRepoIdOrAny(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : ANY.repoId;
} | @Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isAny()
{
return repoId == Env.CTXVALUE_AD_Org_ID_Any;
}
/**
* @return {@code true} if the org in question is not {@code *} (i.e. "ANY"), but a specific organisation's ID
*/
public boolean isRegular()
{
return !isAny();
}
public void ifRegular(@NonNull final Consumer<OrgId> consumer)
{
if (isRegular())
{
consumer.accept(this);
}
}
@Nullable
public OrgId asRegularOrNull() {return isRegular() ? this : null;}
public static boolean equals(@Nullable final OrgId id1, @Nullable final OrgId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgId.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.