instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public void play() {
GolfTournament golfTournament = this.golfTournament;
if (isNotFinished(golfTournament)) {
playHole(golfTournament);
finish(golfTournament);
}
}
// end::play[]
private synchronized void playHole(@NonNull GolfTournament golfTournament) {
GolfCourse golfCourse = golfTournament.getGolfCourse();
Set<Integer> occupiedHoles = new HashSet<>();
for (GolfTournament.Pairing pairing : golfTournament) {
int hole = pairing.nextHole();
if (!occupiedHoles.contains(hole)) {
if (golfCourse.isValidHoleNumber(hole)) {
occupiedHoles.add(hole);
pairing.setHole(hole);
updateScore(this::calculateRunningScore, pairing.getPlayerOne());
updateScore(this::calculateRunningScore, pairing.getPlayerTwo());
}
}
}
}
private Golfer updateScore(@NonNull Function<Integer, Integer> scoreFunction, @NonNull Golfer player) {
player.setScore(scoreFunction.apply(player.getScore()));
this.golferService.update(player);
return player;
|
}
private int calculateFinalScore(@Nullable Integer scoreRelativeToPar) {
int finalScore = scoreRelativeToPar != null ? scoreRelativeToPar : 0;
int parForCourse = getGolfTournament()
.map(GolfTournament::getGolfCourse)
.map(GolfCourse::getParForCourse)
.orElse(GolfCourse.STANDARD_PAR_FOR_COURSE);
return parForCourse + finalScore;
}
private int calculateRunningScore(@Nullable Integer currentScore) {
int runningScore = currentScore != null ? currentScore : 0;
int scoreDelta = this.random.nextInt(SCORE_DELTA_BOUND);
scoreDelta *= this.random.nextBoolean() ? -1 : 1;
return runningScore + scoreDelta;
}
private void finish(@NonNull GolfTournament golfTournament) {
for (GolfTournament.Pairing pairing : golfTournament) {
if (pairing.signScorecard()) {
updateScore(this::calculateFinalScore, pairing.getPlayerOne());
updateScore(this::calculateFinalScore, pairing.getPlayerTwo());
}
}
}
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\service\PgaTourService.java
| 2
|
请完成以下Java代码
|
public int getAPI_Request_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID);
}
@Override
public void setAPI_Request_Audit_Log_ID (final int API_Request_Audit_Log_ID)
{
if (API_Request_Audit_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_API_Request_Audit_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_API_Request_Audit_Log_ID, API_Request_Audit_Log_ID);
}
@Override
public int getAPI_Request_Audit_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_Log_ID);
}
@Override
public void setLogmessage (final @Nullable java.lang.String Logmessage)
{
set_Value (COLUMNNAME_Logmessage, Logmessage);
}
@Override
public java.lang.String getLogmessage()
{
return get_ValueAsString(COLUMNNAME_Logmessage);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
|
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTrxName (final @Nullable java.lang.String TrxName)
{
set_Value (COLUMNNAME_TrxName, TrxName);
}
@Override
public java.lang.String getTrxName()
{
return get_ValueAsString(COLUMNNAME_TrxName);
}
/**
* Type AD_Reference_ID=541329
* Reference name: TypeList
*/
public static final int TYPE_AD_Reference_ID=541329;
/** Created = Created */
public static final String TYPE_Created = "Created";
/** Updated = Updated */
public static final String TYPE_Updated = "Updated";
/** Deleted = Deleted */
public static final String TYPE_Deleted = "Deleted";
@Override
public void setType (final @Nullable java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit_Log.java
| 1
|
请完成以下Java代码
|
public boolean isApplyHandler(final I_C_Printing_Queue queueItem, final I_AD_Archive IGNORED)
{
if (queueItem.getAD_User_ID() <= 0)
{
return false;
}
// return true if the item's user has a C_Printing_Queue_Recipient
final I_AD_User queueUser = Services.get(IUserDAO.class).getByIdInTrx(UserId.ofRepoId(queueItem.getAD_User_ID()), I_AD_User.class);
return queueUser.getC_Printing_Queue_Recipient_ID() > 0;
}
/**
* Updates the given {@code item}, see the javadoc of this class for further details.
*/
@Override
public void afterEnqueueAfterSave(final I_C_Printing_Queue queueItem, final I_AD_Archive IGNORED)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final List<I_C_Printing_Queue_Recipient> recipients = queryBL.createQueryBuilder(I_C_Printing_Queue_Recipient.class, queueItem)
.addOnlyActiveRecordsFilter() // we must retrieve ALL; the caller shall decide
.addEqualsFilter(I_C_Printing_Queue_Recipient.COLUMN_C_Printing_Queue_ID, queueItem.getC_Printing_Queue_ID())
.create()
.list();
if (recipients.isEmpty())
{
resetToUserPrintingQueueRecipient(queueItem);
}
else
{
for (final I_C_Printing_Queue_Recipient queueRecipient : recipients)
{
final I_AD_User userToPrint = InterfaceWrapperHelper.loadOutOfTrx(queueRecipient.getAD_User_ToPrint_ID(), I_AD_User.class);
final int newUserToPrintId = getEffectiveUserToPrint(userToPrint, new HashSet<>()).getAD_User_ID();
queueRecipient.setAD_User_ToPrint_ID(newUserToPrintId);
InterfaceWrapperHelper.save(queueRecipient);
}
}
}
|
private void resetToUserPrintingQueueRecipient(final I_C_Printing_Queue queueItem)
{
final I_AD_User itemUser = Services.get(IUserDAO.class).getByIdInTrx(UserId.ofRepoId(queueItem.getAD_User_ID()), I_AD_User.class);
final int userToPrintId = getEffectiveUserToPrint(itemUser, new HashSet<>()).getAD_User_ID();
final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class);
printingQueueBL.setPrintoutForOtherUsers(queueItem, ImmutableSet.of(userToPrintId));
}
private I_AD_User getEffectiveUserToPrint(final I_AD_User user, final Set<Integer> alreadSeenUserIDs)
{
if (user.getC_Printing_Queue_Recipient_ID() <= 0)
{
return user;
}
if (!alreadSeenUserIDs.add(user.getC_Printing_Queue_Recipient_ID()))
{
return user;
}
return getEffectiveUserToPrint(user.getC_Printing_Queue_Recipient(), alreadSeenUserIDs);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\spi\impl\C_Printing_Queue_RecipientHandler.java
| 1
|
请完成以下Java代码
|
public int getMobileUI_UserProfile_Picking_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID);
}
/**
* PickingJobField AD_Reference_ID=541850
* Reference name: PickingJobField_Options
*/
public static final int PICKINGJOBFIELD_AD_Reference_ID=541850;
/** DocumentNo = DocumentNo */
public static final String PICKINGJOBFIELD_DocumentNo = "DocumentNo";
/** Customer = Customer */
public static final String PICKINGJOBFIELD_Customer = "Customer";
/** Delivery Address = ShipToLocation */
public static final String PICKINGJOBFIELD_DeliveryAddress = "ShipToLocation";
/** Date Ready = PreparationDate */
public static final String PICKINGJOBFIELD_DateReady = "PreparationDate";
/** Handover Location = HandoverLocation */
public static final String PICKINGJOBFIELD_HandoverLocation = "HandoverLocation";
/** Rüstplatz Nr. = Setup_Place_No */
public static final String PICKINGJOBFIELD_RuestplatzNr = "Setup_Place_No";
/** Product = Product */
public static final String PICKINGJOBFIELD_Product = "Product";
/** QtyToDeliver = QtyToDeliver */
public static final String PICKINGJOBFIELD_QtyToDeliver = "QtyToDeliver";
@Override
public void setPickingJobField (final java.lang.String PickingJobField)
{
set_Value (COLUMNNAME_PickingJobField, PickingJobField);
}
@Override
public java.lang.String getPickingJobField()
{
return get_ValueAsString(COLUMNNAME_PickingJobField);
}
@Override
public void setPickingProfile_PickingJobConfig_ID (final int PickingProfile_PickingJobConfig_ID)
{
if (PickingProfile_PickingJobConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_PickingProfile_PickingJobConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PickingProfile_PickingJobConfig_ID, PickingProfile_PickingJobConfig_ID);
|
}
@Override
public int getPickingProfile_PickingJobConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_PickingProfile_PickingJobConfig_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\picking\model\X_PickingProfile_PickingJobConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Date getLockTime() {
return lockTime;
}
@Override
public void setLockTime(Date lockTime) {
this.lockTime = lockTime;
}
@Override
public String getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
|
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName().replace("EntityImpl", "")).append("[")
.append("id=").append(id)
.append(", eventType=").append(eventType);
if (activityId != null) {
sb.append(", activityId=").append(activityId);
}
if (executionId != null) {
sb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId);
} else if (scopeId != null) {
sb.append(", scopeId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeType=").append(scopeType)
.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeDefinitionId != null) {
if (scopeId == null) {
sb.append(", scopeType=").append(scopeType);
}
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (scopeDefinitionKey != null) {
sb.append(", scopeDefinitionKey=").append(scopeDefinitionKey);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\entity\EventSubscriptionEntityImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Shipping createShipping(Order order) {
var provider = selectProvider(order);
return new Shipping(
order,
provider,
ShippingStatus.CREATED,
List.of(new ShippingEvent(
clock.instant(),
ShippingStatus.CREATED,
"Shipping created")));
}
private ShippingProvider selectProvider(Order order) {
int totalItems = order.items().stream()
.map(OrderItem::quantity)
.reduce(0, Integer::sum);
|
if ( totalItems < 5) {
return ShippingProvider.DHL;
}
else if ( totalItems < 10) {
return ShippingProvider.FedEx;
}
else {
return ShippingProvider.UPS;
}
}
public Shipping updateStatus(Shipping shipping, ShippingStatus status) {
return shipping.toStatus(status, clock.instant(), "Shipping status updated");
}
}
|
repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\services\ShippingService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void markBankStatementLinesAsProcessed(final BankStatementId bankStatementId)
{
final boolean processed = true;
bankStatementDAO.updateBankStatementLinesProcessedFlag(bankStatementId, processed);
}
public void deleteFactsForBankStatement(final I_C_BankStatement bankStatement)
{
factAcctDAO.deleteForDocumentModel(bankStatement);
}
public void unreconcile(@NonNull final List<I_C_BankStatementLine> lines)
{
bankStatementBL.unreconcile(lines);
}
|
public String getMsg(final AdMessageKey adMessage)
{
return msgBL.getMsg(Env.getCtx(), adMessage);
}
public String getMsg(final Properties ctx, final AdMessageKey adMessage)
{
return msgBL.getMsg(ctx, adMessage);
}
public String translate(final Properties ctx, final String adMessageOrColumnName)
{
return msgBL.translate(ctx, adMessageOrColumnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\BankStatementDocumentHandlerRequiredServicesFacade.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public PackagingIdentificationType getPackagingIdentification() {
return packagingIdentification;
}
/**
* Sets the value of the packagingIdentification property.
*
* @param value
* allowed object is
* {@link PackagingIdentificationType }
*
*/
public void setPackagingIdentification(PackagingIdentificationType value) {
this.packagingIdentification = value;
}
/**
* Planning Quantity Gets the value of the planningQuantity 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 planningQuantity property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlanningQuantity().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PlanningQuantityType }
*
*
*/
public List<PlanningQuantityType> getPlanningQuantity() {
if (planningQuantity == null) {
planningQuantity = new ArrayList<PlanningQuantityType>();
}
return this.planningQuantity;
}
/**
* Gets the value of the forecastListLineItemExtension property.
*
* @return
|
* possible object is
* {@link ForecastListLineItemExtensionType }
*
*/
public ForecastListLineItemExtensionType getForecastListLineItemExtension() {
return forecastListLineItemExtension;
}
/**
* Sets the value of the forecastListLineItemExtension property.
*
* @param value
* allowed object is
* {@link ForecastListLineItemExtensionType }
*
*/
public void setForecastListLineItemExtension(ForecastListLineItemExtensionType value) {
this.forecastListLineItemExtension = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ForecastListLineItemType.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VariableInstanceEntity other = (VariableInstanceEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
/**
* @param isTransient
* <code>true</code>, if the variable is not stored in the data base.
* Default is <code>false</code>.
*/
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
/**
* @return <code>true</code>, if the variable is transient. A transient
* variable is not stored in the data base.
*/
public boolean isTransient() {
return isTransient;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
|
if (processInstanceId != null){
referenceIdAndClass.put(processInstanceId, ExecutionEntity.class);
}
if (executionId != null){
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
if (caseInstanceId != null){
referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class);
}
if (caseExecutionId != null){
referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class);
}
if (getByteArrayValueId() != null){
referenceIdAndClass.put(getByteArrayValueId(), ByteArrayEntity.class);
}
return referenceIdAndClass;
}
/**
*
* @return <code>true</code> <code>processDefinitionId</code> is introduced in 7.13,
* the check is used to created missing history at {@link LegacyBehavior#createMissingHistoricVariables(org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl) LegacyBehavior#createMissingHistoricVariables}
*/
public boolean wasCreatedBefore713() {
return this.getProcessDefinitionId() == null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceEntity.java
| 1
|
请完成以下Java代码
|
public class HistoricBatchQueryImpl extends AbstractQuery<HistoricBatchQuery, HistoricBatch> implements HistoricBatchQuery {
private static final long serialVersionUID = 1L;
protected String batchId;
protected String type;
protected Boolean completed;
protected boolean isTenantIdSet = false;
protected String[] tenantIds;
public HistoricBatchQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
public HistoricBatchQuery batchId(String batchId) {
ensureNotNull("Batch id", batchId);
this.batchId = batchId;
return this;
}
public String getBatchId() {
return batchId;
}
public HistoricBatchQuery type(String type) {
ensureNotNull("Type", type);
this.type = type;
return this;
}
public HistoricBatchQuery completed(boolean completed) {
this.completed = completed;
return this;
}
public HistoricBatchQuery tenantIdIn(String... tenantIds) {
ensureNotNull("tenantIds", (Object[]) tenantIds);
this.tenantIds = tenantIds;
isTenantIdSet = true;
return this;
}
public String[] getTenantIds() {
return tenantIds;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public HistoricBatchQuery withoutTenantId() {
this.tenantIds = null;
isTenantIdSet = true;
return this;
}
public String getType() {
return type;
}
public HistoricBatchQuery orderById() {
return orderBy(HistoricBatchQueryProperty.ID);
|
}
public HistoricBatchQuery orderByStartTime() {
return orderBy(HistoricBatchQueryProperty.START_TIME);
}
public HistoricBatchQuery orderByEndTime() {
return orderBy(HistoricBatchQueryProperty.END_TIME);
}
@Override
public HistoricBatchQuery orderByTenantId() {
return orderBy(HistoricBatchQueryProperty.TENANT_ID);
}
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricBatchManager()
.findBatchCountByQueryCriteria(this);
}
@Override
public List<HistoricBatch> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricBatchManager()
.findBatchesByQueryCriteria(this, page);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\HistoricBatchQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private TransactionResult handleResult(final OrderId orderId, @NonNull final BPartnerId bPartnerId,
@NonNull final CreditPassConfig config, @NonNull final CreditScore creditScore)
{
final CreditScore finalCreditScore = convertResult(config, creditScore);
final TransactionResult result = transactionResultService.createAndSaveResult(finalCreditScore, bPartnerId, orderId);
if (finalCreditScore.isConverted())
{
sendNotification(config, result.getTransactionResultId());
}
return result;
}
public boolean hasConfigForPartnerId(
@NonNull final BPartnerId bPartnerId)
{
boolean hasConfig = false;
final CreditPassConfig config = creditPassConfigRepository.getConfigByBPartnerId(bPartnerId);
if (config != null)
{
hasConfig = true;
}
return hasConfig;
}
private CreditScore convertResult(@NonNull final CreditPassConfig config, @NonNull final CreditScore creditScore)
{
if (creditScore.getResultCode() == ResultCode.M)
{
return CreditScore.builder()
.requestLogData(creditScore.getRequestLogData())
.resultCode(creditScore.getResultCode())
.resultCodeOverride(config.getResultCode())
.resultText(creditScore.getResultText())
.paymentRule(creditScore.getPaymentRule())
.requestPrice(creditScore.getRequestPrice())
.currency(creditScore.getCurrency())
|
.converted(true)
.build();
}
return creditScore;
}
private void sendNotification(@NonNull final CreditPassConfig config, @NonNull final TransactionResultId transactionResultId)
{
final String message = Services.get(IMsgBL.class).getMsg(Env.getCtx(), CreditPassConstants.CREDITPASS_NOTIFICATION_MESSAGE_KEY);
final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder()
.recipientUserId(config.getNotificationUserId())
.contentPlain(message)
.targetAction(UserNotificationRequest.TargetRecordAction.of(TableRecordReference.of(I_CS_Transaction_Result.Table_Name, transactionResultId.getRepoId())))
.build();
Services.get(INotificationBL.class).sendAfterCommit(userNotificationRequest);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\service\CreditPassTransactionService.java
| 2
|
请完成以下Java代码
|
public class TbGetTelemetryNodeConfiguration implements NodeConfiguration<TbGetTelemetryNodeConfiguration> {
public static final int MAX_FETCH_SIZE = 1000;
private int startInterval;
private int endInterval;
private String startIntervalPattern;
private String endIntervalPattern;
private boolean useMetadataIntervalPatterns;
private String startIntervalTimeUnit;
private String endIntervalTimeUnit;
private FetchMode fetchMode; //FIRST, LAST, ALL
private Direction orderBy; //ASC, DESC
private Aggregation aggregation; //MIN, MAX, AVG, SUM, COUNT, NONE;
private int limit;
private List<String> latestTsKeyNames;
|
@Override
public TbGetTelemetryNodeConfiguration defaultConfiguration() {
TbGetTelemetryNodeConfiguration configuration = new TbGetTelemetryNodeConfiguration();
configuration.setLatestTsKeyNames(Collections.emptyList());
configuration.setFetchMode(FetchMode.FIRST);
configuration.setStartIntervalTimeUnit(TimeUnit.MINUTES.name());
configuration.setStartInterval(2);
configuration.setEndIntervalTimeUnit(TimeUnit.MINUTES.name());
configuration.setEndInterval(1);
configuration.setUseMetadataIntervalPatterns(false);
configuration.setStartIntervalPattern("");
configuration.setEndIntervalPattern("");
configuration.setOrderBy(Direction.ASC);
configuration.setAggregation(Aggregation.NONE);
configuration.setLimit(MAX_FETCH_SIZE);
return configuration;
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbGetTelemetryNodeConfiguration.java
| 1
|
请完成以下Java代码
|
public static void replaceOne() {
Document replaceDocument = new Document();
replaceDocument.append("student_id", 8764)
.append("student_name", "Paul Starc")
.append("address", "Hostel 3")
.append("age", 18)
.append("roll_no", 199406);
UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
System.out.println("updateResult:- " + updateResult);
}
public static void findOneAndReplace() {
Document replaceDocument = new Document();
replaceDocument.append("student_id", 8764)
.append("student_name", "Paul Starc")
.append("address", "Hostel 4")
.append("age", 18)
.append("roll_no", 199406);
Document sort = new Document("roll_no", 1);
Document projection = new Document("_id", 0).append("student_id", 1)
.append("address", 1);
Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
.sort(sort)
.projection(projection)
.returnDocument(ReturnDocument.AFTER));
System.out.println("resultDocument:- " + resultDocument);
}
public static void findOneAndUpdate() {
Document sort = new Document("roll_no", 1);
Document projection = new Document("_id", 0).append("student_id", 1)
.append("address", 1);
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
.sort(sort)
.projection(projection)
.returnDocument(ReturnDocument.AFTER));
System.out.println("resultDocument:- " + resultDocument);
}
public static void setup() {
if (mongoClient == null) {
|
mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student");
}
}
public static void main(String[] args) {
//
// Connect to cluster (default is localhost:27017)
//
setup();
//
// Update a document using updateOne method
//
updateOne();
//
// Update documents using updateMany method
//
updateMany();
//
// replace a document using replaceOne method
//
replaceOne();
//
// replace a document using findOneAndReplace method
//
findOneAndReplace();
//
// Update a document using findOneAndUpdate method
//
findOneAndUpdate();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\update\UpdateFields.java
| 1
|
请完成以下Java代码
|
protected boolean getEnableAuthorities() {
return this.enableAuthorities;
}
/**
* Enables loading of authorities (roles) from the authorities table. Defaults to true
*/
public void setEnableAuthorities(boolean enableAuthorities) {
this.enableAuthorities = enableAuthorities;
}
protected boolean getEnableGroups() {
return this.enableGroups;
}
/**
* Enables support for group authorities. Defaults to false
* @param enableGroups
*/
public void setEnableGroups(boolean enableGroups) {
this.enableGroups = enableGroups;
|
}
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
private JdbcTemplate getJdbc() {
JdbcTemplate template = getJdbcTemplate();
Assert.notNull(template, "JdbcTemplate cannot be null");
return template;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\jdbc\JdbcDaoImpl.java
| 1
|
请完成以下Java代码
|
private Method getMainMethod(Thread thread) {
StackTraceElement[] stackTrace = thread.getStackTrace();
for (int i = stackTrace.length - 1; i >= 0; i--) {
StackTraceElement element = stackTrace[i];
if ("main".equals(element.getMethodName()) && !isLoaderClass(element.getClassName())) {
Method method = getMainMethod(element);
if (method != null) {
return method;
}
}
}
throw new IllegalStateException("Unable to find main method");
}
private boolean isLoaderClass(String className) {
return className.startsWith("org.springframework.boot.loader.");
}
private @Nullable Method getMainMethod(StackTraceElement element) {
try {
Class<?> elementClass = Class.forName(element.getClassName());
Method method = getMainMethod(elementClass);
if (Modifier.isStatic(method.getModifiers())) {
return method;
}
}
catch (Exception ex) {
// Ignore
}
return null;
}
private static Method getMainMethod(Class<?> clazz) throws Exception {
try {
return clazz.getDeclaredMethod("main", String[].class);
}
catch (NoSuchMethodException ex) {
return clazz.getDeclaredMethod("main");
}
}
|
/**
* Returns the actual main method.
* @return the main method
*/
Method getMethod() {
return this.method;
}
/**
* Return the name of the declaring class.
* @return the declaring class name
*/
String getDeclaringClassName() {
return this.method.getDeclaringClass().getName();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\MainMethod.java
| 1
|
请完成以下Java代码
|
public ValueExpression resolveVariable(String variableName) {
int scope = scriptContext.getAttributesScope(variableName);
if (scope != -1) {
Object value = scriptContext.getAttribute(variableName, scope);
if (value instanceof ValueExpression) {
// Just return the existing ValueExpression
return (ValueExpression) value;
} else {
// Create a new ValueExpression based on the variable value
return expressionFactory.createValueExpression(value, Object.class);
}
}
return null;
}
@Override
public ValueExpression setVariable(String name, ValueExpression value) {
ValueExpression previousValue = resolveVariable(name);
scriptContext.setAttribute(name, value, ScriptContext.ENGINE_SCOPE);
return previousValue;
}
}
/**
* FunctionMapper that uses the ScriptContext to resolve functions in EL.
*
*/
private class ScriptContextFunctionMapper extends FunctionMapper {
private ScriptContext scriptContext;
|
ScriptContextFunctionMapper(ScriptContext ctx) {
this.scriptContext = ctx;
}
private String getFullFunctionName(String prefix, String localName) {
return prefix + ":" + localName;
}
@Override
public Method resolveFunction(String prefix, String localName) {
String functionName = getFullFunctionName(prefix, localName);
int scope = scriptContext.getAttributesScope(functionName);
if (scope != -1) {
// Methods are added as variables in the ScriptScope
Object attributeValue = scriptContext.getAttribute(functionName);
return (attributeValue instanceof Method) ? (Method) attributeValue : null;
} else {
return null;
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngine.java
| 1
|
请完成以下Java代码
|
public class ListAndSetAddBenchmark {
public static void main(String[] args) throws IOException, RunnerException {
Options opt = new OptionsBuilder()
.include(ListAndSetAddBenchmark.class.getSimpleName())
.forks(1)
.addProfiler("gc")
.build();
new Runner(opt).run();
}
@Benchmark
public void addElementToArrayList(Params param, Blackhole blackhole) {
param.arrayList.clear();
for (int i = 0; i < param.addNumber; i++) {
blackhole.consume(param.arrayList.add(i));
}
}
|
@Benchmark
public void addElementToHashSet(Params param, Blackhole blackhole) {
param.hashSet.clear();
for (int i = 0; i < param.addNumber; i++) {
blackhole.consume(param.hashSet.add(i));
}
}
@State(Scope.Benchmark)
public static class Params {
public int addNumber = 10000000;
public List<Integer> arrayList = new ArrayList<>();
public Set<Integer> hashSet = new HashSet<>();
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\listandset\benchmark\ListAndSetAddBenchmark.java
| 1
|
请完成以下Java代码
|
public Map<ProductId, Product> retrieveProductsByIds(final Set<ProductId> productIds)
{
final ImmutableList<Product> products = productRepository.getByIds(productIds);
return Maps.uniqueIndex(products, Product::getId);
}
public I_C_UOM getUomById(final UomId uomId)
{
return uomsCache.computeIfAbsent(uomId, uomDAO::getById);
}
public I_C_UOM getUomByProductId(final ProductId productId)
{
final UomId uomId = getProductById(productId).getUomId();
return getUomById(uomId);
}
private void warmUpUOMs(final Collection<UomId> uomIds)
{
if (uomIds.isEmpty())
{
return;
}
|
CollectionUtils.getAllOrLoad(uomsCache, uomIds, this::retrieveUOMsByIds);
}
private Map<UomId, I_C_UOM> retrieveUOMsByIds(final Collection<UomId> uomIds)
{
final List<I_C_UOM> uoms = uomDAO.getByIds(uomIds);
return Maps.uniqueIndex(uoms, uom -> UomId.ofRepoId(uom.getC_UOM_ID()));
}
public ImmutableSet<WarehouseId> getAllActiveWarehouseIds()
{
return warehouseRepository.getAllActiveIds();
}
public Warehouse getWarehouseById(@NonNull final WarehouseId warehouseId)
{
return warehouseRepository.getById(warehouseId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowCache.java
| 1
|
请完成以下Java代码
|
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
EndEvent endEvent = (EndEvent) baseElement;
addEventProperties(endEvent, propertiesNode);
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
EndEvent endEvent = new EndEvent();
String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode);
if (STENCIL_EVENT_END_ERROR.equals(stencilId)) {
convertJsonToErrorDefinition(elementNode, endEvent);
} else if (STENCIL_EVENT_END_CANCEL.equals(stencilId)) {
CancelEventDefinition eventDefinition = new CancelEventDefinition();
endEvent.getEventDefinitions().add(eventDefinition);
} else if (STENCIL_EVENT_END_TERMINATE.equals(stencilId)) {
TerminateEventDefinition eventDefinition = new TerminateEventDefinition();
|
String terminateAllStringValue = getPropertyValueAsString(PROPERTY_TERMINATE_ALL, elementNode);
if (StringUtils.isNotEmpty(terminateAllStringValue)) {
eventDefinition.setTerminateAll("true".equals(terminateAllStringValue));
}
String terminateMiStringValue = getPropertyValueAsString(PROPERTY_TERMINATE_MULTI_INSTANCE, elementNode);
if (StringUtils.isNotEmpty(terminateMiStringValue)) {
eventDefinition.setTerminateMultiInstance("true".equals(terminateMiStringValue));
}
endEvent.getEventDefinitions().add(eventDefinition);
}
return endEvent;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\EndEventJsonConverter.java
| 1
|
请完成以下Java代码
|
public class X_HR_ListType extends PO implements I_HR_ListType, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_HR_ListType (Properties ctx, int HR_ListType_ID, String trxName)
{
super (ctx, HR_ListType_ID, trxName);
/** if (HR_ListType_ID == 0)
{
setHR_ListType_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_HR_ListType (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_HR_ListType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** 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 Payroll List Type.
@param HR_ListType_ID Payroll List Type */
public void setHR_ListType_ID (int HR_ListType_ID)
{
if (HR_ListType_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID));
|
}
/** Get Payroll List Type.
@return Payroll List Type */
public int getHR_ListType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java
| 1
|
请完成以下Java代码
|
private PrintingClient createPrintingClient()
{
final Context ctx = Context.getContext();
ctx.addSource(new EnvContext());
ctx.addSource(new SysConfigContext());
// the swing client can always use the loopback endpoint, as it has direct (DB-)access to the server
ctx.setProperty(Context.CTX_PrintConnectionEndpoint, LoopbackPrintConnectionEndpoint.class.getName());
// ctx.setProperty(Context.CTX_UserInterface, new SwingUserInterface(this));
logger.info("Context: " + ctx);
//
// Create printing client, but don't start it by default
final boolean start = false;
final PrintingClient client = new PrintingClient(start);
return client;
}
@Override
public boolean isStarted()
{
return client.isStarted();
}
@Override
public void start()
{
client.start();
}
|
@Override
public void stop()
{
client.stop();
}
@Override
public void destroy()
{
if (client != null)
{
client.destroy();
}
client = null;
}
@Override
public void restart()
{
stop();
start();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.embedded-client\src\main\java\de\metas\printing\client\impl\PrintingClientDelegate.java
| 1
|
请完成以下Java代码
|
public class Order {
private UUID id;
private Type type;
private int internalAudit;
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
|
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
|
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\domain\Order.java
| 1
|
请完成以下Java代码
|
public static boolean checkLuhn(String cardNumber) {
int sum = 0;
try {
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
if ((cardNumber.length() - i) % 2 == 0) {
digit = doubleAndSumDigits(digit);
}
sum += digit;
}
LOGGER.info("Luhn Algorithm sum of digits is " + sum);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException - Card number probably contained some non-numeric characters, returning false");
return false;
} catch (NullPointerException e) {
LOGGER.error("Null pointer - Card number was probably null, returning false");
return false;
}
boolean result = sum % 10 == 0;
LOGGER.info("Luhn check result (sum divisible by 10): " + result);
return result;
}
/*
* We apply this method to every second number from the right of the card
* number. First, we double the digit, then we sum the digits.
*
* Note: subtracting 9 is equivalent to doubling and summing digits (when
|
* starting with a single digit) 0-4 -> produce single digit when doubled
* 5*2 = 10 -> 1+0 = 1 = 10-9
* 6*2 = 12 -> 1+3 = 3 = 12-9
* 7*2 = 14 -> 1+5 = 5 = 14-9
* 8*2 = 16 -> 1+7 = 7 = 16-9
* 9*2 = 18 -> 1+9 = 9 = 18-9
*/
public static int doubleAndSumDigits(int digit) {
int ret = digit * 2;
if (ret > 9) {
ret -= 9;
}
return ret;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\luhn\LuhnChecker.java
| 1
|
请完成以下Java代码
|
public final class GenerateOneTimeTokenFilter extends OncePerRequestFilter {
public static final String DEFAULT_GENERATE_URL = "/ott/generate";
private final OneTimeTokenService tokenService;
private final OneTimeTokenGenerationSuccessHandler tokenGenerationSuccessHandler;
private RequestMatcher requestMatcher = PathPatternRequestMatcher.withDefaults()
.matcher(HttpMethod.POST, DEFAULT_GENERATE_URL);
private GenerateOneTimeTokenRequestResolver requestResolver = new DefaultGenerateOneTimeTokenRequestResolver();
public GenerateOneTimeTokenFilter(OneTimeTokenService tokenService,
OneTimeTokenGenerationSuccessHandler tokenGenerationSuccessHandler) {
Assert.notNull(tokenService, "tokenService cannot be null");
Assert.notNull(tokenGenerationSuccessHandler, "tokenGenerationSuccessHandler cannot be null");
this.tokenService = tokenService;
this.tokenGenerationSuccessHandler = tokenGenerationSuccessHandler;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (!this.requestMatcher.matches(request)) {
filterChain.doFilter(request, response);
return;
}
GenerateOneTimeTokenRequest generateRequest = this.requestResolver.resolve(request);
if (generateRequest == null) {
filterChain.doFilter(request, response);
return;
}
OneTimeToken ott = this.tokenService.generate(generateRequest);
this.tokenGenerationSuccessHandler.handle(request, response, ott);
}
/**
|
* Use the given {@link RequestMatcher} to match the request.
* @param requestMatcher
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
/**
* Use the given {@link GenerateOneTimeTokenRequestResolver} to resolve
* {@link GenerateOneTimeTokenRequest}.
* @param requestResolver {@link GenerateOneTimeTokenRequestResolver}
* @since 6.5
*/
public void setRequestResolver(GenerateOneTimeTokenRequestResolver requestResolver) {
Assert.notNull(requestResolver, "requestResolver cannot be null");
this.requestResolver = requestResolver;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\ott\GenerateOneTimeTokenFilter.java
| 1
|
请完成以下Java代码
|
public static void stop() throws IOException {
client.close();
buffer = null;
}
private EchoClient() {
try {
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
buffer = ByteBuffer.allocate(256);
} catch (IOException e) {
e.printStackTrace();
}
}
public String sendMessage(String msg) {
buffer = ByteBuffer.wrap(msg.getBytes());
|
String response = null;
try {
client.write(buffer);
buffer.clear();
client.read(buffer);
response = new String(buffer.array()).trim();
System.out.println("response=" + response);
buffer.clear();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
|
repos\tutorials-master\core-java-modules\core-java-nio\src\main\java\com\baeldung\selector\EchoClient.java
| 1
|
请完成以下Java代码
|
private void setCollapsed(boolean collapsed)
{
warehouseStockPanel.setCollapsed(collapsed);
}
public java.awt.Component getComponent()
{
return warehouseStockPanel;
}
/**
* Wrapper class for each of the detail tabs.
*
* @author ad
*
*/
private class InfoProductDetailTab
{
private final IInfoProductDetail detail;
private final Component component;
private final String titleTrl;
private Object refreshKeyLast;
public InfoProductDetailTab(String title, final IInfoProductDetail detail, final Component component)
{
super();
this.titleTrl = Services.get(IMsgBL.class).translate(Env.getCtx(), title);
this.detail = detail;
if(component instanceof JTable)
{
// Wrap the JTable in a scroll pane, else the table header won't be visible
// see http://stackoverflow.com/questions/2320812/jtable-wont-show-column-headers
this.component = new CScrollPane(component);
}
else
{
this.component = component;
}
}
public String getTitleTrl()
{
return titleTrl;
}
public Component getComponent()
{
return component;
}
/**
* Refresh (always)
*/
public void refresh()
{
final int M_Product_ID = getM_Product_ID();
final int M_Warehouse_ID = getM_Warehouse_ID();
final int M_PriceList_Version_ID = getM_PriceList_Version_ID();
final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID();
|
final boolean onlyIfStale = false;
refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
}
/**
* Refresh only if stale
*/
private void refreshIfStale()
{
final int M_Product_ID = getM_Product_ID();
final int M_Warehouse_ID = getM_Warehouse_ID();
final int M_PriceList_Version_ID = getM_PriceList_Version_ID();
final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID();
final boolean onlyIfStale = true;
refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
}
private void refresh(boolean onlyIfStale, int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID)
{
final ArrayKey refreshKey = Util.mkKey(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
if (!onlyIfStale || !isStale(refreshKey))
{
detail.refresh(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
}
this.refreshKeyLast = refreshKey;
}
private boolean isStale(final ArrayKey refreshKey)
{
return !Check.equals(refreshKey, refreshKeyLast);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductDetails.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
ObjectValueExpression other = (ObjectValueExpression) obj;
if (type != other.type) {
return false;
}
return (object == other.object || (object != null && object.equals(other.object)));
}
return false;
}
@Override
public int hashCode() {
return object == null ? 0 : object.hashCode();
}
/**
* Answer the wrapped object, coerced to the expected type.
*/
@Override
public Object getValue(ELContext context) {
return converter.convert(object, type);
}
/**
* Answer <code>null</code>.
*/
@Override
public String getExpressionString() {
return null;
}
/**
* Answer <code>false</code>.
*/
@Override
public boolean isLiteralText() {
return false;
}
|
/**
* Answer <code>null</code>.
*/
@Override
public Class<?> getType(ELContext context) {
return null;
}
/**
* Answer <code>true</code>.
*/
@Override
public boolean isReadOnly(ELContext context) {
return true;
}
/**
* Throw an exception.
*/
@Override
public void setValue(ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", "<object value expression>"));
}
@Override
public String toString() {
return "ValueExpression(" + object + ")";
}
@Override
public Class<?> getExpectedType() {
return type;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\ObjectValueExpression.java
| 1
|
请完成以下Java代码
|
public Builder setBestBeforeDate(final LocalDate bestBeforeDate)
{
this.bestBeforeDate = bestBeforeDate;
return this;
}
private LocalDate getBestBeforeDate()
{
return bestBeforeDate;
}
public Builder setLocator(final LocatorId locatorId, final String locatorCaption)
{
this.locatorId = locatorId;
this.locatorCaption = locatorCaption;
return this;
}
public Builder setBPartnerId(final BPartnerId bpartnerId)
{
this.bpartnerId = bpartnerId;
return this;
}
private BPartnerId getBPartnerId()
{
return bpartnerId;
}
@Nullable
private HUEditorRowAttributesProvider getAttributesProviderOrNull()
{
return attributesProvider;
}
public Builder setAttributesProvider(@Nullable final HUEditorRowAttributesProvider attributesProvider)
{
this.attributesProvider = attributesProvider;
return this;
}
public Builder addIncludedRow(@NonNull final HUEditorRow includedRow)
{
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<HUEditorRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
public Builder setReservedForOrderLine(@Nullable final OrderLineId orderLineId)
{
orderLineReservation = orderLineId;
huReserved = orderLineId != null;
return this;
}
|
public Builder setClearanceStatus(@Nullable final JSONLookupValue clearanceStatusLookupValue)
{
clearanceStatus = clearanceStatusLookupValue;
return this;
}
public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate)
{
this.customProcessApplyPredicate = processApplyPredicate;
return this;
}
@Nullable
private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate()
{
return this.customProcessApplyPredicate;
}
/**
* @param currentRow the row that is currently constructed using this builder
*/
private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow)
{
final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder();
for (final HUEditorRow includedRow : buildIncludedRows())
{
includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations());
}
if (orderLineReservation != null)
{
includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow);
}
return includedOrderLineReservationsBuilder.build();
}
}
@lombok.Builder
@lombok.Value
public static class HUEditorRowHierarchy
{
@NonNull HUEditorRow cuRow;
@Nullable
HUEditorRow parentRow;
@Nullable
HUEditorRow topLevelRow;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java
| 1
|
请完成以下Java代码
|
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setQty_Planned (final @Nullable BigDecimal Qty_Planned)
{
set_Value (COLUMNNAME_Qty_Planned, Qty_Planned);
}
@Override
public BigDecimal getQty_Planned()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Planned);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty_Reported (final @Nullable BigDecimal Qty_Reported)
{
set_Value (COLUMNNAME_Qty_Reported, Qty_Reported);
}
@Override
public BigDecimal getQty_Reported()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported);
return bd != null ? bd : BigDecimal.ZERO;
}
|
/**
* Type AD_Reference_ID=540263
* Reference name: C_Flatrate_DataEntry Type
*/
public static final int TYPE_AD_Reference_ID=540263;
/** Invoicing_PeriodBased = IP */
public static final String TYPE_Invoicing_PeriodBased = "IP";
/** Correction_PeriodBased = CP */
public static final String TYPE_Correction_PeriodBased = "CP";
/** Procurement_PeriodBased = PC */
public static final String TYPE_Procurement_PeriodBased = "PC";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry.java
| 1
|
请完成以下Java代码
|
public void QueryJPQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
// JPQL :
LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------");
Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'");
List results = (List) q.execute();
Iterator<Product> iter = results.iterator();
while (iter.hasNext()) {
Product p = iter.next();
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
}
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
}
public void persistXML() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
pm.makePersistent(productXML);
ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
pm.makePersistent(productXML2);
ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
pm.makePersistent(productXML3);
tx.commit();
} finally {
|
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void listXMLProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
Query q = pm.newQuery("SELECT FROM " + ProductXML.class.getName());
List<ProductXML> products = (List<ProductXML>) q.execute();
Iterator<ProductXML> iter = products.iterator();
while (iter.hasNext()) {
ProductXML p = iter.next();
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.getName(), p.getPrice() });
pm.deletePersistent(p);
}
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
}
}
|
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\GuideToJDO.java
| 1
|
请完成以下Java代码
|
public class ShareRecordMessagingMessageListenerAdapter<K, V> extends MessagingMessageListenerAdapter<K, V>
implements AcknowledgingShareConsumerAwareMessageListener<K, V> {
public ShareRecordMessagingMessageListenerAdapter(@Nullable Object bean, @Nullable Method method,
@Nullable KafkaListenerErrorHandler errorHandler) {
super(bean, method, errorHandler);
}
/**
* Kafka {@link AcknowledgingConsumerAwareMessageListener} entry point.
* <p> Delegate the message to the target listener method,
* with appropriate conversion of the message argument.
* @param record the incoming Kafka {@link ConsumerRecord}.
* @param acknowledgment the acknowledgment.
* @param consumer the consumer.
*/
@Override
@SuppressWarnings("removal")
public void onShareRecord(ConsumerRecord<K, V> record, @Nullable ShareAcknowledgment acknowledgment,
@Nullable ShareConsumer<?, ?> consumer) {
Message<?> message;
if (isConversionNeeded()) {
message = toMessagingMessage(record, acknowledgment, consumer);
|
}
else {
message = NULL_MESSAGE;
}
if (logger.isDebugEnabled()) {
RecordMessageConverter messageConverter = getMessageConverter();
if (!(messageConverter instanceof JacksonProjectingMessageConverter
|| messageConverter instanceof org.springframework.kafka.support.converter.ProjectingMessageConverter)) {
this.logger.debug("Processing [" + message + "]");
}
}
invoke(record, acknowledgment, consumer, message);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\ShareRecordMessagingMessageListenerAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String delPmsMenu(HttpServletRequest req, Long menuId, Model model, DwzAjax dwz) {
try {
if (menuId == null || menuId == 0) {
return operateError("无法获取要删除的数据", model);
}
PmsMenu menu = pmsMenuService.getById(menuId);
if (menu == null) {
return operateError("无法获取要删除的数据", model);
}
Long parentId = menu.getParent().getId(); // 获取父菜单ID
// 先判断此菜单下是否有子菜单
List<PmsMenu> childMenuList = pmsMenuService.listByParentId(menuId);
if (childMenuList != null && !childMenuList.isEmpty()) {
return operateError("此菜单下关联有【" + childMenuList.size() + "】个子菜单,不能支接删除!", model);
}
// 删除掉菜单
pmsMenuService.delete(menuId);
// 删除菜单后,要判断其父菜单是否还有子菜单,如果没有子菜单了就要装其父菜单设为叶子节点
List<PmsMenu> childList = pmsMenuService.listByParentId(parentId);
if (childList == null || childList.isEmpty()) {
|
// 此时要将父菜单设为叶子
PmsMenu parent = pmsMenuService.getById(parentId);
parent.setIsLeaf(PublicEnum.YES.name());
pmsMenuService.update(parent);
}
// 记录系统操作日志
return operateSuccess(model, dwz);
} catch (Exception e) {
// 记录系统操作日志
log.error("== delPmsMenu exception:", e);
return operateError("删除菜单出错", model);
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\controller\PmsMenuController.java
| 2
|
请完成以下Java代码
|
public class Main {
public static void main(String[] args) {
final List<Runnable> actions = new ArrayList<Runnable>(2);
Runnable action = new Runnable() {
@Override
public void run() {
System.out.println("Hello from runnable.");
}
};
actions.add(action);
Book book = new Book("Design Patterns") {
@Override
public String description() {
return "Famous GoF book.";
}
};
System.out.println(String.format("Title: %s, description: %s", book.title, book.description()));
actions.add(new Runnable() {
@Override
public void run() {
System.out.println("Hello from runnable #2.");
}
});
|
int count = 1;
Runnable action2 = new Runnable() {
static final int x = 0;
// static int y = 0;
@Override
public void run() {
System.out.println(String.format("Runnable with captured variables: count = %s, x = %s", count, x));
}
};
actions.add(action2);
for (Runnable a : actions) {
a.run();
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance\src\main\java\com\baeldung\anonymous\Main.java
| 1
|
请完成以下Java代码
|
public void setR_IssueUser_ID (int R_IssueUser_ID)
{
if (R_IssueUser_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueUser_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueUser_ID, Integer.valueOf(R_IssueUser_ID));
}
/** Get IssueUser.
@return User who reported issues
*/
public int getR_IssueUser_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueUser_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
public void setUserName (String UserName)
{
set_ValueNoCheck (COLUMNNAME_UserName, UserName);
}
|
/** Get Registered EMail.
@return Email of the responsible for the System
*/
public String getUserName ()
{
return (String)get_Value(COLUMNNAME_UserName);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getUserName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueUser.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthController {
private Validator validator;
private UserDao userDao;
private Result result;
private UserInfo userInfo;
private Logger logger = Logger.getLogger(getClass().getName());
public AuthController() {
this(null, null, null, null);
}
@Inject
public AuthController(Validator validator, UserDao userDao, Result result, UserInfo userInfo) {
this.validator = validator;
this.userDao = userDao;
this.result = result;
this.userInfo = userInfo;
}
@Get("/register")
public void registrationForm() {
result.use(FreemarkerView.class).withTemplate("auth/register");
}
@Post("/register")
public void register(User user, HttpServletRequest request) {
validator.validate(user);
if(validator.hasErrors()) {
result.include("errors", validator.getErrors());
}
validator.onErrorRedirectTo(this).registrationForm();
if(!user.getPassword()
.equals(request.getParameter("password_confirmation"))) {
result.include("error", "Passwords Do Not Match");
result.redirectTo(this).registrationForm();
}
user.setPassword(
BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
|
Object resp = userDao.add(user);
if(resp != null) {
result.include("status", "Registration Successful! Now Login");
result.redirectTo(this).loginForm();
} else {
result.include("error", "There was an error during registration");
result.redirectTo(this).registrationForm();
}
}
@Get("/login")
public void loginForm() {
result.use(FreemarkerView.class).withTemplate("auth/login");
}
@Post("/login")
public void login(HttpServletRequest request) {
String password = request.getParameter("user.password");
String email = request.getParameter("user.email");
if(email.isEmpty() || password.isEmpty()) {
result.include("error", "Email/Password is Required!");
result.redirectTo(AuthController.class).loginForm();
}
User user = userDao.findByEmail(email);
if(user != null && BCrypt.checkpw(password, user.getPassword())) {
userInfo.setUser(user);
result.include("status", "Login Successful!");
result.redirectTo(IndexController.class).index();
} else {
result.include("error", "Email/Password Does Not Match!");
result.redirectTo(AuthController.class).loginForm();
}
}
}
|
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\controllers\AuthController.java
| 2
|
请完成以下Java代码
|
public class WEBUI_ProductsProposal_AddProductFromBasePriceList extends ProductsProposalViewBasedProcess
{
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
addSelectedRowsToInitialView();
closeAllViewsAndShowInitialView();
return MSG_OK;
}
private void addSelectedRowsToInitialView()
{
final ProductsProposalView initialView = getInitialView();
final List<ProductsProposalRowAddRequest> addRequests = getSelectedRows()
.stream()
.map(this::toProductsProposalRowAddRequest)
|
.collect(ImmutableList.toImmutableList());
initialView.addOrUpdateRows(addRequests);
}
private ProductsProposalRowAddRequest toProductsProposalRowAddRequest(final ProductsProposalRow row)
{
return ProductsProposalRowAddRequest.builder()
.product(row.getProduct())
.asiDescription(row.getAsiDescription())
.asiId(row.getAsiId())
.priceListPrice(row.getPrice().getUserEnteredPrice())
.lastShipmentDays(row.getLastShipmentDays())
.copiedFromProductPriceId(row.getProductPriceId())
.packingMaterialId(row.getPackingMaterialId())
.packingDescription(row.getPackingDescription())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\process\WEBUI_ProductsProposal_AddProductFromBasePriceList.java
| 1
|
请完成以下Java代码
|
public static FreightCostRule ofNullableCode(@Nullable final String code)
{
final FreightCostRule defaultWhenNull = null;
return ofNullableCodeOr(code, defaultWhenNull);
}
@Nullable
public static FreightCostRule ofNullableCodeOr(@Nullable final String code, @Nullable final FreightCostRule defaultWhenNull)
{
return code != null ? ofCode(code) : defaultWhenNull;
}
public static FreightCostRule ofCode(@NonNull final String code)
{
final FreightCostRule type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("No " + FreightCostRule.class + " found for code: " + code);
}
return type;
}
private static final ImmutableMap<String, FreightCostRule> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), FreightCostRule::getCode);
|
public boolean isFixPrice()
{
return this == FixPrice;
}
public boolean isNotFixPrice()
{
return !isFixPrice();
}
@Nullable
public static String toCodeOrNull(final FreightCostRule type)
{
return type != null ? type.getCode() : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCostRule.java
| 1
|
请完成以下Java代码
|
public void setAD_Issue_ID (final int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID);
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setConfigSummary (final @Nullable java.lang.String ConfigSummary)
{
set_Value (COLUMNNAME_ConfigSummary, ConfigSummary);
}
@Override
public java.lang.String getConfigSummary()
{
return get_ValueAsString(COLUMNNAME_ConfigSummary);
}
@Override
public void setDhl_ShipmentOrder_Log_ID (final int Dhl_ShipmentOrder_Log_ID)
{
if (Dhl_ShipmentOrder_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Dhl_ShipmentOrder_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Dhl_ShipmentOrder_Log_ID, Dhl_ShipmentOrder_Log_ID);
}
@Override
public int getDhl_ShipmentOrder_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Dhl_ShipmentOrder_Log_ID);
}
@Override
public de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest getDHL_ShipmentOrderRequest()
{
return get_ValueAsPO(COLUMNNAME_DHL_ShipmentOrderRequest_ID, de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest.class);
}
@Override
public void setDHL_ShipmentOrderRequest(final de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest DHL_ShipmentOrderRequest)
{
set_ValueFromPO(COLUMNNAME_DHL_ShipmentOrderRequest_ID, de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest.class, DHL_ShipmentOrderRequest);
}
@Override
public void setDHL_ShipmentOrderRequest_ID (final int DHL_ShipmentOrderRequest_ID)
{
if (DHL_ShipmentOrderRequest_ID < 1)
set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, null);
else
set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, DHL_ShipmentOrderRequest_ID);
}
@Override
public int getDHL_ShipmentOrderRequest_ID()
{
return get_ValueAsInt(COLUMNNAME_DHL_ShipmentOrderRequest_ID);
}
@Override
public void setDurationMillis (final int DurationMillis)
|
{
set_Value (COLUMNNAME_DurationMillis, DurationMillis);
}
@Override
public int getDurationMillis()
{
return get_ValueAsInt(COLUMNNAME_DurationMillis);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setRequestMessage (final @Nullable java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
@Override
public java.lang.String getRequestMessage()
{
return get_ValueAsString(COLUMNNAME_RequestMessage);
}
@Override
public void setResponseMessage (final @Nullable java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
@Override
public java.lang.String getResponseMessage()
{
return get_ValueAsString(COLUMNNAME_ResponseMessage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_Dhl_ShipmentOrder_Log.java
| 1
|
请完成以下Java代码
|
public void setStorageAttributesKey (final java.lang.String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public java.lang.String getStorageAttributesKey()
{
return get_ValueAsString(COLUMNNAME_StorageAttributesKey);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
@Override
public void setUserElementString2 (final @Nullable java.lang.String UserElementString2)
{
set_Value (COLUMNNAME_UserElementString2, UserElementString2);
}
@Override
public java.lang.String getUserElementString2()
{
return get_ValueAsString(COLUMNNAME_UserElementString2);
}
@Override
public void setUserElementString3 (final @Nullable java.lang.String UserElementString3)
{
set_Value (COLUMNNAME_UserElementString3, UserElementString3);
}
@Override
public java.lang.String getUserElementString3()
{
return get_ValueAsString(COLUMNNAME_UserElementString3);
}
@Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4)
{
set_Value (COLUMNNAME_UserElementString4, UserElementString4);
}
|
@Override
public java.lang.String getUserElementString4()
{
return get_ValueAsString(COLUMNNAME_UserElementString4);
}
@Override
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5)
{
set_Value (COLUMNNAME_UserElementString5, UserElementString5);
}
@Override
public java.lang.String getUserElementString5()
{
return get_ValueAsString(COLUMNNAME_UserElementString5);
}
@Override
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate.java
| 1
|
请完成以下Java代码
|
protected void registerInterceptors(final IModelValidationEngine engine)
{
engine.addModelValidator(C_Flatrate_Conditions.INSTANCE);
engine.addModelValidator(C_SubscriptionProgress.instance);
engine.addModelValidator(C_Flatrate_DataEntry.instance);
engine.addModelValidator(C_Flatrate_Matching.instance);
engine.addModelValidator(new C_Flatrate_Term(contractOrderService, documentLocationBL, glCategoryRepository));
engine.addModelValidator(new C_Invoice_Candidate());
engine.addModelValidator(new C_Invoice_Clearing_Alloc());
engine.addModelValidator(new C_Order());
engine.addModelValidator(new C_OrderLine(groupChangesHandler));
engine.addModelValidator(new C_Invoice_Rejection_Detail());
engine.addModelValidator(new C_BPartner_Location());
|
// 03742
engine.addModelValidator(new C_Flatrate_Transition());
// 04360
engine.addModelValidator(new C_Period());
engine.addModelValidator(new M_InOutLine());
engine.addModelValidator(new M_ShipmentSchedule_QtyPicked());
// 09869
engine.addModelValidator(M_ShipmentSchedule.INSTANCE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\MainValidator.java
| 1
|
请完成以下Java代码
|
public class AlfrescoStartEvent extends StartEvent {
protected String runAs;
protected String scriptProcessor;
public String getRunAs() {
return runAs;
}
public void setRunAs(String runAs) {
this.runAs = runAs;
}
public String getScriptProcessor() {
return scriptProcessor;
}
public void setScriptProcessor(String scriptProcessor) {
|
this.scriptProcessor = scriptProcessor;
}
public AlfrescoStartEvent clone() {
AlfrescoStartEvent clone = new AlfrescoStartEvent();
clone.setValues(this);
return clone;
}
public void setValues(AlfrescoStartEvent otherElement) {
super.setValues(otherElement);
setRunAs(otherElement.getRunAs());
setScriptProcessor(otherElement.getScriptProcessor());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\alfresco\AlfrescoStartEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDescription(String description) {
this.description = description;
}
public void setDiagramResource(String diagramResource) {
this.diagramResource = diagramResource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.")
public String getDiagramResource() {
return diagramResource;
}
public void setGraphicalNotationDefined(boolean graphicalNotationDefined) {
this.graphicalNotationDefined = graphicalNotationDefined;
|
}
@ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).")
public boolean isGraphicalNotationDefined() {
return graphicalNotationDefined;
}
public void setStartFormDefined(boolean startFormDefined) {
this.startFormDefined = startFormDefined;
}
public boolean isStartFormDefined() {
return startFormDefined;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java
| 2
|
请完成以下Java代码
|
public class Car {
private final int DEFAULT_WHEEL_COUNT = 5;
private final String DEFAULT_MODEL = "Basic";
protected int wheels;
protected String model;
public Car() {
this.wheels = DEFAULT_WHEEL_COUNT;
this.model = DEFAULT_MODEL;
}
public Car(int wheels, String model) {
this.wheels = wheels;
this.model = model;
|
}
public void start() {
// Check essential parts
// If okay, start.
}
public static int count = 10;
public static String msg() {
return "Car";
}
public String toString() {
return model;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\inheritance\Car.java
| 1
|
请完成以下Java代码
|
protected PvmExecutionImpl eventNotificationsStarted(PvmExecutionImpl execution) {
execution.incrementSequenceCounter();
// hack around execution tree structure not being in sync with activity instance concept:
// if we end a scope activity, take remembered activity instance from parent and set on
// execution before calling END listeners.
PvmExecutionImpl parent = execution.getParent();
PvmActivity activity = execution.getActivity();
if (parent != null && execution.isScope() &&
activity != null && activity.isScope() &&
(activity.getActivityBehavior() instanceof CompositeActivityBehavior
|| (CompensationBehavior.isCompensationThrowing(execution))
&& !LegacyBehavior.isCompensationThrowing(execution))) {
LOG.debugLeavesActivityInstance(execution, execution.getActivityInstanceId());
// use remembered activity instance id from parent
execution.setActivityInstanceId(parent.getActivityInstanceId());
// make parent go one scope up.
parent.leaveActivityInstance();
}
execution.setTransition(null);
|
return execution;
}
@Override
protected void eventNotificationsFailed(PvmExecutionImpl execution, Exception e) {
execution.activityInstanceEndListenerFailure();
super.eventNotificationsFailed(execution, e);
}
@Override
protected boolean isSkipNotifyListeners(PvmExecutionImpl execution) {
// listeners are skipped if this execution is not part of an activity instance.
return execution.getActivityInstanceId() == null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInstanceEnd.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return toStringValue;
}
@Override
public String getFormatedExpressionString()
{
return expressionString;
}
@Override
public Boolean evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{
return value;
}
@Override
public Boolean evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound)
|
{
return value;
}
@Override
public LogicExpressionResult evaluateToResult(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
return value ? LogicExpressionResult.TRUE : LogicExpressionResult.FALSE;
}
@Override
public ILogicExpression evaluatePartial(final Evaluatee ctx)
{
return this;
}
@Override
public ILogicExpression negate() {return of(!value);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ConstantLogicExpression.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDataKeyId(BsonBinary dataKeyId) {
this.dataKeyId = dataKeyId;
}
public BsonBinary getDataKeyId() {
return dataKeyId;
}
public String getKeyVaultNamespace() {
return keyVaultNamespace;
}
public String getKeyVaultAlias() {
return keyVaultAlias;
}
public String getMasterKeyPath() {
return masterKeyPath;
}
public boolean isAutoDecryption() {
return autoDecryption;
|
}
public boolean isAutoEncryption() {
return autoEncryption;
}
public File getAutoEncryptionLib() {
return autoEncryptionLib;
}
public String dataKeyIdUuid() {
if (dataKeyId == null)
throw new IllegalStateException("data key not initialized");
return dataKeyId.asUuid()
.toString();
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-3\src\main\java\com\baeldung\boot\csfle\config\EncryptionConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
IntegrationFlow inboundProcess(FlowableInboundGateway inboundGateway) {
return IntegrationFlow
.from(inboundGateway)
.handle(new GenericHandler<DelegateExecution>() {
@Override
public Object handle(DelegateExecution execution, MessageHeaders headers) {
return MessageBuilder.withPayload(execution)
.setHeader("projectId", "2143243")
.setHeader("orderId", "246")
.copyHeaders(headers).build();
}
})
.get();
}
@Bean
CommandLineRunner init(
|
final AnalysingService analysingService,
final RuntimeService runtimeService) {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
String integrationGatewayProcess = "integrationGatewayProcess";
runtimeService.startProcessInstanceByKey(
integrationGatewayProcess, Collections.singletonMap("customerId", (Object) 232L));
System.out.println("projectId=" + analysingService.getStringAtomicReference().get());
}
};
} // ...
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-integration\src\main\java\flowable\Application.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public long getDateTimeIntervalEndTs(ZonedDateTime dateTime) {
long offset = getOffsetSafe();
ZonedDateTime shiftedNow = dateTime.minusSeconds(offset);
ZonedDateTime alignedEnd = getAlignedBoundary(shiftedNow, true);
ZonedDateTime actualEnd = alignedEnd.plusSeconds(offset);
return actualEnd.toInstant().toEpochMilli();
}
protected abstract ZonedDateTime alignToIntervalStart(ZonedDateTime reference);
protected ZonedDateTime getAlignedBoundary(ZonedDateTime reference, boolean next) {
ZonedDateTime base = alignToIntervalStart(reference);
return next ? getNextIntervalStart(base) : base;
}
@Override
public void validate() {
try {
|
getZoneId();
} catch (Exception ex) {
throw new IllegalArgumentException("Invalid timezone in interval: " + ex.getMessage());
}
if (offsetSec != null) {
if (offsetSec < 0) {
throw new IllegalArgumentException("Offset cannot be negative.");
}
if (TimeUnit.SECONDS.toMillis(offsetSec) >= getCurrentIntervalDurationMillis()) {
throw new IllegalArgumentException("Offset must be greater than interval duration.");
}
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\aggregation\single\interval\BaseAggInterval.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final H130 other = (H130)obj;
if (deliveryTermCode == null)
{
if (other.deliveryTermCode != null)
{
return false;
}
}
else if (!deliveryTermCode.equals(other.deliveryTermCode))
{
return false;
}
if (deliveryTermText == null)
{
if (other.deliveryTermText != null)
{
return false;
}
}
else if (!deliveryTermText.equals(other.deliveryTermText))
{
return false;
}
if (iataCode == null)
{
if (other.iataCode != null)
{
return false;
}
}
else if (!iataCode.equals(other.iataCode))
{
return false;
}
if (iataText == null)
{
if (other.iataText != null)
{
return false;
}
}
else if (!iataText.equals(other.iataText))
{
return false;
}
if (messageNo == null)
{
if (other.messageNo != null)
{
return false;
}
}
else if (!messageNo.equals(other.messageNo))
{
return false;
}
if (packCode == null)
{
if (other.packCode != null)
{
return false;
}
}
else if (!packCode.equals(other.packCode))
{
return false;
}
if (partner == null)
{
if (other.partner != null)
{
return false;
}
}
else if (!partner.equals(other.partner))
{
return false;
}
if (payTimeNetto == null)
{
if (other.payTimeNetto != null)
|
{
return false;
}
}
else if (!payTimeNetto.equals(other.payTimeNetto))
{
return false;
}
if (payTimeSkonto == null)
{
if (other.payTimeSkonto != null)
{
return false;
}
}
else if (!payTimeSkonto.equals(other.payTimeSkonto))
{
return false;
}
if (record == null)
{
if (other.record != null)
{
return false;
}
}
else if (!record.equals(other.record))
{
return false;
}
if (skonto == null)
{
if (other.skonto != null)
{
return false;
}
}
else if (!skonto.equals(other.skonto))
{
return false;
}
if (transportMode == null)
{
if (other.transportMode != null)
{
return false;
}
}
else if (!transportMode.equals(other.transportMode))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "H130 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", skonto=" + skonto + ", payTimeSkonto=" + payTimeSkonto + ", payTimeNetto="
+ payTimeNetto
+ ", transportMode=" + transportMode + ", deliveryTermCode=" + deliveryTermCode + ", deliveryTermText=" + deliveryTermText + ", packCode=" + packCode
+ ", iataCode=" + iataCode
+ ", iataText=" + iataText + "]";
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\H130.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("qtyReportEvent", qtyReportEvent)
.toString();
}
@Override
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(qtyReportEvent);
}
@Override
public I_C_BPartner getC_BPartner()
{
return qtyReportEvent.getC_BPartner();
}
@Override
public boolean isContractedProduct()
{
final String contractLine_uuid = qtyReportEvent.getContractLine_UUID();
return !Check.isEmpty(contractLine_uuid, true);
}
@Override
public I_M_Product getM_Product()
{
return qtyReportEvent.getM_Product();
}
@Override
public int getProductId()
{
return qtyReportEvent.getM_Product_ID();
}
@Override
public I_C_UOM getC_UOM()
{
return qtyReportEvent.getC_UOM();
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
return qtyReportEvent.getC_Flatrate_Term();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return InterfaceWrapperHelper.create(qtyReportEvent.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class);
}
@Override
public Object getWrappedModel()
{
return qtyReportEvent;
}
|
@Override
public Timestamp getDate()
{
return qtyReportEvent.getDatePromised();
}
@Override
public BigDecimal getQty()
{
return qtyReportEvent.getQtyPromised();
}
@Override
public void setM_PricingSystem_ID(final int M_PricingSystem_ID)
{
qtyReportEvent.setM_PricingSystem_ID(M_PricingSystem_ID);
}
@Override
public void setM_PriceList_ID(final int M_PriceList_ID)
{
qtyReportEvent.setM_PriceList_ID(M_PriceList_ID);
}
@Override
public void setCurrencyId(final CurrencyId currencyId)
{
qtyReportEvent.setC_Currency_ID(CurrencyId.toRepoId(currencyId));
}
@Override
public void setPrice(final BigDecimal price)
{
qtyReportEvent.setPrice(price);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMPricingAware_QtyReportEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JpaItemWriter<Customer> jpaDBWriter(EntityManagerFactory entityManagerFactory) {
JpaItemWriter<Customer> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(entityManagerFactory);
return writer;
}
@Bean
public FlatFileItemWriter<Customer> fileWriter() {
return new FlatFileItemWriterBuilder<Customer>().name("customerItemWriter")
.resource(new FileSystemResource("output/processed_customers.txt"))
.delimited()
.delimiter(",")
.names("id", "name", "email", "type")
.build();
}
@Bean
public CompositeItemWriter<Customer> compositeWriter(JpaItemWriter<Customer> jpaDBWriter, FlatFileItemWriter<Customer> fileWriter) {
return new CompositeItemWriterBuilder<Customer>().delegates(List.of(jpaDBWriter, fileWriter))
.build();
}
@Bean
|
public Step processCustomersStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, FlatFileItemReader<Customer> reader,
CustomerProcessorRouter processorRouter, CompositeItemWriter<Customer> compositeWriter) {
return new StepBuilder("processCustomersStep", jobRepository).<Customer, Customer> chunk(10, transactionManager)
.reader(reader)
.processor(processorRouter)
.writer(compositeWriter)
.build();
}
@Bean
public Job processCustomersJob(JobRepository jobRepository, Step processCustomersStep) {
return new JobBuilder("customerProcessingJob", jobRepository).start(processCustomersStep)
.build();
}
}
|
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\multiprocessorandwriter\config\BatchConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class ApplicationConfiguration {
@Bean
ReactiveTenantExtension tenantExtension() {
return ReactiveTenantExtension.INSTANCE;
}
/**
* Extension that looks up a {@link Tenant} from the {@link reactor.util.context.Context}.
*/
enum ReactiveTenantExtension implements ReactiveEvaluationContextExtension {
INSTANCE;
@Override
public Mono<? extends EvaluationContextExtension> getExtension() {
return Mono.deferContextual(contextView -> Mono.just(new TenantExtension(contextView.get(Tenant.class))));
}
@Override
public String getExtensionId() {
return "my-reactive-tenant-extension";
}
}
/**
* Actual extension providing access to the {@link Tenant} value object.
*/
@RequiredArgsConstructor
static class TenantExtension implements EvaluationContextExtension {
private final Tenant tenant;
@Override
public String getExtensionId() {
return "my-tenant-extension";
|
}
@Override
public Tenant getRootObject() {
return tenant;
}
}
/**
* The root object.
*/
@Value
public static class Tenant {
String tenantId;
}
}
|
repos\spring-data-examples-main\cassandra\reactive\src\main\java\example\springdata\cassandra\spel\ApplicationConfiguration.java
| 2
|
请完成以下Java代码
|
public int getOrder() {
return WRITE_RESPONSE_FILTER_ORDER;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// NOTICE: nothing in "pre" filter stage as CLIENT_RESPONSE_CONN_ATTR is not added
// until the NettyRoutingFilter is run
// @formatter:off
return chain.filter(exchange)
.then(Mono.defer(() -> {
Connection connection = exchange.getAttribute(CLIENT_RESPONSE_CONN_ATTR);
if (connection == null) {
return Mono.empty();
}
if (log.isTraceEnabled()) {
log.trace("NettyWriteResponseFilter start inbound: "
+ connection.channel().id().asShortText() + ", outbound: "
+ exchange.getLogPrefix());
}
ServerHttpResponse response = exchange.getResponse();
// TODO: needed?
final Flux<DataBuffer> body = connection
.inbound()
.receive()
.retain()
.map(byteBuf -> wrap(byteBuf, response));
MediaType contentType = null;
try {
contentType = response.getHeaders().getContentType();
}
catch (Exception e) {
if (log.isTraceEnabled()) {
log.trace("invalid media type", e);
}
}
HttpClientResponse httpClientResponse = exchange.getAttribute(CLIENT_RESPONSE_ATTR);
Mono<Void> write = (isStreamingMediaType(contentType)
? response.writeAndFlushWith(body.map(Flux::just))
: response.writeWith(body));
return write.then(TrailerHeadersFilter.filter(getHeadersFilters(), exchange, httpClientResponse)).then();
}))
|
.doFinally(signalType -> {
if (signalType == SignalType.CANCEL || signalType == SignalType.ON_ERROR) {
cleanup(exchange);
}
});
// @formatter:on
}
protected DataBuffer wrap(ByteBuf byteBuf, ServerHttpResponse response) {
DataBufferFactory bufferFactory = response.bufferFactory();
if (bufferFactory instanceof NettyDataBufferFactory) {
NettyDataBufferFactory factory = (NettyDataBufferFactory) bufferFactory;
return factory.wrap(byteBuf);
}
// MockServerHttpResponse creates these
else if (bufferFactory instanceof DefaultDataBufferFactory) {
DataBuffer buffer = ((DefaultDataBufferFactory) bufferFactory).allocateBuffer(byteBuf.readableBytes());
buffer.write(byteBuf.nioBuffer());
byteBuf.release();
return buffer;
}
throw new IllegalArgumentException("Unknown DataBufferFactory type " + bufferFactory.getClass());
}
private void cleanup(ServerWebExchange exchange) {
Connection connection = exchange.getAttribute(CLIENT_RESPONSE_CONN_ATTR);
if (connection != null) {
connection.dispose();
}
}
// TODO: use framework if possible
private boolean isStreamingMediaType(@Nullable MediaType contentType) {
if (contentType != null) {
for (int i = 0; i < streamingMediaTypes.size(); i++) {
if (streamingMediaTypes.get(i).isCompatibleWith(contentType)) {
return true;
}
}
}
return false;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\NettyWriteResponseFilter.java
| 1
|
请完成以下Java代码
|
public List<String> getCustomMybatisXMLMappers() {
return customMybatisXMLMappers;
}
public void setCustomMybatisXMLMappers(List<String> customMybatisXMLMappers) {
this.customMybatisXMLMappers = customMybatisXMLMappers;
}
public boolean isUseStrongUuids() {
return useStrongUuids;
}
public void setUseStrongUuids(boolean useStrongUuids) {
this.useStrongUuids = useStrongUuids;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
}
public String getDeploymentMode() {
return deploymentMode;
}
public void setDeploymentMode(String deploymentMode) {
this.deploymentMode = deploymentMode;
}
public boolean isSerializePOJOsInVariablesToJson() {
return serializePOJOsInVariablesToJson;
}
public void setSerializePOJOsInVariablesToJson(boolean serializePOJOsInVariablesToJson) {
this.serializePOJOsInVariablesToJson = serializePOJOsInVariablesToJson;
}
public String getJavaClassFieldForJackson() {
return javaClassFieldForJackson;
}
public void setJavaClassFieldForJackson(String javaClassFieldForJackson) {
|
this.javaClassFieldForJackson = javaClassFieldForJackson;
}
public Integer getProcessDefinitionCacheLimit() {
return processDefinitionCacheLimit;
}
public void setProcessDefinitionCacheLimit(Integer processDefinitionCacheLimit) {
this.processDefinitionCacheLimit = processDefinitionCacheLimit;
}
public String getProcessDefinitionCacheName() {
return processDefinitionCacheName;
}
public void setProcessDefinitionCacheName(String processDefinitionCacheName) {
this.processDefinitionCacheName = processDefinitionCacheName;
}
public void setDisableExistingStartEventSubscriptions(boolean disableExistingStartEventSubscriptions) {
this.disableExistingStartEventSubscriptions = disableExistingStartEventSubscriptions;
}
public boolean shouldDisableExistingStartEventSubscriptions() {
return disableExistingStartEventSubscriptions;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\ActivitiProperties.java
| 1
|
请完成以下Java代码
|
public Map<String, CaseElement> getAllCaseElements() {
return allCaseElements;
}
public void setAllCaseElements(Map<String, CaseElement> allCaseElements) {
this.allCaseElements = allCaseElements;
}
public <T extends PlanItemDefinition> List<T> findPlanItemDefinitionsOfType(Class<T> type) {
return planModel.findPlanItemDefinitionsOfType(type, true);
}
public ReactivateEventListener getReactivateEventListener() {
return reactivateEventListener;
}
|
public void setReactivateEventListener(ReactivateEventListener reactivateEventListener) {
this.reactivateEventListener = reactivateEventListener;
}
@Override
public List<FlowableListener> getLifecycleListeners() {
return this.lifecycleListeners;
}
@Override
public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) {
this.lifecycleListeners = lifecycleListeners;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Case.java
| 1
|
请完成以下Java代码
|
public class ShipmentServiceTestImpl implements IShipmentService
{
@NonNull private final IHUShipmentScheduleBL huShipmentScheduleBL = Services.get(IHUShipmentScheduleBL.class);
@NonNull private final ShipmentScheduleWithHUService shipmentScheduleWithHUService;
@NonNull private final PickingJobScheduleService pickingJobScheduleService;
public static ShipmentServiceTestImpl newInstanceForUnitTesting()
{
Adempiere.enableUnitTestMode();
return SpringContextHolder.getBeanOrSupply(
ShipmentServiceTestImpl.class,
() -> new ShipmentServiceTestImpl(
ShipmentScheduleWithHUService.newInstanceForUnitTesting(),
PickingJobScheduleService.newInstanceForUnitTesting()
)
);
}
/**
* Always creates shipments synchronously and directly.
* Ignores {@link GenerateShipmentsForSchedulesRequest#isWaitForShipments()}.
*/
@NonNull
@VisibleForTesting
public Set<InOutId> generateShipmentsForScheduleIds(@NonNull final GenerateShipmentsForSchedulesRequest request)
{
final ShipmentScheduleAndJobScheduleIdSet scheduleIds = request.getScheduleIds();
if (scheduleIds == null || scheduleIds.isEmpty())
{
|
return ImmutableSet.of();
}
final List<ShipmentScheduleWithHU> shipmentScheduleWithHUS = shipmentScheduleWithHUService.prepareShipmentSchedulesWithHU(
PrepareForShipmentSchedulesRequest.builder()
.schedules(pickingJobScheduleService.getShipmentScheduleAndJobSchedulesCollection(scheduleIds))
.quantityTypeToUse(request.getQuantityTypeToUse())
.onTheFlyPickToPackingInstructions(request.isOnTheFlyPickToPackingInstructions())
.qtyToDeliverOverrides(QtyToDeliverMap.EMPTY)
.isFailIfNoPickedHUs(true) // backwards compatibility: true - fail if no picked HUs found
.build()
);
final CalculateShippingDateRule calculateShippingDateRule = computeShippingDateRule(request.getIsShipDateToday());
return huShipmentScheduleBL
.createInOutProducerFromShipmentSchedule()
.setProcessShipments(request.getIsCompleteShipment())
.computeShipmentDate(calculateShippingDateRule)
.setTrxItemExceptionHandler(FailTrxItemExceptionHandler.instance)
.createShipments(shipmentScheduleWithHUS)
.getInOuts()
.stream()
.map(I_M_InOut::getM_InOut_ID)
.map(InOutId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\ShipmentServiceTestImpl.java
| 1
|
请完成以下Java代码
|
public void addStockRecord(@NonNull final I_MD_Stock stockRecord)
{
final ProductId productId = ProductId.ofRepoId(stockRecord.getM_Product_ID());
final I_C_UOM uom = cache.getUomByProductId(productId);
qtyOnHandStock = addToNullable(qtyOnHandStock, stockRecord.getQtyOnHand(), uom);
stockRecordIds.add(stockRecord.getMD_Stock_ID());
}
public void addQuantitiesRecord(@NonNull final ProductWithDemandSupply quantitiesRecord)
{
final I_C_UOM uom = uomDAO.getById(quantitiesRecord.getUomId());
qtyDemandSalesOrder = addToNullable(qtyDemandSalesOrder, quantitiesRecord.getQtyReserved(), uom);
qtySupplyPurchaseOrder = addToNullable(qtySupplyPurchaseOrder, quantitiesRecord.getQtyToMove(), uom);
}
@NonNull
public MaterialCockpitRow createIncludedRow(@NonNull final MainRowWithSubRows mainRowBucket)
{
final MainRowBucketId productIdAndDate = assumeNotNull(
mainRowBucket.getProductIdAndDate(),
"productIdAndDate may not be null; mainRowBucket={}", mainRowBucket);
|
return MaterialCockpitRow.countingSubRowBuilder()
.lookups(rowLookups)
.cache(cache)
.date(productIdAndDate.getDate())
.productId(productIdAndDate.getProductId().getRepoId())
.detailsRowAggregationIdentifier(detailsRowAggregationIdentifier)
.qtyDemandSalesOrder(qtyDemandSalesOrder)
.qtySupplyPurchaseOrder(qtySupplyPurchaseOrder)
.qtyStockEstimateCountAtDate(qtyStockEstimateCountAtDate)
.qtyStockEstimateTimeAtDate(qtyStockEstimateTimeAtDate)
.qtyInventoryCountAtDate(qtyInventoryCountAtDate)
.qtyInventoryTimeAtDate(qtyInventoryTimeAtDate)
.qtyStockCurrentAtDate(qtyStockCurrentAtDate)
.qtyOnHandStock(qtyOnHandStock)
.allIncludedCockpitRecordIds(cockpitRecordIds)
.allIncludedStockRecordIds(stockRecordIds)
.qtyConvertor(qtyConvertorService.getQtyConvertorIfConfigured(productIdAndDate))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\rowfactory\CountingSubRowBucket.java
| 1
|
请完成以下Java代码
|
private static MobileApplicationPermission fromRecord(
@NonNull final I_Mobile_Application_Access applicationAccess,
@NonNull final ImmutableListMultimap<MobileApplicationRepoId, I_Mobile_Application_Action_Access> actionAccessByMobileApplicationId)
{
final MobileApplicationRepoId mobileApplicationId = MobileApplicationRepoId.ofRepoId(applicationAccess.getMobile_Application_ID());
final boolean allowAllActions = applicationAccess.isAllowAllActions();
final ImmutableSet<MobileApplicationActionId> allowedActionIds;
if (allowAllActions)
{
allowedActionIds = ImmutableSet.of(); // not relevant
}
else
{
allowedActionIds = actionAccessByMobileApplicationId.get(mobileApplicationId)
.stream()
.map(action -> MobileApplicationActionId.ofRepoId(action.getMobile_Application_Action_ID()))
.collect(ImmutableSet.toImmutableSet());
}
return MobileApplicationPermission.builder()
.mobileApplicationId(mobileApplicationId)
.allowAccess(true)
.allowAllActions(allowAllActions)
.allowedActionIds(allowedActionIds)
.build();
}
public void createMobileApplicationAccess(@NonNull final CreateMobileApplicationAccessRequest request)
{
final RoleId roleId = request.getRoleId();
final MobileApplicationRepoId applicationId = request.getApplicationId();
I_Mobile_Application_Access accessRecord = queryBL
.createQueryBuilder(I_Mobile_Application_Access.class)
.addEqualsFilter(I_Mobile_Application_Access.COLUMNNAME_AD_Role_ID, roleId)
.addEqualsFilter(I_Mobile_Application_Access.COLUMNNAME_Mobile_Application_ID, applicationId)
.create()
|
.firstOnly(I_Mobile_Application_Access.class);
if (accessRecord == null)
{
accessRecord = InterfaceWrapperHelper.newInstance(I_Mobile_Application_Access.class);
InterfaceWrapperHelper.setValue(accessRecord, I_Mobile_Application_Access.COLUMNNAME_AD_Client_ID, request.getClientId().getRepoId());
accessRecord.setAD_Org_ID(request.getOrgId().getRepoId());
accessRecord.setAD_Role_ID(roleId.getRepoId());
accessRecord.setMobile_Application_ID(applicationId.getRepoId());
accessRecord.setIsAllowAllActions(true);
}
accessRecord.setIsActive(true);
InterfaceWrapperHelper.save(accessRecord);
}
public void deleteMobileApplicationAccess(@NonNull final MobileApplicationRepoId applicationId)
{
queryBL.createQueryBuilder(I_Mobile_Application_Access.class)
.addEqualsFilter(I_Mobile_Application_Access.COLUMNNAME_Mobile_Application_ID, applicationId)
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\mobile_application\MobileApplicationPermissionsRepository.java
| 1
|
请完成以下Java代码
|
private Optional<HUAttributeQueryFilterVO> getOrCreateAttributeFilterVO(@NonNull final I_M_Attribute attribute, @Nullable final String attributeValueType)
{
if (!huRelevantAttributeIds.contains(AttributeId.ofRepoId(attribute.getM_Attribute_ID())))
{
return Optional.empty();
}
return Optional.ofNullable(getOrCreateAttributeFilterVO(onlyAttributes, attribute, attributeValueType));
}
private HUAttributeQueryFilterVO getOrCreateAttributeFilterVO(
@NonNull final Map<AttributeId, HUAttributeQueryFilterVO> targetMap,
@NonNull final I_M_Attribute attribute,
@Nullable final String attributeValueType)
{
final HUAttributeQueryFilterVO attributeFilterVO = targetMap.computeIfAbsent(
AttributeId.ofRepoId(attribute.getM_Attribute_ID()),
k -> new HUAttributeQueryFilterVO(attribute, attributeValueType));
if (attributeValueType != HUAttributeQueryFilterVO.ATTRIBUTEVALUETYPE_Unknown)
{
attributeFilterVO.assertAttributeValueType(attributeValueType);
}
return attributeFilterVO;
}
public boolean matches(@NonNull final IAttributeSet attributes)
{
// If there is no attribute restrictions we can accept this "attributes" right away
if (onlyAttributes == null || onlyAttributes.isEmpty())
{
return true;
}
for (final HUAttributeQueryFilterVO attributeFilter : onlyAttributes.values())
{
if (!attributeFilter.matches(attributes))
{
return false;
}
}
return true;
}
public void setBarcode(final String barcode)
{
this.barcode = barcode != null ? barcode.trim() : null;
}
private Collection<HUAttributeQueryFilterVO> createBarcodeHUAttributeQueryFilterVOs()
{
if (Check.isEmpty(barcode, true))
{
return ImmutableList.of();
}
|
final HashMap<AttributeId, HUAttributeQueryFilterVO> filterVOs = new HashMap<>();
for (final I_M_Attribute attribute : getBarcodeAttributes())
{
final HUAttributeQueryFilterVO barcodeAttributeFilterVO = getOrCreateAttributeFilterVO(
filterVOs,
attribute,
HUAttributeQueryFilterVO.ATTRIBUTEVALUETYPE_Unknown);
barcodeAttributeFilterVO.addValue(barcode);
}
return filterVOs.values();
}
private List<I_M_Attribute> getBarcodeAttributes()
{
final IDimensionspecDAO dimensionSpecsRepo = Services.get(IDimensionspecDAO.class);
final DimensionSpec barcodeDimSpec = dimensionSpecsRepo.retrieveForInternalNameOrNull(HUConstants.DIM_Barcode_Attributes);
if (barcodeDimSpec == null)
{
return ImmutableList.of(); // no barcode dimension spec. Nothing to do
}
return barcodeDimSpec.retrieveAttributes()
.stream()
// Barcode must be a String attribute. In the database, this is forced by a validation rule
.filter(attribute -> attribute.getAttributeValueType().equals(X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40))
.collect(ImmutableList.toImmutableList());
}
public void setAllowSql(final boolean allowSql)
{
this.allowSql = allowSql;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder_Attributes.java
| 1
|
请完成以下Java代码
|
public static GS1HUQRCode fromStringOrNullIfNotHandled(@NonNull final String string)
{
return fromScannedCodeOrNullIfNotHandled(ScannedCode.ofString(string));
}
public static GS1HUQRCode fromScannedCodeOrNullIfNotHandled(@NonNull final ScannedCode scannedCode)
{
final GS1Elements elements = GS1Parser.parseElementsOrNull(scannedCode.getAsString());
return elements != null ? new GS1HUQRCode(scannedCode, elements) : null;
}
public static GS1HUQRCode fromString(@NonNull final String string)
{
final GS1HUQRCode code = fromStringOrNullIfNotHandled(string);
if (code == null)
{
throw new AdempiereException("Invalid GS1 code: " + string);
}
return code;
}
|
@Override
@Deprecated
public String toString() {return getAsString();}
@Override
public String getAsString() {return code.getAsString();}
public Optional<GTIN> getGTIN() {return elements.getGTIN();}
@Override
public Optional<BigDecimal> getWeightInKg() {return elements.getWeightInKg();}
@Override
public Optional<LocalDate> getBestBeforeDate() {return elements.getBestBeforeDate();}
@Override
public Optional<String> getLotNumber() {return elements.getLotNumber();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\gs1\GS1HUQRCode.java
| 1
|
请完成以下Java代码
|
public abstract class C_Invoice_Candidate_ProcessHelper extends ViewBasedProcessTemplate implements IProcessPrecondition
{
private int countUpdated = 0;
private final C_Invoice_Candidate_ProcessCaptionMapperHelper processCaptionMapperHelper = SpringContextHolder.instance.getBean(C_Invoice_Candidate_ProcessCaptionMapperHelper.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept()
.withCaptionMapper(getCaptionMapper());
}
private ProcessPreconditionsResolution.ProcessCaptionMapper getCaptionMapper()
{
return processCaptionMapperHelper.getProcessCaptionMapperForNetAmountsFromQuery(retrieveQuery(false));
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final IQuery<I_C_Invoice_Candidate> query = retrieveQuery(true);
//
// Fail if there is nothing to update
final int countToUpdate = query.count();
if (countToUpdate <= 0)
{
throw new AdempiereException("@NoSelection@");
}
final boolean flagToSet = isApproveForInvoicing();
//
// Update selected invoice candidates
countUpdated = query.update(ic -> {
ic.setApprovalForInvoicing(flagToSet);
return IQueryUpdater.MODEL_UPDATED;
|
});
return MSG_OK;
}
protected IQueryFilter<I_C_Invoice_Candidate> getSelectionFilter()
{
final SqlViewRowsWhereClause viewSqlWhereClause = getViewSqlWhereClause(getSelectedRowIds());
return viewSqlWhereClause.toQueryFilter();
}
private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final String invoiceCandidateTableName = I_C_Invoice_Candidate.Table_Name;
return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(invoiceCandidateTableName));
}
protected abstract boolean isApproveForInvoicing();
protected abstract IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters);
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Notify frontend that the view shall be refreshed because we changed some candidates
if (countUpdated > 0)
{
invalidateView();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_ProcessHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DescriptionType {
@XmlValue
protected String content;
@XmlAttribute(name = "Language", namespace = "http://erpel.at/schemas/1p0/documents")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String language;
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* A code for a unique identification of the language used for the free-text description. Codes according to ISO 639-2 must be used.
|
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DescriptionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Saml2MetadataResponse resolve(HttpServletRequest request) {
RequestMatcher.MatchResult matcher = this.requestMatcher.matcher(request);
if (!matcher.isMatch()) {
return null;
}
String registrationId = matcher.getVariables().get("registrationId");
RelyingPartyRegistration relyingPartyRegistration = this.registrations.resolve(request, registrationId);
if (relyingPartyRegistration == null) {
throw new Saml2Exception("registration not found");
}
registrationId = relyingPartyRegistration.getRegistrationId();
String metadata = this.metadataResolver.resolve(relyingPartyRegistration);
String fileName = this.metadataFilename.replace("{registrationId}", registrationId);
return new Saml2MetadataResponse(metadata, fileName);
}
|
void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
void setMetadataFilename(String metadataFilename) {
Assert.hasText(metadataFilename, "metadataFilename cannot be empty");
Assert.isTrue(metadataFilename.contains("{registrationId}"),
"metadataFilename must contain a {registrationId} match variable");
this.metadataFilename = metadataFilename;
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2MetadataFilter.java
| 2
|
请完成以下Java代码
|
protected ServletContext getServletContext() {
return this.pageContext.getServletContext();
}
private final class PageContextVariableLookupEvaluationContext implements EvaluationContext {
private EvaluationContext delegate;
private PageContextVariableLookupEvaluationContext(EvaluationContext delegate) {
this.delegate = delegate;
}
@Override
public TypedValue getRootObject() {
return this.delegate.getRootObject();
}
@Override
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
@Override
public List<MethodResolver> getMethodResolvers() {
return this.delegate.getMethodResolvers();
}
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return this.delegate.getPropertyAccessors();
}
@Override
public TypeLocator getTypeLocator() {
return this.delegate.getTypeLocator();
}
@Override
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
|
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
@Override
public @Nullable BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, @Nullable Object value) {
this.delegate.setVariable(name, value);
}
@Override
public Object lookupVariable(String name) {
Object result = this.delegate.lookupVariable(name);
if (result == null) {
result = JspAuthorizeTag.this.pageContext.findAttribute(name);
}
return result;
}
}
}
|
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java
| 1
|
请完成以下Java代码
|
private String getManagementScheme(ServiceInstance instance) {
String managementServerScheme = getMetadataValue(instance, KEYS_MANAGEMENT_SCHEME);
if (hasText(managementServerScheme)) {
return managementServerScheme;
}
return getServiceUrl(instance).getScheme();
}
protected String getManagementHost(ServiceInstance instance) {
String managementServerHost = getMetadataValue(instance, KEYS_MANAGEMENT_ADDRESS);
if (hasText(managementServerHost)) {
return managementServerHost;
}
return getServiceUrl(instance).getHost();
}
protected int getManagementPort(ServiceInstance instance) {
String managementPort = getMetadataValue(instance, KEYS_MANAGEMENT_PORT);
if (hasText(managementPort)) {
return Integer.parseInt(managementPort);
}
return getServiceUrl(instance).getPort();
}
protected String getManagementPath(ServiceInstance instance) {
String managementPath = getMetadataValue(instance, KEYS_MANAGEMENT_PATH);
if (hasText(managementPath)) {
return managementPath;
}
return this.managementContextPath;
}
protected URI getServiceUrl(ServiceInstance instance) {
return instance.getUri();
}
|
protected Map<String, String> getMetadata(ServiceInstance instance) {
return (instance.getMetadata() != null) ? instance.getMetadata()
.entrySet()
.stream()
.filter((e) -> e.getKey() != null && e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : emptyMap();
}
public String getManagementContextPath() {
return this.managementContextPath;
}
public void setManagementContextPath(String managementContextPath) {
this.managementContextPath = managementContextPath;
}
public String getHealthEndpointPath() {
return this.healthEndpointPath;
}
public void setHealthEndpointPath(String healthEndpointPath) {
this.healthEndpointPath = healthEndpointPath;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\DefaultServiceInstanceConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Queue directQueue() {
return QueueBuilder.durable("DIRECT_QUEUE").build();
}
/**
* 通过绑定键 将指定队列绑定到一个指定的交换机 .
*
* @param queue the queue
* @param exchange the exchange
* @return the binding
*/
@Bean
public Binding directBinding(@Qualifier("directQueue") Queue queue,
@Qualifier("directExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("DIRECT_ROUTING_KEY").noargs();
}
/* ----------------------------------------------------------------------------Fanout exchange test--------------------------------------------------------------------------- */
/**
* 声明 fanout 交换机.
*
* @return the exchange
*/
@Bean("fanoutExchange")
public FanoutExchange fanoutExchange() {
return (FanoutExchange) ExchangeBuilder.fanoutExchange("FANOUT_EXCHANGE").durable(true).build();
}
/**
* Fanout queue A.
*
* @return the queue
*/
@Bean("fanoutQueueA")
public Queue fanoutQueueA() {
return QueueBuilder.durable("FANOUT_QUEUE_A").build();
}
/**
* Fanout queue B .
*
* @return the queue
*/
@Bean("fanoutQueueB")
public Queue fanoutQueueB() {
|
return QueueBuilder.durable("FANOUT_QUEUE_B").build();
}
/**
* 绑定队列A 到Fanout 交换机.
*
* @param queue the queue
* @param fanoutExchange the fanout exchange
* @return the binding
*/
@Bean
public Binding bindingA(@Qualifier("fanoutQueueA") Queue queue,
@Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue).to(fanoutExchange);
}
/**
* 绑定队列B 到Fanout 交换机.
*
* @param queue the queue
* @param fanoutExchange the fanout exchange
* @return the binding
*/
@Bean
public Binding bindingB(@Qualifier("fanoutQueueB") Queue queue,
@Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue).to(fanoutExchange);
}
}
|
repos\SpringBootBucket-master\springboot-rabbitmq\src\main\java\com\xncoding\pos\config\RabbitConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getArgs() {
return args;
}
public void setArgs(Map<String, String> args) {
this.args = args;
}
public void addArg(String key, String value) {
this.args.put(key, value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
PredicateProperties that = (PredicateProperties) o;
return Objects.equals(name, that.name) && Objects.equals(args, that.args);
}
@Override
public int hashCode() {
return Objects.hash(name, args);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("PredicateDefinition{");
sb.append("name='").append(name).append('\'');
sb.append(", args=").append(args);
sb.append('}');
return sb.toString();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\PredicateProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ShippingService {
private SessionFactory sessionFactory;
private ShippingDao shippingDao;
public ShippingService(SessionFactory sessionFactory, ShippingDao shippingDao) {
this.sessionFactory = sessionFactory;
this.shippingDao = shippingDao;
}
public String createConsignment(Consignment consignment) {
try (Session session = sessionFactory.openSession()) {
consignment.setDelivered(false);
consignment.setId(UUID.randomUUID().toString());
shippingDao.save(session, consignment);
return consignment.getId();
}
}
public void addItem(String consignmentId, Item item) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> addItem(session, consignment, item));
}
}
private void addItem(Session session, Consignment consignment, Item item) {
consignment.getItems()
.add(item);
shippingDao.save(session, consignment);
}
|
public void checkIn(String consignmentId, Checkin checkin) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> checkIn(session, consignment, checkin));
}
}
private void checkIn(Session session, Consignment consignment, Checkin checkin) {
consignment.getCheckins().add(checkin);
consignment.getCheckins().sort(Comparator.comparing(Checkin::getTimeStamp));
if (checkin.getLocation().equals(consignment.getDestination())) {
consignment.setDelivered(true);
}
shippingDao.save(session, consignment);
}
public Consignment view(String consignmentId) {
try (Session session = sessionFactory.openSession()) {
return shippingDao.find(session, consignmentId)
.orElseGet(Consignment::new);
}
}
}
|
repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\ShippingService.java
| 2
|
请完成以下Java代码
|
private ICompositeQueryFilter<I_S_ExternalReference> createFilterFor(@NonNull final ExternalReferenceQuery query)
{
final ICompositeQueryFilter<I_S_ExternalReference> queryFilter = queryBL.createCompositeQueryFilter(I_S_ExternalReference.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_ExternalSystem_ID, query.getExternalSystem().getId())
.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_Type, query.getExternalReferenceType().getCode())
.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_AD_Org_ID, query.getOrgId());
if (query.getExternalReference() != null)
{
queryFilter.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_ExternalReference, query.getExternalReference());
}
if (query.getMetasfreshId() != null)
{
queryFilter.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_Record_ID, query.getMetasfreshId().getValue());
}
return queryFilter;
}
private List<I_S_ExternalReference> listIncludingInactiveBy(final int recordId, @NonNull final IExternalReferenceType type)
{
return queryBL.createQueryBuilder(I_S_ExternalReference.class)
.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_Type, type.getCode())
.addEqualsFilter(I_S_ExternalReference.COLUMNNAME_Record_ID, recordId)
.create()
.list();
}
@NonNull
private ExternalReference buildExternalReference(@NonNull final I_S_ExternalReference record)
|
{
final IExternalReferenceType type = extractType(record);
final ExternalSystem externalSystem = extractSystem(record);
return ExternalReference.builder()
.externalReferenceId(ExternalReferenceId.ofRepoId(record.getS_ExternalReference_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.externalReference(record.getExternalReference())
.externalReferenceType(type)
.externalSystem(externalSystem)
.recordId(record.getRecord_ID())
.version(record.getVersion())
.externalReferenceUrl(record.getExternalReferenceURL())
.build();
}
private ExternalSystem extractSystem(@NonNull final I_S_ExternalReference record)
{
return externalSystemRepository.getById(ExternalSystemId.ofRepoId(record.getExternalSystem_ID()));
}
private IExternalReferenceType extractType(@NonNull final I_S_ExternalReference record)
{
return externalReferenceTypes.ofCode(record.getType())
.orElseThrow(() -> new AdempiereException("Unknown Type=" + record.getType())
.appendParametersToMessage()
.setParameter("type", record.getType())
.setParameter("S_ExternalReference", record));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalReferenceRepository.java
| 1
|
请完成以下Java代码
|
public static WebuiViewToOpen modalOverlay(@NonNull final String viewId)
{
return builder().viewId(viewId).target(ViewOpenTarget.ModalOverlay).build();
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Value
public static class DisplayQRCode
{
@JsonProperty("code")
String code;
@lombok.Builder
@JsonCreator
private DisplayQRCode(@JsonProperty("code") @NonNull final String code)
{
this.code = code;
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Value
@lombok.Builder
public static class WebuiNewRecord
|
{
/**
* If this string is used as field value
* then the frontend will try to open the new record modal window to populate that field.
* <p>
* Used mainly to trigger new BPartner.
*/
public static final String FIELD_VALUE_NEW = "NEW";
@NonNull String windowId;
/**
* Field values to be set by frontend, after the NEW record is created
*/
@NonNull @Singular Map<String, String> fieldValues;
public enum TargetTab
{
SAME_TAB, NEW_TAB,
}
@NonNull @Builder.Default TargetTab targetTab = TargetTab.SAME_TAB;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutionResult.java
| 1
|
请完成以下Java代码
|
public class Person {
@Override
public String toString() {
return "Person [name=" + name + ", nickname=" + nickname + ", age="
+ age + "]";
}
private String name;
private String nickname;
private int age;
public Person() {
}
public Person(String name, String nickname, int age) {
this.name = name;
this.nickname = nickname;
this.age = age;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
repos\tutorials-master\orika\src\main\java\com\baeldung\orika\Person.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setAD_User_Performing_ID (final int AD_User_Performing_ID)
{
if (AD_User_Performing_ID < 1)
set_Value (COLUMNNAME_AD_User_Performing_ID, null);
else
set_Value (COLUMNNAME_AD_User_Performing_ID, AD_User_Performing_ID);
}
@Override
public int getAD_User_Performing_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Performing_ID);
}
@Override
public void setBookedDate (final java.sql.Timestamp BookedDate)
{
set_Value (COLUMNNAME_BookedDate, BookedDate);
}
@Override
public java.sql.Timestamp getBookedDate()
{
return get_ValueAsTimestamp(COLUMNNAME_BookedDate);
}
@Override
public void setBookedSeconds (final @Nullable BigDecimal BookedSeconds)
{
set_Value (COLUMNNAME_BookedSeconds, BookedSeconds);
}
@Override
public BigDecimal getBookedSeconds()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_BookedSeconds);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setComments (final @Nullable java.lang.String Comments)
{
set_Value (COLUMNNAME_Comments, Comments);
}
@Override
public java.lang.String getComments()
{
return get_ValueAsString(COLUMNNAME_Comments);
}
@Override
public void setHoursAndMinutes (final java.lang.String HoursAndMinutes)
{
set_Value (COLUMNNAME_HoursAndMinutes, HoursAndMinutes);
}
@Override
public java.lang.String getHoursAndMinutes()
{
return get_ValueAsString(COLUMNNAME_HoursAndMinutes);
}
@Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue()
{
return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class);
|
}
@Override
public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
@Override
public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
}
@Override
public void setS_TimeBooking_ID (final int S_TimeBooking_ID)
{
if (S_TimeBooking_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, S_TimeBooking_ID);
}
@Override
public int getS_TimeBooking_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeBooking_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_TimeBooking.java
| 2
|
请完成以下Java代码
|
public class ProcessDefinitionInfoEntityImpl
extends AbstractEntity
implements ProcessDefinitionInfoEntity, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
protected String infoJsonId;
public ProcessDefinitionInfoEntityImpl() {}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("processDefinitionId", this.processDefinitionId);
persistentState.put("infoJsonId", this.infoJsonId);
return persistentState;
}
// getters and setters //////////////////////////////////////////////////////
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getInfoJsonId() {
return infoJsonId;
}
public void setInfoJsonId(String infoJsonId) {
this.infoJsonId = infoJsonId;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionInfoEntityImpl.java
| 1
|
请完成以下Java代码
|
private JSONProcessBasicInfo buildJSONProcessBasicInfo(@NonNull final ProcessBasicInfo processBasicInfo)
{
final String language = Env.getAD_Language();
final JSONProcessBasicInfo.JSONProcessBasicInfoBuilder jsonProcessInfoBuilder = JSONProcessBasicInfo.builder()
.processId(String.valueOf(processBasicInfo.getProcessId().getRepoId()))
.value(processBasicInfo.getValue())
.type(processBasicInfo.getType().getCode())
.name(processBasicInfo.getName().translate(language))
.description(processBasicInfo.getTranslatedDescriptionOrNull(language));
if (processBasicInfo.getParameters() != null)
{
final List<JSONProcessParamBasicInfo> processParamBasicInfos = processBasicInfo.getParameters()
.stream()
|
.map(paramInfo -> JSONProcessParamBasicInfo
.builder()
.columnName(paramInfo.getColumnName())
.type(paramInfo.getType())
.name(paramInfo.getName().translate(language))
.description(paramInfo.getTranslatedDescriptionOrNull(language))
.build())
.collect(Collectors.toList());
jsonProcessInfoBuilder.parameters(processParamBasicInfos);
}
return jsonProcessInfoBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\process\impl\ProcessRestController.java
| 1
|
请完成以下Java代码
|
public void setAD_Rule_ID (int AD_Rule_ID)
{
if (AD_Rule_ID < 1)
set_Value (COLUMNNAME_AD_Rule_ID, null);
else
set_Value (COLUMNNAME_AD_Rule_ID, Integer.valueOf(AD_Rule_ID));
}
/** Get Rule.
@return Rule */
@Override
public int getAD_Rule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Rule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation code.
@param Code
Validation Code
*/
@Override
public void setCode (java.lang.String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
@Override
public java.lang.String getCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Code);
}
/** 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);
}
/**
* Type AD_Reference_ID=540047
* Reference name: AD_BoilerPlate_VarType
*/
public static final int TYPE_AD_Reference_ID=540047;
/** SQL = S */
public static final String TYPE_SQL = "S";
/** Rule Engine = R */
public static final String TYPE_RuleEngine = "R";
/** Set Type.
|
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Type.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java
| 1
|
请完成以下Java代码
|
public String getSourceProcessDefinitionId() {
return sourceProcessDefinitionId;
}
public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) {
this.sourceProcessDefinitionId = sourceProcessDefinitionId;
}
public String getTargetProcessDefinitionId() {
return targetProcessDefinitionId;
}
public void setTargetProcessDefinitionId(String targetProcessDefinitionId) {
this.targetProcessDefinitionId = targetProcessDefinitionId;
}
public List<ProcessInstanceBatchMigrationPartResult> getAllMigrationParts() {
return allMigrationParts;
}
public void addMigrationPart(ProcessInstanceBatchMigrationPartResult migrationPart) {
if (allMigrationParts == null) {
allMigrationParts = new ArrayList<>();
}
allMigrationParts.add(migrationPart);
if (!STATUS_COMPLETED.equals(migrationPart.getStatus())) {
if (waitingMigrationParts == null) {
waitingMigrationParts = new ArrayList<>();
}
waitingMigrationParts.add(migrationPart);
} else {
if (RESULT_SUCCESS.equals(migrationPart.getResult())) {
|
if (succesfulMigrationParts == null) {
succesfulMigrationParts = new ArrayList<>();
}
succesfulMigrationParts.add(migrationPart);
} else {
if (failedMigrationParts == null) {
failedMigrationParts = new ArrayList<>();
}
failedMigrationParts.add(migrationPart);
}
}
}
public List<ProcessInstanceBatchMigrationPartResult> getSuccessfulMigrationParts() {
return succesfulMigrationParts;
}
public List<ProcessInstanceBatchMigrationPartResult> getFailedMigrationParts() {
return failedMigrationParts;
}
public List<ProcessInstanceBatchMigrationPartResult> getWaitingMigrationParts() {
return waitingMigrationParts;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceBatchMigrationResult.java
| 1
|
请完成以下Java代码
|
public TypeLocator getTypeLocator() {
return this.delegate.getTypeLocator();
}
@Override
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
@Override
|
public @Nullable BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, @Nullable Object value) {
this.delegate.setVariable(name, value);
}
@Override
public Object lookupVariable(String name) {
Object result = this.delegate.lookupVariable(name);
if (result == null) {
result = JspAuthorizeTag.this.pageContext.findAttribute(name);
}
return result;
}
}
}
|
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java
| 1
|
请完成以下Java代码
|
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getGroupNameAttribute() {
return groupNameAttribute;
}
public void setGroupNameAttribute(String groupNameAttribute) {
this.groupNameAttribute = groupNameAttribute;
}
public String getGroupNameDelimiter() {
return groupNameDelimiter;
}
public void setGroupNameDelimiter(String groupNameDelimiter) {
|
this.groupNameDelimiter = groupNameDelimiter;
}
}
public OAuth2SSOLogoutProperties getSsoLogout() {
return ssoLogout;
}
public void setSsoLogout(OAuth2SSOLogoutProperties ssoLogout) {
this.ssoLogout = ssoLogout;
}
public OAuth2IdentityProviderProperties getIdentityProvider() {
return identityProvider;
}
public void setIdentityProvider(OAuth2IdentityProviderProperties identityProvider) {
this.identityProvider = identityProvider;
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\OAuth2Properties.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LicenseFeeSettingsRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull
public LicenseFeeSettings getById(@NonNull final LicenseFeeSettingsId licenseFeeSettingsId)
{
final I_C_LicenseFeeSettings licenseFeeSettings = InterfaceWrapperHelper.load(licenseFeeSettingsId, I_C_LicenseFeeSettings.class);
return toLicenseFeeSettings(licenseFeeSettings);
}
@NonNull
private LicenseFeeSettings toLicenseFeeSettings(@NonNull final I_C_LicenseFeeSettings record)
{
final LicenseFeeSettingsId licenseFeeSettingsId = LicenseFeeSettingsId.ofRepoId(record.getC_LicenseFeeSettings_ID());
final ImmutableList<LicenseFeeSettingsLine> licenseFeeSettingsLines = queryBL.createQueryBuilder(I_C_LicenseFeeSettingsLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_LicenseFeeSettingsLine.COLUMNNAME_C_LicenseFeeSettings_ID, licenseFeeSettingsId)
.create()
.stream()
.map(this::toLicenseFeeSettingsLine)
.collect(ImmutableList.toImmutableList());
return LicenseFeeSettings.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.licenseFeeSettingsId(licenseFeeSettingsId)
.commissionProductId(ProductId.ofRepoId(record.getCommission_Product_ID()))
|
.pointsPrecision(record.getPointsPrecision())
.lines(licenseFeeSettingsLines)
.build();
}
@NonNull
private LicenseFeeSettingsLine toLicenseFeeSettingsLine(@NonNull final I_C_LicenseFeeSettingsLine record)
{
final LicenseFeeSettingsId licenseFeeSettingsId = LicenseFeeSettingsId.ofRepoId(record.getC_LicenseFeeSettings_ID());
return LicenseFeeSettingsLine.builder()
.licenseFeeSettingsLineId(LicenseFeeSettingsLineId.ofRepoId(licenseFeeSettingsId, record.getC_LicenseFeeSettingsLine_ID()))
.licenseFeeSettingsId(licenseFeeSettingsId)
.seqNo(record.getSeqNo())
.percentOfBasedPoints(Percent.of(record.getPercentOfBasePoints()))
.bpGroupIdMatch(BPGroupId.ofRepoIdOrNull(record.getC_BP_Group_Match_ID()))
.active(record.isActive())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\licensefee\repository\LicenseFeeSettingsRepository.java
| 2
|
请完成以下Java代码
|
public JsonGetStatsResponse getStats(@RequestBody @NonNull final JsonCacheStatsQuery jsonQuery)
{
assertAuth();
final CCacheStatsPredicate filter = jsonQuery.toCCacheStatsPredicate();
final CCacheStatsOrderBy orderBy = jsonQuery.toCCacheStatsOrderBy().orElse(DEFAULT_ORDER_BY);
return cacheMgt.streamStats(filter)
.sorted(orderBy)
.map(JsonCacheStats::of)
.collect(JsonGetStatsResponse.collect());
}
@GetMapping("/byId/{cacheId}")
public JsonCache getById(
@PathVariable("cacheId") final String cacheIdStr,
@RequestParam(name = "limit", required = false, defaultValue = "100") final int limit)
{
assertAuth();
final long cacheId = Long.parseLong(cacheIdStr);
final CacheInterface cacheInterface = cacheMgt.getById(cacheId)
.orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId));
if (cacheInterface instanceof CCache)
{
return JsonCache.of((CCache<?, ?>)cacheInterface, limit);
}
else
{
throw new AdempiereException("Cache of type " + cacheInterface.getClass().getSimpleName() + " is not supported");
|
}
}
@GetMapping("/byId/{cacheId}/reset")
public void resetCacheById(@PathVariable("cacheId") final String cacheIdStr)
{
assertAuth();
final long cacheId = Long.parseLong(cacheIdStr);
final CacheInterface cacheInterface = cacheMgt.getById(cacheId)
.orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId));
cacheInterface.reset();
}
@GetMapping("/remoteCacheInvalidationTableNames")
public Set<String> getRemoteCacheInvalidationTableNames()
{
return cacheMgt.getTableNamesToBroadcast()
.stream()
.sorted()
.collect(ImmutableSet.toImmutableSet());
}
@GetMapping("/remoteCacheInvalidationTableNames/add")
public void enableRemoteCacheInvalidationForTableName(@RequestParam("tableName") final String tableName)
{
cacheMgt.enableRemoteCacheInvalidationForTableName(tableName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\CacheRestControllerTemplate.java
| 1
|
请完成以下Java代码
|
public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> getTbCoreNotificationsMsgProducer() {
return toTbCoreNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() {
return toUsageStats;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() {
return toVersionControl;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() {
return toHousekeeper;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() {
return toEdge;
|
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() {
return toEdgeNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() {
return toEdgeEvents;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() {
return toCalculatedFields;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() {
return toCalculatedFieldNotifications;
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbCoreQueueProducerProvider.java
| 1
|
请完成以下Java代码
|
public class FlowableMyBatisRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
// These hints are coming from https://github.com/mybatis/spring-boot-starter/wiki/MyBatisNativeConfiguration.java
MemberCategory[] memberCategories = MemberCategory.values();
ReflectionHints reflectionHints = hints.reflection();
reflectionHints.registerType(Configuration.class, memberCategories);
reflectionHints.registerType(RawLanguageDriver.class, memberCategories);
reflectionHints.registerType(XMLLanguageDriver.class, memberCategories);
reflectionHints.registerType(RuntimeSupport.class, memberCategories);
reflectionHints.registerType(ProxyFactory.class, memberCategories);
reflectionHints.registerType(Slf4jImpl.class, memberCategories);
reflectionHints.registerType(Log.class, memberCategories);
reflectionHints.registerType(JakartaCommonsLoggingImpl.class, memberCategories);
reflectionHints.registerType(Log4j2Impl.class, memberCategories);
|
reflectionHints.registerType(Jdk14LoggingImpl.class, memberCategories);
reflectionHints.registerType(StdOutImpl.class, memberCategories);
reflectionHints.registerType(NoLoggingImpl.class, memberCategories);
reflectionHints.registerType(SqlSessionFactory.class, memberCategories);
reflectionHints.registerType(PerpetualCache.class, memberCategories);
reflectionHints.registerType(FifoCache.class, memberCategories);
reflectionHints.registerType(LruCache.class, memberCategories);
reflectionHints.registerType(SoftCache.class, memberCategories);
reflectionHints.registerType(WeakCache.class, memberCategories);
ResourceHints resourceHints = hints.resources();
resourceHints.registerPattern("org/apache/ibatis/builder/xml/*.dtd");
resourceHints.registerPattern("org/apache/ibatis/builder/xml/*.xsd");
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\aot\FlowableMyBatisRuntimeHints.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PutProductsRequest getSyncProductsRequest()
{
if (_syncProductsRequest == null)
{
_syncProductsRequest = createSyncProductsRequest();
}
return _syncProductsRequest;
}
private PutProductsRequest createSyncProductsRequest()
{
final PutProductsRequestBuilder request = PutProductsRequest.builder();
//
// Products
for (final String productName : productNames)
{
final SyncProduct syncProduct = createSyncProduct(productName, "10x1 Stk");
request.product(syncProduct);
}
return request.build();
}
public SyncUser createSyncUser(final String email, final String password, @Nullable final String language)
{
return SyncUser.builder()
.uuid(randomUUID())
.email(email)
.password(password)
.language(language)
.build();
}
public SyncProduct createSyncProduct(final String name, final String packingInfo)
{
final SyncProduct.SyncProductBuilder product = SyncProduct.builder()
.uuid(randomUUID())
.name(name)
.packingInfo(packingInfo)
.shared(true);
for (final String language : languages)
{
product.nameTrl(language, name + " " + language);
}
return product.build();
}
private static String randomUUID()
{
return UUID.randomUUID().toString();
}
|
@Transactional
void createDummyProductSupplies()
{
for (final BPartner bpartner : bpartnersRepo.findAll())
{
for (final Contract contract : contractsRepo.findByBpartnerAndDeletedFalse(bpartner))
{
final List<ContractLine> contractLines = contract.getContractLines();
if (contractLines.isEmpty())
{
continue;
}
final ContractLine contractLine = contractLines.get(0);
final Product product = contractLine.getProduct();
productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.productId(product.getId())
.date(LocalDate.now()) // today
.qty(new BigDecimal("10"))
.qtyConfirmedByUser(true)
.build());
productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.productId(product.getId())
.date(LocalDate.now().plusDays(1)) // tomorrow
.qty(new BigDecimal("3"))
.qtyConfirmedByUser(true)
.build());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\DummyDataProducer.java
| 2
|
请完成以下Java代码
|
public int hashCode()
{
if (_hashcode == null)
{
_hashcode = Objects.hash(documentType, documentTypeId, documentId);
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof DocumentKey))
{
return false;
}
final DocumentKey other = (DocumentKey)obj;
return Objects.equals(documentType, other.documentType)
&& Objects.equals(documentTypeId, other.documentTypeId)
&& Objects.equals(documentId, other.documentId);
}
|
public WindowId getWindowId()
{
Check.assume(documentType == DocumentType.Window, "documentType shall be {} but it was {}", DocumentType.Window, documentType);
return WindowId.of(documentTypeId);
}
public DocumentId getDocumentId()
{
return documentId;
}
public DocumentPath getDocumentPath()
{
return DocumentPath.rootDocumentPath(documentType, documentTypeId, documentId);
}
} // DocumentKey
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentCollection.java
| 1
|
请完成以下Java代码
|
private List<I_AD_MigrationData> getKeyData()
{
if (m_migrationDataKeys != null)
{
return m_migrationDataKeys;
}
final List<I_AD_MigrationData> dataKeys = new ArrayList<I_AD_MigrationData>();
final List<I_AD_MigrationData> dataParents = new ArrayList<I_AD_MigrationData>();
for (final I_AD_MigrationData data : getMigrationData())
{
final I_AD_Column column = data.getAD_Column();
if (column == null)
{
logger.warn("Column is null for data: {}", new Object[] { data });
continue;
}
if (column.isKey())
{
dataKeys.add(data);
}
if (column.isParent())
{
dataParents.add(data);
}
}
if (dataKeys.size() == 1)
{
m_migrationDataKeys = dataKeys;
|
}
else if (!dataParents.isEmpty())
{
m_migrationDataKeys = dataParents;
}
else
{
throw new AdempiereException("Invalid key/parent constraints. Keys: " + dataKeys + ", Parents: " + dataParents);
}
return m_migrationDataKeys;
}
private void syncDBColumn(final I_AD_Column column, final boolean drop)
{
final IMigrationExecutorContext migrationCtx = getMigrationExecutorContext();
final ColumnSyncDDLExecutable ddlExecutable = new ColumnSyncDDLExecutable(AdColumnId.ofRepoId(column.getAD_Column_ID()), drop);
migrationCtx.addPostponedExecutable(ddlExecutable);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\POMigrationStepExecutor.java
| 1
|
请完成以下Java代码
|
public void createCollection() {
// 定义集合和字段
FieldType idField = FieldType.newBuilder()
.withName("id")
.withDataType(DataType.Int64)
.withPrimaryKey(true)
.build();
FieldType vectorField = FieldType.newBuilder()
.withName("embedding")
.withDataType(DataType.FloatVector)
.withDimension(1000)
.build();
CreateCollectionParam createCollectionParam = CreateCollectionParam.newBuilder()
.withCollectionName("image_collection")
.withDescription("Image collection")
.withShardsNum(2)
.addFieldType(idField)
.addFieldType(vectorField)
.build();
milvusClient.createCollection(createCollectionParam);
}
public void insertData(long id, INDArray features) {
// 插入数据
List<Long> ids = Collections.singletonList(id);
float[] floatArray = features.toFloatVector();
// 手动将 float[] 转换为 List<Float>
List<Float> floatList = new ArrayList<>();
for (float f : floatArray) {
floatList.add(f); // 将每个 float 添加到列表中
}
// 创建 List<List<Float>>
List<List<Float>> vectors = Collections.singletonList(floatList);
List<InsertParam.Field> fields = new ArrayList<>();
fields.add(new InsertParam.Field("id",ids));
fields.add(new InsertParam.Field("embedding", vectors));
InsertParam insertParam = InsertParam.newBuilder()
.withCollectionName("image_collection")
.withFields(fields)
|
.build();
milvusClient.insert(insertParam);
}
public void flush() {
milvusClient.flush(FlushParam.newBuilder()
.withCollectionNames(Collections.singletonList("image_collection"))
.withSyncFlush(true)
.withSyncFlushWaitingInterval(50L)
.withSyncFlushWaitingTimeout(30L)
.build());
}
public void buildindex() {
// build index
System.out.println("Building AutoIndex...");
final IndexType INDEX_TYPE = IndexType.AUTOINDEX; // IndexType
long startIndexTime = System.currentTimeMillis();
R<RpcStatus> indexR = milvusClient.createIndex(
CreateIndexParam.newBuilder()
.withCollectionName("image_collection")
.withFieldName("embedding")
.withIndexType(INDEX_TYPE)
.withMetricType(MetricType.L2)
.withSyncMode(Boolean.TRUE)
.withSyncWaitingInterval(500L)
.withSyncWaitingTimeout(30L)
.build());
long endIndexTime = System.currentTimeMillis();
System.out.println("Succeed in " + (endIndexTime - startIndexTime) / 1000.00 + " seconds!");
}
}
|
repos\springboot-demo-master\Milvus\src\main\java\com\et\imagesearch\MilvusManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
KotlinJpaMavenBuildCustomizer kotlinJpaMavenBuildCustomizer(InitializrMetadata metadata,
ProjectDescription projectDescription) {
return new KotlinJpaMavenBuildCustomizer(metadata, projectDescription);
}
@Bean
@ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN)
KotlinGradleBuildCustomizer kotlinBuildCustomizerKotlinDsl(KotlinProjectSettings kotlinProjectSettings) {
return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\"');
}
@Bean
@ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY)
KotlinGradleBuildCustomizer kotlinBuildCustomizerGroovyDsl(KotlinProjectSettings kotlinProjectSettings) {
return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\'');
}
/**
* Configuration for Kotlin projects using Spring Boot 2.0 and later.
*/
@Configuration
@ConditionalOnPlatformVersion("2.0.0.M1")
static class SpringBoot2AndLaterKotlinProjectGenerationConfiguration {
@Bean
@ConditionalOnBuildSystem(MavenBuildSystem.ID)
KotlinMavenBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) {
return new KotlinMavenBuildCustomizer(kotlinProjectSettings);
}
@Bean
MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor(
ProjectDescription description) {
return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main")
.parameters(Parameter.of("args", "Array<String>"))
.body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication",
description.getApplicationName())));
}
}
|
/**
* Kotlin source code contributions for projects using war packaging.
*/
@Configuration
@ConditionalOnPackaging(WarPackaging.ID)
static class WarPackagingConfiguration {
@Bean
ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer(
ProjectDescription description) {
return (typeDeclaration) -> {
KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure")
.modifiers(KotlinModifier.OVERRIDE)
.returning("org.springframework.boot.builder.SpringApplicationBuilder")
.parameters(
Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder"))
.body(CodeBlock.ofStatement("return application.sources($L::class.java)",
description.getApplicationName()));
typeDeclaration.addFunctionDeclaration(configure);
};
}
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationDefaultContributorsConfiguration.java
| 2
|
请完成以下Java代码
|
private <ET> QueryResultPage<ET> loadPage(
@NonNull final Class<ET> clazz,
@NonNull final PageDescriptor currentPageDescriptor)
{
final TypedSqlQuery<ET> query = QuerySelectionHelper.createUUIDSelectionQuery(
PlainContextAware.newWithThreadInheritedTrx(),
clazz,
currentPageDescriptor.getPageIdentifier().getSelectionUid());
final int currentPageSize = currentPageDescriptor.getPageSize();
final List<ET> items = query
.addWhereClause(
true /* joinByAnd */,
QuerySelectionHelper.SELECTION_LINE_ALIAS + " > " + currentPageDescriptor.getOffset())
.setLimit(currentPageSize)
.list(clazz);
final int actualPageSize = items.size();
logger.debug("Loaded next page: bufferSize={}, offset={} -> {} records",
currentPageSize, currentPageDescriptor.getOffset(), actualPageSize);
// True when buffer contains as much data as was required. If this flag is false then it's a good indicator that we are on last page.
final boolean pageFullyLoaded = actualPageSize >= currentPageSize;
|
final PageDescriptor nextPageDescriptor;
if (pageFullyLoaded)
{
nextPageDescriptor = currentPageDescriptor.createNext();
pageDescriptorRepository.save(nextPageDescriptor);
}
else
{
nextPageDescriptor = null;
}
return new QueryResultPage<ET>(
currentPageDescriptor,
nextPageDescriptor,
currentPageDescriptor.getTotalSize(),
currentPageDescriptor.getSelectionTime(),
ImmutableList.copyOf(items));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\PaginationService.java
| 1
|
请完成以下Java代码
|
public static boolean isEnabledForTableName(final String tableName)
{
if (!isEnabled())
{
return false;
}
final POInfo poInfo = POInfo.getPOInfo(tableName);
if (poInfo == null)
{
return false;
}
final TableCloningEnabled cloningEnabled = poInfo.getCloningEnabled();
switch (cloningEnabled)
{
case Auto:
return enabledTableNames.contains(tableName);
case Enabled:
return true;
case Disabled:
return false;
default:
logger.warn("CloningEnabled case `{}` not handled. Considering cloning disabled.", cloningEnabled);
return false;
}
}
public static void enableForTableName(final String tableName)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
enabledTableNames.add(tableName);
|
logger.info("Enabled for table: {}", tableName);
}
/**
* Allows other modules to install customer code to be executed each time a record was copied.
* Add a listener here, and it will automatically be added to each {@link CopyRecordSupport} instance that is returned by {@link #getCopyRecordSupport(String)}.
*/
public static void addOnRecordCopiedListener(@NonNull final OnRecordCopiedListener listener)
{
final boolean added = staticOnRecordCopiedListeners.addIfAbsent(listener);
if (added)
{
logger.info("Registered listener: {}", listener);
}
else
{
logger.info("Skip registering listener because it was already registered: {}", listener);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\CopyRecordFactory.java
| 1
|
请完成以下Java代码
|
protected ExecutionEntity getExecution(CommandContext commandContext) {
if (taskId != null) {
TaskEntity task = getTask(commandContext);
if (task != null) {
return task.getExecution();
} else {
return null;
}
} else {
return getProcessInstance(commandContext);
}
}
protected ExecutionEntity getProcessInstance(CommandContext commandContext) {
if (processInstanceId != null) {
return commandContext.getExecutionManager().findExecutionById(processInstanceId);
} else {
return null;
}
}
protected TaskEntity getTask(CommandContext commandContext) {
if (taskId != null) {
return commandContext.getTaskManager().findTaskById(taskId);
} else {
return null;
}
}
|
protected boolean isHistoryRemovalTimeStrategyStart() {
return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy());
}
protected String getHistoryRemovalTimeStrategy() {
return Context.getProcessEngineConfiguration()
.getHistoryRemovalTimeStrategy();
}
protected HistoricProcessInstanceEventEntity getHistoricRootProcessInstance(String rootProcessInstanceId) {
return Context.getCommandContext()
.getDbEntityManager()
.selectById(HistoricProcessInstanceEventEntity.class, rootProcessInstanceId);
}
protected void provideRemovalTime(CommentEntity comment) {
String rootProcessInstanceId = comment.getRootProcessInstanceId();
if (rootProcessInstanceId != null) {
HistoricProcessInstanceEventEntity historicRootProcessInstance = getHistoricRootProcessInstance(rootProcessInstanceId);
if (historicRootProcessInstance != null) {
Date removalTime = historicRootProcessInstance.getRemovalTime();
comment.setRemovalTime(removalTime);
}
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AddCommentCmd.java
| 1
|
请完成以下Java代码
|
private DocTypeId getDocTypeIdByType(
@NonNull final String type,
@NonNull final ClientId clientId,
@NonNull final OrgId orgId)
{
final DocTypeQuery docTypeQuery = DocTypeQuery.builder()
.docBaseType(type)
.adClientId(clientId.getRepoId())
.adOrgId(orgId.getRepoId())
.build();
return docTypeDAO.getDocTypeId(docTypeQuery);
}
private BPartnerQuery buildBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier)
{
final IdentifierString.Type type = bpartnerIdentifier.getType();
final BPartnerQuery query;
switch (type)
{
case METASFRESH_ID:
query = BPartnerQuery.builder()
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
break;
case EXTERNAL_ID:
query = BPartnerQuery.builder()
.externalId(bpartnerIdentifier.asExternalId())
.build();
break;
case GLN:
query = BPartnerQuery.builder()
.gln(bpartnerIdentifier.asGLN())
.build();
break;
case VALUE:
query = BPartnerQuery.builder()
|
.bpartnerValue(bpartnerIdentifier.asValue())
.build();
break;
default:
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
return query;
}
@VisibleForTesting
public String buildDocumentNo(@NonNull final DocTypeId docTypeId)
{
final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class);
final String documentNo = documentNoFactory.forDocType(docTypeId.getRepoId(), /* useDefiniteSequence */false)
.setClientId(Env.getClientId())
.setFailOnError(true)
.build();
if (documentNo == null)
{
throw new AdempiereException("Cannot fetch documentNo for " + docTypeId);
}
return documentNo;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\remittanceadvice\impl\CreateRemittanceAdviceService.java
| 1
|
请完成以下Java代码
|
private MDunningRun getParent()
{
if (m_parent == null)
m_parent = new MDunningRun(getCtx(), getC_DunningRun_ID(), get_TrxName());
return m_parent;
} // getParent
@Override
protected boolean beforeSave(boolean newRecord)
{
final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class);
I_C_DunningLevel level = getC_DunningLevel();
// Set Amt
if (isProcessed())
{
MDunningRunLine[] theseLines = getLines();
for (int i = 0; i < theseLines.length; i++)
{
theseLines[i].setProcessed(true);
theseLines[i].saveEx(get_TrxName());
}
if (level.isSetCreditStop() || level.isSetPaymentTerm())
{
final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
final I_C_BPartner thisBPartner = bpartnersRepo.getById(getC_BPartner_ID());
final BPartnerStats stats =bpartnerStatsDAO.getCreateBPartnerStats(thisBPartner);
if (level.isSetCreditStop())
|
{
// set this particular credit status in the bp stats
bpartnerStatsDAO.setSOCreditStatus(stats, X_C_BPartner_Stats.SOCREDITSTATUS_CreditStop);
}
if (level.isSetPaymentTerm())
{
thisBPartner.setC_PaymentTerm_ID(level.getC_PaymentTerm_ID());
}
bpartnersRepo.save(thisBPartner);
}
}
return true;
} // beforeSave
} // MDunningRunEntry
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRunEntry.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
StringBuffer sql = new StringBuffer("");
int cnt = 0;
log.info("Set Print Format");
try
{
sql.append("UPDATE AD_PrintFormat pf "
+ "SET AD_PrintPaper_ID = " + p_Record_ID + " "
+ "WHERE EXISTS (SELECT * FROM AD_PrintPaper pp "
+ "WHERE pf.AD_PrintPaper_ID=pp.AD_PrintPaper_ID "
+ "AND IsLandscape = (SELECT IsLandscape FROM AD_PrintPaper "
+ "WHERE AD_PrintPaper_ID=" + p_Record_ID + "))");
if (p_AD_Client_ID != -1) {
sql.append(" AND AD_Client_ID = " + p_AD_Client_ID);
|
}
cnt = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), get_TrxName());
log.info("Updated " + cnt + " columns");
log.debug("Committing ...");
DB.commit(true, null);
}
catch (Exception e)
{
log.error("set print format", e);
}
return "@Copied@=" + cnt;
} // doIt
} // AD_PrintPaper_Default
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\AD_PrintPaper_Default.java
| 1
|
请完成以下Java代码
|
public void execute(PvmExecutionImpl execution) {
execution.activityInstanceDone();
ActivityBehavior activityBehavior = getActivityBehavior(execution);
if (activityBehavior instanceof FlowNodeActivityBehavior) {
FlowNodeActivityBehavior behavior = (FlowNodeActivityBehavior) activityBehavior;
ActivityImpl activity = execution.getActivity();
String activityInstanceId = execution.getActivityInstanceId();
if(activityInstanceId != null) {
LOG.debugLeavesActivityInstance(execution, activityInstanceId);
}
try {
behavior.doLeave(execution);
} catch (RuntimeException e) {
|
throw e;
} catch (Exception e) {
throw new PvmException("couldn't leave activity <"+activity.getProperty("type")+" id=\""+activity.getId()+"\" ...>: "+e.getMessage(), e);
}
} else {
throw new PvmException("Behavior of current activity is not an instance of " + FlowNodeActivityBehavior.class.getSimpleName() + ". Execution " + execution);
}
}
public String getCanonicalName() {
return "activity-leave";
}
public boolean isAsyncCapable() {
return false;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityLeave.java
| 1
|
请完成以下Java代码
|
public class IndexController {
private final HttpSession httpSession;
/**
* 登录页面
* @return
*/
@ResponseBody
@RequestMapping("/login")
public String login() {
return "login page.";
}
/**
* 登录请求
* @param username
* @return
*/
@RequestMapping("/login/submit")
public String loginSubmit(@RequestParam("username") String username) {
if (StringUtils.isNotBlank(username)) {
httpSession.setAttribute("username", username);
return "/index";
}
|
return "/login";
}
/**
* 首页
* @return
*/
@ResponseBody
@RequestMapping("/index")
public String index() {
log.info("session id: {}", httpSession.getId());
return "index page.";
}
/**
* 退出登录
* @return
*/
@RequestMapping("/logout")
public String logout() {
httpSession.invalidate();
return "/login";
}
}
|
repos\spring-boot-best-practice-master\spring-boot-session\src\main\java\cn\javastack\springboot\session\IndexController.java
| 1
|
请完成以下Java代码
|
public void setM_PackagingContainer_ID(final int M_PackagingContainer_ID)
{
if (M_PackagingContainer_ID < 1)
set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, null);
else
set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, M_PackagingContainer_ID);
}
@Override
public int getM_PackagingContainer_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_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);
}
@Override
public void setValue(final @Nullable java.lang.String Value)
{
set_Value(COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWidth(final @Nullable BigDecimal Width)
{
set_Value(COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public OffHeapProperties getOffHeap() {
return this.offHeap;
}
public PeerCacheProperties getPeer() {
return this.peer;
}
public CacheServerProperties getServer() {
return this.server;
}
public static class CompressionProperties {
private String compressorBeanName;
private String[] regionNames = {};
public String getCompressorBeanName() {
return this.compressorBeanName;
}
public void setCompressorBeanName(String compressorBeanName) {
this.compressorBeanName = compressorBeanName;
}
public String[] getRegionNames() {
return this.regionNames;
}
public void setRegionNames(String[] regionNames) {
this.regionNames = regionNames;
}
}
public static class OffHeapProperties {
|
private String memorySize;
private String[] regionNames = {};
public String getMemorySize() {
return this.memorySize;
}
public void setMemorySize(String memorySize) {
this.memorySize = memorySize;
}
public String[] getRegionNames() {
return this.regionNames;
}
public void setRegionNames(String[] regionNames) {
this.regionNames = regionNames;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java
| 2
|
请完成以下Java代码
|
public IPair<String, String> splitIntoStreet1AndStreet2(@NonNull final String streets1And2)
{
final List<String> list = Splitter.on(STREET_DELIMITER)
.limit(2)
.splitToList(streets1And2);
return ImmutablePair.of(
list.size() > 0 ? list.get(0) : null,
list.size() > 1 ? list.get(1) : null);
}
private static String dateToCsvString(@Nullable final LocalDate date)
{
if (date == null)
{
return "";
}
return date.format(DATE_FORMATTER);
}
private static String timeToString(@Nullable final LocalTime time)
{
if (time == null)
{
return "";
}
return time.format(TIME_FORMATTER);
}
private static String intToString(@NonNull final Optional<Integer> integer)
{
if (integer.isPresent())
{
return Integer.toString(integer.get());
}
return "";
}
private static String intToString(@Nullable final Integer integer)
{
if (integer == null)
{
return "";
}
return Integer.toString(integer);
}
private static String bigDecimalToString(@Nullable final BigDecimal bigDecimal)
{
|
if (bigDecimal == null)
{
return "";
}
return bigDecimal.toString();
}
private static String stringToString(@NonNull final Optional<String> string)
{
if (string.isPresent())
{
return string.get();
}
return "";
}
private String truncateCheckDigitFromParcelNo(@NonNull final String parcelNumber)
{
return StringUtils.trunc(parcelNumber, 11, TruncateAt.STRING_END);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\Converters.java
| 1
|
请完成以下Java代码
|
public class SysTenant implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编码
*/
private Integer id;
/**
* 名称
*/
private String name;
/**
* 创建人
*/
@Dict(dictTable ="sys_user",dicText = "realname",dicCode = "username")
private String createBy;
/**
* 创建时间
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 开始时间
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date beginDate;
/**
* 结束时间
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date endDate;
/**
* 状态 1正常 0冻结
*/
@Dict(dicCode = "tenant_status")
private Integer status;
/**
* 所属行业
*/
@Dict(dicCode = "trade")
private String trade;
/**
* 公司规模
*/
@Dict(dicCode = "company_size")
private String companySize;
/**
* 公司地址
*/
private String companyAddress;
/**
* 公司logo
*/
private String companyLogo;
|
/**
* 门牌号
*/
private String houseNumber;
/**
* 工作地点
*/
private String workPlace;
/**
* 二级域名(暂时无用,预留字段)
*/
private String secondaryDomain;
/**
* 登录背景图片(暂时无用,预留字段)
*/
private String loginBkgdImg;
/**
* 职级
*/
@Dict(dicCode = "company_rank")
private String position;
/**
* 部门
*/
@Dict(dicCode = "company_department")
private String department;
@TableLogic
private Integer delFlag;
/**更新人登录名称*/
private String updateBy;
/**更新日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 允许申请管理员 1允许 0不允许
*/
private Integer applyStatus;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysTenant.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isAutoStartup() {
return this.autoStartup;
}
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
public Duration getStartupDelay() {
return this.startupDelay;
}
public void setStartupDelay(Duration startupDelay) {
this.startupDelay = startupDelay;
}
public boolean isWaitForJobsToCompleteOnShutdown() {
return this.waitForJobsToCompleteOnShutdown;
|
}
public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
}
public boolean isOverwriteExistingJobs() {
return this.overwriteExistingJobs;
}
public void setOverwriteExistingJobs(boolean overwriteExistingJobs) {
this.overwriteExistingJobs = overwriteExistingJobs;
}
public Map<String, String> getProperties() {
return this.properties;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-quartz\src\main\java\org\springframework\boot\quartz\autoconfigure\QuartzProperties.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.