instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getQuery() {
return query.toString();
}
public static class Parameter {
private final Object value;
private final int type;
private final String name;
public Parameter(Object value, int type, String name) {
this.value = value;
this.type = type;
this.name = name;
}
} | public TenantId getTenantId() {
return securityCtx.getTenantId();
}
public CustomerId getCustomerId() {
return securityCtx.getCustomerId();
}
public EntityType getEntityType() {
return securityCtx.getEntityType();
}
public boolean isIgnorePermissionCheck() {
return securityCtx.isIgnorePermissionCheck();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\SqlQueryContext.java | 1 |
请完成以下Java代码 | public boolean isCashBank(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankId != null && bankRepo.isCashBank(bankId);
}
public BankAccount getById(@NonNull final BankAccountId bankAccountId)
{
return bankAccountDAO.getById(bankAccountId);
}
@NonNull
public BankAccount getByIdNotNull(@NonNull final BankAccountId bankAccountId)
{
return Optional.ofNullable(getById(bankAccountId))
.orElseThrow(() -> new AdempiereException("No Bank Account found for " + bankAccountId));
}
public String createBankAccountName(@NonNull final BankAccountId bankAccountId)
{
final BankAccount bankAccount = getById(bankAccountId);
final CurrencyCode currencyCode = currencyRepo.getCurrencyCodeById(bankAccount.getCurrencyId());
final BankId bankId = bankAccount.getBankId();
if (bankId != null)
{
final Bank bank = bankRepo.getById(bankId);
return bank.getBankName() + "_" + currencyCode.toThreeLetterCode();
}
return currencyCode.toThreeLetterCode();
}
public DataImportConfigId getDataImportConfigIdForBankAccount(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankRepo.retrieveDataImportConfigIdForBank(bankId);
}
public boolean isImportAsSingleSummaryLine(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankRepo.isImportAsSingleSummaryLine(bankId);
} | @NonNull
public Optional<BankId> getBankIdBySwiftCode(@NonNull final String swiftCode)
{
return bankRepo.getBankIdBySwiftCode(swiftCode);
}
@NonNull
public Optional<BankAccountId> getBankAccountId(
@NonNull final BankId bankId,
@NonNull final String accountNo)
{
return bankAccountDAO.getBankAccountId(bankId, accountNo);
}
@NonNull
public Optional<BankAccountId> getBankAccountIdByIBAN(@NonNull final String iban)
{
return bankAccountDAO.getBankAccountIdByIBAN(iban);
}
@NonNull
public Optional<String> getBankName(@NonNull final BankAccountId bankAccountId)
{
return Optional.of(bankAccountDAO.getById(bankAccountId))
.map(BankAccount::getBankId)
.map(bankRepo::getById)
.map(Bank::getBankName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\api\BankAccountService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RpNotifyRecordDaoImpl extends BaseDaoImpl<RpNotifyRecord> implements RpNotifyRecordDao {
@Override
public RpNotifyRecord getNotifyByMerchantNoAndMerchantOrderNoAndNotifyType(String merchantNo, String merchantOrderNo, String notifyType) {
Map<String , Object> paramMap = new HashMap<String , Object>();
paramMap.put("merchantNo",merchantNo);
paramMap.put("merchantOrderNo",merchantOrderNo);
paramMap.put("notifyType",notifyType);
return super.getBy(paramMap);
}
@Override
public int deleteByPrimaryKey(String id) {
return 0;
} | @Override
public int insertSelective(RpNotifyRecord record) {
return 0;
}
@Override
public RpNotifyRecord selectByPrimaryKey(String id) {
return null;
}
@Override
public int updateByPrimaryKey(RpNotifyRecord record) {
return 0;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\dao\impl\RpNotifyRecordDaoImpl.java | 2 |
请完成以下Java代码 | public class BpmnHistoryCleanupJobHandler implements JobHandler {
public static final String TYPE = "bpmn-history-cleanup";
private static final String DEFAULT_BATCH_NAME = "Flowable BPMN History Cleanup";
@Override
public String getType() {
return TYPE;
}
@Override
public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
long inProgressDeletions = processEngineConfiguration.getManagementService()
.createBatchQuery()
.searchKey(DEFAULT_BATCH_NAME)
.status(DeleteProcessInstanceBatchConstants.STATUS_IN_PROGRESS)
.count();
if (inProgressDeletions > 0) { | return;
}
int batchSize = processEngineConfiguration.getCleanInstancesBatchSize();
HistoricProcessInstanceQuery query = processEngineConfiguration.getHistoryCleaningManager().createHistoricProcessInstanceCleaningQuery();
query.deleteSequentiallyUsingBatch(batchSize, DEFAULT_BATCH_NAME);
BatchQuery batchCleaningQuery = processEngineConfiguration.getHistoryCleaningManager().createBatchCleaningQuery();
if (batchCleaningQuery != null) {
batchCleaningQuery.delete();
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\jobexecutor\BpmnHistoryCleanupJobHandler.java | 1 |
请完成以下Java代码 | public Job findByIdForUpdate(TenantId tenantId, JobId jobId) {
return DaoUtil.getData(jobRepository.findByIdForUpdate(jobId.getId()));
}
@Override
public Job findLatestByTenantIdAndKey(TenantId tenantId, String key) {
return DaoUtil.getData(jobRepository.findLatestByTenantIdAndKey(tenantId.getId(), key, Limit.of(1)));
}
@Override
public boolean existsByTenantAndKeyAndStatusOneOf(TenantId tenantId, String key, JobStatus... statuses) {
return jobRepository.existsByTenantIdAndKeyAndStatusIn(tenantId.getId(), key, Arrays.stream(statuses).toList());
}
@Override
public boolean existsByTenantIdAndTypeAndStatusOneOf(TenantId tenantId, JobType type, JobStatus... statuses) {
return jobRepository.existsByTenantIdAndTypeAndStatusIn(tenantId.getId(), type, Arrays.stream(statuses).toList());
}
@Override
public boolean existsByTenantIdAndEntityIdAndStatusOneOf(TenantId tenantId, EntityId entityId, JobStatus... statuses) {
return jobRepository.existsByTenantIdAndEntityIdAndStatusIn(tenantId.getId(), entityId.getId(), Arrays.stream(statuses).toList());
}
@Override
public Job findOldestByTenantIdAndTypeAndStatusForUpdate(TenantId tenantId, JobType type, JobStatus status) {
return DaoUtil.getData(jobRepository.findOldestByTenantIdAndTypeAndStatusForUpdate(tenantId.getId(), type.name(), status.name()));
} | @Override
public void removeByTenantId(TenantId tenantId) {
jobRepository.deleteByTenantId(tenantId.getId());
}
@Override
public int removeByEntityId(TenantId tenantId, EntityId entityId) {
return jobRepository.deleteByEntityId(entityId.getId());
}
@Override
public EntityType getEntityType() {
return EntityType.JOB;
}
@Override
protected Class<JobEntity> getEntityClass() {
return JobEntity.class;
}
@Override
protected JpaRepository<JobEntity, UUID> getRepository() {
return jobRepository;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\job\JpaJobDao.java | 1 |
请完成以下Spring Boot application配置 | server.port = 8081
spring.dubbo.application.name=service-provider
# dubbo服务发布者实现类注解@service所在的包
spring.dubbo.base-package=com.dubbo.producer
spring.dubbo.registry.address=zookeeper://127.0.0.1
spring.dubbo.registry.port=2181
spring.d | ubbo.protocol.name=dubbo
spring.dubbo.protocol.serialization=hessian2
spring.dubbo.provider.retries=0 | repos\spring-boot-quick-master\quick-dubbo\dubbo-producer\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void removeFromHUsScheduledToMoveList(@NonNull final DDOrderLineId ddOrderLineId, @NonNull final Set<HuId> huIds)
{
if (huIds.isEmpty())
{
return;
}
//
// Create the query to select the lines we want to remove
queryBL.createQueryBuilder(I_DD_OrderLine_HU_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_DD_OrderLine_ID, ddOrderLineId)
.addInArrayFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_M_HU_ID, huIds)
.create()
.delete();
}
public boolean isScheduledToMove(@NonNull final HuId huId)
{
// TODO: only not processed ones
return queryBL.createQueryBuilder(I_DD_OrderLine_HU_Candidate.class)
.addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_M_HU_ID, huId)
.create()
.anyMatch();
}
public ImmutableList<DDOrderMoveSchedule> getByDDOrderId(final DDOrderId ddOrderId)
{
return newLoaderAndSaver().loadByDDOrderId(ddOrderId);
}
public ImmutableList<DDOrderMoveSchedule> getByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds)
{
return newLoaderAndSaver().loadByDDOrderLineIds(ddOrderLineIds);
}
public boolean hasInProgressSchedules(@NonNull final DDOrderLineId ddOrderLineId)
{
return queryBL.createQueryBuilder(I_DD_Order_MoveSchedule.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_DD_OrderLine_ID, ddOrderLineId)
.addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_Status, DDOrderMoveScheduleStatus.IN_PROGRESS) | .create()
.anyMatch();
}
public boolean hasInProgressSchedules(final DDOrderId ddOrderId)
{
return queryBL.createQueryBuilder(I_DD_Order_MoveSchedule.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_DD_Order_ID, ddOrderId)
.addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_Status, DDOrderMoveScheduleStatus.IN_PROGRESS)
.create()
.anyMatch();
}
public Set<DDOrderId> retrieveDDOrderIdsInTransit(@NonNull final LocatorId inTransitLocatorId)
{
return queryInTransitSchedules(inTransitLocatorId)
.create()
.listDistinctAsImmutableSet(I_DD_OrderLine_HU_Candidate.COLUMNNAME_DD_Order_ID, DDOrderId.class);
}
public IQueryBuilder<I_DD_OrderLine_HU_Candidate> queryInTransitSchedules(final @NotNull LocatorId inTransitLocatorId)
{
return queryBL.createQueryBuilder(I_DD_OrderLine_HU_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_Status, DDOrderMoveScheduleStatus.IN_PROGRESS)
.addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_InTransit_Locator_ID, inTransitLocatorId)
.addNotNull(I_DD_OrderLine_HU_Candidate.COLUMNNAME_M_HU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleRepository.java | 1 |
请完成以下Java代码 | public void setProductCount(Integer productCount) {
this.productCount = productCount;
}
public Integer getProductCommentCount() {
return productCommentCount;
}
public void setProductCommentCount(Integer productCommentCount) {
this.productCommentCount = productCommentCount;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBigPic() {
return bigPic;
}
public void setBigPic(String bigPic) {
this.bigPic = bigPic;
}
public String getBrandStory() {
return brandStory;
}
public void setBrandStory(String brandStory) {
this.brandStory = brandStory;
}
@Override
public String toString() { | StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", firstLetter=").append(firstLetter);
sb.append(", sort=").append(sort);
sb.append(", factoryStatus=").append(factoryStatus);
sb.append(", showStatus=").append(showStatus);
sb.append(", productCount=").append(productCount);
sb.append(", productCommentCount=").append(productCommentCount);
sb.append(", logo=").append(logo);
sb.append(", bigPic=").append(bigPic);
sb.append(", brandStory=").append(brandStory);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrand.java | 1 |
请完成以下Java代码 | public Short getIndepyear() {
return indepyear;
}
public void setIndepyear(Short indepyear) {
this.indepyear = indepyear;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public Float getLifeexpectancy() {
return lifeexpectancy;
}
public void setLifeexpectancy(Float lifeexpectancy) {
this.lifeexpectancy = lifeexpectancy;
}
public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold;
}
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname;
} | public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
}
public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
} | repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java | 1 |
请完成以下Java代码 | public void pushProduct(final I_PMM_Product pmmProduct)
{
if (disabled.get())
{
logger.info("Disabled is set to true in this thread; -> doing nothing");
return;
}
final IAgentSync agent = getAgentSync();
final SyncProduct syncProduct = SyncObjectsFactory.newFactory().createSyncProduct(pmmProduct);
final PutProductsRequest syncProductsRequest = PutProductsRequest.of(syncProduct);
agent.syncProducts(syncProductsRequest);
}
@Override
@ManagedOperation
public void pushAllInfoMessages()
{
if (disabled.get())
{
logger.info("Disabled is set to true in this thread; -> doing nothing");
return;
}
final IAgentSync agent = getAgentSync();
final String infoMessage = SyncObjectsFactory.newFactory().createSyncInfoMessage();
agent.syncInfoMessage(PutInfoMessageRequest.builder()
.message(infoMessage)
.build());
}
@Override
public void pushRfQs(@Nullable final List<SyncRfQ> syncRfqs)
{
if (disabled.get())
{ | logger.info("Disabled is set to true in this thread; -> doing nothing");
return;
}
if (syncRfqs == null || syncRfqs.isEmpty())
{
return;
}
final IAgentSync agent = getAgentSync();
agent.syncRfQs(syncRfqs);
}
@Override
public void pushRfQCloseEvents(
@Nullable final List<SyncRfQCloseEvent> syncRfQCloseEvents)
{
if (disabled.get())
{
logger.info("Disabled is set to true in this thread; -> doing nothing");
return;
}
if (syncRfQCloseEvents == null || syncRfQCloseEvents.isEmpty())
{
return;
}
final IAgentSync agent = getAgentSync();
agent.closeRfQs(syncRfQCloseEvents);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\WebuiPush.java | 1 |
请完成以下Java代码 | public static String fromIdAsString(final int id)
{
return fromId(id).toString();
}
public static int toId(final String uuid)
{
if (uuid == null || uuid.trim().isEmpty())
{
return -1;
}
return toId(UUID.fromString(uuid));
}
private static final String toString(byte[] data)
{
StringBuilder sb = new StringBuilder();
for (final byte b : data)
{
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(b);
}
return sb | .insert(0, "[" + data.length + "] ")
.toString();
}
@SuppressWarnings("unused")
private static final String toByteString(final long data)
{
final byte[] dataBytes = ByteBuffer.allocate(8).putLong(data).array();
return toString(dataBytes);
}
private UUIDs()
{
super();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\util\UUIDs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeploymentResource extends BaseDeploymentResource {
@Autowired
protected EventRegistryRestResponseFactory restResponseFactory;
@ApiOperation(value = "Get a deployment", tags = { "Deployment" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the deployment was found and returned."),
@ApiResponse(code = 404, message = "Indicates the requested deployment was not found.")
})
@GetMapping(value = "/event-registry-repository/deployments/{deploymentId}", produces = "application/json")
public EventDeploymentResponse getDeployment(@ApiParam(name = "deploymentId", value ="The id of the deployment to get.") @PathVariable String deploymentId) {
EventDeployment deployment = getEventDeployment(deploymentId);
return restResponseFactory.createDeploymentResponse(deployment);
}
@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }, code = 204) | @ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested deployment was not found.")
})
@DeleteMapping(value = "/event-registry-repository/deployments/{deploymentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteDeployment(@ApiParam(name = "deploymentId") @PathVariable String deploymentId) {
EventDeployment deployment = getEventDeployment(deploymentId);
if (restApiInterceptor != null) {
restApiInterceptor.deleteDeployment(deployment);
}
repositoryService.deleteDeployment(deploymentId);
}
} | repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\DeploymentResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SupplierExtensionType {
@XmlElement(name = "FiscalNumber")
protected String fiscalNumber;
@XmlElement(name = "RegisteredOfficeOfCompany")
protected String registeredOfficeOfCompany;
@XmlElement(name = "LegalFormOfCompany")
protected String legalFormOfCompany;
@XmlElement(name = "TribnalPlaceRegistrationLocation")
protected String tribnalPlaceRegistrationLocation;
/**
* Fiscal number.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFiscalNumber() {
return fiscalNumber;
}
/**
* Sets the value of the fiscalNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFiscalNumber(String value) {
this.fiscalNumber = value;
}
/**
* Registered office of the company.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegisteredOfficeOfCompany() {
return registeredOfficeOfCompany;
}
/**
* Sets the value of the registeredOfficeOfCompany property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegisteredOfficeOfCompany(String value) { | this.registeredOfficeOfCompany = value;
}
/**
* Legal form of the company.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLegalFormOfCompany() {
return legalFormOfCompany;
}
/**
* Sets the value of the legalFormOfCompany property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLegalFormOfCompany(String value) {
this.legalFormOfCompany = value;
}
/**
* Place of the commercial register entry of the company.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTribnalPlaceRegistrationLocation() {
return tribnalPlaceRegistrationLocation;
}
/**
* Sets the value of the tribnalPlaceRegistrationLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTribnalPlaceRegistrationLocation(String value) {
this.tribnalPlaceRegistrationLocation = 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\SupplierExtensionType.java | 2 |
请完成以下Java代码 | public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
} | @Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Trl.java | 1 |
请完成以下Java代码 | protected static <T extends ProcessEngineException> T generateException(Class<T> exceptionClass, String message, String variableName, String description) {
String formattedMessage = formatMessage(message, variableName, description);
try {
Constructor<T> constructor = exceptionClass.getConstructor(String.class);
return constructor.newInstance(formattedMessage);
}
catch (Exception e) {
throw LOG.exceptionWhileInstantiatingClass(exceptionClass.getName(), e);
}
}
protected static String formatMessage(String message, String variableName, String description) {
return formatMessageElement(message, ": ") + formatMessageElement(variableName, " ") + description; | }
protected static String formatMessageElement(String element, String delimiter) {
if (element != null && !element.isEmpty()) {
return element.concat(delimiter);
}
else {
return "";
}
}
public static void ensureActiveCommandContext(String operation) {
if(Context.getCommandContext() == null) {
throw LOG.notInsideCommandContext(operation);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EnsureUtil.java | 1 |
请完成以下Java代码 | public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setPP_Order_Weighting_RunCheck_ID (final int PP_Order_Weighting_RunCheck_ID)
{
if (PP_Order_Weighting_RunCheck_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, PP_Order_Weighting_RunCheck_ID);
}
@Override
public int getPP_Order_Weighting_RunCheck_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_RunCheck_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Weighting_Run getPP_Order_Weighting_Run()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class);
}
@Override
public void setPP_Order_Weighting_Run(final org.eevolution.model.I_PP_Order_Weighting_Run PP_Order_Weighting_Run)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class, PP_Order_Weighting_Run);
}
@Override
public void setPP_Order_Weighting_Run_ID (final int PP_Order_Weighting_Run_ID)
{
if (PP_Order_Weighting_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, PP_Order_Weighting_Run_ID); | }
@Override
public int getPP_Order_Weighting_Run_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID);
}
@Override
public void setWeight (final BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_RunCheck.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void create(final String username, final String password) {
Name dn = LdapNameBuilder
.newInstance()
.add("ou", "users")
.add("cn", username)
.build();
DirContextAdapter context = new DirContextAdapter(dn);
context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"});
context.setAttributeValue("cn", username);
context.setAttributeValue("sn", username);
context.setAttributeValue("userPassword", digestSHA(password));
ldapTemplate.bind(context);
}
public void modify(final String username, final String password) {
Name dn = LdapNameBuilder
.newInstance()
.add("ou", "users")
.add("cn", username)
.build();
DirContextOperations context = ldapTemplate.lookupContext(dn);
context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"});
context.setAttributeValue("cn", username);
context.setAttributeValue("sn", username);
context.setAttributeValue("userPassword", digestSHA(password)); | ldapTemplate.modifyAttributes(context);
}
private String digestSHA(final String password) {
String base64;
try {
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(password.getBytes());
base64 = Base64
.getEncoder()
.encodeToString(digest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return "{SHA}" + base64;
}
} | repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\ldap\data\service\LdapClient.java | 2 |
请完成以下Java代码 | public String getMessageName() {
return messageName;
}
public String getProcessInstanceName() {
return processInstanceName;
}
public String getBusinessKey() {
return businessKey;
}
public String getLinkedProcessInstanceId() {
return linkedProcessInstanceId;
}
public String getLinkedProcessInstanceType() { | return linkedProcessInstanceType;
}
public String getTenantId() {
return tenantId;
}
public Map<String, Object> getVariables() {
return variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\runtime\ProcessInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | public class ReactivateEventListenerParseHandler extends AbstractPlanItemParseHandler<ReactivateEventListener> {
@Override
public Collection<Class<? extends BaseElement>> getHandledTypes() {
return Collections.singletonList(ReactivateEventListener.class);
}
@Override
protected void executePlanItemParse(CmmnParserImpl cmmnParser, CmmnParseResult cmmnParseResult, PlanItem planItem, ReactivateEventListener reactivateEventListener) {
// the behavior is the same as with the user event listener
planItem.setBehavior(cmmnParser.getActivityBehaviorFactory().createUserEventListenerActivityBehavior(planItem, reactivateEventListener));
// if we are parsing a reactivation listener, we automatically set the parent completion rule to ignore as the listener does not have an impact on
// parent completion at all as it is used when the case is completed to only mark the case eligible for reactivation
ParentCompletionRule parentCompletionRule = new ParentCompletionRule();
parentCompletionRule.setName("listenerIgnoredForCompletion");
parentCompletionRule.setType(ParentCompletionRule.IGNORE); | if (planItem.getItemControl() == null) {
PlanItemControl planItemControl = new PlanItemControl();
planItem.setItemControl(planItemControl);
}
planItem.getItemControl().setParentCompletionRule(parentCompletionRule);
// check, if there is an available condition set on the listener and set it on the reactivation listener as the reactivate condition expression
// explicitly as we need the default one to be a predefined one making the listener unavailable at runtime
if (StringUtils.isNotEmpty(reactivateEventListener.getAvailableConditionExpression())) {
reactivateEventListener.setReactivationAvailableConditionExpression(reactivateEventListener.getAvailableConditionExpression());
}
// additionally, we only set the listener to be available once the case is not active anymore (which in fact will make the listener unavailable at
// all at runtime as it is used only in history to reactivate the case again)
reactivateEventListener.setAvailableConditionExpression("${caseInstance.getState() != 'active'}");
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\handler\ReactivateEventListenerParseHandler.java | 1 |
请完成以下Java代码 | public IDocLineSortItemFinder setContext(final Properties ctx)
{
_ctx = ctx;
return this;
}
private final Properties getCtx()
{
Check.assumeNotNull(_ctx, "_ctx not null");
return _ctx;
}
@Override
public DocLineSortItemFinder setDocBaseType(final String docBaseType)
{
_docTypeSet = true;
_docBaseType = docBaseType;
return this;
}
@Override
public DocLineSortItemFinder setC_DocType(final I_C_DocType docType)
{
_docTypeSet = true;
_docType = docType;
return this;
}
private final String getDocBaseType()
{
Check.assume(_docTypeSet, "DocType or DocbaseType was set");
if (_docType != null)
{
return _docType.getDocBaseType();
}
else if (_docBaseType != null)
{
return _docBaseType;
}
else
{ | // throw new AdempiereException("DocBaseType not found"); // can be null
return null;
}
}
@Override
public DocLineSortItemFinder setC_BPartner_ID(final int bpartnerId)
{
_bpartnerIdSet = true;
_bpartnerId = bpartnerId;
return this;
}
private final int getC_BPartner_ID()
{
Check.assume(_bpartnerIdSet, "C_BPartner_ID was set");
return _bpartnerId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\docline\sort\api\impl\DocLineSortItemFinder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAreas() {
return areas;
}
public void setAreas(String areas) {
this.areas = areas;
}
public String getBankAccountName() {
return bankAccountName;
}
public void setBankAccountName(String bankAccountName) {
this.bankAccountName = bankAccountName;
}
public String getBankAccountNo() {
return bankAccountNo;
}
public void setBankAccountNo(String bankAccountNo) {
this.bankAccountNo = bankAccountNo;
}
public String getBankAccountType() {
return bankAccountType;
}
public void setBankAccountType(String bankAccountType) {
this.bankAccountType = bankAccountType;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getBankName() {
return bankName;
} | public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getCvn2() {
return cvn2;
}
public void setCvn2(String cvn2) {
this.cvn2 = cvn2;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
public String getIsDefault() {
return isDefault;
}
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
public String getIsAuth() {
return isAuth;
}
public void setIsAuth(String isAuth) {
this.isAuth = isAuth;
}
public String getStatusDesc() {
if (StringUtil.isEmpty(this.getStatus())) {
return "";
} else {
return PublicStatusEnum.getEnum(this.getStatus()).getDesc();
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserQuickPayBankAccount.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public IgnoreUrlsConfig ignoreUrlsConfig() {
return new IgnoreUrlsConfig();
}
@Bean
public JwtTokenUtil jwtTokenUtil() {
return new JwtTokenUtil();
}
@Bean
public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
return new RestfulAccessDeniedHandler();
}
@Bean
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
return new RestAuthenticationEntryPoint();
}
@Bean
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
return new JwtAuthenticationTokenFilter();
}
@ConditionalOnBean(name = "dynamicSecurityService")
@Bean | public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
return new DynamicAccessDecisionManager();
}
@ConditionalOnBean(name = "dynamicSecurityService")
@Bean
public DynamicSecurityMetadataSource dynamicSecurityMetadataSource() {
return new DynamicSecurityMetadataSource();
}
@ConditionalOnBean(name = "dynamicSecurityService")
@Bean
public DynamicSecurityFilter dynamicSecurityFilter(){
return new DynamicSecurityFilter();
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\config\CommonSecurityConfig.java | 2 |
请完成以下Java代码 | public int getExternalSystem_Status_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Status_ID);
}
@Override
public void setExternalSystemMessage (final @Nullable java.lang.String ExternalSystemMessage)
{
set_Value (COLUMNNAME_ExternalSystemMessage, ExternalSystemMessage);
}
@Override
public java.lang.String getExternalSystemMessage()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemMessage);
}
/**
* ExternalSystemStatus AD_Reference_ID=541502
* Reference name: ExpectedStatus
*/
public static final int EXTERNALSYSTEMSTATUS_AD_Reference_ID=541502;
/** Active = Active */
public static final String EXTERNALSYSTEMSTATUS_Active = "Active";
/** Inactive = Inactive */
public static final String EXTERNALSYSTEMSTATUS_Inactive = "Inactive";
/** Error = Error */ | public static final String EXTERNALSYSTEMSTATUS_Error = "Error ";
/** Down = Down */
public static final String EXTERNALSYSTEMSTATUS_Down = "Down";
@Override
public void setExternalSystemStatus (final java.lang.String ExternalSystemStatus)
{
set_Value (COLUMNNAME_ExternalSystemStatus, ExternalSystemStatus);
}
@Override
public java.lang.String getExternalSystemStatus()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Status.java | 1 |
请完成以下Java代码 | private IQueryBuilder<I_EDI_Desadv> createEDIDesadvQueryBuilder()
{
final IQueryFilter<I_EDI_Desadv> processQueryFilter = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBuilder<I_EDI_Desadv> queryBuilder = queryBL.createQueryBuilder(I_EDI_Desadv.class, getCtx(), get_TrxName())
.addOnlyActiveRecordsFilter()
.addInArrayOrAllFilter(I_EDI_Desadv.COLUMNNAME_EDI_ExportStatus, X_EDI_Desadv.EDI_EXPORTSTATUS_Error, X_EDI_Desadv.EDI_EXPORTSTATUS_Pending)
.filter(processQueryFilter);
queryBuilder.orderBy()
.addColumn(I_EDI_Desadv.COLUMNNAME_POReference)
.addColumn(I_EDI_Desadv.COLUMNNAME_EDI_Desadv_ID);
return queryBuilder;
} | private Iterator<I_EDI_Desadv> createIterator()
{
final IQueryBuilder<I_EDI_Desadv> queryBuilder = createEDIDesadvQueryBuilder();
final Iterator<I_EDI_Desadv> iterator = queryBuilder
.create()
.iterate(I_EDI_Desadv.class);
if(!iterator.hasNext())
{
addLog("Found no EDI_Desadvs to enqueue within the current selection");
}
return iterator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_EnqueueForExport.java | 1 |
请完成以下Java代码 | public boolean isSerializePOJOsInVariablesToJson() {
return serializePOJOsInVariablesToJson;
}
public void setSerializePOJOsInVariablesToJson(boolean serializePOJOsInVariablesToJson) {
this.serializePOJOsInVariablesToJson = serializePOJOsInVariablesToJson;
}
public String getJavaClassFieldForJackson() {
return javaClassFieldForJackson;
}
public void setJavaClassFieldForJackson(String javaClassFieldForJackson) {
this.javaClassFieldForJackson = javaClassFieldForJackson;
}
public Integer getProcessDefinitionCacheLimit() {
return processDefinitionCacheLimit;
} | public void setProcessDefinitionCacheLimit(Integer processDefinitionCacheLimit) {
this.processDefinitionCacheLimit = processDefinitionCacheLimit;
}
public String getProcessDefinitionCacheName() {
return processDefinitionCacheName;
}
public void setProcessDefinitionCacheName(String processDefinitionCacheName) {
this.processDefinitionCacheName = processDefinitionCacheName;
}
public void setDisableExistingStartEventSubscriptions(boolean disableExistingStartEventSubscriptions) {
this.disableExistingStartEventSubscriptions = disableExistingStartEventSubscriptions;
}
public boolean shouldDisableExistingStartEventSubscriptions() {
return disableExistingStartEventSubscriptions;
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\ActivitiProperties.java | 1 |
请完成以下Java代码 | public boolean isHandled(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.isHandled(model);
}
@Override
public IAttributeStorage getAttributeStorage(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.getAttributeStorage(model);
}
@Override
public IAttributeStorage getAttributeStorageIfHandled(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.getAttributeStorageIfHandled(model);
}
@Override
public final IHUAttributesDAO getHUAttributesDAO()
{ // TODO tbp: this exception is false: this.huAttributesDAO is NOT NULL!
throw new HUException("No IHUAttributesDAO found on " + this);
}
@Override
public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
{
this.huAttributesDAO = huAttributesDAO;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUAttributesDAO(huAttributesDAO);
}
}
@Override
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
} | @Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUStorageFactory(huStorageFactory);
}
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
return huStorageFactory;
}
@Override
public void flush()
{
final IHUAttributesDAO huAttributesDAO = this.huAttributesDAO;
if (huAttributesDAO != null)
{
huAttributesDAO.flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ClassAttributeStorageFactory.java | 1 |
请完成以下Java代码 | public class OnlineAddressType {
@XmlElement(required = true)
protected List<String> email;
protected List<String> url;
/**
* Gets the value of the email 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 email property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEmail().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getEmail() {
if (email == null) {
email = new ArrayList<String>();
}
return this.email;
}
/**
* Gets the value of the url 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 url property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUrl().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getUrl() {
if (url == null) {
url = new ArrayList<String>();
}
return this.url;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\OnlineAddressType.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(
@NonNull final IProcessPreconditionsContext context)
{
if (!I_C_PurchaseCandidate.Table_Name.equals(context.getTableName()))
{
return ProcessPreconditionsResolution.reject();
}
final boolean containsEligibleRecords = context
.streamSelectedModels(I_C_PurchaseCandidate.class)
.anyMatch(I_C_PurchaseCandidate::isPrepared);
return ProcessPreconditionsResolution.acceptIf(containsEligibleRecords);
}
@Override
protected String doIt() throws Exception
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final ImmutableSet<PurchaseCandidateId> purchaseCandidateIds = queryBL
.createQueryBuilder(I_C_PurchaseCandidate.class)
.filter(getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false))) | .addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_IsPrepared, true)
.create()
.iterateAndStreamIds(PurchaseCandidateId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
createPurchaseOrders(purchaseCandidateIds);
return MSG_OK;
}
protected void createPurchaseOrders(final ImmutableSet<PurchaseCandidateId> purchaseCandidateIds)
{
C_PurchaseCandidates_GeneratePurchaseOrders.enqueue(purchaseCandidateIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\process\C_PurchaseCandiate_Create_PurchaseOrders.java | 1 |
请完成以下Java代码 | public static InitializrMetadataBuilder create() {
return new InitializrMetadataBuilder(new InitializrConfiguration());
}
private static class InitializerPropertiesCustomizer implements InitializrMetadataCustomizer {
private final InitializrProperties properties;
InitializerPropertiesCustomizer(InitializrProperties properties) {
this.properties = properties;
}
@Override
public void customize(InitializrMetadata metadata) {
metadata.getDependencies().merge(this.properties.getDependencies());
metadata.getTypes().merge(this.properties.getTypes());
metadata.getBootVersions().merge(this.properties.getBootVersions());
metadata.getPackagings().merge(this.properties.getPackagings());
metadata.getJavaVersions().merge(this.properties.getJavaVersions());
metadata.getLanguages().merge(this.properties.getLanguages());
metadata.getConfigurationFileFormats().merge(this.properties.getConfigurationFileFormats());
this.properties.getGroupId().apply(metadata.getGroupId());
this.properties.getArtifactId().apply(metadata.getArtifactId());
this.properties.getVersion().apply(metadata.getVersion());
this.properties.getName().apply(metadata.getName());
this.properties.getDescription().apply(metadata.getDescription());
this.properties.getPackageName().apply(metadata.getPackageName());
}
}
private static class ResourceInitializrMetadataCustomizer implements InitializrMetadataCustomizer {
private static final Log logger = LogFactory.getLog(ResourceInitializrMetadataCustomizer.class); | private static final Charset UTF_8 = StandardCharsets.UTF_8;
private final Resource resource;
ResourceInitializrMetadataCustomizer(Resource resource) {
this.resource = resource;
}
@Override
public void customize(InitializrMetadata metadata) {
logger.info("Loading initializr metadata from " + this.resource);
try (InputStream in = this.resource.getInputStream()) {
String content = StreamUtils.copyToString(in, UTF_8);
ObjectMapper objectMapper = new ObjectMapper();
InitializrMetadata anotherMetadata = objectMapper.readValue(content, InitializrMetadata.class);
metadata.merge(anotherMetadata);
}
catch (Exception ex) {
throw new IllegalStateException("Cannot merge", ex);
}
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrMetadataBuilder.java | 1 |
请完成以下Java代码 | public void setBarcodes(SendungsRueckmeldung.Sendung.Position.Barcodes value) {
this.barcodes = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="BarcodeNr" maxOccurs="unbounded" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="1"/>
* <maxLength value="35"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"barcodeNr"
})
public static class Barcodes {
@XmlElement(name = "BarcodeNr")
protected List<String> barcodeNr;
/**
* Gets the value of the barcodeNr 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 barcodeNr property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBarcodeNr().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getBarcodeNr() {
if (barcodeNr == null) {
barcodeNr = new ArrayList<String>();
}
return this.barcodeNr;
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\SendungsRueckmeldung.java | 1 |
请完成以下Java代码 | public IntentEventListenerInstanceQuery elementId(String elementId) {
innerQuery.planItemInstanceElementId(elementId);
return this;
}
@Override
public IntentEventListenerInstanceQuery planItemDefinitionId(String planItemDefinitionId) {
innerQuery.planItemDefinitionId(planItemDefinitionId);
return this;
}
@Override
public IntentEventListenerInstanceQuery name(String name) {
innerQuery.planItemInstanceName(name);
return this;
}
@Override
public IntentEventListenerInstanceQuery stageInstanceId(String stageInstanceId) {
innerQuery.stageInstanceId(stageInstanceId);
return this;
}
@Override
public IntentEventListenerInstanceQuery stateAvailable() {
innerQuery.planItemInstanceStateAvailable();
return this;
}
@Override
public IntentEventListenerInstanceQuery stateSuspended() {
innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED);
return this;
}
@Override
public IntentEventListenerInstanceQuery orderByName() {
innerQuery.orderByName();
return this;
}
@Override
public IntentEventListenerInstanceQuery asc() {
innerQuery.asc();
return this;
}
@Override
public IntentEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
}
@Override
public IntentEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this; | }
@Override
public IntentEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return innerQuery.count();
}
@Override
public IntentEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return IntentEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<IntentEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<IntentEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<IntentEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(IntentEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private UserPermissionMapper userPermissionMapper;
/**
* 获取用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUserName();
System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集
List<Role> roleList = userRoleMapper.findByUserName(userName);
Set<String> roleSet = new HashSet<String>();
for (Role r : roleList) {
roleSet.add(r.getName());
}
simpleAuthorizationInfo.setRoles(roleSet);
// 获取用户权限集
List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
Set<String> permissionSet = new HashSet<String>();
for (Permission p : permissionList) {
permissionSet.add(p.getName());
}
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo;
}
/**
* 登录认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal(); | String password = new String((char[]) token.getCredentials());
System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
User user = userMapper.findByUserName(userName);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
if (user.getStatus().equals("0")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
} | repos\SpringAll-master\13.Spring-Boot-Shiro-Authorization\src\main\java\com\springboot\shiro\ShiroRealm.java | 2 |
请完成以下Java代码 | private CommonErrorHandler findDelegate(Throwable thrownException) {
Throwable cause = findCause(thrownException);
if (cause != null) {
Class<? extends Throwable> causeClass = cause.getClass();
for (Entry<Class<? extends Throwable>, CommonErrorHandler> entry : this.delegates.entrySet()) {
if (entry.getKey().isAssignableFrom(causeClass)) {
return entry.getValue();
}
}
}
return null;
}
@Nullable
private Throwable findCause(Throwable thrownException) {
if (this.causeChainTraversing) {
return traverseCauseChain(thrownException);
}
return shallowTraverseCauseChain(thrownException);
}
@Nullable
private Throwable shallowTraverseCauseChain(Throwable thrownException) { | Throwable cause = thrownException;
if (cause instanceof ListenerExecutionFailedException) {
cause = thrownException.getCause();
}
return cause;
}
@Nullable
private Throwable traverseCauseChain(Throwable thrownException) {
Throwable cause = thrownException;
while (cause != null && cause.getCause() != null) {
if (this.exceptionMatcher.match(cause)) {
return cause;
}
cause = cause.getCause();
}
return cause;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonDelegatingErrorHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2022-02-18T14:17:41.660Z[GMT]")public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix; | }
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if ("query".equals(location)) {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\auth\ApiKeyAuth.java | 2 |
请完成以下Java代码 | public final class NetworkUtil {
private static final Logger LOG = LoggerFactory.getLogger(NetworkUtil.class);
/**
* 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
*
* @param request
* @return
* @throws IOException
*/
public final static String getIpAddress(HttpServletRequest request)
throws IOException {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = request.getHeader("X-Forwarded-For");
// LOG.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip= {}" ,ip);
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
// LOG.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip= {}" , ip);
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
// LOG.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip= {}" , ip);
}
if (ip == null || ip.length() == 0 | || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
// LOG.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip= {}" , ip);
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
// LOG.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip= {}" , ip);
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
// LOG.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip= {}" , ip);
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
} | repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\utils\NetworkUtil.java | 1 |
请完成以下Java代码 | public ProcessDefinitionQueryImpl createProcessDefinitionQuery() {
return new ProcessDefinitionQueryImpl();
}
public ProcessInstanceQueryImpl createProcessInstanceQuery() {
return new ProcessInstanceQueryImpl();
}
public ExecutionQueryImpl createExecutionQuery() {
return new ExecutionQueryImpl();
}
public TaskQueryImpl createTaskQuery() {
return new TaskQueryImpl();
}
public JobQueryImpl createJobQuery() {
return new JobQueryImpl();
}
public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() {
return new HistoricProcessInstanceQueryImpl();
}
public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() {
return new HistoricActivityInstanceQueryImpl();
}
public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() {
return new HistoricTaskInstanceQueryImpl();
} | public HistoricDetailQueryImpl createHistoricDetailQuery() {
return new HistoricDetailQueryImpl();
}
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl();
}
// getters and setters
// //////////////////////////////////////////////////////
public SqlSession getSqlSession() {
return sqlSession;
}
public DbSqlSessionFactory getDbSqlSessionFactory() {
return dbSqlSessionFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java | 1 |
请完成以下Java代码 | public void start(int port) {
try {
serverSocket = new ServerSocket(port);
while (true)
new EchoClientHandler(serverSocket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
} finally {
stop();
}
}
public void stop() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static class EchoClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public EchoClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine; | while ((inputLine = in.readLine()) != null) {
if (".".equals(inputLine)) {
out.println("bye");
break;
}
out.println(inputLine);
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
LOG.debug(e.getMessage());
}
}
}
public static void main(String[] args) {
EchoMultiServer server = new EchoMultiServer();
server.start(5555);
}
} | repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\socket\EchoMultiServer.java | 1 |
请完成以下Java代码 | public class CompositeRecordTextProvider implements IRecordTextProvider
{
private static final Logger logger = LogManager.getLogger(CompositeRecordTextProvider.class);
private final CopyOnWriteArrayList<IRecordTextProvider> ctxProviders = new CopyOnWriteArrayList<>();
private IRecordTextProvider defaultCtxProvider = NullRecordTextProvider.instance;
public final void addCtxProvider(final IRecordTextProvider ctxProvider)
{
Check.assumeNotNull(ctxProvider, "ctx provider not null");
ctxProviders.addIfAbsent(ctxProvider);
}
public void setDefaultCtxProvider(final IRecordTextProvider defaultCtxProvider)
{
Check.assumeNotNull(defaultCtxProvider, "defaultCtxProvider not null");
this.defaultCtxProvider = defaultCtxProvider;
}
@Override
public Optional<String> getTextMessageIfApplies(final ITableRecordReference referencedRecord)
{
// take the providers one by one and see if any of them applies to the given referenced record
for (final IRecordTextProvider ctxProvider : ctxProviders)
{
final Optional<String> textMessage = ctxProvider.getTextMessageIfApplies(referencedRecord);
if (textMessage != null && textMessage.isPresent())
{
return textMessage; | }
}
// Fallback to default provider
final Optional<String> textMessage = defaultCtxProvider.getTextMessageIfApplies(referencedRecord);
// guard against development issues (usually the text message shall never be null)
if (textMessage == null)
{
new AdempiereException("Possible development issue. " + defaultCtxProvider + " returned null for " + referencedRecord)
.throwIfDeveloperModeOrLogWarningElse(logger);
return Optional.absent();
}
return textMessage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\spi\impl\CompositeRecordTextProvider.java | 1 |
请完成以下Java代码 | public Object getProperty(String name) {
if (properties == null) {
return null;
}
return properties.get(name);
}
@SuppressWarnings("unchecked")
public Map<String, Object> getProperties() {
if (properties == null) {
return Collections.EMPTY_MAP;
}
return properties;
} | // getters and setters //////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@Override
public ProcessDefinitionImpl getProcessDefinition() {
return processDefinition;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ProcessElementImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setUsername(String username) {
this.username = username;
}
@Value("${spring.cloud.nacos.config.password:#{null}}")
public void setPassword(String password) {
this.password = password;
}
public String getDataType() {
return dataType;
}
public String getServerAddr() {
return serverAddr;
}
public String getNamespace() {
return namespace;
}
public String getDataId() { | return dataId;
}
public String getRouteGroup() {
return routeGroup;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\config\GatewayRoutersConfig.java | 2 |
请完成以下Java代码 | private final ITrxItemProcessorContext createProcessorContext()
{
if (_processorCtx != null)
{
return _processorCtx;
}
final Properties ctx = _ctx != null ? _ctx : Env.getCtx();
final ITrx trx = trxManager.getTrx(_trxName);
final ITrxItemProcessorContext processorCtx = executorService.createProcessorContext(ctx, trx);
return processorCtx;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx)
{
setContext(ctx, ITrx.TRXNAME_None);
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx, final String trxName)
{
this._processorCtx = null;
this._ctx = ctx;
this._trxName = trxName;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setContext(final ITrxItemProcessorContext processorCtx)
{
this._processorCtx = processorCtx;
this._ctx = null;
this._trxName = null;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setProcessor(final ITrxItemProcessor<IT, RT> processor)
{
this._processor = processor;
return this;
}
private final ITrxItemProcessor<IT, RT> getProcessor()
{
Check.assumeNotNull(_processor, "processor is set");
return _processor;
}
@Override
public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler)
{
this._exceptionHandler = exceptionHandler;
return this;
} | private final ITrxItemExceptionHandler getExceptionHandler()
{
return _exceptionHandler;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy)
{
this._onItemErrorPolicy = onItemErrorPolicy;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch)
{
if (itemsPerBatch == Integer.MAX_VALUE)
{
this.itemsPerBatch = null;
}
else
{
this.itemsPerBatch = itemsPerBatch;
}
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints)
{
this._useTrxSavepoints = useTrxSavepoints;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java | 1 |
请完成以下Java代码 | public void warnFilteringDuplicatesEnabledWithNullDeploymentName() {
logWarn("047", "Deployment name set to null. Filtering duplicates will not work properly.");
}
public void warnReservedErrorCode(int initialCode) {
logWarn("048", "With error code {} you are using a reserved error code. Falling back to default error code 0. "
+ "If you want to override built-in error codes, please disable the built-in error code provider.", initialCode);
}
public void warnResetToBuiltinCode(Integer builtinCode, int initialCode) {
logWarn("049", "You are trying to override the built-in code {} with {}. "
+ "Falling back to built-in code. If you want to override built-in error codes, "
+ "please disable the built-in error code provider.", builtinCode, initialCode);
}
public ProcessEngineException exceptionSettingJobRetriesAsyncNoJobsSpecified() {
return new ProcessEngineException(exceptionMessage(
"050",
"You must specify at least one of jobIds or jobQuery."));
}
public ProcessEngineException exceptionSettingJobRetriesAsyncNoProcessesSpecified() {
return new ProcessEngineException(exceptionMessage(
"051",
"You must specify at least one of or one of processInstanceIds, processInstanceQuery, or historicProcessInstanceQuery."));
}
public ProcessEngineException exceptionSettingJobRetriesJobsNotSpecifiedCorrectly() {
return new ProcessEngineException(exceptionMessage(
"052",
"You must specify exactly one of jobId, jobIds or jobDefinitionId as parameter. The parameter can not be null."));
}
public ProcessEngineException exceptionNoJobFoundForId(String jobId) { | return new ProcessEngineException(exceptionMessage(
"053",
"No job found with id '{}'.'", jobId));
}
public ProcessEngineException exceptionJobRetriesMustNotBeNegative(Integer retries) {
return new ProcessEngineException(exceptionMessage(
"054",
"The number of job retries must be a non-negative Integer, but '{}' has been provided.", retries));
}
public ProcessEngineException exceptionWhileRetrievingDiagnosticsDataRegistryNull() {
return new ProcessEngineException(
exceptionMessage("055", "Error while retrieving diagnostics data. Diagnostics registry was not initialized."));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CommandLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String index() {
return "index.html";
}
/**
* POST /uploadFile -> receive and locally save a file.
*
* @param uploadfile The uploaded file as Multipart file parameter in the
* HTTP request. The RequestParam name must be the same of the attribute
* "name" in the input tag with type file.
*
* @return An http OK status in case of success, an http 4xx status in case
* of errors.
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("uploadfile") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path
String filename = uploadfile.getOriginalFilename(); | String directory = env.getProperty("netgloo.paths.uploadedFiles");
String filepath = Paths.get(directory, filename).toString();
// Save the file locally
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(uploadfile.getBytes());
stream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile
} // class MainController | repos\spring-boot-samples-master\spring-boot-file-upload-with-ajax\src\main\java\netgloo\controllers\MainController.java | 2 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product dispense = (Product) o;
return Objects.equals(id, dispense.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductName() {
return productName;
} | public void setProductName(String productName) {
this.productName = productName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public CustomerOrder getCustomerOrder() {
return customerOrder;
}
public void setCustomerOrder(CustomerOrder co) {
this.customerOrder = co;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="customerorder_id", nullable = false)
private CustomerOrder customerOrder;
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Product.java | 1 |
请完成以下Java代码 | public void collectHeaderPropertiesChanged(@NonNull final IView view)
{
viewChanges(view).setHeaderPropertiesChanged();
autoflushIfEnabled();
}
public void collectHeaderPropertiesChanged(@NonNull final ViewId viewId)
{
viewChanges(viewId).setHeaderPropertiesChanged();
autoflushIfEnabled();
}
private void collectFromChanges(@NonNull final ViewChanges changes)
{
viewChanges(changes.getViewId()).collectFrom(changes);
autoflushIfEnabled();
}
@Nullable
private ViewChangesCollector getParentOrNull()
{
final ViewChangesCollector threadLocalCollector = getCurrentOrNull();
if (threadLocalCollector != null && threadLocalCollector != this)
{
return threadLocalCollector;
}
return null;
}
void flush()
{
final ImmutableList<ViewChanges> changesList = getAndClean();
if (changesList.isEmpty())
{
return;
}
//
// Try flushing to parent collector if any
final ViewChangesCollector parentCollector = getParentOrNull();
if (parentCollector != null)
{
logger.trace("Flushing {} to parent collector: {}", this, parentCollector);
changesList.forEach(parentCollector::collectFromChanges);
}
//
// Fallback: flush to websocket
else
{
logger.trace("Flushing {} to websocket", this);
final ImmutableList<JSONViewChanges> jsonChangeEvents = changesList.stream()
.filter(ViewChanges::hasChanges)
.map(JSONViewChanges::of)
.collect(ImmutableList.toImmutableList());
sendToWebsocket(jsonChangeEvents);
}
}
private void autoflushIfEnabled()
{
if (!autoflush)
{
return;
}
flush();
}
private ImmutableList<ViewChanges> getAndClean() | {
if (viewChangesMap.isEmpty())
{
return ImmutableList.of();
}
final ImmutableList<ViewChanges> changesList = ImmutableList.copyOf(viewChangesMap.values());
viewChangesMap.clear();
return changesList;
}
private void sendToWebsocket(@NonNull final List<JSONViewChanges> jsonChangeEvents)
{
if (jsonChangeEvents.isEmpty())
{
return;
}
WebsocketSender websocketSender = _websocketSender;
if (websocketSender == null)
{
websocketSender = this._websocketSender = SpringContextHolder.instance.getBean(WebsocketSender.class);
}
try
{
websocketSender.convertAndSend(jsonChangeEvents);
logger.debug("Sent to websocket: {}", jsonChangeEvents);
}
catch (final Exception ex)
{
logger.warn("Failed sending to websocket {}: {}", jsonChangeEvents, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChangesCollector.java | 1 |
请完成以下Java代码 | public boolean hasElementLines()
{
return !elementLines.isEmpty();
}
public static final class Builder
{
private static final Logger logger = LogManager.getLogger(DocumentLayoutElementGroupDescriptor.Builder.class);
private String internalName;
private LayoutType layoutType;
public Integer columnCount = null;
private final List<DocumentLayoutElementLineDescriptor.Builder> elementLinesBuilders = new ArrayList<>();
private Builder()
{
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("layoutType", layoutType)
.add("elementsLines-count", elementLinesBuilders.size())
.toString();
}
public DocumentLayoutElementGroupDescriptor build()
{
final DocumentLayoutElementGroupDescriptor result = new DocumentLayoutElementGroupDescriptor(this);
logger.trace("Built {} for {}", result, this);
return result;
}
private List<DocumentLayoutElementLineDescriptor> buildElementLines()
{
return elementLinesBuilders
.stream()
.map(elementLinesBuilder -> elementLinesBuilder.build())
.collect(GuavaCollectors.toImmutableList());
}
public Builder setInternalName(final String internalName)
{
this.internalName = internalName;
return this;
}
public Builder setLayoutType(final LayoutType layoutType)
{ | this.layoutType = layoutType;
return this;
}
public Builder setLayoutType(final String layoutTypeStr)
{
layoutType = LayoutType.fromNullable(layoutTypeStr);
return this;
}
public Builder setColumnCount(final int columnCount)
{
this.columnCount = CoalesceUtil.firstGreaterThanZero(columnCount, 1);
return this;
}
public Builder addElementLine(@NonNull final DocumentLayoutElementLineDescriptor.Builder elementLineBuilder)
{
elementLinesBuilders.add(elementLineBuilder);
return this;
}
public Builder addElementLines(@NonNull final List<DocumentLayoutElementLineDescriptor.Builder> elementLineBuilders)
{
elementLinesBuilders.addAll(elementLineBuilders);
return this;
}
public boolean hasElementLines()
{
return !elementLinesBuilders.isEmpty();
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementLinesBuilders.stream().flatMap(DocumentLayoutElementLineDescriptor.Builder::streamElementBuilders);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementGroupDescriptor.java | 1 |
请完成以下Java代码 | private void processSchedule(final DDOrderMoveSchedule schedule)
{
schedule.assertInTransit();
//
// generate movement InTransit -> DropTo Locator
final LocatorId dropToLocatorId = this.dropToLocatorId != null ? this.dropToLocatorId : schedule.getDropToLocatorId();
final MovementId dropToMovementId = createDropToMovement(schedule, dropToLocatorId);
//
// update the schedule
schedule.markAsDroppedTo(dropToLocatorId, dropToMovementId);
}
private MovementId createDropToMovement(@NonNull final DDOrderMoveSchedule schedule, @NonNull final LocatorId dropToLocatorId)
{
final I_DD_Order ddOrder = ddOrderLowLevelDAO.getById(schedule.getDdOrderId());
final HUMovementGenerateRequest request = DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId())
.movementDate(movementDate)
.fromLocatorId(schedule.getInTransitLocatorId().orElseThrow()) | .toLocatorId(dropToLocatorId)
.huIdsToMove(schedule.getPickedHUIds())
.build();
final HUMovementGeneratorResult result = new HUMovementGenerator(request).createMovement();
final PPOrderId forwardPPOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID());
if (forwardPPOrderId != null)
{
reserveHUsForManufacturing(forwardPPOrderId, result);
}
return result.getSingleMovementLineId().getMovementId();
}
private void reserveHUsForManufacturing(@NonNull final PPOrderId ppOrderId, @NonNull final HUMovementGeneratorResult result)
{
ppOrderSourceHUService.addSourceHUs(ppOrderId, result.getMovedHUIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\drop_to\DDOrderDropToCommand.java | 1 |
请完成以下Java代码 | public ScalesGetWeightHandler<C> setCmd(final C cmd)
{
this.cmd = cmd;
return this;
}
public ScalesGetWeightHandler<C> setWeightFieldName(final String fieldName)
{
this.weightFieldName = fieldName;
return this;
}
public ScalesGetWeightHandler<C> setUOMFieldName(final String fieldName)
{
this.uomFieldName = fieldName;
return this;
}
/**
* The weighing result number will be round to the given precision using {@link RoundingMode#HALF_UP}.<br>
* If called with a value less than zero, or not called at all, then no rounding will be done.
*
* @param roundWeightToPrecision | * @task http://dewiki908/mediawiki/index.php/09207_Wiegen_nur_eine_Nachkommastelle_%28101684670982%29
*/
public ScalesGetWeightHandler<C> setroundWeightToPrecision(final int roundWeightToPrecision)
{
this.roundWeightToPrecision = roundWeightToPrecision;
return this;
}
@Override
public String toString()
{
return String.format(
"ScalesGetWeightHandler [endpoint=%s, parser=%s, cmd=%s, weightFieldName=%s, uomFieldName=%s, weightRoundToPrecision=%s]",
endpoint, parser, cmd, weightFieldName, uomFieldName, roundWeightToPrecision);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\ScalesGetWeightHandler.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public int getSuspensionState() {
return suspensionState;
} | public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
public Integer getInstances() {
return instances;
}
public void setInstances(Integer instances) {
this.instances = instances;
}
public Integer getIncidents() {
return incidents;
}
public void setIncidents(Integer incidents) {
this.incidents = incidents;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessDefinitionStatisticsDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | PromptTemplate promptTemplate(
@Value("classpath:prompt-template.st") Resource promptTemplate
) throws IOException {
String template = promptTemplate.getContentAsString(StandardCharsets.UTF_8);
return PromptTemplate
.builder()
.renderer(StTemplateRenderer
.builder()
.startDelimiterToken('<')
.endDelimiterToken('>')
.build())
.template(template)
.build();
}
@Bean
ChatClient chatClient(
ChatModel chatModel,
VectorStore vectorStore,
PromptTemplate promptTemplate | ) {
return ChatClient
.builder(chatModel)
.defaultAdvisors(
QuestionAnswerAdvisor
.builder(vectorStore)
.promptTemplate(promptTemplate)
.searchRequest(SearchRequest
.builder()
.topK(MAX_RESULTS)
.build())
.build()
)
.build();
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-vector-stores\spring-ai-oracle\src\main\java\com\baeldung\springai\vectorstore\oracle\RAGChatbotConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class StatisticsServiceImpl implements StatisticsService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private DataPointRepository repository;
@Autowired
private ExchangeRatesService ratesService;
/**
* {@inheritDoc}
*/
@Override
public List<DataPoint> findByAccountName(String accountName) {
Assert.hasLength(accountName);
return repository.findByIdAccount(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public DataPoint save(String accountName, Account account) {
Instant instant = LocalDate.now().atStartOfDay()
.atZone(ZoneId.systemDefault()).toInstant();
DataPointId pointId = new DataPointId(accountName, Date.from(instant));
Set<ItemMetric> incomes = account.getIncomes().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Set<ItemMetric> expenses = account.getExpenses().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Map<StatisticMetric, BigDecimal> statistics = createStatisticMetrics(incomes, expenses, account.getSaving());
DataPoint dataPoint = new DataPoint();
dataPoint.setId(pointId);
dataPoint.setIncomes(incomes); | dataPoint.setExpenses(expenses);
dataPoint.setStatistics(statistics);
dataPoint.setRates(ratesService.getCurrentRates());
log.debug("new datapoint has been created: {}", pointId);
return repository.save(dataPoint);
}
private Map<StatisticMetric, BigDecimal> createStatisticMetrics(Set<ItemMetric> incomes, Set<ItemMetric> expenses, Saving saving) {
BigDecimal savingAmount = ratesService.convert(saving.getCurrency(), Currency.getBase(), saving.getAmount());
BigDecimal expensesAmount = expenses.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal incomesAmount = incomes.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return ImmutableMap.of(
StatisticMetric.EXPENSES_AMOUNT, expensesAmount,
StatisticMetric.INCOMES_AMOUNT, incomesAmount,
StatisticMetric.SAVING_AMOUNT, savingAmount
);
}
/**
* Normalizes given item amount to {@link Currency#getBase()} currency with
* {@link TimePeriod#getBase()} time period
*/
private ItemMetric createItemMetric(Item item) {
BigDecimal amount = ratesService
.convert(item.getCurrency(), Currency.getBase(), item.getAmount())
.divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP);
return new ItemMetric(item.getTitle(), amount);
}
} | repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\service\StatisticsServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class cartProductDao {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
@Transactional
public CartProduct addCartProduct(CartProduct cartProduct) {
this.sessionFactory.getCurrentSession().save(cartProduct);
return cartProduct;
}
@Transactional
public List<CartProduct> getCartProducts() {
return this.sessionFactory.getCurrentSession().createQuery("from CART_PRODUCT ").list();
}
@Transactional
public List<Product> getProductByCartID(Integer cart_id) {
String sql = "SELECT product_id FROM cart_product WHERE cart_id = :cart_id";
List<Integer> productIds = this.sessionFactory.getCurrentSession()
.createNativeQuery(sql) | .setParameter("cart_id", cart_id)
.list();
sql = "SELECT * FROM product WHERE id IN (:product_ids)";
return this.sessionFactory.getCurrentSession()
.createNativeQuery(sql, Product.class)
.setParameterList("product_ids", productIds)
.list();
}
@Transactional
public void updateCartProduct(CartProduct cartProduct) {
this.sessionFactory.getCurrentSession().update(cartProduct);
}
@Transactional
public void deleteCartProduct(CartProduct cartProduct) {
this.sessionFactory.getCurrentSession().delete(cartProduct);
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\dao\cartProductDao.java | 2 |
请完成以下Java代码 | protected boolean checkElements () {
X_CM_Template thisTemplate = new X_CM_Template(getCtx(), this.getCM_Template_ID(), get_TrxName());
StringBuffer thisElementList = new StringBuffer(thisTemplate.getElements());
while (thisElementList.indexOf("\n")>=0) {
String thisElement = thisElementList.substring(0,thisElementList.indexOf("\n"));
thisElementList.delete(0,thisElementList.indexOf("\n")+1);
checkElement(thisElement);
}
String thisElement = thisElementList.toString();
checkElement(thisElement);
return true;
}
/**
* Check single Element, if not existing create it...
* @param elementName
*/
protected void checkElement(String elementName) {
int [] tableKeys = X_CM_CStage_Element.getAllIDs("CM_CStage_Element", "CM_CStage_ID=" + this.get_ID() + " AND Name like '" + elementName + "'", get_TrxName());
if (tableKeys==null || tableKeys.length==0) {
X_CM_CStage_Element thisElement = new X_CM_CStage_Element(getCtx(), 0, get_TrxName());
thisElement.setAD_Client_ID(getAD_Client_ID());
thisElement.setAD_Org_ID(getAD_Org_ID());
thisElement.setCM_CStage_ID(this.get_ID());
thisElement.setContentHTML(" ");
thisElement.setName(elementName);
thisElement.save(get_TrxName());
}
}
/**
* Check whether all Template Table records exits
* @return true if updated
*/
protected boolean checkTemplateTable () {
int [] tableKeys = X_CM_TemplateTable.getAllIDs("CM_TemplateTable", "CM_Template_ID=" + this.getCM_Template_ID(), get_TrxName());
if (tableKeys!=null) {
for (int i=0;i<tableKeys.length;i++) {
X_CM_TemplateTable thisTemplateTable = new X_CM_TemplateTable(getCtx(), tableKeys[i], get_TrxName()); | int [] existingKeys = X_CM_CStageTTable.getAllIDs("CM_CStageTTable", "CM_TemplateTable_ID=" + thisTemplateTable.get_ID(), get_TrxName());
if (existingKeys==null || existingKeys.length==0) {
X_CM_CStageTTable newCStageTTable = new X_CM_CStageTTable(getCtx(), 0, get_TrxName());
newCStageTTable.setAD_Client_ID(getAD_Client_ID());
newCStageTTable.setAD_Org_ID(getAD_Org_ID());
newCStageTTable.setCM_CStage_ID(get_ID());
newCStageTTable.setCM_TemplateTable_ID(thisTemplateTable.get_ID());
newCStageTTable.setDescription(thisTemplateTable.getDescription());
newCStageTTable.setName(thisTemplateTable.getName());
newCStageTTable.setOtherClause(thisTemplateTable.getOtherClause());
newCStageTTable.setWhereClause(thisTemplateTable.getWhereClause());
newCStageTTable.save();
}
}
}
return true;
}
} // MCStage | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MCStage.java | 1 |
请完成以下Java代码 | public void setDateLastAlert (final java.sql.Timestamp DateLastAlert)
{
set_Value (COLUMNNAME_DateLastAlert, DateLastAlert);
}
@Override
public java.sql.Timestamp getDateLastAlert()
{
return get_ValueAsTimestamp(COLUMNNAME_DateLastAlert);
}
@Override
public void setDynPriorityStart (final int DynPriorityStart)
{
set_Value (COLUMNNAME_DynPriorityStart, DynPriorityStart);
}
@Override
public int getDynPriorityStart()
{
return get_ValueAsInt(COLUMNNAME_DynPriorityStart);
}
@Override
public void setEndWaitTime (final java.sql.Timestamp EndWaitTime)
{
set_Value (COLUMNNAME_EndWaitTime, EndWaitTime);
}
@Override
public java.sql.Timestamp getEndWaitTime()
{
return get_ValueAsTimestamp(COLUMNNAME_EndWaitTime);
}
@Override
public void setPriority (final int Priority)
{
set_Value (COLUMNNAME_Priority, Priority);
}
@Override
public int getPriority()
{
return get_ValueAsInt(COLUMNNAME_Priority);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID); | }
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTextMsg (final java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
@Override
public java.lang.String getTextMsg()
{
return get_ValueAsString(COLUMNNAME_TextMsg);
}
/**
* 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_Activity.java | 1 |
请完成以下Java代码 | protected void createSnapshotsByParentIds(final Set<Integer> huIds)
{
Check.assumeNotEmpty(huIds, "huIds not empty");
query(I_M_HU_Attribute.class)
.addInArrayOrAllFilter(I_M_HU_Attribute.COLUMN_M_HU_ID, huIds)
.create()
.insertDirectlyInto(I_M_HU_Attribute_Snapshot.class)
.mapCommonColumns()
.mapColumnToConstant(I_M_HU_Attribute_Snapshot.COLUMNNAME_Snapshot_UUID, getSnapshotId())
.execute();
}
@Override
protected int getModelId(final I_M_HU_Attribute_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_Attribute_ID();
}
@Override
protected I_M_HU_Attribute getModel(I_M_HU_Attribute_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_Attribute();
}
@Override
protected Map<Integer, I_M_HU_Attribute_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU hu)
{
return query(I_M_HU_Attribute_Snapshot.class)
.addEqualsFilter(I_M_HU_Attribute_Snapshot.COLUMN_M_HU_ID, hu.getM_HU_ID())
.addEqualsFilter(I_M_HU_Attribute_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create() | .map(I_M_HU_Attribute_Snapshot.class, snapshot2ModelIdFunction);
}
@Override
protected Map<Integer, I_M_HU_Attribute> retrieveModelsByParent(final I_M_HU hu)
{
return query(I_M_HU_Attribute.class)
.addEqualsFilter(I_M_HU_Attribute.COLUMN_M_HU_ID, hu.getM_HU_ID())
.create()
.mapById(I_M_HU_Attribute.class);
}
@Override
protected I_M_HU_Attribute_Snapshot retrieveModelSnapshot(final I_M_HU_Attribute model)
{
throw new UnsupportedOperationException();
}
@Override
protected void restoreModelWhenSnapshotIsMissing(final I_M_HU_Attribute model)
{
// shall not happen because we never delete an attribute
throw new HUException("Cannot restore " + model + " because snapshot is missing");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Attribute_SnapshotHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected String getMybatisCfgPath() {
return DmnEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE;
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
if (dmnEngineConfiguration == null) {
dmnEngineConfiguration = new StandaloneInMemDmnEngineConfiguration();
}
initialiseCommonProperties(engineConfiguration, dmnEngineConfiguration);
initEngine();
initServiceConfigurations(engineConfiguration, dmnEngineConfiguration);
}
@Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
}
@Override | protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
}
@Override
protected DmnEngine buildEngine() {
if (dmnEngineConfiguration == null) {
throw new FlowableException("DmnEngineConfiguration is required");
}
return dmnEngineConfiguration.buildDmnEngine();
}
public DmnEngineConfiguration getDmnEngineConfiguration() {
return dmnEngineConfiguration;
}
public DmnEngineConfigurator setDmnEngineConfiguration(DmnEngineConfiguration dmnEngineConfiguration) {
this.dmnEngineConfiguration = dmnEngineConfiguration;
return this;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine-configurator\src\main\java\org\flowable\dmn\engine\configurator\DmnEngineConfigurator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static void setUrlDecodingCharset(Charset charset) {
urlDecodingCharset = charset;
}
/**
* Set the supplier for providing {@link ClassLoader} to used.
* <p>
* Default is a returned instance from {@link ClassUtils#getDefaultClassLoader()}.
* </p>
*
* @param supplier
* the supplier for providing {@link ClassLoader} to used
*
* @since 3.0.2
*/
public static void setClassLoaderSupplier(Supplier<ClassLoader> supplier) {
classLoaderSupplier = supplier; | }
private static String preserveSubpackageName(final String baseUrlString, final Resource resource,
final String rootPath) {
try {
return rootPath + (rootPath.endsWith("/") ? "" : "/")
+ Normalizer
.normalize(URLDecoder.decode(resource.getURL().toString(), urlDecodingCharset), Normalizer.Form.NFC)
.substring(baseUrlString.length());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
} | repos\spring-boot-starter-master\mybatis-spring-boot-autoconfigure\src\main\java\org\mybatis\spring\boot\autoconfigure\SpringBootVFS.java | 2 |
请完成以下Java代码 | public int getOrder() {
return ROUTE_TO_URL_FILTER_ORDER;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
if (route == null) {
return chain.filter(exchange);
}
log.trace("RouteToRequestUrlFilter start");
URI uri = exchange.getRequest().getURI();
boolean encoded = containsEncodedParts(uri);
URI routeUri = route.getUri();
if (hasAnotherScheme(routeUri)) {
// this is a special url, save scheme to special attribute
// replace routeUri with schemeSpecificPart
exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, routeUri.getScheme());
routeUri = URI.create(routeUri.getSchemeSpecificPart());
} | if ("lb".equalsIgnoreCase(routeUri.getScheme()) && routeUri.getHost() == null) {
// Load balanced URIs should always have a host. If the host is null it is
// most likely because the host name was invalid (for example included an
// underscore)
throw new IllegalStateException("Invalid host: " + routeUri.toString());
}
URI mergedUrl = UriComponentsBuilder.fromUri(uri)
// .uri(routeUri)
.scheme(routeUri.getScheme())
.host(routeUri.getHost())
.port(routeUri.getPort())
.build(encoded)
.toUri();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, mergedUrl);
return chain.filter(exchange);
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\RouteToRequestUrlFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringbootHibernateManyToManyMappingApplication implements CommandLineRunner{
@Autowired
private PostRepository postRepository;
public static void main(String[] args) {
SpringApplication.run(SpringbootHibernateManyToManyMappingApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Post post = new Post("Hibernate Many to Many Mapping Example with Spring Boot",
"Hibernate Many to Many Mapping Example with Spring Boot",
"Hibernate Many to Many Mapping Example with Spring Boot");
Post post1 = new Post("Hibernate One to Many Mapping Example with Spring Boot",
"Hibernate One to Many Mapping Example with Spring Boot",
"Hibernate One to Many Mapping Example with Spring Boot");
Tag springBoot = new Tag("Spring Boot");
Tag hibernate = new Tag("Hibernate"); | // add tag references post
post.getTags().add(springBoot);
post.getTags().add(hibernate);
// add post references tag
springBoot.getPosts().add(post);
hibernate.getPosts().add(post);
springBoot.getPosts().add(post1);
post1.getTags().add(springBoot);
this.postRepository.save(post);
this.postRepository.save(post1);
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-many-to-many-mapping\src\main\java\net\alanbinu\springboot\SpringbootHibernateManyToManyMappingApplication.java | 2 |
请完成以下Java代码 | public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String address) {
this.author = address;
} | public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\java\com\baeldung\spring\data\jpa\optionalfields\Book.java | 1 |
请完成以下Java代码 | class ArticleWithAuthorDAO {
private static final String QUERY_TEMPLATE = "SELECT ARTICLE.TITLE, AUTHOR.LAST_NAME, AUTHOR.FIRST_NAME FROM ARTICLE %s AUTHOR ON AUTHOR.id=ARTICLE.AUTHOR_ID";
private final Connection connection;
ArticleWithAuthorDAO(Connection connection) {
this.connection = connection;
}
List<ArticleWithAuthor> articleInnerJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "INNER JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleLeftJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "LEFT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleRightJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "RIGHT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleFullJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "FULL JOIN");
return executeQuery(query);
}
private List<ArticleWithAuthor> executeQuery(String query) {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(query);
return mapToList(resultSet);
} catch (SQLException e) {
e.printStackTrace();
} | return null;
}
private List<ArticleWithAuthor> mapToList(ResultSet resultSet) throws SQLException {
List<ArticleWithAuthor> list = new ArrayList<>();
while (resultSet.next()) {
ArticleWithAuthor articleWithAuthor = new ArticleWithAuthor(
resultSet.getString("TITLE"),
resultSet.getString("FIRST_NAME"),
resultSet.getString("LAST_NAME")
);
list.add(articleWithAuthor);
}
return list;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\joins\ArticleWithAuthorDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final static String RESPONSE
= "We check your review and get back to you with an e-mail ASAP :)";
private final BookRepository bookRepository;
private final BookReviewRepository bookReviewRepository;
public BookstoreService(BookReviewRepository bookReviewRepository, BookRepository bookRepository) {
this.bookReviewRepository = bookReviewRepository;
this.bookRepository = bookRepository;
}
public void insertBook() {
Book book = new Book();
book.setAuthor("Mark Janel");
book.setIsbn("001-LD");
book.setTitle("Lucky Day");
book.setId(1L);
bookRepository.save(book); | }
@Transactional
public String postReview(BookReview bookReview) {
Book book = bookRepository.getOne(1L);
bookReview.setBook(book);
bookReview.registerReviewEvent();
bookReviewRepository.save(bookReview);
return RESPONSE;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public Object getPrincipal() {
return this.clientPrincipal;
}
@Override
public Object getCredentials() {
return "";
}
/**
* Returns the {@link RegisteredClient registered client}.
* @return the {@link RegisteredClient}
*/
public RegisteredClient getRegisteredClient() {
return this.registeredClient;
}
/**
* Returns the {@link OAuth2AccessToken access token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/** | * Returns the {@link OAuth2RefreshToken refresh token}.
* @return the {@link OAuth2RefreshToken} or {@code null} if not available
*/
@Nullable
public OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the additional parameters.
* @return a {@code Map} of the additional parameters, may be empty
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AccessTokenAuthenticationToken.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String delete(long id) {
try {
User user = new User(id);
userDao.delete(user);
}
catch (Exception ex) {
return "Error deleting the user: " + ex.toString();
}
return "User successfully deleted!";
}
/**
* /get-by-email --> Return the id for the user having the passed email.
*
* @param email The email to search in the database.
* @return The user id or a message error if the user is not found.
*/
@RequestMapping("/get-by-email")
@ResponseBody
public String getByEmail(String email) {
String userId;
try {
User user = userDao.findByEmail(email);
userId = String.valueOf(user.getId());
}
catch (Exception ex) {
return "User not found";
}
return "The user id is: " + userId;
}
/**
* /update --> Update the email and the name for the user in the database
* having the passed id.
* | * @param id The id for the user to update.
* @param email The new email.
* @param name The new name.
* @return A string describing if the user is successfully updated or not.
*/
@RequestMapping("/update")
@ResponseBody
public String updateUser(long id, String email, String name) {
try {
User user = userDao.findOne(id);
user.setEmail(email);
user.setName(name);
userDao.save(user);
}
catch (Exception ex) {
return "Error updating the user: " + ex.toString();
}
return "User successfully updated!";
}
// ------------------------
// PRIVATE FIELDS
// ------------------------
@Autowired
private UserDao userDao;
} // class UserController | repos\spring-boot-samples-master\spring-boot-mysql-springdatajpa-hibernate\src\main\java\netgloo\controllers\UserController.java | 2 |
请完成以下Java代码 | public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year; | }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Car car = (Car) o;
return year == car.year && Objects.equals(id, car.id) && Objects.equals(make, car.make) && Objects.equals(model, car.model);
}
@Override
public int hashCode() {
return Objects.hash(id, make, model, year);
}
} | repos\tutorials-master\persistence-modules\spring-data-cassandra-2\src\main\java\org\baeldung\springcassandra\model\Car.java | 1 |
请完成以下Java代码 | public void removeFile(String bucketName, String objectName) {
minioClient.removeObject(
RemoveObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
}
/**
* batch delete file
*
* @param bucketName
* @param keys
* @return
*/
public void removeFiles(String bucketName, List<String> keys) {
List<DeleteObject> objects = new LinkedList<>();
keys.forEach(s -> {
objects.add(new DeleteObject(s));
try {
removeFile(bucketName, s);
} catch (Exception e) {
log.error("[MinioUtil]>>>>batch delete file,Exception:", e);
}
});
}
/**
* get file url
*
* @param bucketName
* @param objectName
* @param expires
* @return url
*/
@SneakyThrows(Exception.class)
public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build(); | return minioClient.getPresignedObjectUrl(args);
}
/**
* get file url
*
* @param bucketName
* @param objectName
* @return url
*/
@SneakyThrows(Exception.class)
public String getPresignedObjectUrl(String bucketName, String objectName) {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.method(Method.GET).build();
return minioClient.getPresignedObjectUrl(args);
}
/**
* change URLDecoder to UTF8
*
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
return URLDecoder.decode(url, "UTF-8");
}
} | repos\springboot-demo-master\minio\src\main\java\demo\et\minio\util\MinioUtils.java | 1 |
请完成以下Java代码 | public class Colors
{
/**
* Get {@link Color} from an html hex color
*
* @param htmlColor html color (e.g. #aa00cc, aa00cc, aa)
* @return null if the given string is empty or can'T be parsed into a color.
*/
public static Color toColor(String htmlColor)
{
if (htmlColor == null || htmlColor.length() == 0)
return null;
String hex = htmlColor;
if (hex.startsWith("#"))
hex = hex.substring(1);
if (hex.length() < 6)
{
StringBuffer sb = new StringBuffer(hex);
while(sb.length() < 6)
sb.append("0");
hex = sb.toString(); | }
final int rgb;
try
{
rgb = Integer.parseInt(hex, 16);
}
catch (NumberFormatException e)
{
return null;
}
return new Color(rgb);
}
public static String toHtmlColor(Color color)
{
return "#" + Integer.toHexString(color.getRGB() | 0xFF000000).substring(2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\Colors.java | 1 |
请完成以下Java代码 | public class OutputStreamExamples {
public void fileOutputStreamByteSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes);
}
}
public void fileOutputStreamByteSubSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes, 6, 5);
}
}
public void fileOutputStreamByteSingle(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) { | out.write(bytes[6]);
}
}
public void bufferedOutputStream(String file, String... data) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
for (String s : data) {
out.write(s.getBytes());
out.write(" ".getBytes());
}
}
}
public void outputStreamWriter(String file, String data) throws IOException {
try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) {
writer.write(data);
}
}
} | repos\tutorials-master\core-java-modules\core-java-io-apis\src\main\java\com\baeldung\outputstream\OutputStreamExamples.java | 1 |
请完成以下Java代码 | public final void onEvent(FlowableEvent event) {
if (isValidEvent(event)) {
// Check if this event
if (event.getType() == FlowableEngineEventType.ENTITY_CREATED) {
onCreate(event);
} else if (event.getType() == FlowableEngineEventType.ENTITY_INITIALIZED) {
onInitialized(event);
} else if (event.getType() == FlowableEngineEventType.ENTITY_DELETED) {
onDelete(event);
} else if (event.getType() == FlowableEngineEventType.ENTITY_UPDATED) {
onUpdate(event);
} else {
// Entity-specific event
onEntityEvent(event);
}
}
}
@Override
public boolean isFailOnException() {
return failOnException;
}
/**
* @return true, if the event is an {@link FlowableEntityEvent} and (if needed) the entityClass set in this instance, is assignable from the entity class in the event.
*/
protected boolean isValidEvent(FlowableEvent event) {
boolean valid = false;
if (event instanceof FlowableEntityEvent) {
if (entityClass == null) {
valid = true;
} else {
valid = entityClass.isAssignableFrom(((FlowableEntityEvent) event).getEntity().getClass());
}
}
return valid;
}
/**
* Called when an entity create event is received.
*/
protected void onCreate(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity initialized event is received.
*/ | protected void onInitialized(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity delete event is received.
*/
protected void onDelete(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity update event is received.
*/
protected void onUpdate(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an event is received, which is not a create, an update or delete.
*/
protected void onEntityEvent(FlowableEvent event) {
// Default implementation is a NO-OP
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\event\BaseEntityEventListener.java | 1 |
请完成以下Java代码 | public Quantity getQty()
{
return Quantity.of(qty, uom);
}
public void setQty(@NonNull final Quantity qty)
{
this.qty = qty.toBigDecimal();
this.uom = qty.getUOM();
}
@Override
public IPricingResult getPrice()
{
return pricingResult;
}
public void setPrice(final IPricingResult price)
{
pricingResult = price;
}
@Override
public boolean isDisplayed()
{
return displayed;
}
public void setDisplayed(final boolean displayed)
{
this.displayed = displayed;
}
@Override
public String getDescription()
{
return description;
} | public void setDescription(final String description)
{
this.description = description;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
@Override
public I_PP_Order getPP_Order()
{
return ppOrder;
}
public void setPP_Order(I_PP_Order ppOrder)
{
this.ppOrder = ppOrder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLine.java | 1 |
请完成以下Java代码 | private Properties getCtx()
{
return Env.getCtx();
}
@Override
public IAskDialogBuilder setParentComponent(final Object parentCompObj)
{
this._parentCompObj = parentCompObj;
return this;
}
@Override
public IAskDialogBuilder setParentWindowNo(final int windowNo)
{
this._parentWindowNo = windowNo;
return this;
}
private Window getParentWindowOrNull()
{
Window parent = null;
if (_parentCompObj instanceof Component)
{
parent = SwingUtils.getParentWindow((Component)_parentCompObj);
}
if (parent == null && Env.isRegularOrMainWindowNo(_parentWindowNo))
{
parent = Env.getWindow(_parentWindowNo);
}
return parent;
}
@Override
public IAskDialogBuilder setAD_Message(final String adMessage, Object ... params)
{
this._adMessage = adMessage;
this._adMessageParams = params;
return this;
}
private String getAD_Message_Translated()
{
if (Check.isEmpty(_adMessage, true))
{
return "";
}
final Properties ctx = getCtx();
if (Check.isEmpty(_adMessageParams))
{
return msgBL.getMsg(ctx, _adMessage);
}
else
{ | return msgBL.getMsg(ctx, _adMessage, _adMessageParams);
}
}
@Override
public IAskDialogBuilder setAdditionalMessage(final String additionalMessage)
{
this._additionalMessage = additionalMessage;
return this;
}
private String getAdditionalMessage()
{
return this._additionalMessage;
}
@Override
public IAskDialogBuilder setDefaultAnswer(final boolean defaultAnswer)
{
this._defaultAnswer = defaultAnswer;
return this;
}
private boolean getDefaultAnswer()
{
return this._defaultAnswer;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingAskDialogBuilder.java | 1 |
请完成以下Java代码 | public int getRecipientCountryId()
{
return get_ValueAsInt(COLUMNNAME_RecipientCountryId);
}
/**
* RecipientType AD_Reference_ID=541372
* Reference name: RecipientTypeList
*/
public static final int RECIPIENTTYPE_AD_Reference_ID=541372;
/** COMPANY = COMPANY */
public static final String RECIPIENTTYPE_COMPANY = "COMPANY";
/** INDIVIDUAL = INDIVIDUAL */
public static final String RECIPIENTTYPE_INDIVIDUAL = "INDIVIDUAL";
@Override
public void setRecipientType (final java.lang.String RecipientType)
{
set_Value (COLUMNNAME_RecipientType, RecipientType);
}
@Override
public java.lang.String getRecipientType()
{
return get_ValueAsString(COLUMNNAME_RecipientType);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{ | set_Value (COLUMNNAME_RegionName, RegionName);
}
@Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setRevolut_Payment_Export_ID (final int Revolut_Payment_Export_ID)
{
if (Revolut_Payment_Export_ID < 1)
set_ValueNoCheck (COLUMNNAME_Revolut_Payment_Export_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Revolut_Payment_Export_ID, Revolut_Payment_Export_ID);
}
@Override
public int getRevolut_Payment_Export_ID()
{
return get_ValueAsInt(COLUMNNAME_Revolut_Payment_Export_ID);
}
@Override
public void setRoutingNo (final @Nullable java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java-gen\de\metas\payment\revolut\model\X_Revolut_Payment_Export.java | 1 |
请完成以下Java代码 | public final class LogUtils {
public static final String EXEC_TIME_KEY = "exec_time";
private LogUtils() {
}
public static void updateExecutionTime(Long execTime) {
MDC.remove(EXEC_TIME_KEY);
MDC.put(EXEC_TIME_KEY, nonNull(execTime) ? execTime.toString() : "NA" );
}
public static void clearExecutionTime() {
MDC.remove(EXEC_TIME_KEY);
}
public static void clearAll() {
MDC.clear(); | }
public static void logHttpTraffic(Logger logger, long startTime, String message, Object... arguments) {
long execTime = (System.nanoTime() - startTime)/1_000_000;
updateExecutionTime(execTime);
logger.info(message, arguments);
clearExecutionTime();
}
public static String getTraceId() {
return MDC.get("traceId");
}
public static String getSpanId() {
return MDC.get("spanId");
}
} | repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\logs\LogUtils.java | 1 |
请完成以下Java代码 | public I_SEPA_Export createSEPAExportFromPaySelection(final I_C_PaySelection from, final boolean isGroupTransactions)
{
return new CreateSEPAExportFromPaySelectionCommand(from, isGroupTransactions)
.run();
}
@Override
public Date getDueDate(final I_SEPA_Export_Line line)
{
// NOTE: for now, return SystemTime + 1
// return TimeUtil.addDays(line.getSEPA_Export().getPaymentDate(), 1);
// ts: unrelated: don'T add another day, because it turn our that it makes the creditors get their money one day after they expected it
final Timestamp paymentDate = line.getSEPA_Export().getPaymentDate();
if (paymentDate == null)
{
return SystemTime.asTimestamp();
}
return paymentDate;
}
@Override
public SEPACreditTransferXML exportCreditTransferXML(@NonNull final I_SEPA_Export sepaExport, @NonNull final SEPAExportContext exportContext)
{
final SEPAProtocol protocol = SEPAProtocol.ofCode(sepaExport.getSEPA_Protocol());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final SEPAMarshaler marshaler = newSEPAMarshaler(protocol, exportContext);
try
{
marshaler.marshal(sepaExport, out);
} | catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
return SEPACreditTransferXML.builder()
.filename(FileUtil.stripIllegalCharacters(sepaExport.getDocumentNo()) + ".xml")
.contentType(MimeType.TYPE_XML)
.content(out.toByteArray())
.build();
}
private SEPAMarshaler newSEPAMarshaler(@NonNull final SEPAProtocol protocol, @NonNull final SEPAExportContext exportContext)
{
if (SEPAProtocol.CREDIT_TRANSFER_PAIN_001_001_03_CH_02.equals(protocol))
{
final BankRepository bankRepository = SpringContextHolder.instance.getBean(BankRepository.class);
return new SEPAVendorCreditTransferMarshaler_Pain_001_001_03_CH_02(bankRepository, exportContext, bankAccountService);
}
else if (SEPAProtocol.DIRECT_DEBIT_PAIN_008_003_02.equals(protocol))
{
return new SEPACustomerDirectDebitMarshaler_Pain_008_003_02(bankAccountService);
}
else
{
throw new AdempiereException("Unknown SEPA protocol: " + protocol);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\SEPADocumentBL.java | 1 |
请完成以下Java代码 | private static class PriceLimit
{
BigDecimal valueAsBigDecimal;
BigDecimal basePrice;
BigDecimal priceAddAmt;
BigDecimal discountPercentToSubtract;
BigDecimal paymentTermDiscountPercentToAdd;
CurrencyPrecision precision;
@lombok.Builder
private PriceLimit(
@lombok.NonNull final BigDecimal basePrice,
@lombok.NonNull final BigDecimal priceAddAmt,
@lombok.NonNull final BigDecimal discountPercentToSubtract,
@lombok.NonNull final BigDecimal paymentTermDiscountPercentToAdd,
@lombok.NonNull final CurrencyPrecision precision)
{
this.basePrice = NumberUtils.stripTrailingDecimalZeros(basePrice);
this.priceAddAmt = NumberUtils.stripTrailingDecimalZeros(priceAddAmt);
this.discountPercentToSubtract = NumberUtils.stripTrailingDecimalZeros(discountPercentToSubtract);
this.paymentTermDiscountPercentToAdd = NumberUtils.stripTrailingDecimalZeros(paymentTermDiscountPercentToAdd);
this.precision = precision;
//
// Formula:
// PriceLimit = (basePrice + priceAddAmt) - discountPercentToSubtract% + paymentTermDiscountPercentToAdd%
BigDecimal value = basePrice.add(priceAddAmt);
final BigDecimal multiplier = Env.ONEHUNDRED.subtract(discountPercentToSubtract).add(paymentTermDiscountPercentToAdd)
.divide(Env.ONEHUNDRED, 12, RoundingMode.HALF_UP);
if (multiplier.compareTo(Env.ONEHUNDRED) != 0)
{ | value = precision.round(value.multiply(multiplier));
}
valueAsBigDecimal = value;
}
public ITranslatableString toFormulaString()
{
return TranslatableStrings.builder()
.append("(").append(basePrice, DisplayType.CostPrice).append(" + ").append(priceAddAmt, DisplayType.CostPrice).append(")")
.append(" - ").append(discountPercentToSubtract, DisplayType.Number).append("%")
.append(" + ").append(paymentTermDiscountPercentToAdd, DisplayType.Number).append("%")
.append(" (precision: ").append(precision.toInt()).append(")")
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\pricing\PharmaPriceLimitRuleInstance.java | 1 |
请完成以下Java代码 | public class Handler extends URLStreamHandler {
// NOTE: in order to be found as a URL protocol handler, this class must be public,
// must be named Handler and must be in a package ending '.nested'
private static final String PREFIX = "nested:";
@Override
protected InetAddress getHostAddress(URL url) {
// Some Windows users have reported that calls to java.net.URL.getHostAddress()
// can be slow. Since we only deal with local files we always return null here.
return null;
}
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new NestedUrlConnection(url);
}
/** | * Assert that the specified URL is a valid "nested" URL.
* @param url the URL to check
*/
public static void assertUrlIsNotMalformed(String url) {
if (url == null || !url.startsWith(PREFIX)) {
throw new IllegalArgumentException("'url' must not be null and must use 'nested' protocol");
}
NestedLocation.parse(url.substring(PREFIX.length()));
}
/**
* Clear any internal caches.
*/
public static void clearCache() {
NestedLocation.clearCache();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\Handler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<String> isAuthenticated(ServerWebExchange request) {
log.debug("REST request to check if the current user is authenticated");
return request.getPrincipal().map(Principal::getName);
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" "));
Instant now = Instant.now();
Instant validity;
if (rememberMe) {
validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS);
} else {
validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS);
}
// @formatter:off
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(validity)
.subject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken { | private String idToken;
JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\rest\AuthenticateController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private boolean isExcludedPath(String path) {
// 使用缓存避免重复计算
return EXCLUDED_PATHS_CACHE.computeIfAbsent(path, p -> {
// 精确匹配
if (exactPatterns.contains(p)) {
return true;
}
// 通配符匹配
return wildcardPatterns.stream().anyMatch(p::startsWith);
});
}
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI() | .info(new Info()
.title("JeecgBoot 后台服务API接口文档")
.version("3.9.0")
.contact(new Contact().name("北京国炬信息技术有限公司").url("www.jeccg.com").email("jeecgos@163.com"))
.description("后台API接口")
.termsOfService("NO terms of service")
.license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.html")))
.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN))
.components(new Components().addSecuritySchemes(CommonConstant.X_ACCESS_TOKEN,
new SecurityScheme()
.name(CommonConstant.X_ACCESS_TOKEN)
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER) // 关键:指定为 header
));
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\Swagger3Config.java | 2 |
请完成以下Java代码 | public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
return this.delegate.schedule(wrap(task), startTime);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
return this.delegate.scheduleAtFixedRate(wrap(task), startTime, period);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
return this.delegate.scheduleAtFixedRate(wrap(task), period);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
return this.delegate.scheduleWithFixedDelay(wrap(task), startTime, delay);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
return this.delegate.scheduleWithFixedDelay(wrap(task), delay);
}
@Override
public ScheduledFuture<?> schedule(Runnable task, Instant startTime) {
return this.delegate.schedule(wrap(task), startTime);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period) {
return this.delegate.scheduleAtFixedRate(wrap(task), startTime, period);
} | @Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period) {
return this.delegate.scheduleAtFixedRate(wrap(task), period);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay) {
return this.delegate.scheduleWithFixedDelay(wrap(task), startTime, delay);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay) {
return this.delegate.scheduleWithFixedDelay(wrap(task), delay);
}
@Override
public Clock getClock() {
return this.delegate.getClock();
}
private Runnable wrap(Runnable delegate) {
return DelegatingSecurityContextRunnable.create(delegate, this.securityContext);
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\scheduling\DelegatingSecurityContextTaskScheduler.java | 1 |
请完成以下Java代码 | public void setType(Integer type) {
this.type = type;
}
@CamundaQueryParam(value="userIdIn", converter = StringArrayConverter.class)
public void setUserIdIn(String[] userIdIn) {
this.userIdIn = userIdIn;
}
@CamundaQueryParam(value="groupIdIn", converter = StringArrayConverter.class)
public void setGroupIdIn(String[] groupIdIn) {
this.groupIdIn = groupIdIn;
}
@CamundaQueryParam(value="resourceType", converter = IntegerConverter.class)
public void setResourceType(int resourceType) {
this.resourceType = resourceType;
}
@CamundaQueryParam("resourceId")
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
protected AuthorizationQuery createNewQuery(ProcessEngine engine) {
return engine.getAuthorizationService().createAuthorizationQuery();
}
protected void applyFilters(AuthorizationQuery query) {
if (id != null) {
query.authorizationId(id);
}
if (type != null) {
query.authorizationType(type);
}
if (userIdIn != null) {
query.userIdIn(userIdIn);
} | if (groupIdIn != null) {
query.groupIdIn(groupIdIn);
}
if (resourceType != null) {
query.resourceType(resourceType);
}
if (resourceId != null) {
query.resourceId(resourceId);
}
}
@Override
protected void applySortBy(AuthorizationQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_RESOURCE_ID)) {
query.orderByResourceId();
} else if (sortBy.equals(SORT_BY_RESOURCE_TYPE)) {
query.orderByResourceType();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationQueryDto.java | 1 |
请完成以下Java代码 | public class ConcatenatingNull {
public static void main(String[] args) {
String[] values = { "Java ", null, "", "is ", "great!" };
concatenateUsingPlusOperator(values);
concatenateUsingHelperMethod(values);
concatenateUsingStringBuilder(values);
concatenateUsingJoin(values);
concatenateUsingStringJoiner(values);
concatenateUsingCollectorsJoining(values);
concatenateUsingStringConcat(values);
}
public static String concatenateUsingStringConcat(String[] values) {
String result = "";
for (String value : values) {
result = result.concat(getNonNullString(value));
}
return result;
}
public static String concatenateUsingCollectorsJoining(String[] values) {
String result = Stream.of(values).filter(value -> null != value).collect(Collectors.joining(""));
return result;
}
public static String concatenateUsingStringJoiner(String[] values) {
StringJoiner result = new StringJoiner("");
for (String value : values) {
result = result.add(getNonNullString(value));
}
return result.toString();
}
public static String concatenateUsingJoin(String[] values) {
String result = String.join("", values);
return result;
}
public static String concatenateUsingStringBuilder(String[] values) {
StringBuilder result = new StringBuilder();
for (String value : values) {
result = result.append(getNonNullString(value));
} | return result.toString();
}
public static String concatenateUsingHelperMethod(String[] values) {
String result = "";
for (String value : values) {
result = result + getNonNullString(value);
}
return result;
}
public static String concatenateUsingPlusOperator(String[] values) {
String result = "";
for (String value : values) {
result = result + (value == null ? "" : value);
}
return result;
}
private static String getNonNullString(String value) {
return value == null ? "" : value;
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-4\src\main\java\com\baeldung\concatenation\ConcatenatingNull.java | 1 |
请完成以下Java代码 | private static void updateSubScriptionProgressFromRequest(
@NonNull final I_C_SubscriptionProgress subscriptionProgress,
@NonNull final ChangeRecipientsRequest request)
{
subscriptionProgress.setDropShip_BPartner_ID(request.getDropShip_BPartner_ID());
subscriptionProgress.setDropShip_Location_ID(request.getDropShip_Location_ID());
subscriptionProgress.setDropShip_User_ID(request.getDropShip_User_ID());
save(subscriptionProgress);
}
private static void updateShipmentScheduleFromRequest(
@NonNull final I_C_SubscriptionProgress subscriptionProgress,
@NonNull final ChangeRecipientsRequest changeRecipientsRequest)
{
final I_M_ShipmentSchedule shipmentSchedule = InterfaceWrapperHelper.load(subscriptionProgress.getM_ShipmentSchedule_ID(), I_M_ShipmentSchedule.class);
ShipmentScheduleDocumentLocationAdapterFactory | .mainLocationAdapter(shipmentSchedule)
.setFrom(extractDropShipLocation(changeRecipientsRequest));
save(shipmentSchedule);
}
@NonNull
private static DocumentLocation extractDropShipLocation(final @NonNull ChangeRecipientsRequest changeRecipientsRequest)
{
final BPartnerId dropShipBPartnerId = BPartnerId.ofRepoId(changeRecipientsRequest.getDropShip_BPartner_ID());
return DocumentLocation.builder()
.bpartnerId(dropShipBPartnerId)
.bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(dropShipBPartnerId, changeRecipientsRequest.getDropShip_Location_ID()))
.contactId(BPartnerContactId.ofRepoIdOrNull(dropShipBPartnerId, changeRecipientsRequest.getDropShip_User_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\ChangeRecipient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataSourceConfig {
private String driver;
private String url;
private String username;
private String password;
@Override
public String toString()
{
return "DataSourceConfig [driver=" + driver + ", url=" + url + ", username=" + username + "]";
}
public String getDriver()
{
return driver;
}
public void setDriver(String driver)
{
this.driver = driver;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getUsername()
{ | return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
} | repos\Spring-Boot-Advanced-Projects-main\spring-propertysource-example\src\main\java\net\alanbinu\springboot2\springpropertysourceexample\DataSourceConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ReceiptsScheduleDeletedHandler
implements MaterialEventHandler<ReceiptScheduleDeletedEvent>
{
private static final Logger logger = LogManager.getLogger(ReceiptsScheduleDeletedHandler.class);
private final CandidateChangeService candidateChangeHandler;
private final CandidateRepositoryRetrieval candidateRepositoryRetrieval;
public ReceiptsScheduleDeletedHandler(
@NonNull final CandidateChangeService candidateChangeHandler,
@NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval)
{
this.candidateChangeHandler = candidateChangeHandler;
this.candidateRepositoryRetrieval = candidateRepositoryRetrieval;
}
@Override
public Collection<Class<? extends ReceiptScheduleDeletedEvent>> getHandledEventType()
{
return ImmutableList.of(ReceiptScheduleDeletedEvent.class);
}
@Override
public void handleEvent(@NonNull final ReceiptScheduleDeletedEvent event)
{
final CandidatesQuery query = ReceiptsScheduleHandlerUtil.queryByReceiptScheduleId(event);
final Candidate candidateToDelete = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query);
if (candidateToDelete == null)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("No deletable candidate found; query={}", query);
return;
}
final BigDecimal actualQty = candidateToDelete.computeActualQty();
final boolean candidateHasTransactions = actualQty.signum() > 0;
if (candidateHasTransactions) | {
Loggables.withLogger(logger, Level.DEBUG).addLog("candidateId={} for the deleted receiptScheduleId={} already has actual trasactions",
candidateToDelete.getId(), event.getReceiptScheduleId());
candidateChangeHandler.onCandidateNewOrChange(candidateToDelete.withQuantity(actualQty));
}
else
{
Loggables.withLogger(logger, Level.DEBUG).addLog("candidateId={} for the deleted receiptScheduleId={} can be deleted",
candidateToDelete.getId(), event.getReceiptScheduleId());
candidateChangeHandler.onCandidateDelete(candidateToDelete);
}
}
protected CandidatesQuery createCandidatesQuery(@NonNull final ReceiptScheduleDeletedEvent deletedEvent)
{
final PurchaseDetailsQuery purchaseDetailsQuery = PurchaseDetailsQuery.builder()
.receiptScheduleRepoId(deletedEvent.getReceiptScheduleId())
.build();
return CandidatesQuery.builder()
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PURCHASE)
.purchaseDetailsQuery(purchaseDetailsQuery)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\receiptschedule\ReceiptsScheduleDeletedHandler.java | 2 |
请完成以下Java代码 | private static class CompliedJaspersCacheFileSystem
{
@NonNull private final Path compiledJaspersDir;
public CompliedJaspersCacheFileSystem()
{
try
{
final Path basePath = Paths.get(FileUtil.getTempDir(), "compiled_jaspers");
this.compiledJaspersDir = Files.createDirectories(basePath);
logger.info("Using compiled reports cache directory: {}", this.compiledJaspersDir);
}
catch (IOException e)
{
throw new AdempiereException("Failed to create the base temporary directory for compiled reports.", e);
}
}
public JasperEntry getByJrxmlFile(@NonNull final File jrxmlFile)
{
return JasperEntry.builder()
.jrxmlFile(jrxmlFile)
.jasperFile(getCompiledAssetFile(jrxmlFile, jasperExtension))
.hashFile(getCompiledAssetFile(jrxmlFile, ".hash"))
.build();
} | private File getCompiledAssetFile(@NonNull final File jrxmlFile, @NonNull final String extension)
{
final Path jrxmlPath = jrxmlFile.toPath().toAbsolutePath();
// 1. Get the path *relative* to the drive/volume root.
// Example: For C:\workspaces\...\report.jrxml, this isolates:
// "workspaces\dt204\metasfresh\backend\de.metas.fresh\...\report_lu.jrxml"
// We use the full relative path to ensure no collisions.
final Path relativePath = jrxmlPath.getRoot().relativize(jrxmlPath);
// 2. Separate the directory structure (parent) from the file name.
final Path relativeDirPath = relativePath.getParent();
// 3. Resolve the cache directory path: compiledJaspersDir + relativeDirPath
final Path cacheDir = compiledJaspersDir.resolve(relativeDirPath);
// 4. Create the final compiled file name (only changes extension).
final String compiledFileName = FileUtil.changeFileExtension(jrxmlFile.getName(), extension);
// 5. Resolve the final cached path.
final Path cachedPath = cacheDir.resolve(compiledFileName);
return cachedPath.toFile();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\JasperCompileClassLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ArticleMapping _id(UUID _id) {
this._id = _id;
return this;
}
/**
* Alberta-Id des Artikels
* @return _id
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", required = true, description = "Alberta-Id des Artikels")
public UUID getId() {
return _id;
}
public void setId(UUID _id) {
this._id = _id;
}
public ArticleMapping customerId(String customerId) {
this.customerId = customerId;
return this;
}
/**
* eindeutige Artikelnummer aus WaWi
* @return customerId
**/
@Schema(example = "43435", required = true, description = "eindeutige Artikelnummer aus WaWi")
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public ArticleMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true; | }
if (o == null || getClass() != o.getClass()) {
return false;
}
ArticleMapping articleMapping = (ArticleMapping) o;
return Objects.equals(this._id, articleMapping._id) &&
Objects.equals(this.customerId, articleMapping.customerId) &&
Objects.equals(this.updated, articleMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, customerId, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ArticleMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\ArticleMapping.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CreateCollectionService {
@Resource
private MongoTemplate mongoTemplate;
/**
* 创建【集合】
*
* 创建一个大小没有限制的集合(默认集合创建方式)
*
* @return 创建集合的结果
*/
public Object createCollection() {
// 设置集合名称
String collectionName = "users1";
// 创建集合并返回集合信息
mongoTemplate.createCollection(collectionName);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建视图成功" : "创建视图失败";
}
/**
* 创建【固定大小集合】
*
* 创建集合并设置 `capped=true` 创建 `固定大小集合`,可以配置参数 `size` 限制文档大小,可以配置参数 `max` 限制集合文档数量。
*
* @return 创建集合的结果
*/
public Object createCollectionFixedSize() {
// 设置集合名称
String collectionName = "users2";
// 设置集合参数
long size = 1024L;
long max = 5L;
// 创建固定大小集合
CollectionOptions collectionOptions = CollectionOptions.empty()
// 创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。
.capped()
// 固定集合指定一个最大值,以千字节计(KB),如果 capped 为 true,也需要指定该字段。
.size(size)
// 指定固定集合中包含文档的最大数量。
.maxDocuments(max);
// 执行创建集合
mongoTemplate.createCollection(collectionName, collectionOptions);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建视图成功" : "创建视图失败";
} | /**
* 创建【验证文档数据】的集合
*
* 创建集合并在文档"插入"与"更新"时进行数据效验,如果符合创建集合设置的条件就进允许更新与插入,否则则按照设置的设置的策略进行处理。
*
* * 效验级别:
* - off:关闭数据校验。
* - strict:(默认值) 对所有的文档"插入"与"更新"操作有效。
* - moderate:仅对"插入"和满足校验规则的"文档"做"更新"操作有效。对已存在的不符合校验规则的"文档"无效。
* * 执行策略:
* - error:(默认值) 文档必须满足校验规则,才能被写入。
* - warn:对于"文档"不符合校验规则的 MongoDB 允许写入,但会记录一条告警到 mongod.log 中去。日志内容记录报错信息以及该"文档"的完整记录。
*
* @return 创建集合结果
*/
public Object createCollectionValidation() {
// 设置集合名称
String collectionName = "users3";
// 设置验证条件,只允许岁数大于20的用户信息插入
CriteriaDefinition criteria = Criteria.where("age").gt(20);
// 设置集合选项验证对象
CollectionOptions collectionOptions = CollectionOptions.empty()
.validator(Validator.criteria(criteria))
// 设置效验级别
.strictValidation()
// 设置效验不通过后执行的动作
.failOnValidationError();
// 执行创建集合
mongoTemplate.createCollection(collectionName, collectionOptions);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建集合成功" : "创建集合失败";
}
} | repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\CreateCollectionService.java | 2 |
请完成以下Java代码 | public void checkReadDiagnosticsData() {
}
@Override
public void checkReadHistoryLevel() {
}
@Override
public void checkReadTableCount() {
}
@Override
public void checkReadTableName() {
}
@Override
public void checkReadTableMetaData() {
}
@Override
public void checkReadProperties() {
}
@Override
public void checkSetProperty() {
}
@Override
public void checkDeleteProperty() {
}
@Override
public void checkDeleteLicenseKey() {
}
@Override
public void checkSetLicenseKey() {
}
@Override
public void checkReadLicenseKey() {
}
@Override
public void checkRegisterProcessApplication() {
}
@Override
public void checkUnregisterProcessApplication() {
}
@Override
public void checkReadRegisteredDeployments() { | }
@Override
public void checkReadProcessApplicationForDeployment() {
}
@Override
public void checkRegisterDeployment() {
}
@Override
public void checkUnregisterDeployment() {
}
@Override
public void checkDeleteMetrics() {
}
@Override
public void checkDeleteTaskMetrics() {
}
@Override
public void checkReadSchemaLog() {
}
// helper //////////////////////////////////////////////////
protected TenantManager getTenantManager() {
return Context.getCommandContext().getTenantManager();
}
protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) {
return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId);
}
protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) {
return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId);
}
protected ExecutionEntity findExecutionById(String processInstanceId) {
return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId);
}
protected DeploymentEntity findDeploymentById(String deploymentId) {
return Context.getCommandContext().getDeploymentManager().findDeploymentById(deploymentId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantCommandChecker.java | 1 |
请完成以下Java代码 | public String getActivityId() {
return activityId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getErrorMessage() {
return errorMessage;
}
public String getExecutionId() {
return executionId;
}
public String getId() {
return id;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public Date getCreateTime() {
return createTime;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionVersionTag() {
return processDefinitionVersionTag;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Integer getRetries() {
return retries;
}
public boolean isSuspended() {
return suspended;
}
public String getWorkerId() {
return workerId;
}
public String getTopicName() {
return topicName;
}
public String getTenantId() {
return tenantId;
}
public long getPriority() { | return priority;
}
public String getBusinessKey() {
return businessKey;
}
public static ExternalTaskDto fromExternalTask(ExternalTask task) {
ExternalTaskDto dto = new ExternalTaskDto();
dto.activityId = task.getActivityId();
dto.activityInstanceId = task.getActivityInstanceId();
dto.errorMessage = task.getErrorMessage();
dto.executionId = task.getExecutionId();
dto.id = task.getId();
dto.lockExpirationTime = task.getLockExpirationTime();
dto.createTime = task.getCreateTime();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processDefinitionKey = task.getProcessDefinitionKey();
dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag();
dto.processInstanceId = task.getProcessInstanceId();
dto.retries = task.getRetries();
dto.suspended = task.isSuspended();
dto.topicName = task.getTopicName();
dto.workerId = task.getWorkerId();
dto.tenantId = task.getTenantId();
dto.priority = task.getPriority();
dto.businessKey = task.getBusinessKey();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskDto.java | 1 |
请完成以下Java代码 | public class SysPermissionDataRule implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
private String id;
/**
* 对应的菜单id
*/
private String permissionId;
/**
* 规则名称
*/
private String ruleName;
/**
* 字段
*/
private String ruleColumn;
/**
* 条件
*/
private String ruleConditions;
/**
* 规则值
*/
private String ruleValue;
/**
* 状态值 1有效 0无效
*/
private String status;
/** | * 创建时间
*/
private Date createTime;
/**
* 创建人
*/
private String createBy;
/**
* 修改时间
*/
private Date updateTime;
/**
* 修改人
*/
private String updateBy;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysPermissionDataRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static WebSocketRegistryListener webSocketRegistryListener() {
return new WebSocketRegistryListener();
}
@Bean
public WebSocketConnectHandlerDecoratorFactory wsConnectHandlerDecoratorFactory() {
return new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher);
}
@Bean
@SuppressWarnings("unchecked")
public SessionRepositoryMessageInterceptor<S> sessionRepositoryInterceptor() {
return new SessionRepositoryMessageInterceptor<>(this.sessionRepository);
}
/**
* A {@link StompEndpointRegistry} that applies {@link HandshakeInterceptor}.
*/
static class SessionStompEndpointRegistry implements StompEndpointRegistry {
private final WebMvcStompEndpointRegistry registry;
private final HandshakeInterceptor interceptor;
SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, HandshakeInterceptor interceptor) {
this.registry = registry;
this.interceptor = interceptor;
}
@Override
public StompWebSocketEndpointRegistration addEndpoint(String... paths) {
StompWebSocketEndpointRegistration endpoints = this.registry.addEndpoint(paths);
endpoints.addInterceptors(this.interceptor);
return endpoints;
}
@Override
public void setOrder(int order) {
this.registry.setOrder(order); | }
@Override
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
this.registry.setUrlPathHelper(urlPathHelper);
}
@Override
public WebMvcStompEndpointRegistry setErrorHandler(StompSubProtocolErrorHandler errorHandler) {
return this.registry.setErrorHandler(errorHandler);
}
@Override
public WebMvcStompEndpointRegistry setPreserveReceiveOrder(boolean preserveReceiveOrder) {
return this.registry.setPreserveReceiveOrder(preserveReceiveOrder);
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\config\annotation\AbstractSessionWebSocketMessageBrokerConfigurer.java | 2 |
请完成以下Java代码 | private Path parseNonLocalWindowsFileURL(@NonNull final URL url)
{
try
{
final String normalizedPath = Stream.of(url.getAuthority(), url.getPath())
.filter(Check::isNotBlank)
.collect(Collectors.joining());
return Paths.get("//" + normalizedPath);
}
catch (final Throwable throwable)
{
return null;
}
}
/**
* Creates a file path for the given {@code baseDirectory} and {@code subdirectory}.
*
* @throws RuntimeException if the resulting file path is not within the given {@code baseDirectory}.
*/
@NonNull
public static Path createAndValidatePath(@NonNull final Path baseDirectory,
@NonNull final Path subdirectory)
{
final Path baseDirectoryAbs = baseDirectory.normalize().toAbsolutePath();
final Path outputFilePath = baseDirectoryAbs.resolve(
subdirectory).normalize().toAbsolutePath();
// Validate that the outputFilePath is within the base directory
if (!outputFilePath.startsWith(baseDirectoryAbs))
{
throw new RuntimeException("Invalid path " + outputFilePath + "! The result of baseDirectory=" + baseDirectory + " and subdirectory=" + subdirectory + " needs to be within baseDirectory");
}
return outputFilePath;
}
public static void copy(@NonNull final File from, @NonNull final OutputStream out) throws IOException
{
try (final InputStream in = Files.newInputStream(from.toPath()))
{ | copy(in, out);
}
}
/**
* Copies the content from a given {@link InputStream} to the specified {@link File}.
* The method writes the data to a temporary file first, and then renames it to the target file.
* This ensures that we don'T end up with a partially written file that's then already processed by some other component.
*
* @throws IOException if an I/O error occurs during reading, writing, or renaming the file
*/
public static void copy(@NonNull final InputStream in, @NonNull final File to) throws IOException
{
final File tempFile = new File(to.getAbsolutePath() + ".part");
try (final FileOutputStream out = new FileOutputStream(tempFile))
{
copy(in, out);
}
// rename the temporary file to the final destination
if (!tempFile.renameTo(to))
{
throw new IOException("Failed to rename the temporary file "
+ tempFile.getAbsolutePath() + " to " + to.getAbsolutePath());
}
}
public static void copy(@NonNull final InputStream in, @NonNull final OutputStream out) throws IOException
{
final byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.flush();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\FileUtil.java | 1 |
请完成以下Java代码 | public static String convertToEngineKey(final String key, final int windowNo)
{
final String keyPrefix = windowNo + "|";
if (key.startsWith(keyPrefix))
{
String retValue = WINDOW_CONTEXT_PREFIX + key.substring(keyPrefix.length());
retValue = StringUtils.replace(retValue, "|", "_");
return retValue;
}
else
{
String retValue = null;
if (key.startsWith("#"))
{
retValue = GLOBAL_CONTEXT_PREFIX + key.substring(1);
}
else
{
retValue = key;
}
retValue = StringUtils.replace(retValue, "#", "_"); | return retValue;
}
}
public ScriptExecutor putAll(final Map<String, ? extends Object> context)
{
final ScriptEngine engine = getEngine();
context.entrySet()
.stream()
.forEach(entry -> engine.put(entry.getKey(), entry.getValue()));
return this;
}
public ScriptExecutor setThrowExceptionIfResultNotEmpty()
{
throwExceptionIfResultNotEmpty = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\ScriptExecutor.java | 1 |
请完成以下Java代码 | public int getCleanInstancesBatchSize() {
return cleanInstancesBatchSize;
}
public CmmnEngineConfiguration setCleanInstancesBatchSize(int cleanInstancesBatchSize) {
this.cleanInstancesBatchSize = cleanInstancesBatchSize;
return this;
}
public CmmnHistoryCleaningManager getCmmnHistoryCleaningManager() {
return cmmnHistoryCleaningManager;
}
public CmmnEngineConfiguration setCmmnHistoryCleaningManager(CmmnHistoryCleaningManager cmmnHistoryCleaningManager) {
this.cmmnHistoryCleaningManager = cmmnHistoryCleaningManager;
return this;
}
public boolean isHandleCmmnEngineExecutorsAfterEngineCreate() {
return handleCmmnEngineExecutorsAfterEngineCreate;
}
public CmmnEngineConfiguration setHandleCmmnEngineExecutorsAfterEngineCreate(boolean handleCmmnEngineExecutorsAfterEngineCreate) {
this.handleCmmnEngineExecutorsAfterEngineCreate = handleCmmnEngineExecutorsAfterEngineCreate;
return this;
}
public boolean isAlwaysUseArraysForDmnMultiHitPolicies() {
return alwaysUseArraysForDmnMultiHitPolicies;
}
public CmmnEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) {
this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies;
return this;
}
public CaseDefinitionLocalizationManager getCaseDefinitionLocalizationManager() {
return caseDefinitionLocalizationManager;
} | public CmmnEngineConfiguration setCaseDefinitionLocalizationManager(CaseDefinitionLocalizationManager caseDefinitionLocalizationManager) {
this.caseDefinitionLocalizationManager = caseDefinitionLocalizationManager;
return this;
}
public CaseLocalizationManager getCaseLocalizationManager() {
return caseLocalizationManager;
}
public CmmnEngineConfiguration setCaseLocalizationManager(CaseLocalizationManager caseLocalizationManager) {
this.caseLocalizationManager = caseLocalizationManager;
return this;
}
public PlanItemLocalizationManager getPlanItemLocalizationManager() {
return planItemLocalizationManager;
}
public CmmnEngineConfiguration setPlanItemLocalizationManager(PlanItemLocalizationManager planItemLocalizationManager) {
this.planItemLocalizationManager = planItemLocalizationManager;
return this;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static ServiceName forProcessApplicationDeploymentService(String moduleName, String deploymentName) {
return PROCESS_APPLICATION_MODULE.append(moduleName).append("DEPLOY").append(deploymentName);
}
public static ServiceName forNoViewProcessApplicationStartService(String moduleName) {
return PROCESS_APPLICATION_MODULE.append(moduleName).append("NO_VIEW");
}
/**
* @return the {@link ServiceName} of the {@link MscExecutorService}.
*/
public static ServiceName forMscExecutorService() {
return BPM_PLATFORM.append("executor-service");
}
/**
* @return the {@link ServiceName} of the {@link MscRuntimeContainerJobExecutor}
*/
public static ServiceName forMscRuntimeContainerJobExecutorService(String jobExecutorName) {
return JOB_EXECUTOR.append(jobExecutorName);
}
/**
* @return the {@link ServiceName} of the {@link MscBpmPlatformPlugins}
*/ | public static ServiceName forBpmPlatformPlugins() {
return BPM_PLATFORM_PLUGINS;
}
/**
* @return the {@link ServiceName} of the {@link ProcessApplicationStopService}
*/
public static ServiceName forProcessApplicationStopService(String moduleName) {
return PROCESS_APPLICATION_MODULE.append(moduleName).append("STOP");
}
/**
* @return the {@link ServiceName} of the {@link org.jboss.as.threads.BoundedQueueThreadPoolService}
*/
public static ServiceName forManagedThreadPool(String threadPoolName) {
return JOB_EXECUTOR.append(threadPoolName);
}
/**
* @return the {@link ServiceName} of the {@link org.jboss.as.threads.ThreadFactoryService}
*/
public static ServiceName forThreadFactoryService(String threadFactoryName) {
return ThreadsServices.threadFactoryName(threadFactoryName);
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ServiceNames.java | 2 |
请完成以下Java代码 | public boolean supports(ConfigAttribute attribute) {
return attribute instanceof PreInvocationAttribute;
}
@Override
public boolean supports(Class<?> clazz) {
return MethodInvocation.class.isAssignableFrom(clazz);
}
@Override
public int vote(Authentication authentication, MethodInvocation method, Collection<ConfigAttribute> attributes) {
// Find prefilter and preauth (or combined) attributes
// if both null, abstain else call advice with them
PreInvocationAttribute preAttr = findPreInvocationAttribute(attributes);
if (preAttr == null) { | // No expression based metadata, so abstain
return ACCESS_ABSTAIN;
}
return this.preAdvice.before(authentication, method, preAttr) ? ACCESS_GRANTED : ACCESS_DENIED;
}
private @Nullable PreInvocationAttribute findPreInvocationAttribute(Collection<ConfigAttribute> config) {
for (ConfigAttribute attribute : config) {
if (attribute instanceof PreInvocationAttribute) {
return (PreInvocationAttribute) attribute;
}
}
return null;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\prepost\PreInvocationAuthorizationAdviceVoter.java | 1 |
请完成以下Java代码 | 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 script
*/
public void setOnKeyUp (String script)
{
addAttribute ("onkeyup", script);
}
/**
* Determine if this element needs a line break, if pretty printing.
*/ | public boolean getNeedLineBreak ()
{
java.util.Enumeration en = elements ();
int i = 0;
int j = 0;
while (en.hasMoreElements ())
{
j++;
Object obj = en.nextElement ();
if (obj instanceof img)
i++;
}
if (i == j)
return false;
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\a.java | 1 |
请完成以下Java代码 | public Class<? extends AppDeploymentEntity> getManagedEntityClass() {
return AppDeploymentEntityImpl.class;
}
@Override
public AppDeploymentEntity create() {
return new AppDeploymentEntityImpl();
}
@Override
public AppDeploymentEntity findLatestDeploymentByName(String deploymentName) {
List<?> list = getDbSqlSession().selectList("selectAppDeploymentsByName", deploymentName, 0, 1);
if (list != null && !list.isEmpty()) {
return (AppDeploymentEntity) list.get(0);
}
return null;
} | @Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return getDbSqlSession().getSqlSession().selectList("selectAppResourceNamesByDeploymentId", deploymentId);
}
@Override
@SuppressWarnings("unchecked")
public List<AppDeployment> findDeploymentsByQueryCriteria(AppDeploymentQueryImpl deploymentQuery) {
return getDbSqlSession().selectList("selectAppDeploymentsByQueryCriteria", deploymentQuery);
}
@Override
public long findDeploymentCountByQueryCriteria(AppDeploymentQueryImpl deploymentQuery) {
return (Long) getDbSqlSession().selectOne("selectAppDeploymentCountByQueryCriteria", deploymentQuery);
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\data\impl\MybatisAppDeploymentDataManager.java | 1 |
请完成以下Java代码 | public String initUpdateForm() {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
@PostMapping("/pets/{petId}/edit")
public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult result,
RedirectAttributes redirectAttributes) {
String petName = pet.getName();
// checking if the pet name already exists for the owner
if (StringUtils.hasText(petName)) {
Pet existingPet = owner.getPet(petName, false);
if (existingPet != null && !Objects.equals(existingPet.getId(), pet.getId())) {
result.rejectValue("name", "duplicate", "already exists");
}
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
if (result.hasErrors()) {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
updatePetDetails(owner, pet);
redirectAttributes.addFlashAttribute("message", "Pet details has been edited"); | return "redirect:/owners/{ownerId}";
}
/**
* Updates the pet details if it exists or adds a new pet to the owner.
* @param owner The owner of the pet
* @param pet The pet with updated details
*/
private void updatePetDetails(Owner owner, Pet pet) {
Integer id = pet.getId();
Assert.state(id != null, "'pet.getId()' must not be null");
Pet existingPet = owner.getPet(id);
if (existingPet != null) {
// Update existing pet's properties
existingPet.setName(pet.getName());
existingPet.setBirthDate(pet.getBirthDate());
existingPet.setType(pet.getType());
}
else {
owner.addPet(pet);
}
this.owners.save(owner);
}
} | repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\PetController.java | 1 |
请完成以下Java代码 | public List<I_GL_Journal> retrievePostedWithoutFactAcct(final Properties ctx, final Date startTime)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final String trxName = ITrx.TRXNAME_ThreadInherited;
final IQueryBuilder<I_GL_Journal> queryBuilder = queryBL.createQueryBuilder(I_GL_Journal.class, ctx, trxName)
.addOnlyActiveRecordsFilter();
queryBuilder
.addEqualsFilter(I_GL_Journal.COLUMNNAME_Posted, true) // Posted
.addEqualsFilter(I_GL_Journal.COLUMNNAME_Processed, true) // Processed
.addInArrayOrAllFilter(I_GL_Journal.COLUMNNAME_DocStatus, IDocument.STATUS_Closed, IDocument.STATUS_Completed); // DocStatus in ('CO', 'CL')
// Exclude the entries that don't have either Credit or Debit amounts. These entries will produce 0 in posting
final ICompositeQueryFilter<I_GL_Journal> nonZeroFilter = queryBL.createCompositeQueryFilter(I_GL_Journal.class).setJoinOr()
.addNotEqualsFilter(I_GL_Journal.COLUMNNAME_TotalCr, BigDecimal.ZERO)
.addNotEqualsFilter(I_GL_Journal.COLUMNNAME_TotalDr, BigDecimal.ZERO);
queryBuilder.filter(nonZeroFilter);
// Only the documents created after the given start time
if (startTime != null) | {
queryBuilder.addCompareFilter(I_GL_Journal.COLUMNNAME_Created, Operator.GREATER_OR_EQUAL, startTime);
}
// Check if there are fact accounts created for each document
final IQueryBuilder<I_Fact_Acct> factAcctQuery = queryBL.createQueryBuilder(I_Fact_Acct.class, ctx, trxName)
.addEqualsFilter(I_Fact_Acct.COLUMNNAME_AD_Table_ID, InterfaceWrapperHelper.getTableId(I_GL_Journal.class));
queryBuilder
.addNotInSubQueryFilter(I_GL_Journal.COLUMNNAME_GL_Journal_ID, I_Fact_Acct.COLUMNNAME_Record_ID, factAcctQuery.create()) // has no accounting
;
return queryBuilder
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\impl\GLJournalDAO.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.