instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private CustomerTradeMargin toCustomerTradeMargin(@NonNull final I_C_Customer_Trade_Margin record)
{
final CustomerTradeMarginId customerTradeMarginId = CustomerTradeMarginId.ofRepoId(record.getC_Customer_Trade_Margin_ID());
return CustomerTradeMargin.builder()
.customerTradeMarginId(customerTradeMarginId)
.commissionProductId(ProductId.ofRepoId(record.getCommission_Product_ID()))
.pointsPrecision(record.getPointsPrecision())
.name(record.getName())
.description(record.getDescription())
.lines(retrieveLinesForTradeMargin(customerTradeMarginId))
.build();
}
@NonNull
private ImmutableList<CustomerTradeMarginLine> retrieveLinesForTradeMargin(@NonNull final CustomerTradeMarginId customerTradeMarginId)
{
return queryBL.createQueryBuilder(I_C_Customer_Trade_Margin_Line.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Customer_Trade_Margin_Line.COLUMNNAME_C_Customer_Trade_Margin_ID, customerTradeMarginId)
.create()
.stream()
.map(this::toCustomerTradeMarginLine)
.collect(ImmutableList.toImmutableList()); | }
@NonNull
private CustomerTradeMarginLine toCustomerTradeMarginLine(@NonNull final I_C_Customer_Trade_Margin_Line record)
{
final CustomerTradeMarginId customerTradeMarginId = CustomerTradeMarginId.ofRepoId(record.getC_Customer_Trade_Margin_ID());
return CustomerTradeMarginLine.builder()
.customerTradeMarginLineId(CustomerTradeMarginLineId.ofRepoId(customerTradeMarginId, record.getC_Customer_Trade_Margin_Line_ID()))
.customerTradeMarginId(customerTradeMarginId)
.seqNo(record.getSeqNo())
.marginPercent(record.getMargin())
.customerId(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_Customer_ID()))
.productCategoryId(ProductCategoryId.ofRepoIdOrNull(record.getM_Product_Category_ID()))
.productId(ProductId.ofRepoIdOrNull(record.getM_Product_ID()))
.active(record.isActive())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserService {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestTemplate restTemplate;
@HystrixCollapser(batchMethod = "findUserBatch", collapserProperties = {
@HystrixProperty(name = "timerDelayInMilliseconds", value = "100")
})
public Future<User> findUser(Long id) {
log.info("获取单个用户信息");
// return new AsyncResult<User>() {
// @Override
// public User invoke() {
// return restTemplate.getForObject("http://Server-Provider/user/{id}", User.class, id);
// }
// };
return null;
}
@HystrixCommand
public List<User> findUserBatch(List<Long> ids) {
log.info("批量获取用户信息,ids: " + ids);
User[] users = restTemplate.getForObject("http://Server-Provider/user/users?ids={1}", User[].class, StringUtils.join(ids, ","));
return Arrays.asList(users);
}
public String getCacheKey(Long id) {
return String.valueOf(id);
}
@CacheResult(cacheKeyMethod = "getCacheKey")
@HystrixCommand(fallbackMethod = "getUserDefault", commandKey = "getUserById", groupKey = "userGroup",
threadPoolKey = "getUserThread")
public User getUser(Long id) {
log.info("获取用户信息");
return restTemplate.getForObject("http://Server-Provider/user/{id}", User.class, id);
}
@HystrixCommand(fallbackMethod = "getUserDefault2")
public User getUserDefault(Long id) {
String a = null;
// 测试服务降级
a.toString();
User user = new User();
user.setId(-1L);
user.setUsername("defaultUser"); | user.setPassword("123456");
return user;
}
public User getUserDefault2(Long id, Throwable e) {
System.out.println(e.getMessage());
User user = new User();
user.setId(-2L);
user.setUsername("defaultUser2");
user.setPassword("123456");
return user;
}
public List<User> getUsers() {
return this.restTemplate.getForObject("http://Server-Provider/user", List.class);
}
public String addUser() {
User user = new User(1L, "mrbird", "123456");
HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode();
if (status.is2xxSuccessful()) {
return "新增用户成功";
} else {
return "新增用户失败";
}
}
@CacheRemove(commandKey = "getUserById")
@HystrixCommand
public void updateUser(@CacheKey("id") User user) {
this.restTemplate.put("http://Server-Provider/user", user);
}
public void deleteUser(@PathVariable Long id) {
this.restTemplate.delete("http://Server-Provider/user/{1}", id);
}
} | repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\Service\UserService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void execute()
{
trxManager.runInThreadInheritedTrx(this::reopenPickingJob);
}
private void reopenPickingJob()
{
if (!jobToReopen.getDocStatus().isCompleted())
{
return;
}
final PickingJob reopenedJob = jobToReopen
.withDocStatus(PickingJobDocStatus.Drafted)
.withLockedBy(null);
pickingJobRepository.save(reservePickingSlotIfPossible(reopenedJob));
jobToReopen.getLines().forEach(this::reactivateLine);
}
@NonNull
private PickingJob reservePickingSlotIfPossible(@NonNull final PickingJob pickingJob)
{
final PickingSlotId slotId = pickingJob.getPickingSlotId()
.orElse(null);
if (slotId == null)
{
return pickingJob;
}
return PickingJobAllocatePickingSlotCommand.builder()
.pickingJobRepository(pickingJobRepository)
.pickingSlotService(pickingSlotService)
.pickingJob(pickingJob.withPickingSlot(null))
.pickingSlotId(slotId)
.failIfNotAllocated(false)
.build()
.execute();
}
private void reactivateLine(@NonNull final PickingJobLine line)
{ | line.getSteps().forEach(this::reactivateStepIfNeeded);
}
private void reactivateStepIfNeeded(@NonNull final PickingJobStep step)
{
final IMutableHUContext huContext = huService.createMutableHUContextForProcessing();
step.getPickFroms().getKeys()
.stream()
.map(key -> step.getPickFroms().getPickFrom(key))
.map(PickingJobStepPickFrom::getPickedTo)
.filter(Objects::nonNull)
.map(PickingJobStepPickedTo::getActualPickedHUs)
.flatMap(List::stream)
.filter(pickStepHu -> huIdsToPick.containsKey(pickStepHu.getActualPickedHU().getId()))
.forEach(pickStepHU -> {
final HuId huId = pickStepHU.getActualPickedHU().getId();
final I_M_HU hu = huService.getById(huId);
shipmentScheduleService.addQtyPickedAndUpdateHU(AddQtyPickedRequest.builder()
.scheduleId(step.getScheduleId())
.qtyPicked(CatchWeightHelper.extractQtys(
huContext,
step.getProductId(),
pickStepHU.getQtyPicked(),
hu))
.tuOrVHU(hu)
.huContext(huContext)
.anonymousHuPickedOnTheFly(huIdsToPick.get(huId).isAnonymousHuPickedOnTheFly())
.build());
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobReopenCommand.java | 2 |
请完成以下Java代码 | protected final IQueryBuilder<I_C_Conversion_Rate> retrieveRateQuery(
@NonNull final CurrencyConversionContext conversionCtx,
@NonNull final CurrencyId currencyFromId,
@NonNull final CurrencyId currencyToId)
{
final CurrencyConversionTypeId conversionTypeId = conversionCtx.getConversionTypeId();
final Instant conversionDate = conversionCtx.getConversionDate();
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_Conversion_Rate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Conversion_Rate.COLUMN_C_Currency_ID, currencyFromId)
.addEqualsFilter(I_C_Conversion_Rate.COLUMN_C_Currency_ID_To, currencyToId)
.addEqualsFilter(I_C_Conversion_Rate.COLUMN_C_ConversionType_ID, conversionTypeId)
.addCompareFilter(I_C_Conversion_Rate.COLUMN_ValidFrom, Operator.LESS_OR_EQUAL, conversionDate)
.addCompareFilter(I_C_Conversion_Rate.COLUMN_ValidTo, Operator.GREATER_OR_EQUAL, conversionDate)
.addInArrayOrAllFilter(I_C_Conversion_Rate.COLUMN_AD_Client_ID, ClientId.SYSTEM, conversionCtx.getClientId())
.addInArrayOrAllFilter(I_C_Conversion_Rate.COLUMN_AD_Org_ID, OrgId.ANY, conversionCtx.getOrgId())
//
.orderBy()
.addColumn(I_C_Conversion_Rate.COLUMN_AD_Client_ID, Direction.Descending, Nulls.Last)
.addColumn(I_C_Conversion_Rate.COLUMN_AD_Org_ID, Direction.Descending, Nulls.Last)
.addColumn(I_C_Conversion_Rate.COLUMN_ValidFrom, Direction.Descending, Nulls.Last)
.endOrderBy()
//
.setLimit(QueryLimit.ONE) // first only
; | }
@Override
public @Nullable BigDecimal retrieveRateOrNull(
final CurrencyConversionContext conversionCtx,
final CurrencyId currencyFromId,
final CurrencyId currencyToId)
{
final List<Map<String, Object>> recordsList = retrieveRateQuery(conversionCtx, currencyFromId, currencyToId)
.setLimit(QueryLimit.ONE)
.create()
.listColumns(I_C_Conversion_Rate.COLUMNNAME_MultiplyRate);
if (recordsList.isEmpty())
{
return null;
}
final Map<String, Object> record = recordsList.get(0);
return (BigDecimal)record.get(I_C_Conversion_Rate.COLUMNNAME_MultiplyRate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyDAO.java | 1 |
请完成以下Java代码 | private MColumn retrieveColumn(final I_EXP_FormatLine formatLine)
{
final int adColumnId = formatLine.getAD_Column_ID();
if (adColumnId <= 0)
{
throw new ExportProcessorException(MSG_EXPColumnMandatory)
.setParameter(I_EXP_FormatLine.COLUMNNAME_EXP_FormatLine_ID, formatLine);
}
final Properties ctx = InterfaceWrapperHelper.getCtx(formatLine);
return MColumn.get(ctx, adColumnId);
}
// NOTE: commented @Cached out because is no longer applied anyways (not a service)
// @Cached
public IReplicationAccessContext getDefaultIReplicationAccessContext()
{
final int limit = IQuery.NO_LIMIT;
final boolean isApplyAccessFilter = false;
return new ReplicationAccessContext(limit, isApplyAccessFilter); // TODO hardcoded
}
// metas: end
private static int getDisplayType(@NonNull final MColumn column, @NonNull final I_EXP_FormatLine formatLine)
{
if (formatLine.getAD_Reference_Override_ID() > 0)
{
return formatLine.getAD_Reference_Override_ID();
}
return column.getAD_Reference_ID();
} | private void createAttachment(@NonNull final CreateAttachmentRequest request)
{
try
{
final String documentAsString = writeDocumentToString(outDocument);
final byte[] data = documentAsString.getBytes();
final AttachmentEntryService attachmentEntryService = SpringContextHolder.instance.getBean(AttachmentEntryService.class);
attachmentEntryService.createNewAttachment(request.getTarget(), request.getAttachmentName(), data);
}
catch (final Exception exception)
{
throw AdempiereException.wrapIfNeeded(exception);
}
}
private static String writeDocumentToString(@NonNull final Document document) throws TransformerException
{
final TransformerFactory tranFactory = TransformerFactory.newInstance();
final Transformer aTransformer = tranFactory.newTransformer();
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
final Source src = new DOMSource(document);
final Writer writer = new StringWriter();
final Result dest2 = new StreamResult(writer);
aTransformer.transform(src, dest2);
return writer.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\exp\ExportHelper.java | 1 |
请完成以下Java代码 | public int size() {
return elements.length;
}
@Override
public boolean isEmpty() {
return elements.length == 0;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <T1> T1[] toArray(T1[] a) {
return null;
}
@Override
public boolean add(T t) {
return false;
}
@Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
} | @Override
public boolean addAll(Collection<? extends T> c) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public void clear() {
}
} | repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\parallelstream\MyBookContainer.java | 1 |
请完成以下Java代码 | public I_EXP_ProcessorParameter createParameter(String key, String name, String desc, String help, String value)
{
final String whereClause = I_EXP_ProcessorParameter.COLUMNNAME_EXP_Processor_ID+"=?"
+" AND "+I_EXP_ProcessorParameter.COLUMNNAME_Value+"=?";
I_EXP_ProcessorParameter para = new Query(this.getCtx(), I_EXP_ProcessorParameter.Table_Name, whereClause, this.get_TrxName())
.setParameters(this.getEXP_Processor_ID(), key)
.firstOnly(I_EXP_ProcessorParameter.class);
if (para == null)
{
para = new X_EXP_ProcessorParameter(this.getCtx(), 0, this.get_TrxName());
para.setEXP_Processor_ID(this.getEXP_Processor_ID());
para.setValue(key);
}
para.setIsActive(true);
para.setName(name);
para.setDescription(desc);
para.setHelp(help);
para.setParameterValue(value);
InterfaceWrapperHelper.save(para);
return para;
}
@Override
protected boolean beforeDelete() | {
deleteParameters();
// deleteLog(true);
return true;
}
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
return false;
if (newRecord || is_ValueChanged(COLUMNNAME_EXP_Processor_Type_ID))
{
deleteParameters();
final IExportProcessor proc = getIExportProcessor();
proc.createInitialParameters(this);
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEXPProcessor.java | 1 |
请完成以下Java代码 | public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(final String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public void setOperation(final String operation) {
this.operation = operation;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
return other.name == null;
} else
return name.equals(other.name);
}
@Override | public String toString() {
return "Bar [name=" + name + "]";
}
@PrePersist
public void onPrePersist() {
LOGGER.info("@PrePersist");
audit(OPERATION.INSERT);
}
@PreUpdate
public void onPreUpdate() {
LOGGER.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
LOGGER.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\model\Bar.java | 1 |
请完成以下Java代码 | public class PaymentTypeInformation19CH {
@XmlElement(name = "InstrPrty")
@XmlSchemaType(name = "string")
protected Priority2Code instrPrty;
@XmlElement(name = "SvcLvl")
protected ServiceLevel8Choice svcLvl;
@XmlElement(name = "LclInstrm")
protected LocalInstrument2Choice lclInstrm;
@XmlElement(name = "CtgyPurp")
protected CategoryPurpose1CHCode ctgyPurp;
/**
* Gets the value of the instrPrty property.
*
* @return
* possible object is
* {@link Priority2Code }
*
*/
public Priority2Code getInstrPrty() {
return instrPrty;
}
/**
* Sets the value of the instrPrty property.
*
* @param value
* allowed object is
* {@link Priority2Code }
*
*/
public void setInstrPrty(Priority2Code value) {
this.instrPrty = value;
}
/**
* Gets the value of the svcLvl property.
*
* @return
* possible object is
* {@link ServiceLevel8Choice }
*
*/
public ServiceLevel8Choice getSvcLvl() {
return svcLvl;
}
/**
* Sets the value of the svcLvl property.
*
* @param value
* allowed object is
* {@link ServiceLevel8Choice }
*
*/
public void setSvcLvl(ServiceLevel8Choice value) {
this.svcLvl = value;
}
/**
* Gets the value of the lclInstrm property.
*
* @return
* possible object is
* {@link LocalInstrument2Choice } | *
*/
public LocalInstrument2Choice getLclInstrm() {
return lclInstrm;
}
/**
* Sets the value of the lclInstrm property.
*
* @param value
* allowed object is
* {@link LocalInstrument2Choice }
*
*/
public void setLclInstrm(LocalInstrument2Choice value) {
this.lclInstrm = value;
}
/**
* Gets the value of the ctgyPurp property.
*
* @return
* possible object is
* {@link CategoryPurpose1CHCode }
*
*/
public CategoryPurpose1CHCode getCtgyPurp() {
return ctgyPurp;
}
/**
* Sets the value of the ctgyPurp property.
*
* @param value
* allowed object is
* {@link CategoryPurpose1CHCode }
*
*/
public void setCtgyPurp(CategoryPurpose1CHCode value) {
this.ctgyPurp = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentTypeInformation19CH.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: listener-demo
# RabbitMQ 相关配置项
rabbitmq:
host: localhost
port: 5672
username: guest
password: g | uest
server:
port: ${random.int[10000,19999]} # 随机端口,方便启动多个消费者 | repos\SpringBoot-Labs-master\labx-18\labx-18-sc-bus-rabbitmq-demo-listener\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public String getOperationRef() {
return operationRef;
}
public void setOperationRef(String operationRef) {
this.operationRef = operationRef;
}
public String getExtensionId() {
return extensionId;
}
public void setExtensionId(String extensionId) {
this.extensionId = extensionId;
}
public boolean isExtended() {
return extensionId != null && !extensionId.isEmpty();
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public boolean isUseLocalScopeForResultVariable() {
return useLocalScopeForResultVariable;
}
public void setUseLocalScopeForResultVariable(boolean useLocalScopeForResultVariable) {
this.useLocalScopeForResultVariable = useLocalScopeForResultVariable;
}
public boolean isTriggerable() {
return triggerable;
}
public void setTriggerable(boolean triggerable) {
this.triggerable = triggerable;
}
public boolean isStoreResultVariableAsTransient() {
return storeResultVariableAsTransient; | }
public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) {
this.storeResultVariableAsTransient = storeResultVariableAsTransient;
}
@Override
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setUseLocalScopeForResultVariable(otherElement.isUseLocalScopeForResultVariable());
setTriggerable(otherElement.isTriggerable());
setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient());
fieldExtensions = new ArrayList<>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ServiceTask.java | 1 |
请完成以下Java代码 | public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}"); | return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java | 1 |
请完成以下Java代码 | public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
public String getCategory() {
return category;
}
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
public Map<String, Object> getTaskLocalVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (VariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (VariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public List<VariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new VariableInitializingList();
}
return queryVariables; | }
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
public Integer getAppVersion() {
return this.appVersion;
}
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public String toString() {
return "Task[id=" + id + ", name=" + name + "]";
}
private String truncate(String string, int maxLength) {
if (string != null) {
return string.length() > maxLength ? string.substring(0, maxLength) : string;
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java | 1 |
请完成以下Java代码 | private void addClosingDifference(@NonNull final Money closingDifferenceAmt, @NonNull final UserId cashierId, @Nullable final String description)
{
add(POSCashJournalLine.builder()
.type(POSCashJournalLineType.CASH_CLOSING_DIFFERENCE)
.amount(closingDifferenceAmt)
.cashierId(cashierId)
.description(description)
.build());
}
private void add(@NonNull final POSCashJournalLine line)
{
lines.add(line);
updateTotals();
}
private void updateTotals()
{
Money cashEndingBalance = this.cashBeginningBalance;
for (final POSCashJournalLine line : lines)
{
if (line.isCash())
{
cashEndingBalance = cashEndingBalance.add(line.getAmount());
}
}
this.cashEndingBalance = cashEndingBalance;
}
public void addPayments(final POSOrder posOrder)
{
final POSOrderId posOrderId = posOrder.getLocalIdNotNull(); | final UserId cashierId = posOrder.getCashierId();
posOrder.streamPaymentsNotDeleted()
.filter(POSPayment::isSuccessful)
.forEach(posPayment -> addPayment(posPayment, posOrderId, cashierId));
}
private void addPayment(final POSPayment posPayment, POSOrderId posOrderId, UserId cashierId)
{
add(
POSCashJournalLine.builder()
.type(POSCashJournalLineType.ofPaymentMethod(posPayment.getPaymentMethod()))
.amount(posPayment.getAmount())
.cashierId(cashierId)
.posOrderAndPaymentId(POSOrderAndPaymentId.of(posOrderId, posPayment.getLocalIdNotNull()))
.build()
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSCashJournal.java | 1 |
请完成以下Java代码 | public class ReceiptScheduleValidator extends AbstractModuleInterceptor
{
public static final ReceiptScheduleValidator instance = new ReceiptScheduleValidator();
private ReceiptScheduleValidator()
{
}
@Override
protected void onBeforeInit()
{
//
// 07344: Register RS AggregationKey Dependencies
registerRSAggregationKeyDependencies();
}
@Override
protected void registerInterceptors(@NonNull IModelValidationEngine engine)
{
engine.addModelValidator(new C_Order_ReceiptSchedule());
engine.addModelValidator(new M_ReceiptSchedule());
engine.addModelValidator(new M_ReceiptSchedule_Alloc());
engine.addModelValidator(new C_OrderLine_ReceiptSchedule());
}
@Override
protected void onAfterInit()
{
registerFactories();
// task 08452
Services.get(IReceiptScheduleBL.class).addReceiptScheduleListener(OrderLineReceiptScheduleListener.INSTANCE);
}
/**
* Public for testing purposes only!
*/
public static void registerRSAggregationKeyDependencies()
{
final IAggregationKeyRegistry keyRegistry = Services.get(IAggregationKeyRegistry.class); | final String registrationKey = ReceiptScheduleHeaderAggregationKeyBuilder.REGISTRATION_KEY;
//
// Register Handlers
keyRegistry.registerAggregationKeyValueHandler(registrationKey, new ReceiptScheduleKeyValueHandler());
//
// Register ReceiptScheduleHeaderAggregationKeyBuilder
keyRegistry.registerDependsOnColumnnames(registrationKey,
I_M_ReceiptSchedule.COLUMNNAME_C_DocType_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Location_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BP_Location_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID,
I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_AD_User_ID,
I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID,
I_M_ReceiptSchedule.COLUMNNAME_DateOrdered,
I_M_ReceiptSchedule.COLUMNNAME_C_Order_ID,
I_M_ReceiptSchedule.COLUMNNAME_POReference);
}
public void registerFactories()
{
Services.get(IAttributeSetInstanceAwareFactoryService.class)
.registerFactoryForTableName(I_M_ReceiptSchedule.Table_Name, new ReceiptScheduleASIAwareFactory());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\ReceiptScheduleValidator.java | 1 |
请完成以下Java代码 | public void setValidateWorkflow (final @Nullable java.lang.String ValidateWorkflow)
{
set_Value (COLUMNNAME_ValidateWorkflow, ValidateWorkflow);
}
@Override
public java.lang.String getValidateWorkflow()
{
return get_ValueAsString(COLUMNNAME_ValidateWorkflow);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVersion (final int Version)
{
set_Value (COLUMNNAME_Version, Version);
}
@Override
public int getVersion()
{
return get_ValueAsInt(COLUMNNAME_Version);
}
@Override
public void setWaitingTime (final int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public int getWaitingTime() | {
return get_ValueAsInt(COLUMNNAME_WaitingTime);
}
/**
* WorkflowType AD_Reference_ID=328
* Reference name: AD_Workflow Type
*/
public static final int WORKFLOWTYPE_AD_Reference_ID=328;
/** General = G */
public static final String WORKFLOWTYPE_General = "G";
/** Document Process = P */
public static final String WORKFLOWTYPE_DocumentProcess = "P";
/** Document Value = V */
public static final String WORKFLOWTYPE_DocumentValue = "V";
/** Manufacturing = M */
public static final String WORKFLOWTYPE_Manufacturing = "M";
/** Quality = Q */
public static final String WORKFLOWTYPE_Quality = "Q";
/** Repair = R */
public static final String WORKFLOWTYPE_Repair = "R";
@Override
public void setWorkflowType (final java.lang.String WorkflowType)
{
set_Value (COLUMNNAME_WorkflowType, WorkflowType);
}
@Override
public java.lang.String getWorkflowType()
{
return get_ValueAsString(COLUMNNAME_WorkflowType);
}
@Override
public void setWorkingTime (final int WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public int getWorkingTime()
{
return get_ValueAsInt(COLUMNNAME_WorkingTime);
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow.java | 1 |
请完成以下Java代码 | public class MSLAMeasure extends X_PA_SLA_Measure
{
/**
*
*/
private static final long serialVersionUID = -2844941499854811255L;
/**
* Standard Constructor
* @param ctx context
* @param PA_SLA_Measure_ID id
* @param trxName transaction
*/
public MSLAMeasure (Properties ctx, int PA_SLA_Measure_ID, String trxName)
{
super (ctx, PA_SLA_Measure_ID, trxName);
if (PA_SLA_Measure_ID == 0)
{
// setPA_SLA_Goal_ID (0);
setDateTrx (new Timestamp(System.currentTimeMillis()));
setMeasureActual (Env.ZERO);
setProcessed (false);
}
} // MSLAMeasure
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MSLAMeasure (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MSLAMeasure
/**
* Parent Constructor
* @param goal parent
* @param DateTrx optional date
* @param MeasureActual optional measure
* @param Description optional description
*/
public MSLAMeasure (MSLAGoal goal, Timestamp DateTrx, BigDecimal MeasureActual,
String Description)
{
super (goal.getCtx(), 0, goal.get_TrxName());
setClientOrg(goal);
setPA_SLA_Goal_ID(goal.getPA_SLA_Goal_ID());
if (DateTrx != null)
setDateTrx (DateTrx); | else
setDateTrx (new Timestamp(System.currentTimeMillis()));
if (MeasureActual != null)
setMeasureActual(MeasureActual);
else
setMeasureActual (Env.ZERO);
if (Description != null)
setDescription(Description);
} // MSLAMeasure
/**
* Set Link to Source
* @param AD_Table_ID table
* @param Record_ID record
*/
public void setLink (int AD_Table_ID, int Record_ID)
{
setAD_Table_ID(AD_Table_ID);
setRecord_ID(Record_ID);
} // setLink
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MSLAMeasure[");
sb.append(get_ID()).append("-PA_SLA_Goal_ID=").append(getPA_SLA_Goal_ID())
.append(",").append(getDateTrx())
.append(",Actual=").append(getMeasureActual())
.append ("]");
return sb.toString ();
} // toString
} // MSLAMeasure | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSLAMeasure.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getContractNumber() {
return contractNumber;
}
/**
* Sets the value of the contractNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContractNumber(String value) {
this.contractNumber = value;
}
/**
* Gets the value of the agreementNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAgreementNumber() {
return agreementNumber;
}
/**
* Sets the value of the agreementNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAgreementNumber(String value) {
this.agreementNumber = value;
}
/**
* Gets the value of the timeForPayment property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getTimeForPayment() {
return timeForPayment;
}
/**
* Sets the value of the timeForPayment property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setTimeForPayment(BigInteger value) {
this.timeForPayment = value;
}
/**
* Additional free text.Gets the value of the freeText 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 freeText property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFreeText().add(newItem);
* </pre>
*
* | * <p>
* Objects of the following type(s) are allowed in the list
* {@link FreeTextType }
*
*
*/
public List<FreeTextType> getFreeText() {
if (freeText == null) {
freeText = new ArrayList<FreeTextType>();
}
return this.freeText;
}
/**
* Reference to the consignment.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDERSExtensionType.java | 2 |
请完成以下Java代码 | public class DemoController {
@Resource
private DemoService demoService;
@GetMapping("/monoTest")
public Mono<Object> monoTest() {
// method one
// String data = getOneResult("monoTest()");
// return Mono.just(data);
// method two
return Mono.create(cityMonoSink -> {
String data = demoService.getOneResult("monoTest()");
cityMonoSink.success(data); | });
}
@GetMapping("/fluxTest")
public Flux<Object> fluxTest() {
// method one
// List<String> list = getMultiResult("fluxTest()");
// return Flux.fromIterable(list);
// method two
return Flux.fromIterable(demoService.getMultiResult("fluxTest()"));
}
} | repos\springboot-demo-master\webflux\src\main\java\com\et\webflux\DemoController.java | 1 |
请完成以下Java代码 | public Optional<String> getTableIdColumnName(@NonNull final String recordIdColumnName)
{
return tableAndRecordColumnNames.stream()
.filter(tableAndRecordColumnName -> tableAndRecordColumnName.equalsByColumnName(recordIdColumnName))
.map(TableAndColumnName::getTableNameAsString)
.findFirst();
}
@Value
@Builder
private static class POInfoHeader
{
@NonNull String tableName;
@NonNull AdTableId adTableId;
@NonNull TableAccessLevel accessLevel;
boolean isView;
boolean isChangeLog;
int webuiViewPageLength;
@NonNull TableCloningEnabled cloningEnabled;
@NonNull TableWhenChildCloningStrategy whenChildCloningStrategy;
@NonNull TableDownlineCloningStrategy downlineCloningStrategy;
}
public static class POInfoMap
{
private final ImmutableMap<AdTableId, POInfo> byTableId;
private final ImmutableMap<String, POInfo> byTableNameUC;
public POInfoMap(@NonNull final List<POInfo> poInfos)
{
byTableId = Maps.uniqueIndex(poInfos, POInfo::getAdTableId);
byTableNameUC = Maps.uniqueIndex(poInfos, POInfo::getTableNameUC);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("size", byTableId.size())
.toString();
} | @Nullable
public POInfo getByTableIdOrNull(@NonNull final AdTableId tableId)
{
return byTableId.get(tableId);
}
@NonNull
public POInfo getByTableId(@NonNull final AdTableId tableId)
{
final POInfo poInfo = getByTableIdOrNull(tableId);
if (poInfo == null)
{
throw new AdempiereException("No POInfo found for " + tableId);
}
return poInfo;
}
@Nullable
public POInfo getByTableNameOrNull(@NonNull final String tableName)
{
return byTableNameUC.get(tableName.toUpperCase());
}
@NonNull
public POInfo getByTableName(@NonNull final String tableName)
{
final POInfo poInfo = getByTableNameOrNull(tableName);
if (poInfo == null)
{
throw new AdempiereException("No POInfo found for " + tableName);
}
return poInfo;
}
public Stream<POInfo> stream() {return byTableId.values().stream();}
public int size() {return byTableId.size();}
public ImmutableCollection<POInfo> toCollection() {return byTableId.values();}
}
} // POInfo | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfo.java | 1 |
请完成以下Spring Boot application配置 | jasypt:
encryptor:
password: G9w0BAQEFAASCBKYwggSiAgEAAoIBAQC
property:
prefix: "ENC@["
suffix: "]"
javastack:
username: ENC@[VA058GV86AaUx4wSoCKekKrDJv6tP4eTwWkoCGHnt6Tb3F7ETJnKAs3QiR | kZFD5k]
password: ENC@[7Y7FVXO5qS4lAx3o5B4atyHW8kGUv0o6903xL2ofTOicdcJw71/m+UeFUVfX0VPM] | repos\spring-boot-best-practice-master\spring-boot-jasypt\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** MediaType AD_Reference_ID=388 */
public static final int MEDIATYPE_AD_Reference_ID=388;
/** image/gif = GIF */
public static final String MEDIATYPE_ImageGif = "GIF";
/** image/jpeg = JPG */
public static final String MEDIATYPE_ImageJpeg = "JPG";
/** image/png = PNG */
public static final String MEDIATYPE_ImagePng = "PNG";
/** application/pdf = PDF */
public static final String MEDIATYPE_ApplicationPdf = "PDF";
/** text/css = CSS */
public static final String MEDIATYPE_TextCss = "CSS";
/** text/js = JS */
public static final String MEDIATYPE_TextJs = "JS";
/** Set Media Type.
@param MediaType
Defines the media type for the browser
*/
public void setMediaType (String MediaType)
{
set_Value (COLUMNNAME_MediaType, MediaType);
}
/** Get Media Type.
@return Defines the media type for the browser
*/
public String getMediaType ()
{ | return (String)get_Value(COLUMNNAME_MediaType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media.java | 1 |
请完成以下Java代码 | public void setShipmentAllocation_BestBefore_Policy (final @Nullable java.lang.String ShipmentAllocation_BestBefore_Policy)
{
set_Value (COLUMNNAME_ShipmentAllocation_BestBefore_Policy, ShipmentAllocation_BestBefore_Policy);
}
@Override
public java.lang.String getShipmentAllocation_BestBefore_Policy()
{
return get_ValueAsString(COLUMNNAME_ShipmentAllocation_BestBefore_Policy);
}
@Override
public void setSinglePriceTag_ID (final @Nullable java.lang.String SinglePriceTag_ID)
{
set_ValueNoCheck (COLUMNNAME_SinglePriceTag_ID, SinglePriceTag_ID);
} | @Override
public java.lang.String getSinglePriceTag_ID()
{
return get_ValueAsString(COLUMNNAME_SinglePriceTag_ID);
}
@Override
public void setStatus (final @Nullable java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setData(T data) {
this.data = data;
}
public static class ResponseParam {
private int code;
private String msg;
private ResponseParam(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResponseParam buildParam(int code, String msg) {
return new ResponseParam(code, msg);
}
public int getCode() {
return code; | }
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\config\BaseResult.java | 2 |
请完成以下Java代码 | protected HistoricProcessInstanceEntity findProcessInstanceById(String instanceId, CommandContext commandContext) {
return commandContext.getHistoricProcessInstanceManager()
.findHistoricProcessInstance(instanceId);
}
protected void registerTransactionHandler(SetRemovalTimeBatchConfiguration configuration,
Map<Class<? extends DbEntity>, DbOperation> operations,
Integer chunkSize,
MessageEntity currentJob,
CommandContext commandContext) {
CommandExecutor newCommandExecutor = commandContext.getProcessEngineConfiguration().getCommandExecutorTxRequiresNew();
TransactionListener transactionResulthandler = createTransactionHandler(configuration, operations, chunkSize,
currentJob, newCommandExecutor);
commandContext.getTransactionContext().addTransactionListener(TransactionState.COMMITTED, transactionResulthandler);
}
protected int getUpdateChunkSize(SetRemovalTimeBatchConfiguration configuration, CommandContext commandContext) {
return configuration.getChunkSize() == null
? commandContext.getProcessEngineConfiguration().getRemovalTimeUpdateChunkSize()
: configuration.getChunkSize();
}
protected TransactionListener createTransactionHandler(SetRemovalTimeBatchConfiguration configuration,
Map<Class<? extends DbEntity>, DbOperation> operations,
Integer chunkSize,
MessageEntity currentJob,
CommandExecutor newCommandExecutor) {
return new ProcessSetRemovalTimeResultHandler(configuration, chunkSize, newCommandExecutor, this,
currentJob.getId(), operations);
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override | protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration,
List<String> processInstanceIds) {
return new SetRemovalTimeBatchConfiguration(processInstanceIds)
.setRemovalTime(configuration.getRemovalTime())
.setHasRemovalTime(configuration.hasRemovalTime())
.setHierarchical(configuration.isHierarchical())
.setUpdateInChunks(configuration.isUpdateInChunks())
.setChunkSize(configuration.getChunkSize());
}
@Override
protected SetRemovalTimeJsonConverter getJsonConverterInstance() {
return SetRemovalTimeJsonConverter.INSTANCE;
}
@Override
public int calculateInvocationsPerBatchJob(String batchType, SetRemovalTimeBatchConfiguration configuration) {
if (configuration.isUpdateInChunks()) {
return 1;
}
return super.calculateInvocationsPerBatchJob(batchType, configuration);
}
@Override
public String getType() {
return Batch.TYPE_PROCESS_SET_REMOVAL_TIME;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\ProcessSetRemovalTimeJobHandler.java | 1 |
请完成以下Java代码 | public void iterateWithEnhancedForLoop() {
for (String country : countries) {
System.out.println(country);
}
}
/**
* Iterate over a list using an Iterator
*/
public void iterateWithIterator() {
Iterator<String> countriesIterator = countries.iterator();
while(countriesIterator.hasNext()) {
System.out.println(countriesIterator.next());
}
}
/**
* Iterate over a list using a ListIterator
*/
public void iterateWithListIterator() {
ListIterator<String> listIterator = countries.listIterator(); | while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
/**
* Iterate over a list using the Iterable.forEach() method
*/
public void iterateWithForEach() {
countries.forEach(System.out::println);
}
/**
* Iterate over a list using the Stream.forEach() method
*/
public void iterateWithStreamForEach() {
countries.stream().forEach((c) -> System.out.println(c));
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list\src\main\java\com\baeldung\list\WaysToIterate.java | 1 |
请完成以下Java代码 | public class FlowableCmmnEventBuilder {
public static FlowableCaseStartedEvent createCaseStartedEvent(CaseInstance caseInstance) {
return new FlowableCaseStartedEventImpl(caseInstance);
}
public static FlowableCaseEndedEvent createCaseEndedEvent(CaseInstance caseInstance, String endingState) {
return new FlowableCaseEndedEventImpl(caseInstance, endingState);
}
public static FlowableCaseStageStartedEvent createStageStartedEvent(CaseInstance caseInstance, PlanItemInstance stageInstance) {
return new FlowableCaseStageStartedEventImpl(caseInstance, stageInstance);
}
public static FlowableCaseStageEndedEvent createStageEndedEvent(CaseInstance caseInstance, PlanItemInstance stageInstance, String endingState) {
return new FlowableCaseStageEndedEventImpl(caseInstance, stageInstance, endingState);
}
public static FlowableEntityEvent createCaseBusinessStatusUpdatedEvent(CaseInstance caseInstance, String oldBusinessStatus, String newBusinessStatus) {
return new FlowableCaseBusinessStatusUpdatedEventImpl(caseInstance, oldBusinessStatus, newBusinessStatus);
}
public static FlowableEntityEvent createTaskCreatedEvent(Task task) {
FlowableEntityEventImpl event = new FlowableEntityEventImpl(task, FlowableEngineEventType.TASK_CREATED);
event.setScopeId(task.getScopeId());
event.setScopeDefinitionId(task.getScopeDefinitionId());
event.setScopeType(task.getScopeType());
event.setSubScopeId(task.getId()); | return event;
}
public static FlowableEntityEvent createTaskAssignedEvent(Task task) {
FlowableEntityEventImpl event = new FlowableEntityEventImpl(task, FlowableEngineEventType.TASK_ASSIGNED);
event.setScopeId(task.getScopeId());
event.setScopeDefinitionId(task.getScopeDefinitionId());
event.setScopeType(task.getScopeType());
event.setSubScopeId(task.getId());
return event;
}
public static FlowableEntityEvent createTaskCompletedEvent(Task task) {
FlowableEntityEventImpl event = new FlowableEntityEventImpl(task, FlowableEngineEventType.TASK_COMPLETED);
event.setScopeId(task.getScopeId());
event.setScopeDefinitionId(task.getScopeDefinitionId());
event.setScopeType(task.getScopeType());
event.setSubScopeId(task.getId());
return event;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\event\FlowableCmmnEventBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void updateContextAfterError(@NonNull final Exchange exchange)
{
final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange);
final PurchaseOrderRow csvRow = exchange.getProperty(PROPERTY_CURRENT_CSV_ROW, PurchaseOrderRow.class);
final Exception ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
final RuntimeCamelException augmentedEx = new RuntimeCamelException("Exception processing file " + exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY) + " and row '" + csvRow + "'", ex);
exchange.setProperty(Exchange.EXCEPTION_CAUGHT, augmentedEx);
if (csvRow == null || Check.isBlank(csvRow.getExternalHeaderId()))
{
importOrdersRouteContext.errorInUnknownRow();
return;
}
final JsonExternalId externalHeaderId = JsonExternalId.of(csvRow.getExternalHeaderId());
importOrdersRouteContext.getPurchaseCandidatesToProcess().remove(externalHeaderId);
importOrdersRouteContext.getPurchaseCandidatesWithError().add(externalHeaderId);
}
private void enqueueCandidatesProcessor(@NonNull final Exchange exchange)
{
final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); | if (importOrdersRouteContext.isDoNotProcessAtAll())
{
final Object fileName = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY);
throw new RuntimeCamelException("No purchase order candidates from file " + fileName.toString() + " can be imported to metasfresh");
}
final JsonPurchaseCandidatesRequest.JsonPurchaseCandidatesRequestBuilder builder = JsonPurchaseCandidatesRequest.builder();
for (final JsonExternalId externalId : importOrdersRouteContext.getPurchaseCandidatesToProcess())
{
final JsonPurchaseCandidateReference reference = JsonPurchaseCandidateReference.builder()
.externalSystemCode(importOrdersRouteContext.getExternalSystemCode())
.externalHeaderId(externalId)
.build();
builder.purchaseCandidate(reference);
}
exchange.getIn().setBody(builder.build());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\GetPurchaseOrderFromFileRouteBuilder.java | 2 |
请完成以下Java代码 | protected IScriptFactory createScriptFactory()
{
return new RolloutDirScriptFactory();
}
@Override
protected void configureScriptExecutorFactory(final IScriptExecutorFactory scriptExecutorFactory)
{
scriptExecutorFactory.setDryRunMode(config.isJustMarkScriptAsExecuted());
}
@Override
protected IScriptScanner createScriptScanner(final IScriptScannerFactory scriptScannerFactory)
{
final CompositeScriptScanner scriptScanners = new CompositeScriptScanner();
final File sqlDir = constructSqlDir(config.getRolloutDirName());
if (config.getScriptFileName() != null && !config.getScriptFileName().isEmpty())
{
if (new File(config.getScriptFileName()).exists())
{
final String filename = config.getScriptFileName();
final IScriptScanner scriptScanner = scriptScannerFactory.createScriptScannerByFilename(filename);
scriptScanners.addScriptScanner(scriptScanner);
}
else
{
final String filename = sqlDir.getAbsolutePath() + File.separator + config.getScriptFileName();
final IScriptScanner scriptScanner = scriptScannerFactory.createScriptScannerByFilename(filename);
scriptScanners.addScriptScanner(scriptScanner);
}
}
else
{
final String filename = sqlDir.getAbsolutePath();
final IScriptScanner scriptScanner = scriptScannerFactory.createScriptScannerByFilename(filename);
scriptScanners.addScriptScanner(scriptScanner);
}
//
config.getAdditionalSqlDirs()
.stream()
.forEach(file -> {
final IScriptScanner scriptScanner = scriptScannerFactory.createScriptScanner(file);
if (scriptScanner == null)
{ | throw new RuntimeException("Cannot create script scanner from " + file);
}
logger.info("Additional SQL source: {}", file);
scriptScanners.addScriptScanner(scriptScanner);
});
return new GloballyOrderedScannerDecorator(scriptScanners);
}
@Override
protected IScriptsApplierListener createScriptsApplierListener()
{
return config.getScriptsApplierListener();
}
@Override
protected IDatabase createDatabase()
{
return dbconnectionMaker.createDb(dbConnectionSettings, dbName);
}
};
scriptApplier.run();
}
private File constructSqlDir(final String rolloutDirName)
{
if (rolloutDirName == null || rolloutDirName.trim().isEmpty())
{
throw new IllegalArgumentException("Rollout directory not specified");
}
final File rolloutDir = directoryChecker.checkDirectory("Rollout directory", rolloutDirName);
logger.info("Rollout directory: " + rolloutDir);
final File sqlDir = directoryChecker.checkDirectory("SQL Directory", new File(rolloutDir, "sql"));
logger.info("SQL directory: {}", sqlDir);
return sqlDir;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\MigrationScriptApplier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class TasksController {
@Autowired
private TasksService tasksService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public TaskResponse createTask(@RequestBody CreateTaskRequest body) {
var task = tasksService.createTask(body.title(), body.createdBy());
return buildResponse(task);
}
@GetMapping
public List<TaskResponse> searchTasks(@RequestParam("status") Optional<String> status, @RequestParam("createdBy") Optional<String> createdBy) {
var tasks = tasksService.search(status, createdBy);
return tasks.stream()
.map(this::buildResponse)
.collect(Collectors.toList());
}
@GetMapping("/{id}")
public TaskResponse getTask(@PathVariable("id") String id) {
var task = tasksService.getTaskById(id);
return buildResponse(task);
}
@DeleteMapping("/{id}") | public void deleteTask(@PathVariable("id") String id) {
tasksService.deleteTaskById(id);
}
@PatchMapping("/{id}")
public TaskResponse patchTask(@PathVariable("id") String id, @RequestBody PatchTaskRequest body) {
var task = tasksService.updateTask(id, body.status(), body.assignedTo());
return buildResponse(task);
}
private TaskResponse buildResponse(final TaskRecord task) {
return new TaskResponse(task.getId(), task.getTitle(), task.getCreated(), task.getCreatedBy(), task.getAssignedTo(), task.getStatus());
}
@ExceptionHandler(UnknownTaskException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleUnknownTask() {
}
} | repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\java\com\baeldung\tasksservice\adapters\http\TasksController.java | 2 |
请完成以下Java代码 | public String getTabId()
{
return tabId;
}
@JsonIgnore
public DocumentId getRowId()
{
return rowId;
}
public final void setDeleted()
{
deleted = Boolean.TRUE;
}
@JsonAnyGetter
private Map<String, Object> getOtherProperties()
{
return otherProperties;
}
@JsonAnySetter
private void putOtherProperty(final String name, final Object jsonValue)
{
otherProperties.put(name, jsonValue);
}
protected final JSONDocumentBase putDebugProperty(final String name, final Object jsonValue)
{
otherProperties.put("debug-" + name, jsonValue);
return this;
} | public final void setFields(final Collection<JSONDocumentField> fields)
{
setFields(fields == null ? null : Maps.uniqueIndex(fields, JSONDocumentField::getField));
}
@JsonIgnore
protected final void setFields(final Map<String, JSONDocumentField> fieldsByName)
{
this.fieldsByName = fieldsByName;
if (unboxPasswordFields && fieldsByName != null && !fieldsByName.isEmpty())
{
fieldsByName.forEach((fieldName, field) -> field.unboxPasswordField());
}
}
@JsonIgnore
protected final int getFieldsCount()
{
return fieldsByName == null ? 0 : fieldsByName.size();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentBase.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HibernateSearchConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.hibernatesearch.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf); | return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto")));
properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect")));
return properties;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernatesearch\HibernateSearchConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class ProductService {
private final String PRODUCT_ADDED_TO_CART_TOPIC = "product-added-to-cart";
private final ProductRepository repository;
private final DiscountService discountService;
private final KafkaTemplate<String, ProductAddedToCartEvent> kafkaTemplate;
public ProductService(ProductRepository repository, DiscountService discountService) {
this.repository = repository;
this.discountService = discountService;
this.kafkaTemplate = new KafkaTemplate<>();
}
public void addProductToCart(String productId, String cartId) {
repository.findById(productId) | .switchIfEmpty(Mono.error(() -> new IllegalArgumentException("not found!")))
.flatMap(this::computePrice)
.map(price -> new ProductAddedToCartEvent(productId, price.value(), price.currency(), cartId))
.subscribe(event -> kafkaTemplate.send(PRODUCT_ADDED_TO_CART_TOPIC, cartId, event));
}
private Mono<Price> computePrice(Product product) {
if (product.category().isEligibleForDiscount()) {
return discountService.discountForProduct(product.id())
.map(product.basePrice()::applyDiscount);
}
return Mono.just(product.basePrice());
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-performance\src\main\java\com\baeldung\spring\reactive\performance\webflux\ProductService.java | 2 |
请完成以下Java代码 | private IUserRolePermissions getUserRolePermissions()
{
if (userRolePermissions != null)
{
return userRolePermissions;
}
return Env.getUserRolePermissions();
}
public Builder setAD_Tab(final GridTab gridTab)
{
this.gridTab = gridTab;
return this;
}
public Builder setMaxQueryRecordsPerTab(final int maxQueryRecordsPerTab)
{
this.maxQueryRecordsPerTab = maxQueryRecordsPerTab;
return this;
} | private int getMaxQueryRecordsPerTab()
{
if (maxQueryRecordsPerTab != null)
{
return maxQueryRecordsPerTab;
}
else if (gridTab != null)
{
return gridTab.getMaxQueryRecords();
}
return 0;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\GridTabMaxRowsRestrictionChecker.java | 1 |
请完成以下Java代码 | private ImmutableList<JsonDataEntryLine> toJsonDataEntryLines(
@NonNull final DataEntrySection layoutSection,
@NonNull final DataEntryRecord dataEntryRecord)
{
final ImmutableList.Builder<JsonDataEntryLine> lines = ImmutableList.builder();
for (final DataEntryLine layoutLine : layoutSection.getLines())
{
final JsonDataEntryLine line = toJsonDataEntryLine(layoutLine, dataEntryRecord);
lines.add(line);
}
return lines.build();
}
private JsonDataEntryLine toJsonDataEntryLine(
@NonNull final DataEntryLine layoutLine,
@NonNull final DataEntryRecord dataEntryRecord)
{
final ImmutableList<JsonDataEntryField> fields = toJsonDataEntryFields(layoutLine, dataEntryRecord);
return JsonDataEntryLine.builder()
.fields(fields)
.build();
}
@NonNull
private ImmutableList<JsonDataEntryField> toJsonDataEntryFields(
@NonNull final DataEntryLine layoutLine,
@NonNull final DataEntryRecord dataEntryRecord)
{
final ImmutableList.Builder<JsonDataEntryField> fields = ImmutableList.builder();
for (final DataEntryField layoutField : layoutLine.getFields())
{
// some fields can be excluded from the response, according to this flag
if (!layoutField.isAvailableInApi())
{
continue;
}
final JsonDataEntryField field = toJsonDataEntryField(layoutField, dataEntryRecord);
fields.add(field);
}
return fields.build();
}
private JsonDataEntryField toJsonDataEntryField(
@NonNull final DataEntryField layoutField,
@NonNull final DataEntryRecord dataEntryRecord)
{
final Object fieldValue = dataEntryRecord.getFieldValue(layoutField.getId()).orElse(null); | return JsonDataEntryField.builder()
.id(layoutField.getId())
.caption(layoutField.getCaption().translate(adLanguage))
.description(layoutField.getDescription().translate(adLanguage))
.type(JsonFieldType.getBy(layoutField.getType()))
.mandatory(layoutField.isMandatory())
.listValues(toJsonDataEntryListValues(layoutField))
.value(fieldValue)
.build();
}
@NonNull
private ImmutableList<JsonDataEntryListValue> toJsonDataEntryListValues(@NonNull final DataEntryField layoutField)
{
return layoutField.getListValues()
.stream()
.map(this::toJsonDataEntryListValue)
.collect(ImmutableList.toImmutableList());
}
private JsonDataEntryListValue toJsonDataEntryListValue(@NonNull final DataEntryListValue listValue)
{
return JsonDataEntryListValue.builder()
.id(listValue.getId())
.name(listValue.getName().translate(adLanguage))
.description(listValue.getDescription().translate(adLanguage))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\JsonDataEntryFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public IBarService barJpaService() {
return new BarJpaService();
}
@Bean
public IBarService barSpringDataJpaService() {
return new BarSpringDataJpaService();
}
@Bean
public IFooService fooHibernateService() {
return new FooService();
}
@Bean
public IBarAuditableService barHibernateAuditableService() {
return new BarAuditableService();
}
@Bean
public IFooAuditableService fooHibernateAuditableService() {
return new FooAuditableService();
}
@Bean
public IBarDao barJpaDao() {
return new BarJpaDao();
}
@Bean
public IBarDao barHibernateDao() {
return new BarDao(); | }
@Bean
public IBarAuditableDao barHibernateAuditableDao() {
return new BarAuditableDao();
}
@Bean
public IFooDao fooHibernateDao() {
return new FooDao();
}
@Bean
public IFooAuditableDao fooHibernateAuditableDao() {
return new FooAuditableDao();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "true");
// hibernateProperties.setProperty("hibernate.format_sql", "true");
hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
// Envers properties
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
return hibernateProperties;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\audit\PersistenceConfig.java | 2 |
请完成以下Java代码 | public class AuthorNameAge {
private String name;
private int age;
public AuthorNameAge(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + Objects.hashCode(this.name);
hash = 79 * hash + this.age;
return hash;
}
@Override | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AuthorNameAge other = (AuthorNameAge) obj;
if (this.age != other.age) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaClassBasedProjections\src\main\java\com\bookstore\projection\AuthorNameAge.java | 1 |
请完成以下Java代码 | public ol removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
/**
* The onclick event occurs when the pointing device button is clicked over
* an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnClick (String script)
{
addAttribute ("onclick", script);
}
/**
* The ondblclick event occurs when the pointing device button is double
* clicked over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnDblClick (String script)
{
addAttribute ("ondblclick", script);
}
/**
* The onmousedown event occurs when the pointing device button is pressed
* over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseDown (String script)
{
addAttribute ("onmousedown", script);
}
/**
* The onmouseup event occurs when the pointing device button is released
* over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseUp (String script)
{
addAttribute ("onmouseup", script);
}
/**
* The onmouseover event occurs when the pointing device is moved onto an
* element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseOver (String script)
{
addAttribute ("onmouseover", script);
}
/**
* The onmousemove event occurs when the pointing device is moved while it
* is over an element. This attribute may be used with most elements.
*
* @param script The script
*/ | public void setOnMouseMove (String script)
{
addAttribute ("onmousemove", script);
}
/**
* The onmouseout event occurs when the pointing device is moved away from
* an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseOut (String script)
{
addAttribute ("onmouseout", script);
}
/**
* The onkeypress event occurs when a key is pressed and released over an
* element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyPress (String script)
{
addAttribute ("onkeypress", script);
}
/**
* The onkeydown event occurs when a key is pressed down over an element.
* This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyDown (String script)
{
addAttribute ("onkeydown", script);
}
/**
* The onkeyup event occurs when a key is released over an element. This
* attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyUp (String script)
{
addAttribute ("onkeyup", script);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\ol.java | 1 |
请完成以下Java代码 | public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet. | @return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Resilience4JConfigBuilder.Resilience4JCircuitBreakerConfiguration apply(String id) {
// 创建 TimeLimiterConfig 对象
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.ofDefaults(); // 默认
// 创建 CircuitBreakerConfig 对象
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.ofDefaults(); // 默认
// 创建 Resilience4JCircuitBreakerConfiguration 对象
return new Resilience4JConfigBuilder(id)
.timeLimiterConfig(timeLimiterConfig)
.circuitBreakerConfig(circuitBreakerConfig)
.build();
}
});
// 设置编号为 "slow" 的自定义配置
resilience4JCircuitBreakerFactory.configure(new Consumer<Resilience4JConfigBuilder>() {
@Override
public void accept(Resilience4JConfigBuilder resilience4JConfigBuilder) {
// 创建 TimeLimiterConfig 对象
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)) // 自定义
.build();
// 创建 CircuitBreakerConfig 对象
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() // 自定义
.slidingWindow(5, 5, CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
.build();
// 设置 Resilience4JCircuitBreakerConfiguration 对象
resilience4JConfigBuilder
.timeLimiterConfig(timeLimiterConfig)
.circuitBreakerConfig(circuitBreakerConfig);
}
}, "slow");
}
};
}
// @Bean
// public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() { | // return factory -> factory.configureDefault(
// id -> new Resilience4JConfigBuilder(id)
// .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build())
// .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
// .build());
// }
// @Bean
// public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
// return factory -> factory.configure(builder -> builder
// .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build())
// .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()),
// "slow");
// }
} | repos\SpringBoot-Labs-master\labx-24\labx-24-resilience4j-demo02\src\main\java\cn\iocoder\springcloud\labx24\resilience4jdemo\config\Resilience4jConfig.java | 2 |
请完成以下Spring Boot application配置 | langchain:
api:
# "demo" is a free API key for testing purposes only. Please replace it with your own API key.
key: demo
# key: OPEN_API_ | KEY
# API call to complete before it is timed out.
timeout: 30 | repos\springboot-demo-master\rag\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AD_Archive
{
private final PrintOutputFacade printOutputFacade;
private final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class);
public AD_Archive(@NonNull final PrintOutputFacade printOutputFacade)
{
this.printOutputFacade = printOutputFacade;
}
/**
* Check if the archive references a docOutBoundConfig, and if yes, copy its settings (possibly overriding previous settings).
* <p>
* Note: if the config id is changed to <code>null</code>, then do nothing.
* <p>
* task http://dewiki908/mediawiki/index.php/09417_Massendruck_-_Sofort-Druckjob_via_Ausgehende-Belege_konfig_einstellbar_%28101934367465%29
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = I_AD_Archive.COLUMNNAME_C_Doc_Outbound_Config_ID)
public void updateArchiveFlags(final I_AD_Archive archive)
{
if (archive.getC_Doc_Outbound_Config_ID() <= 0)
{
return; // nothing to do
}
// task 09417: also check if the archive references a docOutBoundConfig, and if yes, use its settings.
final I_C_Doc_Outbound_Config config = InterfaceWrapperHelper.create(archive.getC_Doc_Outbound_Config(),
I_C_Doc_Outbound_Config.class);
archive.setIsDirectEnqueue(config.isDirectEnqueue());
archive.setIsDirectProcessQueueItem(config.isDirectProcessQueueItem());
}
/**
* If direct print is required for given {@link AD_Archive} then this method enqueues the archive to printing queue.
*/
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, | ifColumnsChanged = {
I_AD_Archive.COLUMNNAME_IsDirectProcessQueueItem,
I_AD_Archive.COLUMNNAME_IsDirectEnqueue,
I_AD_Archive.COLUMNNAME_C_Doc_Outbound_Config_ID,
I_AD_Archive.COLUMNNAME_IsActive })
public void printArchive(final I_AD_Archive archive)
{
final PrintArchiveParameters printArchiveParameters = PrintArchiveParameters.builder()
.archive(archive)
.printOutputFacade(printOutputFacade)
.hwPrinterId(null)
.hwTrayId(null)
.enforceEnqueueToPrintQueue(false)
.build();
printingQueueBL.printArchive(printArchiveParameters);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_Archive.java | 2 |
请完成以下Java代码 | public boolean isUseInASI()
{
return false;
}
@Override
public boolean isDefinedByTemplate()
{
return false;
}
@Override
public void addAttributeValueListener(final IAttributeValueListener listener)
{
// nothing
}
@Override
public List<ValueNamePair> getAvailableValues()
{
throw new InvalidAttributeValueException("method not supported for " + this);
}
@Override
public IAttributeValuesProvider getAttributeValuesProvider()
{
throw new InvalidAttributeValueException("method not supported for " + this);
}
@Override
public I_C_UOM getC_UOM()
{
return null;
}
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
return NullAttributeValueCallout.instance;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
return null;
}
@Override
public void removeAttributeValueListener(final IAttributeValueListener listener)
{
// nothing
}
@Override
public boolean isReadonlyUI()
{
return true;
}
@Override
public boolean isDisplayedUI() | {
return false;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public int getDisplaySeqNo()
{
return 0;
}
@Override
public NamePair getNullAttributeValue()
{
return null;
}
/**
* @return true; we consider Null attributes as always generated
*/
@Override
public boolean isNew()
{
return true;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java | 1 |
请完成以下Java代码 | public class ExcelUtils {
public static Workbook openWorkbook(String filePath) throws IOException {
try (InputStream fileInputStream = new FileInputStream(filePath)) {
if (filePath.toLowerCase()
.endsWith("xlsx")) {
return new XSSFWorkbook(fileInputStream);
} else if (filePath.toLowerCase()
.endsWith("xls")) {
return new HSSFWorkbook(fileInputStream);
} else {
throw new IllegalArgumentException("The specified file is not an Excel file");
}
} catch (OLE2NotOfficeXmlFileException | NotOLE2FileException e) {
throw new IllegalArgumentException(
"The file format is not supported. Ensure the file is a valid Excel file.", e);
}
}
public static Sheet getSheet(Workbook workbook, String sheetName) {
return workbook.getSheet(sheetName);
}
public static List<String> getColumnNames1(Sheet sheet) {
List<String> columnNames = new ArrayList<>();
Row headerRow = sheet.getRow(0);
if (headerRow != null) { | for (Cell cell : headerRow) {
if (cell.getCellType() != CellType.BLANK && cell.getStringCellValue() != null
&& !cell.getStringCellValue()
.trim()
.isEmpty()) {
columnNames.add(cell.getStringCellValue()
.trim());
}
}
}
return columnNames;
}
public static List<String> getColumnNames(Sheet sheet) {
Row headerRow = sheet.getRow(0);
if (headerRow == null) {
return Collections.EMPTY_LIST;
}
return StreamSupport.stream(headerRow.spliterator(), false)
.filter(cell -> cell.getCellType() != CellType.BLANK)
.map(nonEmptyCell -> nonEmptyCell.getStringCellValue())
.filter(cellValue -> cellValue != null && !cellValue.trim()
.isEmpty())
.map(String::trim)
.collect(Collectors.toList());
}
} | repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\poi\columnnames\ExcelUtils.java | 1 |
请完成以下Java代码 | public void setIsMembershipBadgeToPrint (boolean IsMembershipBadgeToPrint)
{
set_Value (COLUMNNAME_IsMembershipBadgeToPrint, Boolean.valueOf(IsMembershipBadgeToPrint));
}
/** Get Zu druckende Mitgliederausweise.
@return Zu druckende Mitgliederausweise */
@Override
public boolean isMembershipBadgeToPrint ()
{
Object oo = get_Value(COLUMNNAME_IsMembershipBadgeToPrint);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Body.
@param LetterBody Body */
@Override
public void setLetterBody (java.lang.String LetterBody)
{
set_Value (COLUMNNAME_LetterBody, LetterBody);
}
/** Get Body.
@return Body */
@Override
public java.lang.String getLetterBody ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBody);
}
/** Set Body (parsed).
@param LetterBodyParsed Body (parsed) */
@Override
public void setLetterBodyParsed (java.lang.String LetterBodyParsed)
{
set_Value (COLUMNNAME_LetterBodyParsed, LetterBodyParsed);
}
/** Get Body (parsed).
@return Body (parsed) */
@Override
public java.lang.String getLetterBodyParsed ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBodyParsed);
}
/** Set Subject. | @param LetterSubject Subject */
@Override
public void setLetterSubject (java.lang.String LetterSubject)
{
set_Value (COLUMNNAME_LetterSubject, LetterSubject);
}
/** Get Subject.
@return Subject */
@Override
public java.lang.String getLetterSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_C_Letter.java | 1 |
请完成以下Java代码 | private String encodedNonNullPassword(byte[] digest) {
if (this.encodeHashAsBase64) {
return Utf8.decode(Base64.getEncoder().encode(digest));
}
return new String(Hex.encode(digest));
}
/**
* Takes a previously encoded password and compares it with a rawpassword after mixing
* in the salt and encoding that value
* @param rawPassword plain text password
* @param encodedPassword previously encoded password
* @return true or false
*/
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
String salt = extractSalt(encodedPassword);
String rawPasswordEncoded = digest(salt, rawPassword);
return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded);
}
/**
* Sets the number of iterations for which the calculated hash value should be
* "stretched". If this is greater than one, the initial digest is calculated, the
* digest function will be called repeatedly on the result for the additional number | * of iterations.
* @param iterations the number of iterations which will be executed on the hashed
* password/salt value. Defaults to 1.
*/
public void setIterations(int iterations) {
this.digester.setIterations(iterations);
}
private String extractSalt(String prefixEncodedPassword) {
int start = prefixEncodedPassword.indexOf(PREFIX);
if (start != 0) {
return "";
}
int end = prefixEncodedPassword.indexOf(SUFFIX, start);
if (end < 0) {
return "";
}
return prefixEncodedPassword.substring(start, end + 1);
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\MessageDigestPasswordEncoder.java | 1 |
请完成以下Java代码 | public class MMovementLineConfirm extends X_M_MovementLineConfirm
{
/**
*
*/
private static final long serialVersionUID = 2406580342096137696L;
/**
* Standard Constructor
* @param ctx ctx
* @param M_MovementLineConfirm_ID id
* @param trxName transaction
*/
public MMovementLineConfirm (Properties ctx, int M_MovementLineConfirm_ID, String trxName)
{
super (ctx, M_MovementLineConfirm_ID, trxName);
if (M_MovementLineConfirm_ID == 0)
{
// setM_MovementConfirm_ID (0); Parent
// setM_MovementLine_ID (0);
setConfirmedQty (Env.ZERO);
setDifferenceQty (Env.ZERO);
setScrappedQty (Env.ZERO);
setTargetQty (Env.ZERO);
setProcessed (false);
} } // M_MovementLineConfirm
/**
* M_MovementLineConfirm
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MMovementLineConfirm (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // M_MovementLineConfirm
/**
* Parent Constructor
* @param parent parent
*/
public MMovementLineConfirm (MMovementConfirm parent)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setM_MovementConfirm_ID(parent.getM_MovementConfirm_ID());
} // MMovementLineConfirm
/** Movement Line */
private MMovementLine m_line = null;
/**
* Set Movement Line
* @param line line
*/
public void setMovementLine (MMovementLine line)
{
setM_MovementLine_ID(line.getM_MovementLine_ID());
setTargetQty(line.getMovementQty());
setConfirmedQty(getTargetQty()); // suggestion
m_line = line;
} // setMovementLine
/**
* Get Movement Line
* @return line
*/
public MMovementLine getLine()
{
if (m_line == null)
m_line = new MMovementLine (getCtx(), getM_MovementLine_ID(), get_TrxName());
return m_line;
} // getLine | /**
* Process Confirmation Line.
* - Update Movement Line
* @return success
*/
public boolean processLine ()
{
MMovementLine line = getLine();
line.setTargetQty(getTargetQty());
line.setMovementQty(getConfirmedQty());
line.setConfirmedQty(getConfirmedQty());
line.setScrappedQty(getScrappedQty());
return line.save(get_TrxName());
} // processConfirmation
/**
* Is Fully Confirmed
* @return true if Target = Confirmed qty
*/
public boolean isFullyConfirmed()
{
return getTargetQty().compareTo(getConfirmedQty()) == 0;
} // isFullyConfirmed
/**
* Before Delete - do not delete
* @return false
*/
protected boolean beforeDelete ()
{
return false;
} // beforeDelete
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
// Calculate Difference = Target - Confirmed - Scrapped
BigDecimal difference = getTargetQty();
difference = difference.subtract(getConfirmedQty());
difference = difference.subtract(getScrappedQty());
setDifferenceQty(difference);
//
return true;
} // beforeSave
} // M_MovementLineConfirm | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMovementLineConfirm.java | 1 |
请完成以下Java代码 | public String generateRandomCharacters(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomAlphabet(int length, boolean lowerCase) {
int low;
int hi;
if (lowerCase) {
low = 97;
hi = 122;
} else {
low = 65;
hi = 90;
}
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
.build();
return pwdGenerator.generate(length);
}
public Stream<Character> getRandomAlphabets(int count, boolean upperCase) { | IntStream characters = null;
if (upperCase) {
characters = random.ints(count, 65, 90);
} else {
characters = random.ints(count, 97, 122);
}
return characters.mapToObj(data -> (char) data);
}
public Stream<Character> getRandomNumbers(int count) {
IntStream numbers = random.ints(count, 48, 57);
return numbers.mapToObj(data -> (char) data);
}
public Stream<Character> getRandomSpecialChars(int count) {
IntStream specialChars = random.ints(count, 33, 45);
return specialChars.mapToObj(data -> (char) data);
}
} | repos\tutorials-master\core-java-modules\core-java-string-apis\src\main\java\com\baeldung\password\RandomPasswordGenerator.java | 1 |
请完成以下Java代码 | public IArchiveStorage getArchiveStorage(final Properties ctx)
{
final ClientId adClientId = Env.getClientId(ctx);
final StorageType storageType = getStorageType(adClientId);
final AccessMode accessMode = getAccessMode();
return getArchiveStorage(adClientId, storageType, accessMode);
}
@Override
public IArchiveStorage getArchiveStorage(final I_AD_Archive archive)
{
final ClientId adClientId = ClientId.ofRepoId(archive.getAD_Client_ID());
final StorageType storageType = getStorageType(archive);
final AccessMode accessMode = getAccessMode();
return getArchiveStorage(adClientId, storageType, accessMode);
}
private IArchiveStorage getArchiveStorage(
final ClientId adClientId,
final StorageType storageType,
final AccessMode accessMode)
{
final ArchiveStorageKey key = ArchiveStorageKey.of(adClientId, storageType, accessMode);
return archiveStorages.getOrLoad(key, this::createArchiveStorage);
}
private IArchiveStorage createArchiveStorage(@NonNull final ArchiveStorageKey key)
{
final Class<? extends IArchiveStorage> storageClass = getArchiveStorageClass(key.getStorageType(), key.getAccessMode());
try
{
final IArchiveStorage storage = storageClass.newInstance();
storage.init(key.getClientId());
return storage;
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e)
.appendParametersToMessage() | .setParameter("storageClass", storageClass);
}
}
@Override
public IArchiveStorage getArchiveStorage(final Properties ctx, final StorageType storageType)
{
final ClientId adClientId = Env.getClientId(ctx);
final AccessMode accessMode = getAccessMode();
return getArchiveStorage(adClientId, storageType, accessMode);
}
@Override
public IArchiveStorage getArchiveStorage(final Properties ctx, final StorageType storageType, final AccessMode accessMode)
{
final ClientId adClientId = Env.getClientId(ctx);
return getArchiveStorage(adClientId, storageType, accessMode);
}
/**
* Remove all registered {@link IArchiveStorage} classes.
* <p>
* NOTE: to be used only in testing
*/
public void removeAllArchiveStorages()
{
storageClasses.clear();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveStorageFactory.java | 1 |
请完成以下Java代码 | private DocumentFieldDescriptor.Builder createQtyFieldDescriptor()
{
return DocumentFieldDescriptor.builder(IInvoiceLineQuickInput.COLUMNNAME_Qty)
.setCaption(msgBL.translatable(IInvoiceLineQuickInput.COLUMNNAME_Qty))
.setWidgetType(DocumentFieldWidgetType.Quantity)
.setMandatoryLogic(true)
.addCharacteristic(Characteristic.PublicField);
}
private DocumentFieldDescriptor.Builder createPackingItemFieldDescriptor()
{
return DocumentFieldDescriptor.builder(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID)
.setCaption(msgBL.translatable(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID))
.setWidgetType(DocumentFieldWidgetType.Lookup)
.setLookupDescriptorProvider(lookupDescriptorProviders.sql()
.setCtxTableName(null) // ctxTableName
.setCtxColumnName(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID)
.setDisplayType(DisplayType.TableDir)
.setAD_Val_Rule_ID(AdValRuleId.ofRepoId(540480)) // FIXME: hardcoded "M_HU_PI_Item_Product_For_Org_Product_And_DateInvoiced" | .build())
.setValueClass(LookupValue.IntegerLookupValue.class)
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true)
.setMandatoryLogic(ConstantLogicExpression.FALSE)
.setDisplayLogic(ConstantLogicExpression.TRUE)
.addCharacteristic(Characteristic.PublicField);
}
private QuickInputLayoutDescriptor createLayout(final DocumentEntityDescriptor entityDescriptor)
{
return QuickInputLayoutDescriptor.onlyFields(entityDescriptor, new String[][] {
{ IInvoiceLineQuickInput.COLUMNNAME_M_Product_ID, IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID },
{ IInvoiceLineQuickInput.COLUMNNAME_Qty }
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\invoiceline\InvoiceLineQuickInputDescriptorFactory.java | 1 |
请完成以下Java代码 | public List<NotificationRequestId> findIdsByRuleId(TenantId tenantId, NotificationRequestStatus requestStatus, NotificationRuleId ruleId) {
return notificationRequestRepository.findAllIdsByStatusAndRuleId(requestStatus, ruleId.getId()).stream()
.map(NotificationRequestId::new).collect(Collectors.toList());
}
@Override
public List<NotificationRequest> findByRuleIdAndOriginatorEntityIdAndStatus(TenantId tenantId, NotificationRuleId ruleId, EntityId originatorEntityId, NotificationRequestStatus status) {
return DaoUtil.convertDataList(notificationRequestRepository.findAllByRuleIdAndOriginatorEntityIdAndOriginatorEntityTypeAndStatus(ruleId.getId(), originatorEntityId.getId(), originatorEntityId.getEntityType(), status));
}
@Override
public PageData<NotificationRequest> findAllByStatus(NotificationRequestStatus status, PageLink pageLink) {
return DaoUtil.toPageData(notificationRequestRepository.findAllByStatus(status, DaoUtil.toPageable(pageLink)));
}
@Override
public void updateById(TenantId tenantId, NotificationRequestId requestId, NotificationRequestStatus requestStatus, NotificationRequestStats stats) {
notificationRequestRepository.updateStatusAndStatsById(requestId.getId(), requestStatus, JacksonUtil.valueToTree(stats));
}
@Override
public boolean existsByTenantIdAndStatusAndTargetId(TenantId tenantId, NotificationRequestStatus status, NotificationTargetId targetId) {
return notificationRequestRepository.existsByTenantIdAndStatusAndTargetsContaining(tenantId.getId(), status, targetId.getId().toString());
}
@Override
public boolean existsByTenantIdAndStatusAndTemplateId(TenantId tenantId, NotificationRequestStatus status, NotificationTemplateId templateId) {
return notificationRequestRepository.existsByTenantIdAndStatusAndTemplateId(tenantId.getId(), status, templateId.getId());
}
@Override
public int removeAllByCreatedTimeBefore(long ts) {
return notificationRequestRepository.deleteAllByCreatedTimeBefore(ts);
}
@Override | public NotificationRequestInfo findInfoById(TenantId tenantId, NotificationRequestId id) {
NotificationRequestInfoEntity info = notificationRequestRepository.findInfoById(id.getId());
return info != null ? info.toData() : null;
}
@Override
public void removeByTenantId(TenantId tenantId) {
notificationRequestRepository.deleteByTenantId(tenantId.getId());
}
@Override
protected Class<NotificationRequestEntity> getEntityClass() {
return NotificationRequestEntity.class;
}
@Override
protected JpaRepository<NotificationRequestEntity, UUID> getRepository() {
return notificationRequestRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_REQUEST;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRequestDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SysClientDetails findByClientId(String clientId) {
return sysClientDetailsRepository.findFirstByClientId(clientId).orElseThrow(() -> new ClientRegistrationException("Loading client exception."));
}
@Override
public void addClientDetails(SysClientDetails clientDetails) throws ClientAlreadyExistsException {
clientDetails.setId(null);
if (sysClientDetailsRepository.findFirstByClientId(clientDetails.getClientId()).isPresent()) {
throw new ClientAlreadyExistsException(String.format("Client id %s already exist.", clientDetails.getClientId()));
}
sysClientDetailsRepository.save(clientDetails);
}
@Override
public void updateClientDetails(SysClientDetails clientDetails) throws NoSuchClientException {
SysClientDetails exist = sysClientDetailsRepository.findFirstByClientId(clientDetails.getClientId()).orElseThrow(() -> new NoSuchClientException("No such client!"));
clientDetails.setClientSecret(exist.getClientSecret());
sysClientDetailsRepository.save(clientDetails);
} | @Override
public void updateClientSecret(String clientId, String clientSecret) throws NoSuchClientException {
SysClientDetails exist = sysClientDetailsRepository.findFirstByClientId(clientId).orElseThrow(() -> new NoSuchClientException("No such client!"));
exist.setClientSecret(passwordEncoder.encode(clientSecret));
sysClientDetailsRepository.save(exist);
}
@Override
public void removeClientDetails(String clientId) throws NoSuchClientException {
sysClientDetailsRepository.deleteByClientId(clientId);
}
@Override
public List<SysClientDetails> findAll() {
return sysClientDetailsRepository.findAll();
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\service\impl\SysClientDetailsServiceImpl.java | 2 |
请完成以下Java代码 | private void action_treeAddAll()
{
log.info("");
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeAdd(item);
}
} // action_treeAddAll
/**
* Action: Delete All Nodes from Tree | */
private void action_treeDeleteAll()
{
log.info("");
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeDelete(item);
}
} // action_treeDeleteAll
} // VTreeMaintenance | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTreeMaintenance.java | 1 |
请完成以下Java代码 | public class ExecuteChangeTenantIdCmd extends BaseChangeTenantIdCmd {
protected static final Logger LOGGER = LoggerFactory.getLogger(ExecuteChangeTenantIdCmd.class);
protected final Set<String> entityTypes;
protected final boolean dispatchEvent;
public ExecuteChangeTenantIdCmd(ChangeTenantIdBuilderImpl builder, String engineScopeType, Set<String> entityTypes) {
this(builder, engineScopeType, entityTypes, true);
}
public ExecuteChangeTenantIdCmd(ChangeTenantIdBuilderImpl builder, String engineScopeType, Set<String> entityTypes, boolean dispatchEvent) {
super(builder, engineScopeType);
this.entityTypes = entityTypes;
this.dispatchEvent = dispatchEvent;
}
@Override
protected Map<String, Long> executeOperation(DbSqlSession dbSqlSession, Map<String, Object> parameters) {
if (LOGGER.isDebugEnabled()) {
String definitionTenantId = builder.getDefinitionTenantId();
String option = definitionTenantId != null
? " but only for instances from the '" + definitionTenantId + "' tenant definitions"
: "";
LOGGER.debug("Executing instance migration from '{}' to '{}'{}.",
parameters.get("sourceTenantId"), parameters.get("targetTenantId"), option);
}
Map<String, Long> results = new HashMap<>();
for (String entityType : entityTypes) { | results.put(entityType, (long) dbSqlSession.directUpdate("changeTenantId" + entityType, parameters));
}
return results;
}
@Override
protected void beforeReturn(CommandContext commandContext, ChangeTenantIdResult result) {
FlowableEventDispatcher eventDispatcher = getEngineConfiguration(commandContext)
.getEventDispatcher();
if (dispatchEvent && eventDispatcher != null && eventDispatcher.isEnabled()) {
String sourceTenantId = builder.getSourceTenantId();
String targetTenantId = builder.getTargetTenantId();
String definitionTenantId = builder.getDefinitionTenantId();
eventDispatcher.dispatchEvent(new FlowableChangeTenantIdEventImpl(engineScopeType, sourceTenantId, targetTenantId, definitionTenantId),
engineScopeType);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\tenant\ExecuteChangeTenantIdCmd.java | 1 |
请完成以下Java代码 | public CaseInstanceMigrationDocument getCaseInstanceMigrationDocument() {
return this.caseInstanceMigrationDocumentDocumentBuilder.build();
}
@Override
public void migrate(String caseInstanceId) {
getCmmnMigrationService().migrateCaseInstance(caseInstanceId, getCaseInstanceMigrationDocument());
}
@Override
public CaseInstanceMigrationValidationResult validateMigration(String caseInstanceId) {
return getCmmnMigrationService().validateMigrationForCaseInstance(caseInstanceId, getCaseInstanceMigrationDocument());
}
@Override
public void migrateCaseInstances(String caseDefinitionId) {
getCmmnMigrationService().migrateCaseInstancesOfCaseDefinition(caseDefinitionId, getCaseInstanceMigrationDocument());
}
@Override
public Batch batchMigrateCaseInstances(String caseDefinitionId) {
return getCmmnMigrationService().batchMigrateCaseInstancesOfCaseDefinition(caseDefinitionId, getCaseInstanceMigrationDocument());
}
@Override
public CaseInstanceMigrationValidationResult validateMigrationOfCaseInstances(String caseDefinitionId) {
return getCmmnMigrationService().validateMigrationForCaseInstancesOfCaseDefinition(caseDefinitionId, getCaseInstanceMigrationDocument());
}
@Override
public void migrateCaseInstances(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId) { | getCmmnMigrationService().migrateCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, getCaseInstanceMigrationDocument());
}
@Override
public Batch batchMigrateCaseInstances(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId) {
return getCmmnMigrationService().batchMigrateCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, getCaseInstanceMigrationDocument());
}
@Override
public CaseInstanceMigrationValidationResult validateMigrationOfCaseInstances(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId) {
return getCmmnMigrationService().validateMigrationForCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, getCaseInstanceMigrationDocument());
}
protected CmmnMigrationService getCmmnMigrationService() {
if (cmmnMigrationService == null) {
throw new FlowableException("CaseMigrationService cannot be null, Obtain your builder instance from the CaseMigrationService to access this feature");
}
return cmmnMigrationService;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getExtraCharge() {
return extraCharge;
}
/**
* Sets the value of the extraCharge property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setExtraCharge(BigDecimal value) {
this.extraCharge = value;
}
/**
* The tax amount for this line item (gross - net = tax amount)
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getTaxAmount() {
return taxAmount;
}
/**
* Sets the value of the taxAmount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTaxAmount(BigDecimal value) {
this.taxAmount = value;
}
/**
* The overall amount for this line item (net value).
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getLineItemAmount() {
return lineItemAmount;
}
/** | * Sets the value of the lineItemAmount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setLineItemAmount(BigDecimal value) {
this.lineItemAmount = value;
}
/**
* Gets the value of the listLineItemExtension property.
*
* @return
* possible object is
* {@link ListLineItemExtensionType }
*
*/
public ListLineItemExtensionType getListLineItemExtension() {
return listLineItemExtension;
}
/**
* Sets the value of the listLineItemExtension property.
*
* @param value
* allowed object is
* {@link ListLineItemExtensionType }
*
*/
public void setListLineItemExtension(ListLineItemExtensionType value) {
this.listLineItemExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ListLineItemType.java | 2 |
请完成以下Java代码 | public int getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
} | public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public Integer getAppVersion() {
return this.appVersion;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoggingProperties {
private static final int DEFAULT_LOG_DISK_SPACE_LIMIT = 0;
private static final int DEFAULT_LOG_FILE_SIZE_LIMIT = 0;
private static final String DEFAULT_LOG_LEVEL = "config";
private int logDiskSpaceLimit = DEFAULT_LOG_DISK_SPACE_LIMIT;
private int logFileSizeLimit = DEFAULT_LOG_FILE_SIZE_LIMIT;
private String level = DEFAULT_LOG_LEVEL;
private String logFile;
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
public int getLogDiskSpaceLimit() {
return this.logDiskSpaceLimit; | }
public void setLogDiskSpaceLimit(int logDiskSpaceLimit) {
this.logDiskSpaceLimit = logDiskSpaceLimit;
}
public String getLogFile() {
return this.logFile;
}
public void setLogFile(String logFile) {
this.logFile = logFile;
}
public int getLogFileSizeLimit() {
return this.logFileSizeLimit;
}
public void setLogFileSizeLimit(int logFileSizeLimit) {
this.logFileSizeLimit = logFileSizeLimit;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\LoggingProperties.java | 2 |
请完成以下Java代码 | public void setIsMultiRowOnly (boolean IsMultiRowOnly)
{
set_Value (COLUMNNAME_IsMultiRowOnly, Boolean.valueOf(IsMultiRowOnly));
}
/** Get Multi Row Only.
@return This applies to Multi-Row view only
*/
public boolean isMultiRowOnly ()
{
Object oo = get_Value(COLUMNNAME_IsMultiRowOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Read Only.
@param IsReadOnly
Field is read only
*/
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Single Row Layout.
@param IsSingleRow
Default for toggle between Single- and Multi-Row (Grid) Layout | */
public void setIsSingleRow (boolean IsSingleRow)
{
set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow));
}
/** Get Single Row Layout.
@return Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public boolean isSingleRow ()
{
Object oo = get_Value(COLUMNNAME_IsSingleRow);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Tab.java | 1 |
请完成以下Java代码 | public T execute(CommandContext commandContext) {
if (executionId == null) {
throw new ActivitiIllegalArgumentException("executionId is null");
}
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId);
if (execution == null) {
throw new ActivitiObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class);
}
if (execution.isSuspended()) {
throw new ActivitiException(getSuspendedExceptionMessage());
} | return execute(commandContext, execution);
}
/**
* Subclasses should implement this method. The provided {@link ExecutionEntity} is guaranteed to be active (ie. not suspended).
*/
protected abstract T execute(CommandContext commandContext, ExecutionEntity execution);
/**
* Subclasses can override this to provide a more detailed exception message that will be thrown when the execution is suspended.
*/
protected String getSuspendedExceptionMessage() {
return "Cannot execution operation because execution '" + executionId + "' is suspended";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\NeedsActiveExecutionCmd.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
} | public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
} | repos\springBoot-master\springboot-elasticsearch\src\main\java\cn\abel\bean\User.java | 1 |
请完成以下Java代码 | public int getWF_Initial_User_ID()
{
return get_ValueAsInt(COLUMNNAME_WF_Initial_User_ID);
}
/**
* WFState AD_Reference_ID=305
* Reference name: WF_Instance State
*/
public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */
public static final String WFSTATE_NotStarted = "ON";
/** Running = OR */
public static final String WFSTATE_Running = "OR";
/** Suspended = OS */
public static final String WFSTATE_Suspended = "OS";
/** Completed = CC */
public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */ | public static final String WFSTATE_Aborted = "CA";
/** Terminated = CT */
public static final String WFSTATE_Terminated = "CT";
@Override
public void setWFState (final java.lang.String WFState)
{
set_Value (COLUMNNAME_WFState, WFState);
}
@Override
public java.lang.String getWFState()
{
return get_ValueAsString(COLUMNNAME_WFState);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Process.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result list(@RequestParam Map<String, Object> params) {
if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
//查询列表数据
PageUtil pageUtil = new PageUtil(params);
return ResultGenerator.genSuccessResult(articleService.getArticlePage(pageUtil));
}
/**
* 详情
*/
@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
public Result info(@PathVariable("id") Integer id) {
Article article = articleService.queryObject(id);
return ResultGenerator.genSuccessResult(article);
}
/**
* 保存
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Result save(@RequestBody Article article, @TokenToUser AdminUser loginUser) {
if (article.getAddName()==null){
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "作者不能为空!");
}
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (articleService.save(article) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("添加失败");
}
}
/** | * 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public Result update(@RequestBody Article article, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (articleService.update(article) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("修改失败");
}
}
/**
* 删除
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result delete(@RequestBody Integer[] ids, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (ids.length < 1) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
if (articleService.deleteBatch(ids) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\ArticleController.java | 2 |
请完成以下Java代码 | private DocumentPath getDocumentPath()
{
final DocumentId documentId = getRowId();
return DocumentPath.rootDocumentPath(windowId, documentId);
}
public Builder setRowId(final DocumentId rowId)
{
this.rowId = rowId;
_rowIdEffective = null;
return this;
}
/** @return view row ID; never null */
public DocumentId getRowId()
{
if (_rowIdEffective == null)
{
if (rowId == null)
{
throw new IllegalStateException("No rowId was provided for " + this);
}
if (isRootRow())
{
_rowIdEffective = rowId;
}
else
{
// NOTE: we have to do this because usually, the root row can have the same ID as one of the included rows,
// because the root/aggregated rows are build on demand and they don't really exist in database.
// Also see https://github.com/metasfresh/metasfresh-webui-frontend/issues/835#issuecomment-307783959
_rowIdEffective = rowId.toIncludedRowId();
}
}
return _rowIdEffective;
}
public Builder setParentRowId(final DocumentId parentRowId)
{
this.parentRowId = parentRowId;
_rowIdEffective = null;
return this;
}
private DocumentId getParentRowId()
{
return parentRowId;
}
public boolean isRootRow()
{
return getParentRowId() == null;
}
private IViewRowType getType()
{
return type;
}
public Builder setType(final IViewRowType type)
{
this.type = type;
return this;
}
public Builder setProcessed(final boolean processed)
{
this.processed = processed;
return this;
}
private boolean isProcessed()
{
if (processed == null)
{
// NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example. | // return DisplayType.toBoolean(values.getOrDefault("Processed", false));
return false;
}
else
{
return processed.booleanValue();
}
}
public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue)
{
if (jsonValue == null || JSONNullValue.isNull(jsonValue))
{
values.remove(fieldName);
}
else
{
values.put(fieldName, jsonValue);
}
return this;
}
private Map<String, Object> getValues()
{
return values;
}
public LookupValue getFieldValueAsLookupValue(final String fieldName)
{
return LookupValue.cast(values.get(fieldName));
}
public Builder addIncludedRow(final IViewRow includedRow)
{
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<IViewRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getReleaseStatus() {
return releaseStatus;
}
public void setReleaseStatus(String releaseStatus) {
this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim();
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public String getCheckFailMsg() { | return checkFailMsg;
}
public void setCheckFailMsg(String checkFailMsg) {
this.checkFailMsg = checkFailMsg;
}
public String getBankErrMsg() {
return bankErrMsg;
}
public void setBankErrMsg(String bankErrMsg) {
this.bankErrMsg = bankErrMsg;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java | 2 |
请完成以下Java代码 | public PurchaseCandidateId getPurchaseCandidateId()
{
return getPurchaseCandidate().getId();
}
public ProductId getProductId()
{
return getPurchaseCandidate().getProductId();
}
public int getUomId()
{
final Quantity purchasedQty = getPurchasedQty();
if (purchasedQty != null)
{
return purchasedQty.getUOMId();
}
return getQtyToPurchase().getUOMId();
}
public OrgId getOrgId()
{
return getPurchaseCandidate().getOrgId();
}
public WarehouseId getWarehouseId()
{
return getPurchaseCandidate().getWarehouseId();
}
public BPartnerId getVendorId()
{
return getPurchaseCandidate().getVendorId();
}
public ZonedDateTime getPurchaseDatePromised()
{
return getPurchaseCandidate().getPurchaseDatePromised();
}
public OrderId getSalesOrderId()
{
final OrderAndLineId salesOrderAndLineId = getPurchaseCandidate().getSalesOrderAndLineIdOrNull();
return salesOrderAndLineId != null ? salesOrderAndLineId.getOrderId() : null;
}
@Nullable
public ForecastLineId getForecastLineId()
{
return getPurchaseCandidate().getForecastLineId();
}
private Quantity getQtyToPurchase()
{
return getPurchaseCandidate().getQtyToPurchase();
}
public boolean purchaseMatchesRequiredQty()
{
return getPurchasedQty().compareTo(getQtyToPurchase()) == 0;
}
private boolean purchaseMatchesOrExceedsRequiredQty()
{
return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0;
}
public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId)
{
this.purchaseOrderAndLineId = purchaseOrderAndLineId;
}
public void markPurchasedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty()) | {
purchaseCandidate.markProcessed();
}
}
public void markReqCreatedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty())
{
purchaseCandidate.setReqCreated(true);
}
}
@Nullable
public BigDecimal getPrice()
{
return purchaseCandidate.getPriceEnteredEff();
}
@Nullable
public UomId getPriceUomId()
{
return purchaseCandidate.getPriceUomId();
}
@Nullable
public Percent getDiscount()
{
return purchaseCandidate.getDiscountEff();
}
@Nullable
public String getExternalPurchaseOrderUrl()
{
return purchaseCandidate.getExternalPurchaseOrderUrl();
}
@Nullable
public ExternalId getExternalHeaderId()
{
return purchaseCandidate.getExternalHeaderId();
}
@Nullable
public ExternalSystemId getExternalSystemId()
{
return purchaseCandidate.getExternalSystemId();
}
@Nullable
public ExternalId getExternalLineId()
{
return purchaseCandidate.getExternalLineId();
}
@Nullable
public String getPOReference()
{
return purchaseCandidate.getPOReference();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java | 1 |
请完成以下Java代码 | public boolean isContextReusePossible() {
return contextReusePossible;
}
public TransactionPropagation getTransactionPropagation() {
return propagation;
}
public CommandConfig setContextReusePossible(boolean contextReusePossible) {
CommandConfig config = new CommandConfig(this);
config.contextReusePossible = contextReusePossible;
return config;
}
public CommandConfig transactionRequired() {
CommandConfig config = new CommandConfig(this);
config.propagation = TransactionPropagation.REQUIRED;
return config; | }
public CommandConfig transactionRequiresNew() {
CommandConfig config = new CommandConfig();
config.contextReusePossible = false;
config.propagation = TransactionPropagation.REQUIRES_NEW;
return config;
}
public CommandConfig transactionNotSupported() {
CommandConfig config = new CommandConfig();
config.contextReusePossible = false;
config.propagation = TransactionPropagation.NOT_SUPPORTED;
return config;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandConfig.java | 1 |
请完成以下Java代码 | public FormFieldValidator createValidator(Element constraint, BpmnParse bpmnParse, ExpressionManager expressionManager) {
String name = constraint.attribute("name");
String config = constraint.attribute("config");
if("validator".equals(name)) {
// custom validators
if(config == null || config.isEmpty()) {
bpmnParse.addError("validator configuration needs to provide either a fully " +
"qualified classname or an expression resolving to a custom FormFieldValidator implementation.",
constraint);
} else {
if(StringUtil.isExpression(config)) {
// expression
Expression validatorExpression = expressionManager.createExpression(config);
return new DelegateFormFieldValidator(validatorExpression);
} else {
// classname
return new DelegateFormFieldValidator(config);
}
}
} else {
// built-in validators
Class<? extends FormFieldValidator> validator = validators.get(name);
if(validator != null) {
FormFieldValidator validatorInstance = createValidatorInstance(validator);
return validatorInstance;
} else { | bpmnParse.addError("Cannot find validator implementation for name '"+name+"'.", constraint);
}
}
return null;
}
protected FormFieldValidator createValidatorInstance(Class<? extends FormFieldValidator> validator) {
try {
return validator.newInstance();
} catch (InstantiationException e) {
throw new ProcessEngineException("Could not instantiate validator", e);
} catch (IllegalAccessException e) {
throw new ProcessEngineException("Could not instantiate validator", e);
}
}
public void addValidator(String name, Class<? extends FormFieldValidator> validatorType) {
validators.put(name, validatorType);
}
public Map<String, Class<? extends FormFieldValidator>> getValidators() {
return validators;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\validator\FormValidators.java | 1 |
请完成以下Java代码 | public int getC_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Payment getC_Payment() throws RuntimeException
{
return (I_C_Payment)MTable.get(getCtx(), I_C_Payment.Table_Name)
.getPO(getC_Payment_ID(), get_TrxName()); }
/** Set Payment.
@param C_Payment_ID
Payment identifier
*/
public void setC_Payment_ID (int C_Payment_ID)
{
if (C_Payment_ID < 1)
set_Value (COLUMNNAME_C_Payment_ID, null);
else
set_Value (COLUMNNAME_C_Payment_ID, Integer.valueOf(C_Payment_ID));
}
/** Get Payment.
@return Payment identifier
*/
public int getC_Payment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/** Set Not Committed Aount.
@param NonCommittedAmt
Amount not committed yet
*/
public void setNonCommittedAmt (BigDecimal NonCommittedAmt)
{
set_Value (COLUMNNAME_NonCommittedAmt, NonCommittedAmt);
}
/** Get Not Committed Aount.
@return Amount not committed yet
*/
public BigDecimal getNonCommittedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_NonCommittedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_SellerFunds.java | 1 |
请完成以下Java代码 | public void addCU(@NonNull final I_M_HU cuHU)
{
assertCU(cuHU);
final TULoaderInstanceKey tuInstanceKey = extractTULoaderInstanceKeyFromCU(cuHU);
final TULoaderInstance tuInstance = tuInstances.computeIfAbsent(tuInstanceKey, this::newTULoaderInstance);
tuInstance.addCU(cuHU);
}
public void closeCurrentTUs()
{
tuInstances.values().forEach(TULoaderInstance::closeCurrentTU);
}
private static void assertCU(final @NonNull I_M_HU cuHU)
{
if (!HuPackingInstructionsVersionId.ofRepoId(cuHU.getM_HU_PI_Version_ID()).isVirtual())
{
throw new AdempiereException("Expected to be CU: " + cuHU);
}
}
private TULoaderInstanceKey extractTULoaderInstanceKeyFromCU(final I_M_HU cuHU)
{
return TULoaderInstanceKey.builder()
.bpartnerId(IHandlingUnitsBL.extractBPartnerIdOrNull(cuHU))
.bpartnerLocationRepoId(cuHU.getC_BPartner_Location_ID())
.locatorId(warehouseDAO.getLocatorIdByRepoIdOrNull(cuHU.getM_Locator_ID()))
.huStatus(cuHU.getHUStatus())
.clearanceStatusInfo(ClearanceStatusInfo.ofHU(cuHU))
.build();
}
private TULoaderInstance newTULoaderInstance(@NonNull final TULoaderInstanceKey key)
{
return TULoaderInstance.builder()
.huContext(huContext)
.tuPI(tuPI)
.capacity(capacity) | .bpartnerId(key.getBpartnerId())
.bpartnerLocationRepoId(key.getBpartnerLocationRepoId())
.locatorId(key.getLocatorId())
.huStatus(key.getHuStatus())
.clearanceStatusInfo(key.getClearanceStatusInfo())
.build();
}
//
//
//
@Value
private static class TULoaderInstanceKey
{
@Nullable BPartnerId bpartnerId;
int bpartnerLocationRepoId;
@Nullable LocatorId locatorId;
@Nullable String huStatus;
@Nullable ClearanceStatusInfo clearanceStatusInfo;
@Builder
private TULoaderInstanceKey(
@Nullable final BPartnerId bpartnerId,
final int bpartnerLocationRepoId,
@Nullable final LocatorId locatorId,
@Nullable final String huStatus,
@Nullable final ClearanceStatusInfo clearanceStatusInfo)
{
this.bpartnerId = bpartnerId;
this.bpartnerLocationRepoId = bpartnerLocationRepoId > 0 ? bpartnerLocationRepoId : -1;
this.locatorId = locatorId;
this.huStatus = StringUtils.trimBlankToNull(huStatus);
this.clearanceStatusInfo = clearanceStatusInfo;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoader.java | 1 |
请完成以下Java代码 | public void updatePurchase(Purchase purchase) {
CompletableFuture.allOf(CompletableFuture.supplyAsync(() -> getOrderDescription(purchase.getOrderId()))
.thenAccept(purchase::setOrderDescription),
CompletableFuture.supplyAsync(() -> getPaymentDescription(purchase.getPaymentId()))
.thenAccept(purchase::setPaymentDescription),
CompletableFuture.supplyAsync(() -> getUserName(purchase.getUserId()))
.thenAccept(purchase::setBuyerName))
.join();
}
public void updatePurchaseHandlingExceptions(Purchase purchase) {
CompletableFuture.allOf(CompletableFuture.supplyAsync(() -> getOrderDescription(purchase.getOrderId()))
.thenAccept(purchase::setOrderDescription)
.orTimeout(1, TimeUnit.SECONDS)
.handle(handleGracefully()),
CompletableFuture.supplyAsync(() -> getPaymentDescription(purchase.getPaymentId()))
.thenAccept(purchase::setPaymentDescription)
.orTimeout(1, TimeUnit.SECONDS)
.handle(handleGracefully()),
CompletableFuture.supplyAsync(() -> getUserName(purchase.getUserId()))
.thenAccept(purchase::setBuyerName)
.orTimeout(1, TimeUnit.SECONDS)
.handle(handleGracefully()))
.join();
}
public String getOrderDescription(String orderId) {
ResponseEntity<String> result = restTemplate.getForEntity(format("%s/orders/%s", BASE_URL, orderId), String.class);
return result.getBody();
}
public String getPaymentDescription(String paymentId) {
ResponseEntity<String> result = restTemplate.getForEntity(format("%s/payments/%s", BASE_URL, paymentId), String.class);
return result.getBody();
} | public String getUserName(String userId) {
ResponseEntity<String> result = restTemplate.getForEntity(format("%s/users/%s", BASE_URL, userId), String.class);
return result.getBody();
}
private static BiFunction<Void, Throwable, Void> handleGracefully() {
return (result, exception) -> {
if (exception != null) {
// handle exception
return null;
}
return result;
};
}
} | repos\tutorials-master\spring-web-modules\spring-resttemplate-1\src\main\java\com\baeldung\resttemplate\restcallscompletablefuture\PurchaseRestCallsAsyncExecutor.java | 1 |
请完成以下Java代码 | public class CategoryPurpose1CHCode {
@XmlElement(name = "Cd", required = true)
protected String cd;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd; | }
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\CategoryPurpose1CHCode.java | 1 |
请完成以下Java代码 | public int getM_Product_ID()
{
return forecastLine.getM_Product_ID();
}
@Override
public void setM_Product_ID(final int productId)
{
forecastLine.setM_Product_ID(productId);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return forecastLine.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
forecastLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return forecastLine.getC_UOM_ID();
}
@Override
public void setC_UOM_ID(final int uomId)
{
forecastLine.setC_UOM_ID(uomId);
}
@Override
public void setQty(final BigDecimal qty)
{
forecastLine.setQty(qty);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyCalculated = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty);
forecastLine.setQtyCalculated(qtyCalculated);
}
@Override
public BigDecimal getQty()
{
return forecastLine.getQty();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final int forecastLine_PIItemProductId = forecastLine.getM_HU_PI_Item_Product_ID();
if (forecastLine_PIItemProductId > 0)
{
return forecastLine_PIItemProductId;
}
return -1;
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU() | {
return forecastLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
forecastLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
private XADataSource createXaDataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) {
String className = connectionDetails.getXaDataSourceClassName();
Assert.state(StringUtils.hasLength(className), "No XA DataSource class name specified");
XADataSource dataSource = createXaDataSourceInstance(className);
bindXaProperties(dataSource, properties, connectionDetails);
return dataSource;
}
private XADataSource createXaDataSourceInstance(String className) {
try {
Class<?> dataSourceClass = ClassUtils.forName(className, this.classLoader);
Object instance = BeanUtils.instantiateClass(dataSourceClass);
Assert.state(instance instanceof XADataSource,
() -> "DataSource class " + className + " is not an XADataSource");
return (XADataSource) instance;
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create XADataSource instance from '" + className + "'");
}
}
private void bindXaProperties(XADataSource target, DataSourceProperties dataSourceProperties,
JdbcConnectionDetails connectionDetails) { | Binder binder = new Binder(getBinderSource(dataSourceProperties, connectionDetails));
binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(target));
}
private ConfigurationPropertySource getBinderSource(DataSourceProperties dataSourceProperties,
JdbcConnectionDetails connectionDetails) {
Map<Object, Object> properties = new HashMap<>(dataSourceProperties.getXa().getProperties());
properties.computeIfAbsent("user", (key) -> connectionDetails.getUsername());
properties.computeIfAbsent("password", (key) -> connectionDetails.getPassword());
try {
properties.computeIfAbsent("url", (key) -> connectionDetails.getJdbcUrl());
}
catch (DataSourceBeanCreationException ex) {
// Continue as not all XA DataSource's require a URL
}
MapConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
aliases.addAliases("user", "username");
return source.withAliases(aliases);
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\XADataSourceAutoConfiguration.java | 2 |
请完成以下Java代码 | public MetricsQuery offset(int offset) {
setFirstResult(offset);
return this;
}
@Override
public MetricsQuery limit(int maxResults) {
setMaxResults(maxResults);
return this;
}
@Override
public MetricsQuery aggregateByReporter() {
aggregateByReporter = true;
return this;
}
@Override
public void setMaxResults(int maxResults) {
if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) {
throw new ProcessEngineException("Metrics interval query row limit can't be set larger than " + DEFAULT_LIMIT_SELECT_INTERVAL + '.');
}
this.maxResults = maxResults;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public Long getStartDateMilliseconds() {
return startDateMilliseconds;
}
public Long getEndDateMilliseconds() {
return endDateMilliseconds;
}
public String getName() {
return name;
}
public String getReporter() {
return reporter;
}
public Long getInterval() {
if (interval == null) {
return DEFAULT_SELECT_INTERVAL;
}
return interval;
}
@Override
public int getMaxResults() {
if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) {
return DEFAULT_LIMIT_SELECT_INTERVAL;
}
return super.getMaxResults();
} | protected class MetricsQueryIntervalCmd implements Command<Object> {
protected MetricsQueryImpl metricsQuery;
public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) {
this.metricsQuery = metricsQuery;
}
@Override
public Object execute(CommandContext commandContext) {
return commandContext.getMeterLogManager()
.executeSelectInterval(metricsQuery);
}
}
protected class MetricsQuerySumCmd implements Command<Object> {
protected MetricsQueryImpl metricsQuery;
public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) {
this.metricsQuery = metricsQuery;
}
@Override
public Object execute(CommandContext commandContext) {
return commandContext.getMeterLogManager()
.executeSelectSum(metricsQuery);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java | 1 |
请完成以下Java代码 | public void setMigrationInstruction(MigrationInstructionDto migrationInstruction) {
this.migrationInstruction = migrationInstruction;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public List<String> getFailures() {
return failures;
}
public void setFailures(List<String> failures) {
this.failures = failures;
}
public String getSourceScopeId() {
return sourceScopeId;
} | public void setSourceScopeId(String sourceScopeId) {
this.sourceScopeId = sourceScopeId;
}
public static List<MigratingActivityInstanceValidationReportDto> from(List<MigratingActivityInstanceValidationReport> reports) {
ArrayList<MigratingActivityInstanceValidationReportDto> dtos = new ArrayList<MigratingActivityInstanceValidationReportDto>();
for (MigratingActivityInstanceValidationReport report : reports) {
dtos.add(MigratingActivityInstanceValidationReportDto.from(report));
}
return dtos;
}
public static MigratingActivityInstanceValidationReportDto from(MigratingActivityInstanceValidationReport report) {
MigratingActivityInstanceValidationReportDto dto = new MigratingActivityInstanceValidationReportDto();
dto.setMigrationInstruction(MigrationInstructionDto.from(report.getMigrationInstruction()));
dto.setActivityInstanceId(report.getActivityInstanceId());
dto.setFailures(report.getFailures());
dto.setSourceScopeId(report.getSourceScopeId());
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigratingActivityInstanceValidationReportDto.java | 1 |
请完成以下Java代码 | private boolean isLineTypeIncluded(int PA_ReportLine_ID)
{
MReportLine line = findReportLine(PA_ReportLine_ID, m_report.getLineSet());
return line.isLineTypeIncluded();
}
private int getIncludedLineID(int PA_ReportLine_ID)
{
if (isLineTypeIncluded(PA_ReportLine_ID))
{
Collection<Integer> ids = getAllLineIDs(PA_ReportLine_ID);
ids.remove(PA_ReportLine_ID);
if (ids.size() != 1)
{
throw new AdempiereException("Calculation not supported for included linesets with more then one line included in parent calculation"); // TODO: translate
}
return ids.iterator().next(); | }
else
{
return PA_ReportLine_ID;
}
}
protected final MReport getPA_Report()
{
return m_report;
}
private int getAD_PInstance_ID()
{
return getPinstanceId().getRepoId();
}
} // FinReport | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\FinReport.java | 1 |
请完成以下Java代码 | public Builder requireAuthorizationConsent(boolean requireAuthorizationConsent) {
return setting(ConfigurationSettingNames.Client.REQUIRE_AUTHORIZATION_CONSENT, requireAuthorizationConsent);
}
/**
* Sets the {@code URL} for the Client's JSON Web Key Set.
* @param jwkSetUrl the {@code URL} for the Client's JSON Web Key Set
* @return the {@link Builder} for further configuration
*/
public Builder jwkSetUrl(String jwkSetUrl) {
return setting(ConfigurationSettingNames.Client.JWK_SET_URL, jwkSetUrl);
}
/**
* Sets the {@link JwsAlgorithm JWS} algorithm that must be used for signing the
* {@link Jwt JWT} used to authenticate the Client at the Token Endpoint for the
* {@link ClientAuthenticationMethod#PRIVATE_KEY_JWT private_key_jwt} and
* {@link ClientAuthenticationMethod#CLIENT_SECRET_JWT client_secret_jwt}
* authentication methods.
* @param authenticationSigningAlgorithm the {@link JwsAlgorithm JWS} algorithm
* that must be used for signing the {@link Jwt JWT} used to authenticate the
* Client at the Token Endpoint
* @return the {@link Builder} for further configuration
*/
public Builder tokenEndpointAuthenticationSigningAlgorithm(JwsAlgorithm authenticationSigningAlgorithm) {
return setting(ConfigurationSettingNames.Client.TOKEN_ENDPOINT_AUTHENTICATION_SIGNING_ALGORITHM,
authenticationSigningAlgorithm); | }
/**
* Sets the expected subject distinguished name associated to the client
* {@code X509Certificate} received during client authentication when using the
* {@code tls_client_auth} method.
* @param x509CertificateSubjectDN the expected subject distinguished name
* associated to the client {@code X509Certificate} received during client
* authentication * @return the {@link Builder} for further configuration
* @return the {@link Builder} for further configuration
*/
public Builder x509CertificateSubjectDN(String x509CertificateSubjectDN) {
return setting(ConfigurationSettingNames.Client.X509_CERTIFICATE_SUBJECT_DN, x509CertificateSubjectDN);
}
/**
* Builds the {@link ClientSettings}.
* @return the {@link ClientSettings}
*/
@Override
public ClientSettings build() {
return new ClientSettings(getSettings());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\ClientSettings.java | 1 |
请完成以下Java代码 | public static IModelInternalAccessor getModelInternalAccessor(@NonNull final Object model)
{
if (model instanceof PO)
{
final PO po = (PO)model;
return new POModelInternalAccessor(po);
}
final POWrapper wrapper = getPOWrapperOrNull(model);
if (wrapper != null)
{
return wrapper.modelInternalAccessor;
}
return null;
}
/**
* {@link POWrapper} internal accessor implementation
*/
private final IModelInternalAccessor modelInternalAccessor = new IModelInternalAccessor()
{
@Override
public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value)
{
POWrapper.this.setValueFromPO(idColumnName, parameterType, value);
}
@Override
public boolean setValue(final String columnName, final Object value)
{
return POWrapper.this.setValue(columnName, value);
}
@Override
public boolean setValueNoCheck(final String columnName, final Object value)
{
return POWrapper.this.setValueNoCheck(columnName, value);
}
;
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
return POWrapper.this.invokeParent(method, methodArgs);
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
return POWrapper.this.invokeEquals(methodArgs);
}
@Override
public Object getValue(final String columnName, final int idx, final Class<?> returnType)
{
return POWrapper.this.getValue(columnName, idx, returnType);
}
@Override
public Object getValue(final String columnName, final Class<?> returnType)
{
final int columnIndex = POWrapper.this.getColumnIndex(columnName);
return POWrapper.this.getValue(columnName, columnIndex, returnType);
}
@Override
public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception
{
return POWrapper.this.getReferencedObject(columnName, interfaceMethod);
}
@Override
public Set<String> getColumnNames() | {
return POWrapper.this.getColumnNames();
}
@Override
public int getColumnIndex(final String columnName)
{
return POWrapper.this.getColumnIndex(columnName);
}
@Override
public boolean isVirtualColumn(final String columnName)
{
return POWrapper.this.isVirtualColumn(columnName);
}
@Override
public boolean isKeyColumnName(final String columnName)
{
return POWrapper.this.isKeyColumnName(columnName);
}
;
@Override
public boolean isCalculated(final String columnName)
{
return POWrapper.this.isCalculated(columnName);
}
@Override
public boolean hasColumnName(final String columnName)
{
return POWrapper.this.hasColumnName(columnName);
}
};
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\POWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WorkflowLaunchersQuery
{
@NonNull MobileApplicationId applicationId;
@NonNull UserId userId;
@Nullable ScannedCode filterByQRCode;
@Nullable DocumentNoFilter filterByDocumentNo;
boolean filterByQtyAvailableAtPickFromLocator;
@Nullable ImmutableSet<WorkflowLaunchersFacetId> facetIds;
boolean excludeAlreadyStarted;
@Default boolean computeActions = true;
@Nullable QueryLimit limit;
@NonNull @Default @With Duration maxStaleAccepted = Duration.ZERO;
public Optional<QueryLimit> getLimit() {return Optional.ofNullable(limit);}
public void assertNoFilterByDocumentNo()
{
if (filterByDocumentNo != null)
{
throw new AdempiereException("Filtering by DocumentNo is not supported");
}
}
public void assertNoFilterByQRCode() | {
if (filterByQRCode != null)
{
throw new AdempiereException("Filtering by QR Code is not supported");
}
}
public void assertNoFacetIds()
{
if (facetIds != null && !facetIds.isEmpty())
{
throw new AdempiereException("Filtering by facets is not supported");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLaunchersQuery.java | 2 |
请完成以下Java代码 | private class User {
@ApiModelProperty(notes = "name of the User")
private String userName;
@ApiModelProperty(notes = "salary of the user")
private Long salary;
public User(String userName, Long salary) {
this.userName = userName;
this.salary = salary;
}
public String getUserName() {
return userName; | }
public void setUserName(String userName) {
this.userName = userName;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
}
} | repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringSwaggerProjectAgain\src\main\java\spring\swagger\resource\UserRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void insertData(String schemaName, String tableName, Document obj) {
try {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.INSERT.getNumber();
mongoTemplate.save(obj,tableName);
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (DuplicateKeyException dke) {
//主键冲突异常,跳过
logger.warn("DuplicateKeyException:", dke);
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
public void updateData(String schemaName, String tableName, DBObject query, Document obj) {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.UPDATE.getNumber();
Document options = new Document(query.toMap());
try {
obj.remove("id");
mongoTemplate.getCollection(tableName).replaceOne(options,obj);
obj.putAll(query.toMap());
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) { | logger.error(schemaName, tableName, obj, e);
}
}
public void deleteData(String schemaName, String tableName, Document obj) {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.DELETE.getNumber();
//保存原始数据
try {
if (obj.containsKey("id")) {
obj.put("_id", obj.get("id"));
obj.remove("id");
mongoTemplate.remove(new BasicQuery(obj),tableName);
}
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
} | repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\service\DataService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void run(String trxName)
{
refreshEx(mview, sourcePO, refreshMode, trxName);
ok[0] = true;
}
@Override
public boolean doCatch(Throwable e)
{
// log the error, return true to rollback the transaction but don't throw it forward
log.error(e.getLocalizedMessage() + ", mview=" + mview + ", sourcePO=" + sourcePO + ", trxName=" + trxName, e);
ok[0] = false;
return true;
}
@Override
public void doFinally()
{
}
});
return ok[0];
}
@Override
public boolean isSourceChanged(MViewMetadata mdata, PO sourcePO, int changeType)
{
final String sourceTableName = sourcePO.get_TableName(); | final Set<String> sourceColumns = mdata.getSourceColumns(sourceTableName);
if (sourceColumns == null || sourceColumns.isEmpty())
return false;
if (changeType == ModelValidator.TYPE_AFTER_NEW || changeType == ModelValidator.TYPE_AFTER_DELETE)
{
return true;
}
for (String sourceColumn : sourceColumns)
{
if (sourcePO.is_ValueChanged(sourceColumn))
{
return true;
}
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableMViewBL.java | 2 |
请完成以下Java代码 | public String toString()
{
// NOTE: keep in sync with the parser!!!
final StringBuilder sb = new StringBuilder("CConnection[");
sb
.append("DBhost=").append(dbHost)
.append(",DBport=").append(dbPort)
.append(",DBname=").append(dbName)
.append(",UID=").append(dbUid)
.append(",PWD=").append(dbPwd);
sb.append("]");
return sb.toString();
} // toStringLong
private static int parseDbPort(final String dbPortString)
{
try
{
if (Check.isBlank(dbPortString)) | {
return -1;
}
else
{
return Integer.parseInt(dbPortString);
}
}
catch (final Exception e)
{
logger.error("Error parsing db port: " + dbPortString, e);
return -1;
}
} // setDbPort
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\db\CConnectionAttributes.java | 1 |
请完成以下Java代码 | public static Set<DocumentId> retrieveRowIdsForLineIds(
@NonNull final SqlViewKeyColumnNamesMap keyColumnNamesMap,
final ViewId viewId,
final Set<Integer> lineIds)
{
final SqlAndParams sqlAndParams = SqlViewSelectionQueryBuilder.buildSqlSelectRowIdsForLineIds(keyColumnNamesMap, viewId.getViewId(), lineIds);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sqlAndParams.getSql(), ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlAndParams.getSqlParams());
rs = pstmt.executeQuery();
final ImmutableSet.Builder<DocumentId> rowIds = ImmutableSet.builder();
while (rs.next())
{
final DocumentId rowId = keyColumnNamesMap.retrieveRowId(rs, "", false); | if (rowId != null)
{
rowIds.add(rowId);
}
}
return rowIds.build();
}
catch (final SQLException ex)
{
throw new DBException(ex, sqlAndParams.getSql(), sqlAndParams.getSqlParams());
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewRowIdsOrderedSelectionFactory.java | 1 |
请完成以下Java代码 | public String getChangeData(Struct sourceRecordChangeValue, String record) {
Map<String, Object> changeDataMap = getChangeDataMap(sourceRecordChangeValue, record);
if (CollectionUtils.isEmpty(changeDataMap)) {
return null;
}
return JSON.toJSONString(changeDataMap);
}
public Map<String, Object> getChangeDataMap(Struct sourceRecordChangeValue, String record) {
Struct struct = (Struct) sourceRecordChangeValue.get(record);
// 将变更的行封装为Map
Map<String, Object> changeData = struct.schema().fields().stream()
.map(Field::name)
.filter(fieldName -> struct.get(fieldName) != null)
.map(fieldName -> Pair.of(fieldName, struct.get(fieldName)))
.collect(toMap(Pair::getKey, Pair::getValue));
if (CollectionUtils.isEmpty(changeData)) {
return null;
}
return changeData;
} | private Map<String, Object> getChangeTableInfo(Struct sourceRecordChangeValue) {
Struct struct = (Struct) sourceRecordChangeValue.get(SOURCE);
Map<String, Object> map = struct.schema().fields().stream()
.map(Field::name)
.filter(fieldName -> struct.get(fieldName) != null && FilterJsonFieldEnum.filterJsonField(fieldName))
.map(fieldName -> Pair.of(fieldName, struct.get(fieldName)))
.collect(toMap(Pair::getKey, Pair::getValue));
if (map.containsKey(FilterJsonFieldEnum.ts_ms.name())) {
map.put("changeTime", map.get(FilterJsonFieldEnum.ts_ms.name()));
map.remove(FilterJsonFieldEnum.ts_ms.name());
}
return map;
}
} | repos\springboot-demo-master\debezium\src\main\java\com\et\debezium\handler\ChangeEventHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
ModelAndView errorPage = new ModelAndView("errorPage");
String errorMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code : 400 . Bad Request";
break;
}
case 401: {
errorMsg = "Http Error Code : 401. Unauthorized";
break;
}
case 404: {
errorMsg = "Http Error Code : 404. Resource not found"; | break;
}
// Handle other 4xx error codes.
case 500: {
errorMsg = "Http Error Code : 500. Internal Server Error";
break;
}
// Handle other 5xx error codes.
}
errorPage.addObject("errorMsg", errorMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest.getAttribute("jakarta.servlet.error.status_code");
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\controller\ErrorController.java | 2 |
请完成以下Java代码 | public static InputStream getInputStream(Object classLoaderSource, String filePath) {
return getInputStream(classLoaderSource.getClass().getClassLoader(), filePath);
}
public static InputStream getInputStream(ClassLoader classLoader, String filePath) {
boolean classPathResource = false;
String path = filePath;
if (path.startsWith(CLASSPATH_URL_PREFIX)) {
path = path.substring(CLASSPATH_URL_PREFIX.length());
classPathResource = true;
}
try {
if (!classPathResource) {
File resourceFile = new File(path);
if (resourceFile.exists()) {
log.info("Reading resource data from file {}", filePath);
return new FileInputStream(resourceFile);
}
}
InputStream classPathStream = classLoader.getResourceAsStream(path);
if (classPathStream != null) {
log.info("Reading resource data from class path {}", filePath);
return classPathStream;
} else {
URL url = Resources.getResource(path);
if (url != null) {
URI uri = url.toURI();
log.info("Reading resource data from URI {}", filePath);
return new FileInputStream(new File(uri));
}
}
} catch (Exception e) {
if (e instanceof NullPointerException) {
log.warn("Unable to find resource: " + filePath);
} else {
log.warn("Unable to find resource: " + filePath, e);
}
}
throw new RuntimeException("Unable to find resource: " + filePath);
} | public static String getUri(Object classLoaderSource, String filePath) {
return getUri(classLoaderSource.getClass().getClassLoader(), filePath);
}
public static String getUri(ClassLoader classLoader, String filePath) {
try {
File resourceFile = new File(filePath);
if (resourceFile.exists()) {
log.info("Reading resource data from file {}", filePath);
return resourceFile.getAbsolutePath();
} else {
URL url = classLoader.getResource(filePath);
return url.toURI().toString();
}
} catch (Exception e) {
if (e instanceof NullPointerException) {
log.warn("Unable to find resource: " + filePath);
} else {
log.warn("Unable to find resource: " + filePath, e);
}
throw new RuntimeException("Unable to find resource: " + filePath);
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ResourceUtils.java | 1 |
请完成以下Java代码 | public static OrderPaySchedule ofList(@NonNull final OrderId orderId, @NonNull final List<OrderPayScheduleLine> lines)
{
return new OrderPaySchedule(orderId, lines);
}
public static Collector<OrderPayScheduleLine, ?, Optional<OrderPaySchedule>> collect()
{
return GuavaCollectors.collectUsingListAccumulator((lines) -> {
if (lines.isEmpty())
{
return Optional.empty();
}
final OrderId orderId = lines.get(0).getOrderId();
return Optional.of(new OrderPaySchedule(orderId, lines));
});
}
public OrderPayScheduleLine getLineByPaymentTermBreakId(@NonNull final PaymentTermBreakId paymentTermBreakId)
{
return lines.stream()
.filter(line -> PaymentTermBreakId.equals(line.getPaymentTermBreakId(), paymentTermBreakId))
.findFirst()
.orElseThrow(() -> new AdempiereException("No line found for " + paymentTermBreakId));
}
public OrderPayScheduleLine getLineById(@NonNull final OrderPayScheduleId payScheduleLineId)
{
return lines.stream()
.filter(line -> line.getId().equals(payScheduleLineId))
.findFirst()
.orElseThrow(() -> new AdempiereException("OrderPayScheduleLine not found for ID: " + payScheduleLineId));
} | public void updateStatusFromContext(final OrderSchedulingContext context)
{
final PaymentTerm paymentTerm = context.getPaymentTerm();
for (final OrderPayScheduleLine line : lines)
{
if (line.getStatus().isPending())
{
final PaymentTermBreak termBreak = paymentTerm.getBreakById(line.getPaymentTermBreakId());
final DueDateAndStatus dueDateAndStatus = context.computeDueDate(termBreak);
line.applyAndProcess(dueDateAndStatus);
}
}
}
public void markAsPaid(final OrderPayScheduleId orderPayScheduleId)
{
final OrderPayScheduleLine line = getLineById(orderPayScheduleId);
final DueDateAndStatus dueDateAndStatus = DueDateAndStatus.paid(line.getDueDate());
line.applyAndProcess(dueDateAndStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderPaySchedule.java | 1 |
请完成以下Java代码 | public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) {
int lines = 0;
try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
reader.skip(Integer.MAX_VALUE);
lines = reader.getLineNumber();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingScanner(String fileName) {
int lines = 0;
try (Scanner scanner = new Scanner(new FileReader(fileName))) {
while (scanner.hasNextLine()) {
scanner.nextLine();
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) {
int lines = 0;
try (Stream<String> fileStream = Files.lines(Paths.get(fileName))) {
lines = (int) fileStream.count();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFilesReadAllLines(String fileName) {
int lines = 0;
try {
List<String> fileStream = Files.readAllLines(Paths.get(fileName));
lines = fileStream.size();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) {
int lines = 1; | try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) {
ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
while (byteBuffer.hasRemaining()) {
byte currentChar = byteBuffer.get();
if (currentChar == '\n') {
lines++;
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) {
int lines = 0;
try {
LineIterator lineIterator = FileUtils.lineIterator(new File(fileName));
while (lineIterator.hasNext()) {
lineIterator.nextLine();
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) {
int lines = 0;
try {
List<String> lineItems = com.google.common.io.Files.readLines(Paths.get(fileName)
.toFile(), Charset.defaultCharset());
lines = lineItems.size();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
} | repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\lines\NumberOfLineFinder.java | 1 |
请完成以下Java代码 | public void setC_RfQ_TopicSubscriberOnly_ID (int C_RfQ_TopicSubscriberOnly_ID)
{
if (C_RfQ_TopicSubscriberOnly_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriberOnly_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriberOnly_ID, Integer.valueOf(C_RfQ_TopicSubscriberOnly_ID));
}
/** Get RfQ Topic Subscriber Restriction.
@return Include Subscriber only for certain products or product categories
*/
@Override
public int getC_RfQ_TopicSubscriberOnly_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriberOnly_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public org.compiere.model.I_M_Product_Category getM_Product_Category() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_Category_ID, org.compiere.model.I_M_Product_Category.class);
}
@Override
public void setM_Product_Category(org.compiere.model.I_M_Product_Category M_Product_Category)
{
set_ValueFromPO(COLUMNNAME_M_Product_Category_ID, org.compiere.model.I_M_Product_Category.class, M_Product_Category);
}
/** Set Produkt-Kategorie.
@param M_Product_Category_ID
Category of a Product
*/
@Override
public void setM_Product_Category_ID (int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, Integer.valueOf(M_Product_Category_ID));
}
/** Get Produkt-Kategorie.
@return Category of a Product
*/
@Override
public int getM_Product_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID);
if (ii == null) | return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriberOnly.java | 1 |
请完成以下Java代码 | private void clearRequestedSessionCache() {
this.requestedSessionCached = false;
this.requestedSession = null;
this.requestedSessionId = null;
}
/**
* Allows creating an HttpSession from a Session instance.
*
* @author Rob Winch
* @since 1.0
*/
private final class HttpSessionWrapper extends HttpSessionAdapter<S> {
HttpSessionWrapper(S session, ServletContext servletContext) {
super(session, servletContext);
}
@Override
public void invalidate() {
super.invalidate();
SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true;
setCurrentSession(null);
clearRequestedSessionCache();
SessionRepositoryFilter.this.sessionRepository.deleteById(getId());
}
}
/**
* Ensures session is committed before issuing an include.
*
* @since 1.3.4
*/
private final class SessionCommittingRequestDispatcher implements RequestDispatcher {
private final RequestDispatcher delegate;
SessionCommittingRequestDispatcher(RequestDispatcher delegate) {
this.delegate = delegate;
} | @Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.delegate.forward(request, response);
}
@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
if (!SessionRepositoryRequestWrapper.this.hasCommittedInInclude) {
SessionRepositoryRequestWrapper.this.commitSession();
SessionRepositoryRequestWrapper.this.hasCommittedInInclude = true;
}
this.delegate.include(request, response);
}
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\SessionRepositoryFilter.java | 1 |
请完成以下Java代码 | public GridField getField() {
return m_mField;
}
/**
* Action Listener Interface
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
// m_text.addActionListener(listener);
} // addActionListener
/**
* Action Listener - start dialog
* @param e Event
*/
@Override
public void actionPerformed(ActionEvent e)
{
if (!m_button.isEnabled())
return;
throw new AdempiereException("legacy feature removed");
}
/**
* Property Change Listener
* @param evt event
*/
@Override
public void propertyChange (PropertyChangeEvent evt) | {
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
@Override
public boolean isAutoCommit()
{
return true;
}
} // VAssignment | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAssignment.java | 1 |
请完成以下Java代码 | public QtyTU add(@NonNull final QtyTU toAdd)
{
if (this.intValue == 0)
{
return toAdd;
}
else if (toAdd.intValue == 0)
{
return this;
}
else
{
return ofInt(this.intValue + toAdd.intValue);
}
}
public QtyTU subtractOrZero(@NonNull final QtyTU toSubtract)
{
if (toSubtract.intValue == 0)
{
return this;
}
else
{
return ofInt(Math.max(this.intValue - toSubtract.intValue, 0));
}
}
public QtyTU min(@NonNull final QtyTU other)
{
return this.intValue <= other.intValue ? this : other;
}
public Quantity computeQtyCUsPerTUUsingTotalQty(@NonNull final Quantity qtyCUsTotal)
{
if (isZero()) | {
throw new AdempiereException("Cannot determine Qty CUs/TU when QtyTU is zero of total CUs " + qtyCUsTotal);
}
else if (isOne())
{
return qtyCUsTotal;
}
else
{
return qtyCUsTotal.divide(toInt());
}
}
public Quantity computeTotalQtyCUsUsingQtyCUsPerTU(@NonNull final Quantity qtyCUsPerTU)
{
return qtyCUsPerTU.multiply(toInt());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\QtyTU.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class SecureReactiveWebOperation implements ReactiveWebOperation {
private final ReactiveWebOperation delegate;
private final SecurityInterceptor securityInterceptor;
private final EndpointId endpointId;
SecureReactiveWebOperation(ReactiveWebOperation delegate, SecurityInterceptor securityInterceptor,
EndpointId endpointId) {
this.delegate = delegate;
this.securityInterceptor = securityInterceptor;
this.endpointId = endpointId;
}
@Override
public Mono<ResponseEntity<Object>> handle(ServerWebExchange exchange, @Nullable Map<String, String> body) {
return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString())
.flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse));
}
private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange,
@Nullable Map<String, String> body, SecurityResponse securityResponse) { | if (!securityResponse.getStatus().equals(HttpStatus.OK)) {
return Mono.just(new ResponseEntity<>(securityResponse.getStatus()));
}
return this.delegate.handle(exchange, body);
}
}
static class CloudFoundryWebFluxEndpointHandlerMappingRuntimeHints implements RuntimeHintsRegistrar {
private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar();
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.reflectiveRegistrar.registerRuntimeHints(hints, CloudFoundryLinksHandler.class);
this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\reactive\CloudFoundryWebFluxEndpointHandlerMapping.java | 2 |
请完成以下Java代码 | public static Builder with(JwsAlgorithm jwsAlgorithm) {
return new Builder(jwsAlgorithm);
}
/**
* Returns a new {@link Builder}, initialized with the provided {@code headers}.
* @param headers the headers
* @return the {@link Builder}
*/
public static Builder from(JwsHeader headers) {
return new Builder(headers);
}
/**
* A builder for {@link JwsHeader}.
*/
public static final class Builder extends AbstractBuilder<JwsHeader, Builder> {
private Builder(JwsAlgorithm jwsAlgorithm) {
Assert.notNull(jwsAlgorithm, "jwsAlgorithm cannot be null"); | algorithm(jwsAlgorithm);
}
private Builder(JwsHeader headers) {
Assert.notNull(headers, "headers cannot be null");
getHeaders().putAll(headers.getHeaders());
}
/**
* Builds a new {@link JwsHeader}.
* @return a {@link JwsHeader}
*/
@Override
public JwsHeader build() {
return new JwsHeader(getHeaders());
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwsHeader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public GroupedOpenApi group01() {
return GroupedOpenApi.builder()
.group("group01")
.addOperationCustomizer((operation, handlerMethod) -> {
operation.addSecurityItem(new SecurityRequirement().addList(headerName));
return operation;
})
.packagesToScan(basePackage)
.build();
}
@Bean
public OpenAPI customOpenAPI() {
Components components = new Components();
//添加右上角的统一安全认证
components.addSecuritySchemes(headerName,
new SecurityScheme()
.type(SecurityScheme.Type.APIKEY)
.scheme("basic")
.name(headerName)
.in(SecurityScheme.In.HEADER) | .description("请求头")
);
return new OpenAPI()
.components(components)
.info(apiInfo());
}
private Info apiInfo() {
Contact contact = new Contact();
contact.setEmail("2449207463@qq.com");
contact.setName("程序员十三");
contact.setUrl("https://juejin.cn/user/3808363978174302");
return new Info()
.title("Swagger文档")
.version("1.0")
.contact(contact)
.license(new License().name("Apache 2.0").url("http://springdoc.org"));
}
} | repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-swagger\src\main\java\cn\lanqiao\springboot3\config\SpringDocConfig.java | 2 |
请完成以下Java代码 | public static ParserTypeEnum fromValue(String value) {
if (value == null || value.trim().isEmpty()) {
return SQL;
}
String trimmedValue = value.trim();
// 首先尝试精确匹配枚举值
for (ParserTypeEnum type : ParserTypeEnum.values()) {
if (type.getValue().equals(trimmedValue)) {
return type;
}
}
// 如果精确匹配失败,尝试忽略大小写匹配
for (ParserTypeEnum type : ParserTypeEnum.values()) {
if (type.getValue().equalsIgnoreCase(trimmedValue)) { | return type;
}
}
// 尝试匹配枚举名称
for (ParserTypeEnum type : ParserTypeEnum.values()) {
if (type.name().equalsIgnoreCase(trimmedValue)) {
return type;
}
}
// 默认返回SQL类型
return SQL;
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\enums\ParserTypeEnum.java | 1 |
请完成以下Java代码 | public PersonType getPerson() {
return person;
}
/**
* Sets the value of the person property.
*
* @param value
* allowed object is
* {@link PersonType }
*
*/
public void setPerson(PersonType value) {
this.person = value;
}
/**
* Gets the value of the eanParty property.
*
* @return | * possible object is
* {@link String }
*
*/
public String getEanParty() {
return eanParty;
}
/**
* Sets the value of the eanParty property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEanParty(String value) {
this.eanParty = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\InsuranceAddressType.java | 1 |
请完成以下Java代码 | public static int getPtypeMenu() {
return PTYPE_MENU;
}
public static void setPtypeMenu(int ptypeMenu) {
PTYPE_MENU = ptypeMenu;
}
public static int getPtypeButton() {
return PTYPE_BUTTON;
}
public static void setPtypeButton(int ptypeButton) {
PTYPE_BUTTON = ptypeButton;
}
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getPtype() {
return ptype;
}
public void setPtype(Integer ptype) {
this.ptype = ptype;
}
public String getPval() {
return pval;
} | public void setPval(String pval) {
this.pval = pval;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\Perm.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.