instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class ClassDelegateHttpHandler extends CmmnClassDelegate implements HttpRequestHandler, HttpResponseHandler {
private static final long serialVersionUID = 1L;
public ClassDelegateHttpHandler(String className, List<FieldExtension> fieldExtension) {
super(className, fieldExtension);
}
public ClassDelegateHttpHandler(Class<?> clazz, List<FieldExtension> fieldExtension) {
super(clazz.getName(), fieldExtension);
}
@Override
public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) {
HttpRequestHandler httpRequestHandler = getHttpRequestHandlerInstance();
httpRequestHandler.handleHttpRequest(execution, httpRequest, client);
}
@Override
public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) {
HttpResponseHandler httpResponseHandler = getHttpResponseHandlerInstance();
httpResponseHandler.handleHttpResponse(execution, httpResponse);
}
protected HttpRequestHandler getHttpRequestHandlerInstance() {
Object delegateInstance = instantiate(className);
if (delegateInstance instanceof HttpRequestHandler) {
return (HttpRequestHandler) delegateInstance;
|
} else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + HttpRequestHandler.class);
}
}
protected HttpResponseHandler getHttpResponseHandlerInstance() {
Object delegateInstance = instantiate(className);
if (delegateInstance instanceof HttpResponseHandler) {
return (HttpResponseHandler) delegateInstance;
} else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + HttpResponseHandler.class);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\http\handler\ClassDelegateHttpHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setEnforceImmediateAckForManual(Boolean enforceImmediateAckForManual) {
this.enforceImmediateAckForManual = enforceImmediateAckForManual;
}
@Override
protected SimpleMessageListenerContainer createContainerInstance() {
return new SimpleMessageListenerContainer();
}
@Override
protected void initializeContainer(SimpleMessageListenerContainer instance,
@Nullable RabbitListenerEndpoint endpoint) {
super.initializeContainer(instance, endpoint);
JavaUtils javaUtils = JavaUtils.INSTANCE
.acceptIfNotNull(this.batchSize, instance::setBatchSize);
String concurrency = null;
if (endpoint != null) {
concurrency = endpoint.getConcurrency();
javaUtils.acceptIfNotNull(concurrency, instance::setConcurrency);
}
javaUtils
.acceptIfCondition(concurrency == null && this.concurrentConsumers != null, this.concurrentConsumers,
instance::setConcurrentConsumers)
.acceptIfCondition((concurrency == null || !(concurrency.contains("-")))
|
&& this.maxConcurrentConsumers != null,
this.maxConcurrentConsumers, instance::setMaxConcurrentConsumers)
.acceptIfNotNull(this.startConsumerMinInterval, instance::setStartConsumerMinInterval)
.acceptIfNotNull(this.stopConsumerMinInterval, instance::setStopConsumerMinInterval)
.acceptIfNotNull(this.consecutiveActiveTrigger, instance::setConsecutiveActiveTrigger)
.acceptIfNotNull(this.consecutiveIdleTrigger, instance::setConsecutiveIdleTrigger)
.acceptIfNotNull(this.receiveTimeout, instance::setReceiveTimeout)
.acceptIfNotNull(this.batchReceiveTimeout, instance::setBatchReceiveTimeout)
.acceptIfNotNull(this.enforceImmediateAckForManual, instance::setEnforceImmediateAckForManual);
if (Boolean.TRUE.equals(this.consumerBatchEnabled)) {
instance.setConsumerBatchEnabled(true);
/*
* 'batchListener=true' turns off container debatching by default, it must be
* true when consumer batching is enabled.
*/
instance.setDeBatchingEnabled(true);
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\SimpleRabbitListenerContainerFactory.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<Task> findTasksByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectTaskByNativeQuery", parameterMap);
}
@Override
public long findTaskCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectTaskCountByNativeQuery", parameterMap);
}
@Override
@SuppressWarnings("unchecked")
public List<Task> findTasksByParentTaskId(String parentTaskId) {
return getDbSqlSession().selectList("selectTasksByParentTaskId", parentTaskId);
}
@Override
public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateTaskTenantIdForDeployment", params);
}
@Override
public void updateAllTaskRelatedEntityCountFlags(boolean newValue) {
getDbSqlSession().directUpdate("updateTaskRelatedEntityCountEnabled", newValue);
}
@Override
public void deleteTasksByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
deleteCachedEntities(dbSqlSession, tasksByExecutionIdMatcher, executionId);
} else {
bulkDelete("deleteTasksByExecutionId", tasksByExecutionIdMatcher, executionId);
}
|
}
@Override
protected IdGenerator getIdGenerator() {
return taskServiceConfiguration.getIdGenerator();
}
protected void setSafeInValueLists(TaskQueryImpl taskQuery) {
if (taskQuery.getCandidateGroups() != null) {
taskQuery.setSafeCandidateGroups(createSafeInValuesList(taskQuery.getCandidateGroups()));
}
if (taskQuery.getInvolvedGroups() != null) {
taskQuery.setSafeInvolvedGroups(createSafeInValuesList(taskQuery.getInvolvedGroups()));
}
if (taskQuery.getScopeIds() != null) {
taskQuery.setSafeScopeIds(createSafeInValuesList(taskQuery.getScopeIds()));
}
if (taskQuery.getOrQueryObjects() != null && !taskQuery.getOrQueryObjects().isEmpty()) {
for (TaskQueryImpl orTaskQuery : taskQuery.getOrQueryObjects()) {
setSafeInValueLists(orTaskQuery);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MybatisTaskDataManager.java
| 2
|
请完成以下Java代码
|
public String getCaseInstanceId() {
return caseInstanceId;
}
@Override
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
@Override
public String getCaseDefinitionId() {
return caseDefinitionId;
}
@Override
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
@Override
public String getElementId() {
|
return elementId;
}
@Override
public void setElementId(String elementId) {
this.elementId = elementId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricMilestoneInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
private void validateSupplierApprovals(final I_C_Order order)
{
if (order.isSOTrx())
{
// Only purchase orders are relevant
return;
}
final ImmutableList<ProductId> productIds = orderDAO.retrieveOrderLines(order)
.stream()
.map(line -> ProductId.ofRepoId(line.getM_Product_ID()))
.collect(ImmutableList.toImmutableList());
for (final ProductId productId : productIds)
{
final ImmutableList<String> supplierApprovalNorms = productBL.retrieveSupplierApprovalNorms(productId);
if (Check.isEmpty(supplierApprovalNorms))
{
// nothing to validate
continue;
}
final BPartnerId partnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
partnerSupplierApprovalService.validateSupplierApproval(partnerId, TimeUtil.asLocalDate(order.getDatePromised(), timeZone), supplierApprovalNorms);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Order.COLUMNNAME_C_BPartner_ID })
public void setBillBPartnerIdIfAssociation(final I_C_Order order)
{
final I_C_BP_Group bpartnerGroup = groupDAO.getByBPartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
if (bpartnerGroup.isAssociation())
{
order.setBill_BPartner_ID(bpartnerGroup.getBill_BPartner_ID());
order.setBill_Location_ID(bpartnerGroup.getBill_Location_ID());
order.setBill_User_ID(bpartnerGroup.getBill_User_ID());
}
else
{
final BPGroupId parentGroupId = BPGroupId.ofRepoIdOrNull(bpartnerGroup.getParent_BP_Group_ID());
if (parentGroupId != null)
{
final I_C_BP_Group parentGroup = groupDAO.getById(parentGroupId);
if (parentGroup.isAssociation())
{
|
order.setBill_BPartner_ID(parentGroup.getBill_BPartner_ID());
order.setBill_Location_ID(parentGroup.getBill_Location_ID());
order.setBill_User_ID(parentGroup.getBill_User_ID());
}
}
}
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void createOrderPaySchedules(final I_C_Order order)
{
orderPayScheduleService.createOrderPaySchedules(order);
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_REACTIVATE)
public void deleteOrderPaySchedules(final I_C_Order order)
{
orderPayScheduleService.deleteByOrderId(OrderId.ofRepoId(order.getC_Order_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_Order.COLUMNNAME_LC_Date, I_C_Order.COLUMNNAME_ETA, I_C_Order.COLUMNNAME_BLDate, I_C_Order.COLUMNNAME_InvoiceDate })
public void updateOrderPaySchedules(final I_C_Order order)
{
orderPayScheduleService.updatePayScheduleStatus(order);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_Order.java
| 1
|
请完成以下Java代码
|
private boolean isDisplayAvailabilityInfoOnlyIfPositive()
{
final Properties ctx = Env.getCtx();
return Services.get(ISysConfigBL.class).getBooleanValue(
SYSCONFIG_DISPLAY_AVAILABILITY_INFO_ONLY_IF_POSITIVE,
true,
Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx));
}
@Value
@Builder
private static class ProductWithAvailabilityInfo
{
@NonNull
ProductId productId;
@NonNull
ITranslatableString productDisplayName;
Quantity qty;
@NonNull
@Default
Group.Type attributesType = Group.Type.ALL_STORAGE_KEYS;
@NonNull
@Default
ImmutableAttributeSet attributes = ImmutableAttributeSet.EMPTY;
}
public static ProductId toProductId(@NonNull final LookupValue lookupValue)
{
return lookupValue.getIdAs(ProductId::ofRepoId);
}
public static ProductAndAttributes toProductAndAttributes(@NonNull final LookupValue lookupValue)
{
final ProductId productId = lookupValue.getIdAs(ProductId::ofRepoId);
final Map<Object, Object> valuesByAttributeIdMap = lookupValue.getAttribute(ATTRIBUTE_ASI);
final ImmutableAttributeSet attributes = ImmutableAttributeSet.ofValuesByAttributeIdMap(valuesByAttributeIdMap);
return ProductAndAttributes.builder()
.productId(productId)
.attributes(attributes)
.build();
|
}
private boolean isFullTextSearchEnabled()
{
final boolean disabled = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DisableFullTextSearch, false);
return !disabled;
}
@Value
@Builder(toBuilder = true)
public static class ProductAndAttributes
{
@NonNull
ProductId productId;
@Default
@NonNull
ImmutableAttributeSet attributes = ImmutableAttributeSet.EMPTY;
}
private interface I_M_Product_Lookup_V
{
String Table_Name = "M_Product_Lookup_V";
String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
String COLUMNNAME_IsActive = "IsActive";
String COLUMNNAME_M_Product_ID = "M_Product_ID";
String COLUMNNAME_Value = "Value";
String COLUMNNAME_Name = "Name";
String COLUMNNAME_UPC = "UPC";
String COLUMNNAME_BPartnerProductNo = "BPartnerProductNo";
String COLUMNNAME_BPartnerProductName = "BPartnerProductName";
String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID";
String COLUMNNAME_Discontinued = "Discontinued";
String COLUMNNAME_DiscontinuedFrom = "DiscontinuedFrom";
String COLUMNNAME_IsBOM = "IsBOM";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\ProductLookupDescriptor.java
| 1
|
请完成以下Java代码
|
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public org.compiere.model.I_AD_Zebra_Config getAD_Zebra_Config()
{
return get_ValueAsPO(COLUMNNAME_AD_Zebra_Config_ID, org.compiere.model.I_AD_Zebra_Config.class);
}
@Override
public void setAD_Zebra_Config(final org.compiere.model.I_AD_Zebra_Config AD_Zebra_Config)
{
set_ValueFromPO(COLUMNNAME_AD_Zebra_Config_ID, org.compiere.model.I_AD_Zebra_Config.class, AD_Zebra_Config);
}
@Override
public void setAD_Zebra_Config_ID (final int AD_Zebra_Config_ID)
{
if (AD_Zebra_Config_ID < 1)
set_Value (COLUMNNAME_AD_Zebra_Config_ID, null);
else
set_Value (COLUMNNAME_AD_Zebra_Config_ID, AD_Zebra_Config_ID);
}
@Override
public int getAD_Zebra_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Zebra_Config_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setC_BP_PrintFormat_ID (final int C_BP_PrintFormat_ID)
{
if (C_BP_PrintFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, C_BP_PrintFormat_ID);
}
@Override
public int getC_BP_PrintFormat_ID()
|
{
return get_ValueAsInt(COLUMNNAME_C_BP_PrintFormat_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setDocumentCopies_Override (final int DocumentCopies_Override)
{
set_Value (COLUMNNAME_DocumentCopies_Override, DocumentCopies_Override);
}
@Override
public int getDocumentCopies_Override()
{
return get_ValueAsInt(COLUMNNAME_DocumentCopies_Override);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_PrintFormat.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public ProductEntity getProductEntity() {
return productEntity;
}
public void setProductEntity(ProductEntity productEntity) {
this.productEntity = productEntity;
}
public int getCount() {
return count;
|
}
public void setCount(int count) {
this.count = count;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
@Override
public String toString() {
return "ShopCartEntity{" +
"id='" + id + '\'' +
", userId='" + userId + '\'' +
", productEntity=" + productEntity +
", count=" + count +
", time=" + time +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\ShopCartEntity.java
| 2
|
请完成以下Java代码
|
public List<I_C_Flatrate_Term> retrieveTermsForOLCand(final I_C_OLCand olCand)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(olCand);
final String trxName = InterfaceWrapperHelper.getTrxName(olCand);
final String wc = I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID + " IN (\n" +
" select " + I_C_Contract_Term_Alloc.COLUMNNAME_C_Flatrate_Term_ID + "\n" +
" from " + I_C_Contract_Term_Alloc.Table_Name + " cta \n" +
" where \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_IsActive + "=" + DB.TO_STRING("Y") + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_AD_Client_ID + "=" + I_C_Flatrate_Term.Table_Name + "." + I_C_Flatrate_Term.COLUMNNAME_AD_Client_ID + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_C_OLCand_ID + "=? \n" +
")";
return new Query(ctx, I_C_Flatrate_Term.Table_Name, wc, trxName) //
.setParameters(olCand.getC_OLCand_ID())
.setClient_ID()
.setOnlyActiveRecords(true)
.setOrderBy(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID)
.list(I_C_Flatrate_Term.class);
}
@Override
public <T extends I_C_OLCand> List<T> retrieveOLCands(final I_C_Flatrate_Term term, final Class<T> clazz)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(term);
|
final String trxName = InterfaceWrapperHelper.getTrxName(term);
final String wc = I_C_OLCand.COLUMNNAME_C_OLCand_ID + " IN (\n" +
" select " + I_C_Contract_Term_Alloc.COLUMNNAME_C_OLCand_ID + "\n" +
" from " + I_C_Contract_Term_Alloc.Table_Name + " cta \n" +
" where \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_IsActive + "=" + DB.TO_STRING("Y") + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_AD_Client_ID + "=" + I_C_OLCand.Table_Name + "." + I_C_OLCand.COLUMNNAME_AD_Client_ID + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_C_Flatrate_Term_ID + "=? \n" +
")";
return new Query(ctx, I_C_OLCand.Table_Name, wc, trxName) //
.setParameters(term.getC_Flatrate_Term_ID())
.setClient_ID()
.setOnlyActiveRecords(true)
.setOrderBy(I_C_OLCand.COLUMNNAME_C_OLCand_ID)
.list(clazz);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionDAO.java
| 1
|
请完成以下Java代码
|
protected String generateSalt() {
return Context.getProcessEngineConfiguration()
.getSaltGenerator()
.generateSalt();
}
public boolean checkPasswordAgainstPolicy() {
PasswordPolicyResult result = Context.getProcessEngineConfiguration()
.getIdentityService()
.checkPasswordAgainstPolicy(newPassword, this);
return result.isValid();
}
public boolean hasNewPassword() {
|
return newPassword != null;
}
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", firstName=" + firstName
+ ", lastName=" + lastName
+ ", email=" + email
+ ", password=******" // sensitive for logging
+ ", salt=******" // sensitive for logging
+ ", lockExpirationTime=" + lockExpirationTime
+ ", attempts=" + attempts
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static Effort ofSeconds(final long seconds)
{
return new Effort(seconds);
}
@NonNull
public Effort addNullSafe(@Nullable final Effort effort)
{
final long secondsToAdd = effort != null
? effort.getSeconds()
: 0;
final long secondsSum = getSeconds() + secondsToAdd;
return new Effort(secondsSum);
}
|
@NonNull
public String getHmm()
{
return HmmUtils.secondsToHmm(seconds);
}
@NonNull
public Effort negate()
{
return new Effort(-seconds);
}
private Effort(final long seconds)
{
this.seconds = seconds;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\Effort.java
| 2
|
请完成以下Java代码
|
private final Map<IFacetCategory, IQueryFilter<ModelType>> createFacetCategoryQueryFilters(final Collection<IFacet<ModelType>> facets)
{
final Map<IFacetCategory, IQueryFilter<ModelType>> facetCategory2filters = new LinkedHashMap<>();
for (final IFacet<ModelType> facet : facets)
{
final IFacetCategory facetCategory = facet.getFacetCategory();
//
// Get create one composite filter per facet category
// (because we join facet filters by "OR" but between categories we do "AND")
ICompositeQueryFilter<ModelType> facetCategoryFilter = (ICompositeQueryFilter<ModelType>)facetCategory2filters.get(facetCategory);
if (facetCategoryFilter == null)
{
facetCategoryFilter = queryBL.createCompositeQueryFilter(modelClass)
// Facet filters of same facet category are joined by "OR"
.setJoinOr()
// If there is no facet filters in this facet category, we are accepting everything
.setDefaultAccept(true);
facetCategory2filters.put(facetCategory, facetCategoryFilter);
}
//
// Add facet filter to facet category filters
final IQueryFilter<ModelType> filter = facet.getFilter();
if (filter != null)
{
facetCategoryFilter.addFilter(filter);
}
}
// TODO: make the facet category's composite query filters immutable, just to prevent somebody from changing them
// because those are part of internal state of this object.
return facetCategory2filters;
}
@Override
public IQueryBuilder<ModelType> createQueryBuilder(final Predicate<IFacetCategory> onlyFacetCategoriesPredicate)
{
final IQueryBuilder<ModelType> queryBuilder = queryBL.createQueryBuilder(modelClass, getCtx(), ITrx.TRXNAME_None);
//
queryBuilder.filter(gridTabBaseQueryFilter);
final IQueryFilter<ModelType> facetCategoriesFilter = createFacetCategoriesFilter(onlyFacetCategoriesPredicate);
queryBuilder.filter(facetCategoriesFilter);
return queryBuilder;
}
|
private final ICompositeQueryFilter<ModelType> createFacetCategoriesFilter(final Predicate<IFacetCategory> onlyFacetCategoriesPredicate)
{
final ICompositeQueryFilter<ModelType> facetCategoriesFilter = queryBL.createCompositeQueryFilter(modelClass)
// We are joining facet category filters by "AND"
.setJoinAnd()
// If there is no facet category filters, we accept everything
.setDefaultAccept(true);
for (final Map.Entry<IFacetCategory, IQueryFilter<ModelType>> facetCategory2filter : facetCategoryFilters.entrySet())
{
final IFacetCategory facetCategory = facetCategory2filter.getKey();
if (onlyFacetCategoriesPredicate != null && !onlyFacetCategoriesPredicate.test(facetCategory))
{
continue;
}
final IQueryFilter<ModelType> filter = facetCategory2filter.getValue();
facetCategoriesFilter.addFilter(filter);
}
return facetCategoriesFilter;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\GridTabFacetFilterable.java
| 1
|
请完成以下Java代码
|
public static long factorialUsingEAAsync(int number) {
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
long result = await(completableFuture);
return result;
}
/**
* Finds factorial of a number using Async of Cactoos
* @param number
* @return
* @throws InterruptedException
* @throws ExecutionException
*/
@Loggable
public static Future<Long> factorialUsingCactoos(int number) throws InterruptedException, ExecutionException {
org.cactoos.func.Async<Integer, Long> asyncFunction = new org.cactoos.func.Async<Integer, Long>(input -> factorial(input));
Future<Long> asyncFuture = asyncFunction.apply(number);
return asyncFuture;
}
/**
* Finds factorial of a number using Guava's ListeningExecutorService.submit()
* @param number
* @return
*/
@Loggable
public static ListenableFuture<Long> factorialUsingGuavaServiceSubmit(int number) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
ListenableFuture<Long> factorialFuture = (ListenableFuture<Long>) service.submit(()-> factorial(number));
return factorialFuture;
}
|
/**
* Finds factorial of a number using Guava's Futures.submitAsync()
* @param number
* @return
*/
@Loggable
public static ListenableFuture<Long> factorialUsingGuavaFutures(int number) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() {
public Long call() {
return factorial(number);
}
}, service);
return Futures.submitAsync(asyncCallable, service);
}
/**
* Finds factorial of a number using @Async of jcabi-aspects
* @param number
* @return
*/
@Async
@Loggable
public static Future<Long> factorialUsingJcabiAspect(int number) {
Future<Long> factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number));
return factorialFuture;
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\async\JavaAsync.java
| 1
|
请完成以下Java代码
|
public void setHelp(final String help)
{
this.help = help;
}
private void setHelp(final String adLanguage, final String helpTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if (helpTrls == null)
{
helpTrls = new HashMap<>();
}
helpTrls.put(adLanguage, helpTrl);
}
@Nullable
public ReferenceId getAD_Reference_Value_ID()
{
return AD_Reference_Value_ID;
}
/**
* Get Column Name or SQL .. with/without AS
*
* @param withAS include AS ColumnName for virtual columns in select statements
* @return column name
*/
public String getColumnSQL(final boolean withAS)
{
// metas
if (ColumnClass != null)
{
return "NULL";
}
// metas end
if (ColumnSQL != null && !ColumnSQL.isEmpty())
{
if (withAS)
{
return ColumnSQL + " AS " + ColumnName;
}
else
{
return ColumnSQL;
}
}
return ColumnName;
} // getColumnSQL
public ColumnSql getColumnSql(@NonNull final String ctxTableName)
{
return ColumnSql.ofSql(getColumnSQL(false), ctxTableName);
}
/**
* Is Virtual Column
*
* @return column is virtual
*/
public boolean isVirtualColumn()
{
return (ColumnSQL != null && !ColumnSQL.isEmpty())
|| (ColumnClass != null && !ColumnClass.isEmpty());
} // isColumnVirtual
public boolean isReadOnly()
{
|
return IsReadOnly;
}
public boolean isUpdateable()
{
return IsUpdateable;
}
public boolean isAlwaysUpdateable()
{
return IsAlwaysUpdateable;
}
public boolean isKey()
{
return IsKey;
}
public boolean isEncryptedField()
{
return IsEncryptedField;
}
public boolean isEncryptedColumn()
{
return IsEncryptedColumn;
}
public boolean isSelectionColumn()
{
return defaultFilterDescriptor != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVO.java
| 1
|
请完成以下Java代码
|
protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, ScriptServiceTask serviceTask, boolean didWriteExtensionElement,
XMLStreamWriter xtw) throws Exception {
boolean extensionElementWritten = super.writePlanItemDefinitionExtensionElements(model, serviceTask, didWriteExtensionElement, xtw);
extensionElementWritten = CmmnXmlUtil.writeIOParameters(ELEMENT_EXTERNAL_WORKER_IN_PARAMETER, serviceTask.getInParameters(),
extensionElementWritten, xtw);
return extensionElementWritten;
}
}
public static class FormAwareServiceTaskExport extends AbstractServiceTaskExport<FormAwareServiceTask> {
@Override
protected Class<? extends FormAwareServiceTask> getExportablePlanItemDefinitionClass() {
return FormAwareServiceTask.class;
}
|
@Override
public void writePlanItemDefinitionSpecificAttributes(FormAwareServiceTask formAwareServiceTask, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(formAwareServiceTask, xtw);
if (StringUtils.isNotBlank(formAwareServiceTask.getFormKey())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_KEY, formAwareServiceTask.getFormKey());
}
if (StringUtils.isNotBlank(formAwareServiceTask.getValidateFormFields())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FIELD_VALIDATION,
formAwareServiceTask.getValidateFormFields());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\AbstractServiceTaskExport.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ShipmentResponse {
protected String identificationNumber;
protected String mpsId;
protected List<ParcelInformationType> parcelInformation;
protected List<FaultCodeType> faults;
/**
* Gets the value of the identificationNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdentificationNumber() {
return identificationNumber;
}
/**
* Sets the value of the identificationNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdentificationNumber(String value) {
this.identificationNumber = value;
}
/**
* Gets the value of the mpsId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMpsId() {
return mpsId;
}
/**
* Sets the value of the mpsId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMpsId(String value) {
this.mpsId = value;
}
/**
* Gets the value of the parcelInformation 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 parcelInformation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getParcelInformation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ParcelInformationType }
*
*
*/
public List<ParcelInformationType> getParcelInformation() {
if (parcelInformation == null) {
parcelInformation = new ArrayList<ParcelInformationType>();
}
return this.parcelInformation;
}
/**
* Gets the value of the faults 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 faults property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFaults().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FaultCodeType }
*
*
*/
public List<FaultCodeType> getFaults() {
if (faults == null) {
faults = new ArrayList<FaultCodeType>();
}
return this.faults;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ShipmentResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonInboundPaymentInfo
{
@ApiModelProperty(required = true, //
dataType = "java.lang.String", //
value = "An external identifier for the payment being posted to metasfresh. Translates to `C_Payment.ExternalId`")
@Nullable
String externalPaymentId;
@ApiModelProperty(required = true, //
dataType = "java.lang.String", //
value = SwaggerDocConstants.BPARTNER_IDENTIFIER_DOC)
@NonNull
String bpartnerIdentifier;
@ApiModelProperty(required = true, //
dataType = "java.lang.String")
@NonNull
String targetIBAN;
@ApiModelProperty(dataType = "java.lang.String", //
value = SwaggerDocConstants.ORDER_IDENTIFIER_DOC)
@Nullable
String orderIdentifier;
@ApiModelProperty(required = true, //
dataType = "java.lang.String")
@NonNull
String currencyCode;
@ApiModelProperty(value = "Optional, to specify the `AD_Org_ID`.\n"
+ "This property needs to be set to the `AD_Org.Value` of an organisation that the invoking user is allowed to access\n"
+ "or the invoking user needs to belong to an organisation, which is then used.")
@Nullable
String orgCode;
@ApiModelProperty(dataType = "java.time.LocalDate",
value = "If this is sent, it is used for both `accounting date` and `payment date`.")
@Nullable
|
LocalDate transactionDate;
@ApiModelProperty(value = "List of payment allocations")
@Nullable
@JsonProperty("lines")
List<JsonPaymentAllocationLine> lines;
@JsonIgnoreProperties(ignoreUnknown = true) // the annotation to ignore properties should be set on the deserializer method (on the builder), and not on the base class
@JsonPOJOBuilder(withPrefix = "")
public static class JsonInboundPaymentInfoBuilder
{
}
public BigDecimal getAmount()
{
return getAmount(JsonPaymentAllocationLine::getAmount);
}
public BigDecimal getDiscountAmt()
{
return getAmount(JsonPaymentAllocationLine::getDiscountAmt);
}
public BigDecimal getWriteOffAmt()
{
return getAmount(JsonPaymentAllocationLine::getWriteOffAmt);
}
private BigDecimal getAmount(final Function<JsonPaymentAllocationLine, BigDecimal> lineToPayAmt)
{
final List<JsonPaymentAllocationLine> lines = getLines();
return lines == null ? BigDecimal.ZERO : lines.stream().map(lineToPayAmt).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\payment\JsonInboundPaymentInfo.java
| 2
|
请完成以下Java代码
|
static String createHowtoDisableMessage(@NonNull final Pointcut pointcut)
{
final String pointcutId = pointcut.getPointcutId();
return String.format("Model interceptor method %s threw an exception.\nYou can disable this method with SysConfig %s='N' (with AD_Client_ID and AD_Org_ID=0!)",
pointcutId, createDisabledSysConfigKey(pointcutId));
}
private static String createDisabledSysConfigKey(@NonNull final String pointcutId)
{
return SYS_CONFIG_NAME_PREFIX + pointcutId;
}
private static ImmutableSet<String> retrieveDisabledPointcutIds()
{
final boolean removePrefix = true;
|
return Services.get(ISysConfigBL.class)
.getValuesForPrefix(SYS_CONFIG_NAME_PREFIX, removePrefix, ClientAndOrgId.SYSTEM)
.entrySet()
.stream()
.filter(entry -> !DisplayType.toBoolean(entry.getValue())) // =Y
.map(Entry::getKey)
.collect(ImmutableSet.toImmutableSet());
}
public boolean isDisabled(@NonNull final Pointcut pointcut)
{
final String pointcutId = pointcut.getPointcutId();
return disabledPointcutIdsSupplier.get().contains(pointcutId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AnnotatedModelInterceptorDisabler.java
| 1
|
请完成以下Java代码
|
public void setDiscountAmt (final @Nullable BigDecimal DiscountAmt)
{
set_ValueNoCheck (COLUMNNAME_DiscountAmt, DiscountAmt);
}
@Override
public BigDecimal getDiscountAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DiscountAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDiscountBaseAmt (final @Nullable BigDecimal DiscountBaseAmt)
{
set_ValueNoCheck (COLUMNNAME_DiscountBaseAmt, DiscountBaseAmt);
}
@Override
public BigDecimal getDiscountBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DiscountBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDiscountDate (final @Nullable java.sql.Timestamp DiscountDate)
{
set_Value (COLUMNNAME_DiscountDate, DiscountDate);
}
@Override
public java.sql.Timestamp getDiscountDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DiscountDate);
}
@Override
public void setDiscountDays (final int DiscountDays)
{
set_Value (COLUMNNAME_DiscountDays, DiscountDays);
}
@Override
public int getDiscountDays()
{
return get_ValueAsInt(COLUMNNAME_DiscountDays);
}
@Override
public void setEDI_cctop_140_v_ID (final int EDI_cctop_140_v_ID)
{
if (EDI_cctop_140_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, EDI_cctop_140_v_ID);
}
@Override
public int getEDI_cctop_140_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_140_v_ID);
}
@Override
public de.metas.esb.edi.model.I_EDI_cctop_invoic_v getEDI_cctop_invoic_v()
{
return get_ValueAsPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class);
}
@Override
public void setEDI_cctop_invoic_v(final de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v)
{
set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v);
|
}
@Override
public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID)
{
if (EDI_cctop_invoic_v_ID < 1)
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null);
else
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID);
}
@Override
public int getEDI_cctop_invoic_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setRate (final @Nullable BigDecimal Rate)
{
set_Value (COLUMNNAME_Rate, Rate);
}
@Override
public BigDecimal getRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_140_v.java
| 1
|
请完成以下Java代码
|
private static List<Object> parsePath(String path) {
if (!StringUtils.hasText(path)) {
return Collections.emptyList();
}
String invalidPathMessage = "Invalid path: '" + path + "'";
List<Object> dataPath = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean readingIndex = false;
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
switch (c) {
case '.':
case '[':
Assert.isTrue(!readingIndex, invalidPathMessage);
break;
case ']':
i++;
Assert.isTrue(readingIndex, invalidPathMessage);
Assert.isTrue(i == path.length() || path.charAt(i) == '.', invalidPathMessage);
break;
default:
sb.append(c);
if (i < path.length() - 1) {
continue;
}
}
String token = sb.toString();
Assert.hasText(token, invalidPathMessage);
dataPath.add(readingIndex ? Integer.parseInt(token) : token);
sb.delete(0, sb.length());
readingIndex = (c == '[');
}
return dataPath;
}
private static @Nullable Object initFieldValue(List<Object> path, GraphQlResponse response) {
Object value = (response.isValid() ? response.getData() : null);
for (Object segment : path) {
if (value == null) {
return null;
}
if (segment instanceof String) {
Assert.isTrue(value instanceof Map, () -> "Invalid path " + path + ", data: " + response.getData());
value = ((Map<?, ?>) value).getOrDefault(segment, null);
}
else {
Assert.isTrue(value instanceof List, () -> "Invalid path " + path + ", data: " + response.getData());
int index = (int) segment;
value = (index < ((List<?>) value).size()) ? ((List<?>) value).get(index) : null;
|
}
}
return value;
}
/**
* Return errors whose path is at, above, or below the given path.
* @param path the field path to match
* @return errors whose path starts with the dataPath
*/
private static List<ResponseError> initFieldErrors(String path, GraphQlResponse response) {
if (path.isEmpty() || response.getErrors().isEmpty()) {
return Collections.emptyList();
}
return response.getErrors().stream()
.filter((error) -> {
String errorPath = error.getPath();
return (!errorPath.isEmpty() && (errorPath.startsWith(path) || path.startsWith(errorPath)));
})
.collect(Collectors.toList());
}
@Override
public String getPath() {
return this.path;
}
@Override
public List<Object> getParsedPath() {
return this.parsedPath;
}
@SuppressWarnings("unchecked")
@Override
public @Nullable <T> T getValue() {
return (T) this.value;
}
@Override
public List<ResponseError> getErrors() {
return this.fieldErrors;
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\AbstractGraphQlResponse.java
| 1
|
请完成以下Java代码
|
public class User {
private static volatile User instance = null;
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
private final String name;
private final String email;
private final String country;
public static User createWithDefaultCountry(String name, String email) {
return new User(name, email, "Argentina");
}
public static User createWithLoggedInstantiationTime(String name, String email, String country) {
LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
return new User(name, email, country);
}
public static User getSingletonInstance(String name, String email, String country) {
if (instance == null) {
synchronized (User.class) {
if (instance == null) {
instance = new User(name, email, country);
}
}
}
return instance;
}
private User(String name, String email, String country) {
|
this.name = name;
this.email = email;
this.country = country;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-creational-2\src\main\java\com\baeldung\constructorsstaticfactorymethods\entities\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
String textValue = valueFields.getTextValue();
if (textValue == null) {
return null;
}
return UUID.fromString(textValue);
}
@Override
public void setValue(Object value, ValueFields valueFields) {
|
if (value != null) {
valueFields.setTextValue(value.toString());
} else {
valueFields.setTextValue(null);
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return UUID.class.isAssignableFrom(value.getClass());
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\UUIDType.java
| 2
|
请完成以下Java代码
|
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sortierbegriff pro Benutzer.
@param AD_User_SortPref_Hdr_ID Sortierbegriff pro Benutzer */
@Override
public void setAD_User_SortPref_Hdr_ID (int AD_User_SortPref_Hdr_ID)
{
if (AD_User_SortPref_Hdr_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Hdr_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Hdr_ID, Integer.valueOf(AD_User_SortPref_Hdr_ID));
}
/** Get Sortierbegriff pro Benutzer.
@return Sortierbegriff pro Benutzer */
@Override
public int getAD_User_SortPref_Hdr_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Hdr_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Eingabe- oder Anzeige-Fenster
*/
@Override
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Fenster.
@return Eingabe- oder Anzeige-Fenster
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
|
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Konferenz.
@param IsConference Konferenz */
@Override
public void setIsConference (boolean IsConference)
{
set_Value (COLUMNNAME_IsConference, Boolean.valueOf(IsConference));
}
/** Get Konferenz.
@return Konferenz */
@Override
public boolean isConference ()
{
Object oo = get_Value(COLUMNNAME_IsConference);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Hdr.java
| 1
|
请完成以下Java代码
|
public boolean isProcessed()
{
return !editable;
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
@Override
public Map<String, DocumentFieldWidgetType> getWidgetTypesByFieldName()
{
return values.getWidgetTypesByFieldName();
}
@Override
public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName()
{
return values.getViewEditorRenderModeByFieldName();
}
@Override
public List<? extends IViewRow> getIncludedRows()
{
return ImmutableList.of();
}
final void assertEditable()
{
if (!editable)
{
throw new AdempiereException("Row is not editable");
}
}
public PricingConditionsRow copyAndChangeToEditable()
{
if (editable)
{
return this;
}
return toBuilder().editable(true).build();
}
public LookupValuesPage getFieldTypeahead(final String fieldName, final String query)
{
|
return lookups.getFieldTypeahead(fieldName, query);
}
public LookupValuesList getFieldDropdown(final String fieldName)
{
return lookups.getFieldDropdown(fieldName);
}
public BPartnerId getBpartnerId()
{
return BPartnerId.ofRepoId(bpartner.getIdAsInt());
}
public String getBpartnerDisplayName()
{
return bpartner.getDisplayName();
}
public boolean isVendor()
{
return !isCustomer();
}
public CurrencyId getCurrencyId()
{
return CurrencyId.ofRepoId(currency.getIdAsInt());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRow.java
| 1
|
请完成以下Java代码
|
public void setProfileInfo (String ProfileInfo)
{
set_Value (COLUMNNAME_ProfileInfo, ProfileInfo);
}
/** Get Profile.
@return Information to help profiling the system for solving support issues
*/
public String getProfileInfo ()
{
return (String)get_Value(COLUMNNAME_ProfileInfo);
}
/** Set Issue Project.
@param R_IssueProject_ID
Implementation Projects
*/
public void setR_IssueProject_ID (int R_IssueProject_ID)
{
if (R_IssueProject_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, Integer.valueOf(R_IssueProject_ID));
}
/** Get Issue Project.
@return Implementation Projects
*/
public int getR_IssueProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueProject_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistics.
@param StatisticsInfo
Information to help profiling the system for solving support issues
*/
public void setStatisticsInfo (String StatisticsInfo)
{
set_Value (COLUMNNAME_StatisticsInfo, StatisticsInfo);
}
/** Get Statistics.
@return Information to help profiling the system for solving support issues
|
*/
public String getStatisticsInfo ()
{
return (String)get_Value(COLUMNNAME_StatisticsInfo);
}
/** SystemStatus AD_Reference_ID=374 */
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
public void setSystemStatus (String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
public String getSystemStatus ()
{
return (String)get_Value(COLUMNNAME_SystemStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueProject.java
| 1
|
请完成以下Java代码
|
public LookupValue createASILookupValue(final AttributeSetInstanceId attributeSetInstanceId)
{
if (attributeSetInstanceId == null)
{
return null;
}
final I_M_AttributeSetInstance asi = loadOutOfTrx(attributeSetInstanceId.getRepoId(), I_M_AttributeSetInstance.class);
if (asi == null)
{
return null;
}
String description = asi.getDescription();
if (Check.isEmpty(description, true))
{
description = "<" + attributeSetInstanceId.getRepoId() + ">";
}
return IntegerLookupValue.of(attributeSetInstanceId.getRepoId(), description);
}
public LookupValue createBPartnerLookupValue(final BPartnerId bpartnerId)
{
if (bpartnerId == null)
{
return null;
}
final I_C_BPartner bpartner = bpartnersRepo.getById(bpartnerId);
if (bpartner == null)
{
return null;
|
}
final String displayName = bpartner.getValue() + "_" + bpartner.getName();
return IntegerLookupValue.of(bpartner.getC_BPartner_ID(), displayName);
}
public String createUOMLookupValueForProductId(final ProductId productId)
{
if (productId == null)
{
return null;
}
final I_C_UOM uom = productBL.getStockUOM(productId);
if (uom == null)
{
return null;
}
return createUOMLookupValue(uom);
}
public String createUOMLookupValue(final I_C_UOM uom)
{
return translate(uom, I_C_UOM.class).getUOMSymbol();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowLookups.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Printer[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set System Printer.
@param AD_Printer_ID System Printer */
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
/** Get System Printer.
@return System Printer */
public int getAD_Printer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Printer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** IsDirectPrint AD_Reference_ID=319 */
public static final int ISDIRECTPRINT_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISDIRECTPRINT_Yes = "Y";
/** No = N */
public static final String ISDIRECTPRINT_No = "N";
/** Set Direct print.
@param IsDirectPrint
Print without dialog
*/
public void setIsDirectPrint (String IsDirectPrint)
{
set_Value (COLUMNNAME_IsDirectPrint, IsDirectPrint);
}
/** Get Direct print.
@return Print without dialog
*/
public String getIsDirectPrint ()
{
return (String)get_Value(COLUMNNAME_IsDirectPrint);
}
/** Set Drucker.
@param PrinterName
Name of the Printer
*/
public void setPrinterName (String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
|
/** Get Drucker.
@return Name of the Printer
*/
public String getPrinterName ()
{
return (String)get_Value(COLUMNNAME_PrinterName);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getPrinterName());
}
/** PrinterType AD_Reference_ID=540227 */
public static final int PRINTERTYPE_AD_Reference_ID=540227;
/** General = G */
public static final String PRINTERTYPE_General = "G";
/** Fax = F */
public static final String PRINTERTYPE_Fax = "F";
/** Label = L */
public static final String PRINTERTYPE_Label = "L";
/** Set Printer Type.
@param PrinterType Printer Type */
public void setPrinterType (String PrinterType)
{
set_Value (COLUMNNAME_PrinterType, PrinterType);
}
/** Get Printer Type.
@return Printer Type */
public String getPrinterType ()
{
return (String)get_Value(COLUMNNAME_PrinterType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Printer.java
| 1
|
请完成以下Java代码
|
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
|
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_BPartner_Allotment.java
| 1
|
请完成以下Java代码
|
public int getDepth()
{
return this.depth;
}
/**
* 添加一个匹配到的模式串(这个状态对应着这个模式串)
* @param keyword
*/
public void addEmit(String keyword)
{
if (this.emits == null)
{
this.emits = new TreeSet<String>();
}
this.emits.add(keyword);
}
/**
* 添加一些匹配到的模式串
* @param emits
*/
public void addEmit(Collection<String> emits)
{
for (String emit : emits)
{
addEmit(emit);
}
}
/**
* 获取这个节点代表的模式串(们)
* @return
*/
public Collection<String> emit()
{
return this.emits == null ? Collections.<String>emptyList() : this.emits;
}
/**
* 获取failure状态
* @return
*/
public State failure()
{
return this.failure;
}
/**
* 设置failure状态
* @param failState
*/
public void setFailure(State failState)
{
this.failure = failState;
}
/**
* 转移到下一个状态
* @param character 希望按此字符转移
* @param ignoreRootState 是否忽略根节点,如果是根节点自己调用则应该是true,否则为false
* @return 转移结果
*/
private State nextState(Character character, boolean ignoreRootState)
{
State nextState = this.success.get(character);
if (!ignoreRootState && nextState == null && this.depth == 0)
{
nextState = this;
}
return nextState;
}
/**
* 按照character转移,根节点转移失败会返回自己(永远不会返回null)
* @param character
* @return
*/
public State nextState(Character character)
|
{
return nextState(character, false);
}
/**
* 按照character转移,任何节点转移失败会返回null
* @param character
* @return
*/
public State nextStateIgnoreRootState(Character character)
{
return nextState(character, true);
}
public State addState(Character character)
{
State nextState = nextStateIgnoreRootState(character);
if (nextState == null)
{
nextState = new State(this.depth + 1);
this.success.put(character, nextState);
}
return nextState;
}
public Collection<State> getStates()
{
return this.success.values();
}
public Collection<Character> getTransitions()
{
return this.success.keySet();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("State{");
sb.append("depth=").append(depth);
sb.append(", emits=").append(emits);
sb.append(", success=").append(success.keySet());
sb.append(", failure=").append(failure);
sb.append('}');
return sb.toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\trie\State.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ConditionalUnitType getQuantity() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link ConditionalUnitType }
*
*/
public void setQuantity(ConditionalUnitType value) {
this.quantity = value;
}
/**
* Gets the value of the startDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartDate() {
return startDate;
}
/**
* Sets the value of the startDate property.
*
* @param value
|
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartDate(XMLGregorianCalendar value) {
this.startDate = value;
}
/**
* Gets the value of the endDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndDate() {
return endDate;
}
/**
* Sets the value of the endDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndDate(XMLGregorianCalendar value) {
this.endDate = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ExtendedPeriodType.java
| 2
|
请完成以下Java代码
|
public void setValue (String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Warehouse.
@param WarehouseName
|
Warehouse Name
*/
public void setWarehouseName (String WarehouseName)
{
set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName);
}
/** Get Warehouse.
@return Warehouse Name
*/
public String getWarehouseName ()
{
return (String)get_Value(COLUMNNAME_WarehouseName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
if (email != null) {
user.setEmail(email.toLowerCase());
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
userRepository.save(user);
log.debug("Changed Information for User: {}", user);
});
}
@Transactional
public void changePassword(String currentClearTextPassword, String newPassword) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<AdminUserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAll(pageable).map(AdminUserDTO::new);
}
@Transactional(readOnly = true)
|
public Page<UserDTO> getAllPublicUsers(Pageable pageable) {
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
});
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
@Transactional(readOnly = true)
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).toList();
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\service\UserService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("admin123")).roles("ADMIN")
.and()
.withUser("hamdamboy").password(passwordEncoder().encode("dan123")).roles("USER");
}
/**
* This is Http security, consists of all incoming requests.
* **/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
|
.authorizeRequests()
// .anyRequest().permitAll() if you fix all permission values, then remove all conditions.
.antMatchers("/index.html").permitAll()
.antMatchers("/profile/**").authenticated()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER")
.and()
.httpBasic();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\2. SpringSecRoleBased\src\main\java\spring\security\security\SpringSecurity.java
| 2
|
请完成以下Java代码
|
public abstract class GenForm
{
private boolean m_selectionActive = true;
private String title;
private int reportEngineType;
private MPrintFormat printFormat = null;
private String askPrintMsg;
private Trx trx;
private ProcessInfo pi;
/** User selection */
private ArrayList<Integer> selection = null;
public void dynInit() throws Exception
{
}
public abstract void configureMiniTable(IMiniTable miniTable);
public abstract void saveSelection(IMiniTable miniTable);
public void validate()
{
}
public String generate()
{
return null;
}
public void executeQuery()
{
}
public Trx getTrx() {
return trx;
}
public void setTrx(Trx trx) {
this.trx = trx;
}
public ProcessInfo getProcessInfo() {
return pi;
}
public void setProcessInfo(ProcessInfo pi) {
this.pi = pi;
|
}
public boolean isSelectionActive() {
return m_selectionActive;
}
public void setSelectionActive(boolean active) {
m_selectionActive = active;
}
public ArrayList<Integer> getSelection() {
return selection;
}
public void setSelection(ArrayList<Integer> selection) {
this.selection = selection;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getReportEngineType() {
return reportEngineType;
}
public void setReportEngineType(int reportEngineType) {
this.reportEngineType = reportEngineType;
}
public MPrintFormat getPrintFormat() {
return this.printFormat;
}
public void setPrintFormat(MPrintFormat printFormat) {
this.printFormat = printFormat;
}
public String getAskPrintMsg() {
return askPrintMsg;
}
public void setAskPrintMsg(String askPrintMsg) {
this.askPrintMsg = askPrintMsg;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\GenForm.java
| 1
|
请完成以下Java代码
|
public class TransactionDependentExecutionListenerExecutionScope {
protected final String processInstanceId;
protected final String executionId;
protected final FlowElement flowElement;
protected final Map<String, Object> executionVariables;
protected final Map<String, Object> customPropertiesMap;
public TransactionDependentExecutionListenerExecutionScope(
String processInstanceId,
String executionId,
FlowElement flowElement,
Map<String, Object> executionVariables,
Map<String, Object> customPropertiesMap
) {
this.processInstanceId = processInstanceId;
this.executionId = executionId;
this.flowElement = flowElement;
this.executionVariables = executionVariables;
this.customPropertiesMap = customPropertiesMap;
}
public String getProcessInstanceId() {
return processInstanceId;
|
}
public String getExecutionId() {
return executionId;
}
public FlowElement getFlowElement() {
return flowElement;
}
public Map<String, Object> getExecutionVariables() {
return executionVariables;
}
public Map<String, Object> getCustomPropertiesMap() {
return customPropertiesMap;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\TransactionDependentExecutionListenerExecutionScope.java
| 1
|
请完成以下Java代码
|
public void setValues(PreparedStatement ps, int i) throws SQLException {
TsKvEntity tsKvEntity = entities.get(i);
ps.setObject(1, tsKvEntity.getEntityId());
ps.setInt(2, tsKvEntity.getKey());
ps.setLong(3, tsKvEntity.getTs());
if (tsKvEntity.getBooleanValue() != null) {
ps.setBoolean(4, tsKvEntity.getBooleanValue());
ps.setBoolean(9, tsKvEntity.getBooleanValue());
} else {
ps.setNull(4, Types.BOOLEAN);
ps.setNull(9, Types.BOOLEAN);
}
ps.setString(5, replaceNullChars(tsKvEntity.getStrValue()));
ps.setString(10, replaceNullChars(tsKvEntity.getStrValue()));
if (tsKvEntity.getLongValue() != null) {
ps.setLong(6, tsKvEntity.getLongValue());
ps.setLong(11, tsKvEntity.getLongValue());
} else {
ps.setNull(6, Types.BIGINT);
ps.setNull(11, Types.BIGINT);
}
|
if (tsKvEntity.getDoubleValue() != null) {
ps.setDouble(7, tsKvEntity.getDoubleValue());
ps.setDouble(12, tsKvEntity.getDoubleValue());
} else {
ps.setNull(7, Types.DOUBLE);
ps.setNull(12, Types.DOUBLE);
}
ps.setString(8, replaceNullChars(tsKvEntity.getJsonValue()));
ps.setString(13, replaceNullChars(tsKvEntity.getJsonValue()));
}
@Override
public int getBatchSize() {
return entities.size();
}
});
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\insert\sql\SqlInsertTsRepository.java
| 1
|
请完成以下Java代码
|
public class DelegateActivitiEventListener extends BaseDelegateEventListener {
protected String className;
protected ActivitiEventListener delegateInstance;
protected boolean failOnException = false;
public DelegateActivitiEventListener(String className, Class<?> entityClass) {
this.className = className;
setEntityClass(entityClass);
}
@Override
public void onEvent(ActivitiEvent event) {
if (isValidEvent(event)) {
getDelegateInstance().onEvent(event);
}
}
@Override
public boolean isFailOnException() {
if (delegateInstance != null) {
return delegateInstance.isFailOnException();
}
return failOnException;
}
|
protected ActivitiEventListener getDelegateInstance() {
if (delegateInstance == null) {
Object instance = ReflectUtil.instantiate(className);
if (instance instanceof ActivitiEventListener) {
delegateInstance = (ActivitiEventListener) instance;
} else {
// Force failing of the listener invocation, since the delegate
// cannot be created
failOnException = true;
throw new ActivitiIllegalArgumentException(
"Class " + className + " does not implement " + ActivitiEventListener.class.getName()
);
}
}
return delegateInstance;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\DelegateActivitiEventListener.java
| 1
|
请完成以下Java代码
|
public abstract class ForwardingInvoiceGenerateResult extends ForwardingObject implements IInvoiceGenerateResult
{
private final IInvoiceGenerateResult delegate;
public ForwardingInvoiceGenerateResult(final IInvoiceGenerateResult delegate)
{
super();
Check.assumeNotNull(delegate, "delegate not null");
this.delegate = delegate;
}
@Override
protected final IInvoiceGenerateResult delegate()
{
return delegate;
}
@Override
public int getInvoiceCount()
{
return delegate().getInvoiceCount();
}
@Override
public List<I_C_Invoice> getC_Invoices()
{
return delegate().getC_Invoices();
}
@Override
public int getNotificationCount()
{
return delegate().getNotificationCount();
}
@Override
public List<I_AD_Note> getNotifications()
{
return delegate().getNotifications();
}
@Override
public String getNotificationsWhereClause()
|
{
return delegate().getNotificationsWhereClause();
}
@Override
public void addInvoice(final I_C_Invoice invoice)
{
delegate().addInvoice(invoice);
}
@Override
public void addNotifications(final List<I_AD_Note> notifications)
{
delegate().addNotifications(notifications);
}
@Override
public String getSummary(final Properties ctx)
{
return delegate().getSummary(ctx);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ForwardingInvoiceGenerateResult.java
| 1
|
请完成以下Java代码
|
public static Set<OrderLineId> getOrderLineIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet());
}
OrderId orderId;
OrderLineId orderLineId;
private OrderAndLineId(@NonNull final OrderId orderId, @NonNull final OrderLineId orderLineId)
{
this.orderId = orderId;
this.orderLineId = orderLineId;
}
public int getOrderRepoId()
{
return orderId.getRepoId();
}
public int getOrderLineRepoId()
{
return orderLineId.getRepoId();
}
public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2)
{
return Objects.equals(o1, o2);
|
}
@JsonValue
public String toJson()
{
return orderId.getRepoId() + "_" + orderLineId.getRepoId();
}
@JsonCreator
public static OrderAndLineId ofJson(@NonNull String json)
{
try
{
final int idx = json.indexOf("_");
return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1)));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java
| 1
|
请完成以下Java代码
|
public boolean isNotExclusive() {
return notExclusive;
}
public void setNotExclusive(boolean notExclusive) {
this.notExclusive = notExclusive;
}
public boolean isAsynchronousLeaveExclusive() {
return !asynchronousLeaveNotExclusive;
}
public void setAsynchronousLeaveExclusive(boolean exclusive) {
this.asynchronousLeaveNotExclusive = !exclusive;
}
public boolean isAsynchronousLeaveNotExclusive() {
return asynchronousLeaveNotExclusive;
}
public void setAsynchronousLeaveNotExclusive(boolean asynchronousLeaveNotExclusive) {
this.asynchronousLeaveNotExclusive = asynchronousLeaveNotExclusive;
}
public Object getBehavior() {
return behavior;
}
public void setBehavior(Object behavior) {
this.behavior = behavior;
}
public List<SequenceFlow> getIncomingFlows() {
return incomingFlows;
}
public void setIncomingFlows(List<SequenceFlow> incomingFlows) {
this.incomingFlows = incomingFlows;
}
public List<SequenceFlow> getOutgoingFlows() {
|
return outgoingFlows;
}
public void setOutgoingFlows(List<SequenceFlow> outgoingFlows) {
this.outgoingFlows = outgoingFlows;
}
public void setValues(FlowNode otherNode) {
super.setValues(otherNode);
setAsynchronous(otherNode.isAsynchronous());
setNotExclusive(otherNode.isNotExclusive());
setAsynchronousLeave(otherNode.isAsynchronousLeave());
setAsynchronousLeaveNotExclusive(otherNode.isAsynchronousLeaveNotExclusive());
if (otherNode.getIncomingFlows() != null) {
setIncomingFlows(otherNode.getIncomingFlows()
.stream()
.map(SequenceFlow::clone)
.collect(Collectors.toList()));
}
if (otherNode.getOutgoingFlows() != null) {
setOutgoingFlows(otherNode.getOutgoingFlows()
.stream()
.map(SequenceFlow::clone)
.collect(Collectors.toList()));
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowNode.java
| 1
|
请完成以下Java代码
|
public Builder setClosableMode(@NonNull final ClosableMode closableMode)
{
this.closableMode = closableMode;
return this;
}
public Builder setCaptionMode(@NonNull final CaptionMode captionMode)
{
this.captionMode = captionMode;
return this;
}
public boolean isValid()
{
return invalidReason == null;
}
public boolean isInvalid()
{
return invalidReason != null;
}
public boolean isNotEmpty()
|
{
return streamElementBuilders().findAny().isPresent();
}
private Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return columnsBuilders.stream().flatMap(DocumentLayoutColumnDescriptor.Builder::streamElementBuilders);
}
public Builder setExcludeSpecialFields()
{
streamElementBuilders().forEach(elementBuilder -> elementBuilder.setExcludeSpecialFields());
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSectionDescriptor.java
| 1
|
请完成以下Java代码
|
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version
Version of the table definition
*/
public void setVersion (String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
public String getVersion ()
{
|
return (String)get_Value(COLUMNNAME_Version);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Format.java
| 1
|
请完成以下Java代码
|
public boolean add(Target t) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("add()", "collection is immutable");
}
else {
if (!contains(t)) {
performAddOperation(referenceSourceParentElement, t);
}
return true;
}
}
public boolean remove(Object o) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("remove()", "collection is immutable");
}
else {
ModelUtil.ensureInstanceOf(o, ModelElementInstanceImpl.class);
performRemoveOperation(referenceSourceParentElement, o);
return true;
}
}
public boolean containsAll(Collection<?> c) {
Collection<Target> modelElementCollection = ModelUtil.getModelElementCollection(getView(referenceSourceParentElement), referenceSourceParentElement.getModelInstance());
return modelElementCollection.containsAll(c);
}
public boolean addAll(Collection<? extends Target> c) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("addAll()", "collection is immutable");
}
else {
boolean result = false;
for (Target o: c) {
result |= add(o);
}
return result;
}
|
}
public boolean removeAll(Collection<?> c) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("removeAll()", "collection is immutable");
}
else {
boolean result = false;
for (Object o: c) {
result |= remove(o);
}
return result;
}
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("clear()", "collection is immutable");
}
else {
Collection<DomElement> view = new ArrayList<DomElement>();
for (Source referenceSourceElement : referenceSourceCollection.get(referenceSourceParentElement)) {
view.add(referenceSourceElement.getDomElement());
}
performClearOperation(referenceSourceParentElement, view);
}
}
};
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ElementReferenceCollectionImpl.java
| 1
|
请完成以下Java代码
|
public void applyTo(Properties properties) {
put(properties, LoggingSystemProperty.LOG_PATH, this.path);
put(properties, LoggingSystemProperty.LOG_FILE, toString());
}
private void put(Properties properties, LoggingSystemProperty property, @Nullable String value) {
if (StringUtils.hasLength(value)) {
properties.put(property.getEnvironmentVariableName(), value);
}
}
@Override
public String toString() {
if (StringUtils.hasLength(this.file)) {
return this.file;
}
return new File(this.path, "spring.log").getPath();
}
/**
* Get a {@link LogFile} from the given Spring {@link Environment}.
|
* @param propertyResolver the {@link PropertyResolver} used to obtain the logging
* properties
* @return a {@link LogFile} or {@code null} if the environment didn't contain any
* suitable properties
*/
public static @Nullable LogFile get(PropertyResolver propertyResolver) {
String file = propertyResolver.getProperty(FILE_NAME_PROPERTY);
String path = propertyResolver.getProperty(FILE_PATH_PROPERTY);
if (StringUtils.hasLength(file) || StringUtils.hasLength(path)) {
return new LogFile(file, path);
}
return null;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LogFile.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<String> add(@RequestBody AiOcr aiOcr){
Object aiOcrList = redisUtil.get(AI_OCR_REDIS_KEY);
aiOcr.setId(UUID.randomUUID().toString().replace("-",""));
if(null == aiOcrList){
List<AiOcr> list = new ArrayList<>();
list.add(aiOcr);
redisUtil.set(AI_OCR_REDIS_KEY, JSONObject.toJSONString(list));
}else{
List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrList.toString(), AiOcr.class);
aiOcrs.add(aiOcr);
redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrs));
}
return Result.OK("添加成功");
}
@PutMapping("/edit")
public Result<String> updateById(@RequestBody AiOcr aiOcr){
Object aiOcrList = redisUtil.get(AI_OCR_REDIS_KEY);
if(null != aiOcrList){
List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrList.toString(), AiOcr.class);
aiOcrs.forEach(item->{
if(item.getId().equals(aiOcr.getId())){
BeanUtils.copyProperties(aiOcr,item);
}
});
redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrs));
}else{
return Result.OK("编辑失败,未找到该数据");
}
return Result.OK("编辑成功");
}
|
@DeleteMapping("/deleteById")
public Result<String> deleteById(@RequestBody AiOcr aiOcr){
Object aiOcrObj = redisUtil.get(AI_OCR_REDIS_KEY);
if(null != aiOcrObj){
List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrObj.toString(), AiOcr.class);
List<AiOcr> aiOcrList = new ArrayList<>();
for(AiOcr ocr: aiOcrs){
if(!ocr.getId().equals(aiOcr.getId())){
aiOcrList.add(ocr);
}
}
if(CollectionUtils.isNotEmpty(aiOcrList)){
redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrList));
}else{
redisUtil.removeAll(AI_OCR_REDIS_KEY);
}
}else{
return Result.OK("删除失败,未找到该数据");
}
return Result.OK("删除成功");
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\ocr\controller\AiOcrController.java
| 2
|
请完成以下Java代码
|
public void setQtyPromised_TU_ThisWeek (java.math.BigDecimal QtyPromised_TU_ThisWeek)
{
throw new IllegalArgumentException ("QtyPromised_TU_ThisWeek is virtual column"); }
/** Get Zusagbar TU (diese Woche).
@return Zusagbar TU (diese Woche) */
@Override
public java.math.BigDecimal getQtyPromised_TU_ThisWeek ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_ThisWeek);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quantity to Order.
@param QtyToOrder Quantity to Order */
@Override
public void setQtyToOrder (java.math.BigDecimal QtyToOrder)
{
set_Value (COLUMNNAME_QtyToOrder, QtyToOrder);
}
/** Get Quantity to Order.
@return Quantity to Order */
@Override
public java.math.BigDecimal getQtyToOrder ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quantity to Order (TU).
@param QtyToOrder_TU Quantity to Order (TU) */
|
@Override
public void setQtyToOrder_TU (java.math.BigDecimal QtyToOrder_TU)
{
set_Value (COLUMNNAME_QtyToOrder_TU, QtyToOrder_TU);
}
/** Get Quantity to Order (TU).
@return Quantity to Order (TU) */
@Override
public java.math.BigDecimal getQtyToOrder_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder_TU);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate.java
| 1
|
请完成以下Java代码
|
public Legend getLegend() {
return legend;
}
public void setLegend(Legend legend) {
this.legend = legend;
}
public Grid getGrid() {
return grid;
}
public void setGrid(Grid grid) {
this.grid = grid;
}
public Toolbox getToolbox() {
return toolbox;
}
public void setToolbox(Toolbox toolbox) {
this.toolbox = toolbox;
}
public XAxis getxAxis() {
return xAxis;
}
|
public void setxAxis(XAxis xAxis) {
this.xAxis = xAxis;
}
public YAxis getyAxis() {
return yAxis;
}
public void setyAxis(YAxis yAxis) {
this.yAxis = yAxis;
}
public List<Serie> getSeries() {
return series;
}
public void setSeries(List<Serie> series) {
this.series = series;
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\api\model\jmh\Option.java
| 1
|
请完成以下Java代码
|
public void setMargin (Insets m)
{
if (m_textArea != null)
m_textArea.setMargin(m);
} // setMargin
/**
* AddFocusListener
* @param l
*/
@Override
public void addFocusListener (FocusListener l)
{
if (m_textArea == null) // during init
super.addFocusListener(l);
else
m_textArea.addFocusListener(l);
}
/**
* Add Text Mouse Listener
* @param l
*/
@Override
public void addMouseListener (MouseListener l)
{
m_textArea.addMouseListener(l);
}
/**
* Add Text Key Listener
* @param l
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textArea.addKeyListener(l);
}
/**
* Add Text Input Method Listener
* @param l
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textArea.addInputMethodListener(l);
}
/**
* Get text Input Method Requests
* @return requests
|
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textArea.getInputMethodRequests();
}
/**
* Set Text Input Verifier
* @param l
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textArea.setInputVerifier(l);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // CTextArea
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java
| 1
|
请完成以下Java代码
|
public class DeviceProfileCacheKey implements VersionedCacheKey {
@Serial
private static final long serialVersionUID = 8220455917177676472L;
private final TenantId tenantId;
private final String name;
private final DeviceProfileId deviceProfileId;
private final boolean defaultProfile;
private final String provisionDeviceKey;
private DeviceProfileCacheKey(TenantId tenantId, String name, DeviceProfileId deviceProfileId, boolean defaultProfile, String provisionDeviceKey) {
this.tenantId = tenantId;
this.name = name;
this.deviceProfileId = deviceProfileId;
this.defaultProfile = defaultProfile;
this.provisionDeviceKey = provisionDeviceKey;
}
public static DeviceProfileCacheKey forName(TenantId tenantId, String name) {
return new DeviceProfileCacheKey(tenantId, name, null, false, null);
}
public static DeviceProfileCacheKey forId(DeviceProfileId id) {
return new DeviceProfileCacheKey(null, null, id, false, null);
}
public static DeviceProfileCacheKey forDefaultProfile(TenantId tenantId) {
return new DeviceProfileCacheKey(tenantId, null, null, true, null);
}
public static DeviceProfileCacheKey forProvisionKey(String provisionDeviceKey) {
return new DeviceProfileCacheKey(null, null, null, false, provisionDeviceKey);
}
/**
* IMPORTANT: Method toString() has to return unique value, if you add additional field to this class, please also refactor toString().
*/
@Override
|
public String toString() {
if (deviceProfileId != null) {
return deviceProfileId.toString();
} else if (defaultProfile) {
return tenantId.toString();
} else if (StringUtils.isNotEmpty(provisionDeviceKey)) {
return provisionDeviceKey;
}
return tenantId + "_" + name;
}
@Override
public boolean isVersioned() {
return deviceProfileId != null;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\device\DeviceProfileCacheKey.java
| 1
|
请完成以下Java代码
|
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getReportObject() {
return reportObject;
}
public void setReportObject(String reportObject) {
this.reportObject = reportObject;
}
public Integer getReportStatus() {
return reportStatus;
}
public void setReportStatus(Integer reportStatus) {
this.reportStatus = reportStatus;
}
public Integer getHandleStatus() {
return handleStatus;
}
public void setHandleStatus(Integer handleStatus) {
this.handleStatus = handleStatus;
}
public String getNote() {
return note;
|
}
public void setNote(String note) {
this.note = note;
}
@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(", reportType=").append(reportType);
sb.append(", reportMemberName=").append(reportMemberName);
sb.append(", createTime=").append(createTime);
sb.append(", reportObject=").append(reportObject);
sb.append(", reportStatus=").append(reportStatus);
sb.append(", handleStatus=").append(handleStatus);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsMemberReport.java
| 1
|
请完成以下Java代码
|
public String getUserEventId() {
return userEventId;
}
public long getEventNanoTime() {
return eventNanoTime;
}
public void setEventNanoTime(long eventNanoTime) {
this.eventNanoTime = eventNanoTime;
}
public long getGlobalSequenceNumber() {
return globalSequenceNumber;
}
public void setGlobalSequenceNumber(long globalSequenceNumber) {
this.globalSequenceNumber = globalSequenceNumber;
}
@Override
public int compareTo(UserEvent other) {
return Long.compare(this.globalSequenceNumber, other.globalSequenceNumber);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
|
return true;
}
if (!(obj instanceof UserEvent)) {
return false;
}
UserEvent userEvent = (UserEvent) obj;
return this.globalSequenceNumber == userEvent.globalSequenceNumber;
}
@Override
public int hashCode() {
return Objects.hash(globalSequenceNumber);
}
}
|
repos\tutorials-master\apache-kafka\src\main\java\com\baeldung\kafka\message\ordering\payload\UserEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthServerConfigurer extends AuthorizationServerConfigurerAdapter {
@Value("${jwt.certificate.store.file}")
private Resource keystore;
@Value("${jwt.certificate.store.password}")
private String keystorePassword;
@Value("${jwt.certificate.key.alias}")
private String keyAlias;
@Value("${jwt.certificate.key.password}")
private String keyPassword;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
public void configure(
ClientDetailsServiceConfigurer clients)
throws Exception {
clients
.inMemory()
.withClient("authserver")
.secret(passwordEncoder.encode("passwordforauthserver"))
.redirectUris("http://localhost:8080/login")
.authorizedGrantTypes("authorization_code",
"refresh_token")
.scopes("myscope")
.autoApprove(true)
.accessTokenValiditySeconds(30)
.refreshTokenValiditySeconds(1800);
}
|
@Override
public void configure(
AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.accessTokenConverter(jwtAccessTokenConverter())
.userDetailsService(userDetailsService);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
keystore, keystorePassword.toCharArray());
KeyPair keyPair = keyStoreKeyFactory.getKeyPair(
keyAlias, keyPassword.toCharArray());
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setKeyPair(keyPair);
return converter;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-security\auth-server\src\main\java\com\baeldung\config\AuthServerConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class ContractChangeParameters
{
@NonNull
Timestamp changeDate;
boolean isCloseInvoiceCandidate;
@Default
boolean isCreditOpenInvoices = false;
String terminationMemo;
String terminationReason;
@Default
String action = ChangeTerm_ACTION_Cancel;
public boolean isVoidSingleContract()
{
return ChangeTerm_ACTION_VoidSingleContract.equals(getAction());
}
}
/**
* Cancels the given <code>term</code> at the given <code>date</code>.
* <p>
* <b>IMPORTANT:</b> Currently, we only create term-change orders if the term has a normal order to begin with!<br>
* In other words, a customer won't be charged if their {@link de.metas.contracts.model.I_C_Flatrate_Conditions#COLUMNNAME_IsNewTermCreatesOrder} value is <code>='N'</code>.
*
* <p>
* Note that a canceled term won't be invoiced further, as the term's <code>C_Invoice_Candidate</code> will be updated and that their <code>QtyOrdered</code> value will be set to their
* <code>QtyInvoiced</code> value. However, existing invoices won't be touched by the cancellation of a term.
*
* @param term the contract term that shall be canceled. If <code>term</code> already has a successor (i.e. {@link I_C_Flatrate_Term#getC_FlatrateTerm_Next_ID()} > 0), then the successor-term is
* also canceled. After successful termination,
|
* <ul>
* <li>the term's {@link I_C_Flatrate_Term#COLUMNNAME_ContractStatus} is set to <code>Qu</code> ("quit")</li> <li>the <code>C_Invoice_Candidate</code> records that reference the term,
* are invalidated.</li> <li>the term's {@link I_C_Flatrate_Term#COLUMNNAME_EndDate} is updated according to the <code>changeDate</code> parameter. If the term's StartDate is after
* <code>changeDate</code>, then the EndDate will be set to the StartDate. If the terms EndDate is before <code>changeDate</code>, then the EndDate won't be updated</li>
* </ul>
*
* @throws SubscriptionChangeException if <code>changeDate</code> is before the term's EndDate and if there is no {@link de.metas.contracts.model.I_C_Contract_Change} record for that date
*/
void cancelContract(@NonNull I_C_Flatrate_Term term, @NonNull ContractChangeParameters contractChangeParameters);
/**
* ending naturally a contract
* Actually is just setting the status to Ending contract
*/
void endContract(I_C_Flatrate_Term term);
boolean isCanceledContract(I_C_Flatrate_Term currentTerm);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\IContractChangeBL.java
| 2
|
请完成以下Java代码
|
public class LaneExport implements BpmnXMLConstants {
public static void writeLanes(Process process, XMLStreamWriter xtw) throws Exception {
if (!process.getLanes().isEmpty()) {
xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_LANESET, BPMN2_NAMESPACE);
xtw.writeAttribute(ATTRIBUTE_ID, "laneSet_" + process.getId());
for (Lane lane : process.getLanes()) {
xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_LANE, BPMN2_NAMESPACE);
xtw.writeAttribute(ATTRIBUTE_ID, lane.getId());
if (StringUtils.isNotEmpty(lane.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, lane.getName());
}
boolean didWriteExtensionStartElement = BpmnXMLUtil.writeExtensionElements(lane, false, xtw);
|
if (didWriteExtensionStartElement) {
xtw.writeEndElement();
}
for (String flowNodeRef : lane.getFlowReferences()) {
xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_FLOWNODE_REF, BPMN2_NAMESPACE);
xtw.writeCharacters(flowNodeRef);
xtw.writeEndElement();
}
xtw.writeEndElement();
}
xtw.writeEndElement();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\export\LaneExport.java
| 1
|
请完成以下Java代码
|
public void init()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
CopyRecordFactory.enableForTableName(org.compiere.model.I_AD_User.Table_Name);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { org.compiere.model.I_AD_User.COLUMNNAME_Firstname, org.compiere.model.I_AD_User.COLUMNNAME_Lastname })
@CalloutMethod(columnNames = { org.compiere.model.I_AD_User.COLUMNNAME_Firstname, org.compiere.model.I_AD_User.COLUMNNAME_Lastname })
public void setName(final org.compiere.model.I_AD_User user)
{
final String contactName = IUserBL.buildContactName(user.getFirstname(), user.getLastname());
if (Check.isEmpty(contactName))
{
return; // make sure not to overwrite an existing name with an empty string!
}
user.setName(contactName);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { org.compiere.model.I_AD_User.COLUMNNAME_C_Title_ID })
public void setTitle(final org.compiere.model.I_AD_User user)
{
if (user.getC_Title_ID() > 0)
{
final String title = extractTitle(user);
user.setTitle(title);
}
else
{
user.setTitle("");
}
}
private String extractTitle(org.compiere.model.I_AD_User user)
{
String userTitle = "";
final Optional<Language> languageForModel = bpPartnerService.getLanguageForModel(user);
final Title title = titleRepository.getByIdAndLang(TitleId.ofRepoId(user.getC_Title_ID()), languageForModel.orElse(null));
if (title != null)
{
userTitle = title.getTitle();
}
return userTitle;
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifUIAction = true)
public void afterSave(@NonNull final I_AD_User userRecord)
|
{
final BPartnerId bPartnerId = BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID());
if (bPartnerId == null)
{
//nothing to do
return;
}
bpPartnerService.updateNameAndGreetingFromContacts(bPartnerId);
}
@ModelChange(timings = {ModelValidator.TYPE_BEFORE_DELETE},
ifUIAction = true)
public void beforeDelete_UIAction(@NonNull final I_AD_User userRecord)
{
final UserId loggedInUserId = Env.getLoggedUserIdIfExists().orElse(null);
if (loggedInUserId != null && loggedInUserId.getRepoId() == userRecord.getAD_User_ID())
{
throw new AdempiereException(MSG_UserDelete)
.setParameter("AD_User_ID", userRecord.getAD_User_ID())
.setParameter("Name", userRecord.getName());
}
userBL.deleteUserDependency(userRecord);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE },
ifUIAction = true)
public void afterDelete(@NonNull final I_AD_User userRecord)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID());
if (bPartnerId == null)
{
//nothing to do
return;
}
bpPartnerService.updateNameAndGreetingFromContacts(bPartnerId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\AD_User.java
| 1
|
请完成以下Java代码
|
public Builder setSmallSize()
{
return setSmallSize(true);
}
/**
* Advice the builder if a small size button is needed or not.
*
* @param smallSize true if small size button shall be created
*/
public Builder setSmallSize(final boolean smallSize)
{
this.smallSize = smallSize;
return this;
}
private boolean isSmallSize()
{
return smallSize;
}
/**
* Advice the builder to set given {@link Insets} to action's button.
*
* @param buttonInsets
* @see AbstractButton#setMargin(Insets)
*/
public Builder setButtonInsets(final Insets buttonInsets)
{
this.buttonInsets = buttonInsets;
|
return this;
}
private final Insets getButtonInsets()
{
return buttonInsets;
}
/**
* Sets the <code>defaultCapable</code> property, which determines whether the button can be made the default button for its root pane.
*
* @param defaultCapable
* @return
* @see JButton#setDefaultCapable(boolean)
*/
public Builder setButtonDefaultCapable(final boolean defaultCapable)
{
buttonDefaultCapable = defaultCapable;
return this;
}
private Boolean getButtonDefaultCapable()
{
return buttonDefaultCapable;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AppsAction.java
| 1
|
请完成以下Java代码
|
public static DocumentFilter createHUIdsFilter(final boolean considerAttributes)
{
return DocumentFilter.singleParameterFilter(HU_IDS_FilterId, PARAM_ConsiderAttributes, Operator.EQUAL, considerAttributes);
}
private static class HUIdsFilterConverter implements SqlDocumentFilterConverter
{
public static final HUIdsFilterConverter instance = new HUIdsFilterConverter();
@Override
public boolean canConvert(final String filterId)
{
return Objects.equals(filterId, HU_IDS_FilterId);
}
@Override
public FilterSql getSql(
final DocumentFilter filter,
final SqlOptions sqlOpts,
final SqlDocumentFilterConverterContext context)
{
if (!HU_IDS_FilterId.equals(filter.getFilterId()))
{
throw new AdempiereException("Invalid filterId " + filter.getFilterId() + ". Expected: " + HU_IDS_FilterId);
}
final int shipmentScheduleId = context.getPropertyAsInt(PARAM_CurrentShipmentScheduleId, -1);
if (shipmentScheduleId <= 0)
{
return FilterSql.allowNoneWithComment("no shipment schedule");
}
final boolean considerAttributes = filter.getParameterValueAsBoolean(PARAM_ConsiderAttributes, false);
final List<Integer> huIds = retrieveAvailableHuIdsForCurrentShipmentScheduleId(shipmentScheduleId, considerAttributes);
if (huIds.isEmpty())
{
return FilterSql.allowNoneWithComment("no M_HU_IDs");
}
|
return FilterSql.ofWhereClause(sqlOpts.getTableNameOrAlias() + "." + I_M_HU.COLUMNNAME_M_HU_ID + " IN " + DB.buildSqlList(huIds));
}
}
private static List<Integer> retrieveAvailableHuIdsForCurrentShipmentScheduleId(
final int shipmentScheduleId,
final boolean considerAttributes)
{
final IHUPickingSlotBL huPickingSlotBL = Services.get(IHUPickingSlotBL.class);
final ShipmentScheduleId sScheduleID = ShipmentScheduleId.ofRepoId(shipmentScheduleId);
final RetrieveAvailableHUIdsToPickRequest request = RetrieveAvailableHUIdsToPickRequest
.builder()
.scheduleId(sScheduleID)
.considerAttributes(considerAttributes)
.onlyTopLevel(false)
.build();
return huPickingSlotBL.retrieveAvailableHUIdsToPickForShipmentSchedule(request)
.stream()
.map(HuId::getRepoId)
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\HUsToPickViewFilters.java
| 1
|
请完成以下Java代码
|
public class TaskUpdatedListenerDelegate implements ActivitiEventListener {
private List<TaskRuntimeEventListener<TaskUpdatedEvent>> taskUpdatedListeners;
private ToAPITaskUpdatedEventConverter taskUpdatedEventConverter;
public TaskUpdatedListenerDelegate(
List<TaskRuntimeEventListener<TaskUpdatedEvent>> taskCreatedListeners,
ToAPITaskUpdatedEventConverter taskCreatedEventConverter
) {
this.taskUpdatedListeners = taskCreatedListeners;
this.taskUpdatedEventConverter = taskCreatedEventConverter;
}
@Override
public void onEvent(ActivitiEvent event) {
|
if (event instanceof ActivitiEntityEvent) {
taskUpdatedEventConverter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (TaskRuntimeEventListener<TaskUpdatedEvent> listener : taskUpdatedListeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskUpdatedListenerDelegate.java
| 1
|
请完成以下Java代码
|
public MinMaxDescriptor toMinMaxDescriptor()
{
return MinMaxDescriptor.builder()
.min(min.getStockQty().toBigDecimal())
.max(max.getStockQty().toBigDecimal())
.highPriority(highPriority)
.build();
}
@Builder
@Value
public static class Identifier
{
@NonNull
ProductId productId;
@NonNull
WarehouseId warehouseId;
@Nullable
LocatorId locatorId;
public static Identifier of(@NonNull final WarehouseId warehouseId, @Nullable final LocatorId locatorId, @NonNull final ProductId productId)
|
{
return builder()
.warehouseId(warehouseId)
.locatorId(locatorId)
.productId(productId)
.build();
}
public static Identifier of(@NonNull final WarehouseId warehouseId, @NonNull final ProductId productId)
{
return builder()
.warehouseId(warehouseId)
.productId(productId)
.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\replenish\ReplenishInfo.java
| 1
|
请完成以下Java代码
|
public String toString()
{
if (any)
{
return MoreObjects.toStringHelper(this).addValue("ANY").toString();
}
else
{
return MoreObjects.toStringHelper(this).add("pattern", pattern).toString();
}
}
public boolean isMatching(@NonNull final DataEntryTab tab)
{
return isMatching(tab.getInternalName())
|| isMatching(tab.getCaption());
}
public boolean isMatching(@NonNull final DataEntrySubTab subTab)
{
return isMatching(subTab.getInternalName())
|| isMatching(subTab.getCaption());
}
public boolean isMatching(@NonNull final DataEntrySection section)
{
return isMatching(section.getInternalName())
|| isMatching(section.getCaption());
}
public boolean isMatching(@NonNull final DataEntryLine line)
{
return isMatching(String.valueOf(line.getSeqNo()));
}
public boolean isMatching(@NonNull final DataEntryField field)
{
return isAny()
|| isMatching(field.getCaption());
}
private boolean isMatching(final ITranslatableString trl)
{
if (isAny())
{
return true;
}
if (isMatching(trl.getDefaultValue()))
{
return true;
|
}
for (final String adLanguage : trl.getAD_Languages())
{
if (isMatching(trl.translate(adLanguage)))
{
return true;
}
}
return false;
}
@VisibleForTesting
boolean isMatching(final String name)
{
if (isAny())
{
return true;
}
final String nameNorm = normalizeString(name);
if (nameNorm == null)
{
return false;
}
return pattern.equalsIgnoreCase(nameNorm);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\NamePattern.java
| 1
|
请完成以下Java代码
|
public int getReferenced_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Referenced_Record_ID);
}
@Override
public void setS_ExternalReference_ID (final int S_ExternalReference_ID)
{
if (S_ExternalReference_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExternalReference_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExternalReference_ID, S_ExternalReference_ID);
}
@Override
public int getS_ExternalReference_ID()
{
return get_ValueAsInt(COLUMNNAME_S_ExternalReference_ID);
}
/**
* Type AD_Reference_ID=541127
* Reference name: ExternalReferenceType
*/
public static final int TYPE_AD_Reference_ID=541127;
/** UserID = UserID */
public static final String TYPE_UserID = "UserID";
/** IssueID = IssueID */
public static final String TYPE_IssueID = "IssueID";
/** Time booking ID = TimeBookingID */
public static final String TYPE_TimeBookingID = "TimeBookingID";
/** MilestoneId = MilestonId */
public static final String TYPE_MilestoneId = "MilestonId";
/** Bpartner = BPartner */
public static final String TYPE_Bpartner = "BPartner";
/** BPartnerLocation = BPartnerLocation */
public static final String TYPE_BPartnerLocation = "BPartnerLocation";
/** Product = Product */
public static final String TYPE_Product = "Product";
|
/** ProductCategory = ProductCategory */
public static final String TYPE_ProductCategory = "ProductCategory";
/** PriceList = PriceList */
public static final String TYPE_PriceList = "PriceList";
/** PriceListVersion = PriceListVersion */
public static final String TYPE_PriceListVersion = "PriceListVersion";
/** ProductPrice = ProductPrice */
public static final String TYPE_ProductPrice = "ProductPrice";
/** BPartnerValue = BPartnerValue */
public static final String TYPE_BPartnerValue = "BPartnerValue";
/** Shipper = Shipper */
public static final String TYPE_Shipper = "Shipper";
/** Warehouse = Warehouse */
public static final String TYPE_Warehouse = "Warehouse";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setVersion (final @Nullable java.lang.String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
@Override
public java.lang.String getVersion()
{
return get_ValueAsString(COLUMNNAME_Version);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java-gen\de\metas\externalreference\model\X_S_ExternalReference.java
| 1
|
请完成以下Java代码
|
public void createAndSubmitWorkpackage()
{
markAsProcessed();
if (hasNoModels() && !isEnqueueWorkpackageWhenNoModelsEnqueued())
{
return;
}
final IWorkPackageQueue workPackageQueue = Services.get(IWorkPackageQueueFactory.class)
.getQueueForEnqueuing(ctx, workpackageProcessorClass);
if (isCreateOneWorkpackagePerModel())
{
for (final Object model : models)
{
createAndSubmitWorkpackage(workPackageQueue, ImmutableList.of(model), null);
}
}
else if (isCreateOneWorkpackagePerAsyncBatch())
{
createAndSubmitWorkpackagesByAsyncBatch(workPackageQueue);
}
else
{
createAndSubmitWorkpackage(workPackageQueue, models, null);
}
}
private void createAndSubmitWorkpackage(
@NonNull final IWorkPackageQueue workPackageQueue,
@NonNull final Collection<Object> modelsToEnqueue,
@Nullable final AsyncBatchId asyncBatchId)
{
workPackageQueue.newWorkPackage()
.setUserInChargeId(userIdInCharge)
.parameters(parameters)
.addElements(modelsToEnqueue)
.setAsyncBatchId(asyncBatchId)
.buildAndEnqueue();
}
private void createAndSubmitWorkpackagesByAsyncBatch(@NonNull final IWorkPackageQueue workPackageQueue)
{
for (final Map.Entry<AsyncBatchId, List<Object>> entry : batchId2Models.entrySet())
{
final AsyncBatchId key = entry.getKey();
final List<Object> value = entry.getValue();
createAndSubmitWorkpackage(workPackageQueue, value, AsyncBatchId.toAsyncBatchIdOrNull(key));
}
}
private boolean hasNoModels()
{
return isCreateOneWorkpackagePerAsyncBatch() ? batchId2Models.isEmpty() : models.isEmpty();
}
}
private static final class ModelsScheduler<ModelType> extends WorkpackagesOnCommitSchedulerTemplate<ModelType>
{
private final Class<ModelType> modelType;
private final boolean collectModels;
public ModelsScheduler(final Class<? extends IWorkpackageProcessor> workpackageProcessorClass, final Class<ModelType> modelType, final boolean collectModels)
{
super(workpackageProcessorClass);
this.modelType = modelType;
this.collectModels = collectModels;
}
@Override
public String toString()
{
|
return MoreObjects.toStringHelper(this)
.add("collectModels", collectModels)
.add("workpackageProcessorClass", getWorkpackageProcessorClass())
.add("modelType", modelType)
.toString();
}
@Override
protected Properties extractCtxFromItem(final ModelType item)
{
return InterfaceWrapperHelper.getCtx(item);
}
@Override
protected String extractTrxNameFromItem(final ModelType item)
{
return InterfaceWrapperHelper.getTrxName(item);
}
@Nullable
@Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final ModelType item)
{
return collectModels ? item : null;
}
@Override
protected boolean isEnqueueWorkpackageWhenNoModelsEnqueued()
{
return !collectModels;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackagesOnCommitSchedulerTemplate.java
| 1
|
请完成以下Java代码
|
public CircuitBreakerConfig setFallbackUri(@Nullable URI fallbackUri) {
if (fallbackUri != null) {
Assert.isTrue(fallbackUri.getScheme().equalsIgnoreCase("forward"),
() -> "Scheme must be forward, but is " + fallbackUri.getScheme());
fallbackPath = fallbackUri.getPath();
}
else {
fallbackPath = null;
}
return this;
}
public CircuitBreakerConfig setFallbackPath(String fallbackPath) {
this.fallbackPath = fallbackPath;
return this;
}
public Set<String> getStatusCodes() {
return statusCodes;
}
public CircuitBreakerConfig setStatusCodes(String... statusCodes) {
return setStatusCodes(new LinkedHashSet<>(Arrays.asList(statusCodes)));
}
public CircuitBreakerConfig setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes;
return this;
}
public boolean isResumeWithoutError() {
return resumeWithoutError;
|
}
public CircuitBreakerConfig setResumeWithoutError(boolean resumeWithoutError) {
this.resumeWithoutError = resumeWithoutError;
return this;
}
}
public static class CircuitBreakerStatusCodeException extends ResponseStatusException {
public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) {
super(statusCode);
}
}
public static class FilterSupplier extends SimpleFilterSupplier {
public FilterSupplier() {
super(CircuitBreakerFilterFunctions.class);
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\CircuitBreakerFilterFunctions.java
| 1
|
请完成以下Java代码
|
private OLCandProcessorDescriptor toOLCandProcessorDescriptor(final I_C_OLCandProcessor olCandProcessorPO)
{
final int olCandProcessorId = olCandProcessorPO.getC_OLCandProcessor_ID();
return OLCandProcessorDescriptor.builder()
.id(olCandProcessorId)
.defaults(OLCandOrderDefaults.builder()
.docTypeTargetId(DocTypeId.ofRepoId(olCandProcessorPO.getC_DocTypeTarget_ID()))
.deliveryRule(DeliveryRule.ofCode(olCandProcessorPO.getDeliveryRule()))
.deliveryViaRule(DeliveryViaRule.ofCode(olCandProcessorPO.getDeliveryViaRule()))
.shipperId(ShipperId.ofRepoId(olCandProcessorPO.getM_Shipper_ID()))
.warehouseId(WarehouseId.ofRepoIdOrNull(olCandProcessorPO.getM_Warehouse_ID()))
.freightCostRule(FreightCostRule.ofCode(olCandProcessorPO.getFreightCostRule()))
.paymentRule(PaymentRule.ofCode(olCandProcessorPO.getPaymentRule()))
.paymentTermId(PaymentTermId.ofRepoId(olCandProcessorPO.getC_PaymentTerm_ID()))
.invoiceRule(InvoiceRule.ofCode(olCandProcessorPO.getInvoiceRule()))
.build())
.userInChangeId(UserId.ofRepoId(olCandProcessorPO.getAD_User_InCharge_ID()))
.aggregationInfo(retrieveOLCandAggregation(olCandProcessorId))
.build();
}
private OLCandAggregation retrieveOLCandAggregation(final int olCandProcessorId)
{
final List<OLCandAggregationColumn> columns = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_OLCandAggAndOrder.class)
.addEqualsFilter(I_C_OLCandAggAndOrder.COLUMN_C_OLCandProcessor_ID, olCandProcessorId)
.addOnlyActiveRecordsFilter()
.orderBy()
.addColumn(I_C_OLCandAggAndOrder.COLUMN_OrderBySeqNo)
.endOrderBy()
.create()
.stream(I_C_OLCandAggAndOrder.class)
.map(this::createOLCandAggregationColumn)
.collect(ImmutableList.toImmutableList());
|
return OLCandAggregation.of(columns);
}
private OLCandAggregationColumn createOLCandAggregationColumn(final I_C_OLCandAggAndOrder olCandAgg)
{
final I_AD_Column adColumn = olCandAgg.getAD_Column_OLCand();
return OLCandAggregationColumn.builder()
.columnName(adColumn.getColumnName())
.adColumnId(AdColumnId.ofRepoId(adColumn.getAD_Column_ID()))
.orderBySeqNo(olCandAgg.getOrderBySeqNo())
.splitOrderDiscriminator(olCandAgg.isSplitOrder())
.groupByColumn(olCandAgg.isGroupBy())
.granularity(granularityByADRefListValue.get(olCandAgg.getGranularity()))
.build();
}
public void handleADSchedulerBeforeDelete(final int adSchedulerId)
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_C_OLCandProcessor.class)
.addEqualsFilter(I_C_OLCandProcessor.COLUMN_AD_Scheduler_ID, adSchedulerId)
.create()
.list(I_C_OLCandProcessor.class)
.forEach(processor -> {
processor.setAD_Scheduler_ID(0);
InterfaceWrapperHelper.save(processor);
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandProcessorRepository.java
| 1
|
请完成以下Java代码
|
public void onValueChanged(IAttributeValueContext attributeValueContext, IAttributeSet attributeSet, I_M_Attribute attribute, Object valueOld, Object valueNew)
{
updateLotNumber(attributeSet, valueNew);
}
/**
* Update the lotNumber based on the LotNumberDate
*
* @param attributeSet
* @param valueNew
*/
private void updateLotNumber(final IAttributeSet attributeSet, final Object valueNew)
{
final Date newDate = (Date)valueNew;
final AttributeId lotNumberId = Services.get(ILotNumberDateAttributeDAO.class).getLotNumberAttributeId();
if (lotNumberId == null)
{
return;
}
final IAttributeStorage attributeStorage = IAttributeStorage.cast(attributeSet);
final String lotNumberValue;
if (newDate == null)
{
lotNumberValue = null;
}
else
{
lotNumberValue = Services.get(ILotNumberBL.class).calculateLotNumber(newDate);
}
attributeStorage.setValue(lotNumberId, lotNumberValue);
|
}
@Override
public Object generateSeedValue(IAttributeSet attributeSet, I_M_Attribute attribute, Object valueInitialDefault)
{
return null;
}
@Override
public boolean isReadonlyUI(IAttributeValueContext ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
return false;
}
@Override
public boolean isAlwaysEditableUI(IAttributeValueContext ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
return true;
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Date;
}
/**
* @return {@code false} because none of the {@code generate*Value()} methods is implemented.
*/
@Override
public boolean canGenerateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HULotNumberAttributeHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController {
@Autowired
private UserService userService;
/**
* 查询用户列表
*
* @return 用户列表
*/
@GetMapping("")
public List<UserVO> list() {
// 查询列表
List<UserVO> result = new ArrayList<>();
result.add(new UserVO().setId(1).setUsername("yudaoyuanma"));
result.add(new UserVO().setId(2).setUsername("woshiyutou"));
result.add(new UserVO().setId(3).setUsername("chifanshuijiao"));
// 返回列表
return result;
}
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/{id}")
public UserVO get(@PathVariable("id") Integer id) {
// 查询并返回用户
return new UserVO().setId(id).setUsername("username:" + id);
}
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/v2/{id}")
public UserVO get2(@PathVariable("id") Integer id) {
return userService.get(id);
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("")
public Integer add(UserAddDTO addDTO) {
// 插入用户记录,返回编号
|
Integer returnId = 1;
// 返回用户编号
return returnId;
}
/**
* 更新指定用户编号的用户
*
* @param id 用户编号
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PutMapping("/{id}")
public Boolean update(@PathVariable("id") Integer id, UserUpdateDTO updateDTO) {
// 将 id 设置到 updateDTO 中
updateDTO.setId(id);
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return success;
}
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable("id") Integer id) {
// 删除用户记录
Boolean success = false;
// 返回是否更新成功
return success;
}
}
|
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController.java
| 2
|
请完成以下Java代码
|
public class UserSearchQueryCriteriaConsumer implements Consumer<SearchCriteria>{
private Predicate predicate;
private CriteriaBuilder builder;
private Root r;
public UserSearchQueryCriteriaConsumer(Predicate predicate, CriteriaBuilder builder, Root r) {
super();
this.predicate = predicate;
this.builder = builder;
this.r= r;
}
@Override
public void accept(SearchCriteria param) {
|
if (param.getOperation().equalsIgnoreCase(">")) {
predicate = builder.and(predicate, builder.greaterThanOrEqualTo(r.get(param.getKey()), param.getValue().toString()));
} else if (param.getOperation().equalsIgnoreCase("<")) {
predicate = builder.and(predicate, builder.lessThanOrEqualTo(r.get(param.getKey()), param.getValue().toString()));
} else if (param.getOperation().equalsIgnoreCase(":")) {
if (r.get(param.getKey()).getJavaType() == String.class) {
predicate = builder.and(predicate, builder.like(r.get(param.getKey()), "%" + param.getValue() + "%"));
} else {
predicate = builder.and(predicate, builder.equal(r.get(param.getKey()), param.getValue()));
}
}
}
public Predicate getPredicate() {
return predicate;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\dao\UserSearchQueryCriteriaConsumer.java
| 1
|
请完成以下Java代码
|
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
|
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java
| 1
|
请完成以下Java代码
|
public int getRevision() {
return revision;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
public Date getDuedate() {
return duedate;
}
public void setDuedate(Date duedate) {
this.duedate = duedate;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
|
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AcquirableJobEntity other = (AcquirableJobEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", duedate=" + duedate
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java
| 1
|
请完成以下Java代码
|
public void setKeepLogDays (int KeepLogDays)
{
set_Value (COLUMNNAME_KeepLogDays, Integer.valueOf(KeepLogDays));
}
/** Get Days to keep Log.
@return Number of days to keep the log entries
*/
public int getKeepLogDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Password Info.
@param PasswordInfo Password Info */
public void setPasswordInfo (String PasswordInfo)
{
set_Value (COLUMNNAME_PasswordInfo, PasswordInfo);
}
/** Get Password Info.
@return Password Info */
public String getPasswordInfo ()
{
return (String)get_Value(COLUMNNAME_PasswordInfo);
}
/** Set Port.
@param Port Port */
public void setPort (int Port)
{
set_Value (COLUMNNAME_Port, Integer.valueOf(Port));
}
/** Get Port.
@return Port */
public int getPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Port);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Now.
|
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_Processor.java
| 1
|
请完成以下Java代码
|
public static String objectSerialization(Person person) throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static String objectAnnotationSerialization(Person person) throws IOException {
return JSON.builder()
.register(JacksonAnnotationExtension.std)
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static String customObjectSerialization(Person person) throws IOException {
return JSON.builder()
.register(new JacksonJrExtension() {
@Override
protected void register(ExtensionContext extensionContext) {
extensionContext.insertProvider(new MyHandlerProvider());
}
})
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
.asString(person);
}
public static Person objectDeserialization(String json) throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.beanFrom(Person.class, json);
}
public static Person customObjectDeserialization(String json) throws IOException {
return JSON.builder()
.register(new JacksonJrExtension() {
@Override
protected void register(ExtensionContext extensionContext) {
extensionContext.insertProvider(new MyHandlerProvider());
}
})
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.beanFrom(Person.class, json);
}
}
|
repos\tutorials-master\jackson-modules\jackson-jr\src\main\java\com\baeldung\jacksonjr\JacksonJrFeatures.java
| 1
|
请完成以下Java代码
|
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid to.
@param ValidTo
|
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Entry.java
| 1
|
请完成以下Java代码
|
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public void draw(Graphics g) {
g.drawImage(image, x, y, null);
}
public Rectangle getRectangleBounds() {
return new Rectangle(x, y, width, height);
}
public Area getEllipseAreaBounds() {
Ellipse2D.Double coll = new Ellipse2D.Double(x, y, width, height);
return new Area(coll);
}
public Ellipse2D getCircleBounds() {
return new Ellipse2D.Double(x, y, 200, 200);
}
public Area getPolygonBounds() {
for (int i = 0; i < xOffsets.length; i++) {
this.xPoints[i] = x + xOffsets[i];
this.yPoints[i] = y + yOffsets[i];
}
Polygon p = new Polygon(xPoints, yPoints, xOffsets.length);
|
return new Area(p);
}
public boolean collidesWith(GameObject other) {
int top = Math.max(y, other.y);
int bottom = Math.min(y + height, other.y + other.height);
int left = Math.max(x, other.x);
int right = Math.min(x + width, other.x + other.height);
if (right <= left || bottom <= top) return false;
for (int i = top; i < bottom; i++) {
for (int j = left; j < right; j++) {
int pixel1 = image.getRGB(j - x, i - y);
int pixel2 = other.image.getRGB(j - other.x, i - other.y);
if (((pixel1 >> 24) & 0xff) > 0 && ((pixel2 >> 24) & 0xff) > 0) {
return true;
}
}
}
return false;
}
}
|
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imagecollision\GameObject.java
| 1
|
请完成以下Java代码
|
public AllocableHUsList getAllocableHUs(@NonNull final AllocableHUsGroupingKey key)
{
return groups.computeIfAbsent(key, this::retrieveAvailableHUsToPick);
}
private AllocableHUsList retrieveAvailableHUsToPick(@NonNull final AllocableHUsGroupingKey key)
{
final ShipmentAllocationBestBeforePolicy bestBeforePolicy = ShipmentAllocationBestBeforePolicy.Expiring_First;
final ProductId productId = key.getProductId();
final ImmutableList<PickFromHU> husEligibleToPick;
final Set<HuId> productSourceHUs = sourceHUs.get(productId);
if (!productSourceHUs.isEmpty())
{
husEligibleToPick = productSourceHUs.stream()
.map(pickFromHUsSupplier::createPickFromHUByTopLevelHUId)
.sorted(PickFromHUsSupplier.getAllocationOrder(bestBeforePolicy))
.collect(ImmutableList.toImmutableList());
}
else if (!key.isSourceHUsOnly())
{
husEligibleToPick = pickFromHUsSupplier.getEligiblePickFromHUs(
PickFromHUsGetRequest.builder()
.pickFromLocatorId(key.getPickFromLocatorId())
.productId(productId)
.asiId(AttributeSetInstanceId.NONE) // TODO match attributes
.bestBeforePolicy(bestBeforePolicy)
.reservationRef(Optional.empty()) // TODO introduce some PP Order reservation
.enforceMandatoryAttributesOnPicking(false)
.build());
}
else
{
husEligibleToPick = ImmutableList.of();
}
final ImmutableList<AllocableHU> hus = CollectionUtils.map(husEligibleToPick, hu -> toAllocableHU(hu.getTopLevelHUId(), productId));
|
return new AllocableHUsList(hus);
}
private AllocableHU toAllocableHU(@NonNull final HuId huId, @NonNull final ProductId productId)
{
final AllocableHUKey key = AllocableHUKey.of(huId, productId);
return allocableHUs.computeIfAbsent(key, this::createAllocableHU);
}
private AllocableHU createAllocableHU(@NonNull final AllocableHUKey key)
{
final HUsLoadingCache husCache = pickFromHUsSupplier.getHusCache();
final I_M_HU topLevelHU = husCache.getHUById(key.getTopLevelHUId());
return new AllocableHU(storageFactory, uomConverter, topLevelHU, key.getProductId());
}
@Value(staticConstructor = "of")
private static class AllocableHUKey
{
@NonNull HuId topLevelHUId;
@NonNull ProductId productId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\manufacturing\issue\plan\AllocableHUsMap.java
| 1
|
请完成以下Java代码
|
public class SimpleVariableInstance implements CoreVariableInstance {
protected String name;
protected TypedValue value;
public SimpleVariableInstance(String name, TypedValue value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TypedValue getTypedValue(boolean deserialize) {
|
return value;
}
public void setValue(TypedValue value) {
this.value = value;
}
public static class SimpleVariableInstanceFactory implements VariableInstanceFactory<SimpleVariableInstance> {
public static final SimpleVariableInstanceFactory INSTANCE = new SimpleVariableInstanceFactory();
@Override
public SimpleVariableInstance build(String name, TypedValue value, boolean isTransient) {
return new SimpleVariableInstance(name, value);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\SimpleVariableInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static String getSign (Map<String , Object> paramMap , String paySecret){
SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap);
if (smap.get("sign") != null) {
smap.remove("sign");
}
StringBuffer stringBuffer = new StringBuffer();
for (Map.Entry<String, Object> m : smap.entrySet()) {
Object value = m.getValue();
if (value != null && StringUtils.isNotBlank(String.valueOf(value))){
stringBuffer.append(m.getKey()).append("=").append(value).append("&");
}
}
stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
LOG.info("签名原文:{}" , stringBuffer.toString());
String argPreSign = stringBuffer.append("&paySecret=").append(paySecret).toString();
String signStr = MD5Util.encode(argPreSign).toUpperCase();
LOG.info("签名结果:{}" , signStr);
return signStr;
}
/**
* 获取参数拼接串
* @param paramMap
* @return
*/
public static String getParamStr(Map<String , Object> paramMap){
SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap);
StringBuffer stringBuffer = new StringBuffer();
for (Map.Entry<String, Object> m : smap.entrySet()) {
Object value = m.getValue();
if (value != null && StringUtils.isNotBlank(String.valueOf(value))){
stringBuffer.append(m.getKey()).append("=").append(value).append("&");
}
}
|
stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
return stringBuffer.toString();
}
/**
* 验证商户签名
* @param paramMap 签名参数
* @param paySecret 签名私钥
* @param signStr 原始签名密文
* @return
*/
public static boolean isRightSign(Map<String , Object> paramMap , String paySecret ,String signStr){
if (StringUtils.isBlank(signStr)){
return false;
}
String sign = getSign(paramMap, paySecret);
if(signStr.equals(sign)){
return true;
}else{
return false;
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\MerchantApiUtil.java
| 2
|
请完成以下Java代码
|
public int getBlockingRetryDeliveryAttempt() {
Assert.state(getHeader(KafkaHeaders.DELIVERY_ATTEMPT) != null,
"Blocking delivery attempt header not present, "
+ "see ContainerProperties.setDeliveryAttemptHeader() to enable");
Integer deliveryAttempts = getHeader(KafkaHeaders.DELIVERY_ATTEMPT, Integer.class);
return deliveryAttempts == null ? 0 : deliveryAttempts;
}
/**
* When using non-blocking retries, get the delivery attempt header value as an int.
* @return 1 if there is no header present; the decoded header value otherwise.
*/
public int getNonBlockingRetryDeliveryAttempt() {
return fromBytes(RetryTopicHeaders.DEFAULT_HEADER_ATTEMPTS);
}
private int fromBytes(String headerName) {
byte[] header = getHeader(headerName, byte[].class);
return header == null ? 1 : ByteBuffer.wrap(header).getInt();
}
/**
* Get a header value with a specific type.
* @param <T> the type.
* @param key the header name.
* @param type the type's {@link Class}.
* @return the value, if present.
* @throws IllegalArgumentException if the type is not correct.
*/
@SuppressWarnings("unchecked")
@Nullable
public <T> T getHeader(String key, Class<T> type) {
Object value = getHeader(key);
if (value == null) {
return null;
}
if (!type.isAssignableFrom(value.getClass())) {
throw new IllegalArgumentException("Incorrect type specified for header '" + key + "'. Expected [" + type
+ "] but actual type is [" + value.getClass() + "]");
}
|
return (T) value;
}
@Override
protected MessageHeaderAccessor createAccessor(Message<?> message) {
return wrap(message);
}
/**
* Create an instance from the payload and headers of the given Message.
* @param message the message.
* @return the accessor.
*/
public static KafkaMessageHeaderAccessor wrap(Message<?> message) {
return new KafkaMessageHeaderAccessor(message);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\KafkaMessageHeaderAccessor.java
| 1
|
请完成以下Java代码
|
public HUMoveToDirectWarehouseService setLoggable(@NonNull final ILoggable loggable)
{
this.loggable = loggable;
return this;
}
public HUMoveToDirectWarehouseService setFailOnFirstError(final boolean failOnFirstError)
{
_failOnFirstError = failOnFirstError;
return this;
}
private boolean isFailOnFirstError()
{
return _failOnFirstError;
}
public HUMoveToDirectWarehouseService setFailIfNoHUs(final boolean failIfNoHUs)
{
_failIfNoHUs = failIfNoHUs;
return this;
}
private boolean isFailIfNoHUs()
{
return _failIfNoHUs;
}
public HUMoveToDirectWarehouseService setDocumentsCollection(final DocumentCollection documentsCollection)
{
this.documentsCollection = documentsCollection;
return this;
}
public HUMoveToDirectWarehouseService setHUView(final HUEditorView huView)
{
this.huView = huView;
return this;
}
private void notifyHUMoved(final I_M_HU hu)
{
final HuId huId = HuId.ofRepoId(hu.getM_HU_ID());
//
// Invalidate all documents which are about this HU.
if (documentsCollection != null)
|
{
try
{
documentsCollection.invalidateDocumentByRecordId(I_M_HU.Table_Name, huId.getRepoId());
}
catch (final Exception ex)
{
logger.warn("Failed invalidating documents for M_HU_ID={}. Ignored", huId, ex);
}
}
//
// Remove this HU from the view
// Don't invalidate. We will do it at the end of all processing.
//
// NOTE/Later edit: we decided to not remove it anymore
// because in some views it might make sense to keep it there.
// The right way would be to check if after moving it, the HU is still elgible for view's filters.
//
// if (huView != null) { huView.removeHUIds(ImmutableSet.of(huId)); }
}
/**
* @return target warehouse where the HUs will be moved to.
*/
@NonNull
private LocatorId getTargetLocatorId()
{
if (_targetLocatorId == null)
{
_targetLocatorId = huMovementBL.getDirectMoveLocatorId();
}
return _targetLocatorId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\HUMoveToDirectWarehouseService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static Optional<BPartnerCreditLimitId> optionalOfRepoId(
@Nullable final Integer bpartnerId,
@Nullable final Integer bPartnerCreditLimitId)
{
return Optional.ofNullable(ofRepoIdOrNull(bpartnerId, bPartnerCreditLimitId));
}
@Nullable
public static BPartnerCreditLimitId ofRepoIdOrNull(
@Nullable final BPartnerId bpartnerId,
@Nullable final Integer bPartnerCreditLimitId)
{
return bpartnerId != null && bPartnerCreditLimitId != null && bPartnerCreditLimitId > 0 ? ofRepoId(bpartnerId, bPartnerCreditLimitId) : null;
}
@Jacksonized
@Builder
private BPartnerCreditLimitId(@NonNull final BPartnerId bpartnerId, final int bPartnerCreditLimitId)
{
this.bpartnerId = bpartnerId;
this.repoId = Check.assumeGreaterThanZero(bPartnerCreditLimitId, "C_BPartner_CreditLimit_ID");
|
}
public static int toRepoId(@Nullable final BPartnerCreditLimitId bPartnerCreditLimitId)
{
return bPartnerCreditLimitId != null ? bPartnerCreditLimitId.getRepoId() : -1;
}
public static boolean equals(final @Nullable BPartnerCreditLimitId id1, final @Nullable BPartnerCreditLimitId id2)
{
return Objects.equals(id1, id2);
}
@JsonValue
public int toJson()
{
return getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerCreditLimitId.java
| 2
|
请完成以下Java代码
|
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getTriggerDay() {
return triggerDay;
}
public void setTriggerDay(Date triggerDay) {
this.triggerDay = triggerDay;
}
public int getRunningCount() {
return runningCount;
}
public void setRunningCount(int runningCount) {
|
this.runningCount = runningCount;
}
public int getSucCount() {
return sucCount;
}
public void setSucCount(int sucCount) {
this.sucCount = sucCount;
}
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLogReport.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final I_AD_EventLog_Entry eventLogEntryRecord = getRecord(I_AD_EventLog_Entry.class);
final I_AD_EventLog eventLogRecord = eventLogEntryRecord.getAD_EventLog();
Check.assumeNotNull(eventLogRecord.getEventTopicName(), "EventTopicName is null");
Check.assumeNotNull(eventLogRecord.getEventTypeName(), "EventTypeName is null");
final Topic topic = Topic.builder()
.name(eventLogRecord.getEventTopicName())
.type(Type.valueOf(eventLogRecord.getEventTypeName()))
.build();
final boolean typeMismatchBetweenTopicAndBus = !Type.valueOf(eventLogRecord.getEventTypeName()).equals(topic.getType());
if (typeMismatchBetweenTopicAndBus)
{
|
addLog("The given event log record has a different topic than the event bus!");
}
final IEventBus eventBus = eventBusFactory.getEventBus(topic);
final ImmutableList<String> handlerToIgnore = ImmutableList.of(eventLogEntryRecord.getClassname());
final Event event = eventLogService.loadEventForReposting(
EventLogId.ofRepoId(eventLogRecord.getAD_EventLog_ID()),
handlerToIgnore);
eventBus.enqueueEvent(event);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\process\AD_EventLog_Entry_RepostEvent.java
| 1
|
请完成以下Java代码
|
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static abstract class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
protected Car() {
}
protected Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
|
public static class Sedan extends Car {
public Sedan() {
}
public Sedan(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model, seatingCapacity, topSpeed);
}
}
public static class Crossover extends Car {
private double towingCapacity;
public Crossover() {
}
public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) {
super(make, model, seatingCapacity, topSpeed);
this.towingCapacity = towingCapacity;
}
public double getTowingCapacity() {
return towingCapacity;
}
public void setTowingCapacity(double towingCapacity) {
this.towingCapacity = towingCapacity;
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\IgnoranceMixinOrIntrospection.java
| 1
|
请完成以下Java代码
|
public TreeNode parent(int target) throws NoSuchElementException {
return parent(this, new TreeNode(target));
}
private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException {
if (target.equals(current) || current == null) {
throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " +
"The target is not in the tree or the target is the topmost root node.",
target.value));
}
if (target.equals(current.left) || target.equals(current.right)) {
return current;
}
return parent(target.value < current.value ? current.left : current.right, target);
}
public TreeNode iterativeParent(int target) {
return iterativeParent(this, new TreeNode(target));
}
private TreeNode iterativeParent(TreeNode current, TreeNode target) {
Deque<TreeNode> parentCandidates = new LinkedList<>();
String notFoundMessage = format("No parent node found for 'target.value=%s' " +
"The target is not in the tree or the target is the topmost root node.",
target.value);
if (target.equals(current)) {
throw new NoSuchElementException(notFoundMessage);
}
|
while (current != null || !parentCandidates.isEmpty()) {
while (current != null) {
parentCandidates.addFirst(current);
current = current.left;
}
current = parentCandidates.pollFirst();
if (target.equals(current.left) || target.equals(current.right)) {
return current;
}
current = current.right;
}
throw new NoSuchElementException(notFoundMessage);
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\parentnodebinarytree\TreeNode.java
| 1
|
请完成以下Java代码
|
public float predict(int[] o, Integer[] s)
{
int[] states = new int[s.length];
float p = predict(o, states);
for (int i = 0; i < states.length; i++)
{
s[i] = states[i];
}
return p;
}
public boolean similar(HiddenMarkovModel model)
{
if (!similar(start_probability, model.start_probability)) return false;
for (int i = 0; i < transition_probability.length; i++)
{
if (!similar(transition_probability[i], model.transition_probability[i])) return false;
if (!similar(emission_probability[i], model.emission_probability[i])) return false;
}
return true;
}
protected static boolean similar(float[] A, float[] B)
{
final float eta = 1e-2f;
for (int i = 0; i < A.length; i++)
if (Math.abs(A[i] - B[i]) > eta) return false;
return true;
}
protected static Object deepCopy(Object object)
{
if (object == null)
{
return null;
}
try
{
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
return new ObjectInputStream(bais).readObject();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HiddenMarkovModel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
authenticationProvider.setHideUserNotFoundExceptions(false);
return authenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
|
http
.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**")
.and()
.authorizeRequests()
.antMatchers("/oauth/**").authenticated()
.and()
.formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
|
repos\Spring-Boot-In-Action-master\springbt_sso_jwt\codesheep-server\src\main\java\cn\codesheep\config\SpringSecurityConfig.java
| 2
|
请完成以下Java代码
|
public void setClassIdFieldName(String classIdFieldName) {
this.classIdFieldName = classIdFieldName;
}
public String getContentClassIdFieldName() {
return this.contentClassIdFieldName;
}
/**
* Configure header name for container object contents type information.
* @param contentClassIdFieldName the header name.
* @since 2.1.3
*/
public void setContentClassIdFieldName(String contentClassIdFieldName) {
this.contentClassIdFieldName = contentClassIdFieldName;
}
public String getKeyClassIdFieldName() {
return this.keyClassIdFieldName;
}
/**
* Configure header name for map key type information.
* @param keyClassIdFieldName the header name.
* @since 2.1.3
*/
public void setKeyClassIdFieldName(String keyClassIdFieldName) {
this.keyClassIdFieldName = keyClassIdFieldName;
}
public void setIdClassMapping(Map<String, Class<?>> idClassMapping) {
this.idClassMapping.putAll(idClassMapping);
createReverseMap();
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
protected @Nullable ClassLoader getClassLoader() {
return this.classLoader;
}
protected void addHeader(Headers headers, String headerName, Class<?> clazz) {
if (this.classIdMapping.containsKey(clazz)) {
headers.add(new RecordHeader(headerName, this.classIdMapping.get(clazz)));
}
else {
headers.add(new RecordHeader(headerName, clazz.getName().getBytes(StandardCharsets.UTF_8)));
}
}
protected String retrieveHeader(Headers headers, String headerName) {
String classId = retrieveHeaderAsString(headers, headerName);
if (classId == null) {
throw new MessageConversionException(
"failed to convert Message content. Could not resolve " + headerName + " in header");
}
return classId;
}
protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) {
Header header = headers.lastHeader(headerName);
if (header != null) {
String classId = null;
if (header.value() != null) {
classId = new String(header.value(), StandardCharsets.UTF_8);
}
return classId;
|
}
return null;
}
private void createReverseMap() {
this.classIdMapping.clear();
for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) {
String id = entry.getKey();
Class<?> clazz = entry.getValue();
this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8));
}
}
public Map<String, Class<?>> getIdClassMapping() {
return Collections.unmodifiableMap(this.idClassMapping);
}
/**
* Configure the TypeMapper to use default key type class.
* @param isKey Use key type headers if true
* @since 2.1.3
*/
public void setUseForKey(boolean isKey) {
if (isKey) {
setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME);
setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME);
setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME);
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java
| 1
|
请完成以下Java代码
|
public void setLetterBody (java.lang.String LetterBody)
{
set_Value (COLUMNNAME_LetterBody, LetterBody);
}
/** Get Body.
@return Body */
@Override
public java.lang.String getLetterBody ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBody);
}
/** Set Subject.
@param LetterSubject Subject */
@Override
public void setLetterSubject (java.lang.String LetterSubject)
{
set_Value (COLUMNNAME_LetterSubject, LetterSubject);
}
/** Get Subject.
@return Subject */
@Override
public java.lang.String getLetterSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
|
*/
@Override
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_T_Letter_Spool.java
| 1
|
请完成以下Java代码
|
private final boolean isDisposed()
{
return disposed;
}
private VEditorActionButton getActionButton()
{
return actionButtonRef.get();
}
private JComponent getTextComponent()
{
return textComponentRef.get();
}
public void updateActionButtonUI()
{
if (isDisposed())
{
return;
}
final JComponent textComponent = getTextComponent();
final VEditorActionButton actionButton = getActionButton();
if (textComponent == null || actionButton == null)
{
dispose();
return;
}
updateActionButtonUI_PreferredSize(actionButton, textComponent);
updateActionButtonUI_Background(actionButton, textComponent);
}
private static void updateActionButtonUI_PreferredSize(final VEditorActionButton actionButton, final JComponent textComponent)
{
final Dimension textCompSize = textComponent.getPreferredSize();
final int textCompHeight = textCompSize.height;
final Dimension buttonSize = new Dimension(textCompHeight, textCompHeight);
actionButton.setPreferredSize(buttonSize);
}
private static void updateActionButtonUI_Background(final VEditorActionButton actionButton, final JComponent textComponent)
{
|
final Color textCompBackground = textComponent.getBackground();
actionButton.setBackground(textCompBackground);
}
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
if (isDisposed())
{
return;
}
final JComponent textComponent = (JComponent)evt.getSource();
if (textComponent == null)
{
return; // shall not happen
}
final VEditorActionButton actionButton = getActionButton();
if (actionButton == null)
{
dispose();
return;
}
final String propertyName = evt.getPropertyName();
if (PROPERTY_PreferredSize.equals(propertyName))
{
updateActionButtonUI_PreferredSize(actionButton, textComponent);
}
else if (PROPERTY_Background.equals(propertyName))
{
updateActionButtonUI_Background(actionButton, textComponent);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorActionButton.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrderItem
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String productCode;
private int quantity;
@ManyToOne
@JoinColumn(name="order_id")
private Order order;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getProductCode()
{
return productCode;
}
public void setProductCode(String productCode)
{
this.productCode = productCode;
}
public int getQuantity()
|
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public Order getOrder()
{
return order;
}
public void setOrder(Order order)
{
this.order = order;
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\orders\entities\OrderItem.java
| 2
|
请完成以下Java代码
|
public boolean isTUIncludedInLU(@NonNull final I_M_HU tu, @NonNull final I_M_HU expectedLU)
{
final I_M_HU actualLU = getLoadingUnitHU(tu);
return actualLU != null && actualLU.getM_HU_ID() == expectedLU.getM_HU_ID();
}
@Override
public List<I_M_HU> retrieveIncludedHUs(final I_M_HU huId)
{
return handlingUnitsRepo.retrieveIncludedHUs(huId);
}
@Override
@NonNull
public ImmutableSet<LocatorId> getLocatorIds(@NonNull final Collection<HuId> huIds)
{
final List<I_M_HU> hus = handlingUnitsRepo.getByIds(huIds);
final ImmutableSet<Integer> locatorIds = hus
.stream()
.map(I_M_HU::getM_Locator_ID)
.filter(locatorId -> locatorId > 0)
.collect(ImmutableSet.toImmutableSet());
return warehouseBL.getLocatorIdsByRepoId(locatorIds);
}
@Override
public Optional<HuId> getHUIdByValueOrExternalBarcode(@NonNull final ScannedCode scannedCode)
{
return Optionals.firstPresentOfSuppliers(
() -> getHUIdByValue(scannedCode.getAsString()),
() -> getByExternalBarcode(scannedCode)
);
}
private Optional<HuId> getHUIdByValue(final String value)
{
final HuId huId = HuId.ofHUValueOrNull(value);
return huId != null && existsById(huId) ? Optional.of(huId) : Optional.empty();
}
|
private Optional<HuId> getByExternalBarcode(@NonNull final ScannedCode scannedCode)
{
return handlingUnitsRepo.createHUQueryBuilder()
.setOnlyActiveHUs(true)
.setOnlyTopLevelHUs()
.addOnlyWithAttribute(AttributeConstants.ATTR_ExternalBarcode, scannedCode.getAsString())
.firstIdOnly();
}
@Override
public Set<HuPackingMaterialId> getHUPackingMaterialIds(@NonNull final HuId huId)
{
return handlingUnitsRepo.retrieveAllItemsNoCache(Collections.singleton(huId))
.stream()
.map(item -> HuPackingMaterialId.ofRepoIdOrNull(item.getM_HU_PackingMaterial_ID()))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Flux<InstanceId> deregister(String name) {
return this.instanceRegistry.getInstances(name)
.flatMap((instance) -> this.instanceRegistry.deregister(instance.getId()));
}
protected Tuple2<String, Flux<Instance>> getApplicationForInstance(Instance instance) {
String name = instance.getRegistration().getName();
return Tuples.of(name, this.instanceRegistry.getInstances(name).filter(Instance::isRegistered));
}
protected Mono<Application> toApplication(String name, Flux<Instance> instances) {
return instances.collectList().map((instanceList) -> {
Tuple2<String, Instant> status = getStatus(instanceList);
return Application.create(name)
.instances(instanceList)
.buildVersion(getBuildVersion(instanceList))
.status(status.getT1())
.statusTimestamp(status.getT2())
.build();
});
}
@Nullable
protected BuildVersion getBuildVersion(List<Instance> instances) {
List<BuildVersion> versions = instances.stream()
.map(Instance::getBuildVersion)
.filter(Objects::nonNull)
.distinct()
.sorted()
.toList();
if (versions.isEmpty()) {
return null;
}
else if (versions.size() == 1) {
return versions.get(0);
}
else {
return BuildVersion.valueOf(versions.get(0) + " ... " + versions.get(versions.size() - 1));
}
}
protected Tuple2<String, Instant> getStatus(List<Instance> instances) {
// TODO: Correct is just a second readmodel for groups
Map<String, Instant> statusWithTime = instances.stream()
.collect(toMap((instance) -> instance.getStatusInfo().getStatus(), Instance::getStatusTimestamp,
this::getMax));
|
if (statusWithTime.size() == 1) {
Map.Entry<String, Instant> e = statusWithTime.entrySet().iterator().next();
return Tuples.of(e.getKey(), e.getValue());
}
if (statusWithTime.containsKey(StatusInfo.STATUS_UP)) {
Instant oldestNonUp = statusWithTime.entrySet()
.stream()
.filter((e) -> !StatusInfo.STATUS_UP.equals(e.getKey()))
.map(Map.Entry::getValue)
.min(naturalOrder())
.orElse(Instant.EPOCH);
Instant latest = getMax(oldestNonUp, statusWithTime.getOrDefault(StatusInfo.STATUS_UP, Instant.EPOCH));
return Tuples.of(StatusInfo.STATUS_RESTRICTED, latest);
}
return statusWithTime.entrySet()
.stream()
.min(Map.Entry.comparingByKey(StatusInfo.severity()))
.map((e) -> Tuples.of(e.getKey(), e.getValue()))
.orElse(Tuples.of(STATUS_UNKNOWN, Instant.EPOCH));
}
protected Instant getMax(Instant t1, Instant t2) {
return (t1.compareTo(t2) >= 0) ? t1 : t2;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\ApplicationRegistry.java
| 2
|
请完成以下Java代码
|
private I_C_BankStatementLine getC_BankStatementLine()
{
return getModel(I_C_BankStatementLine.class);
}
CurrencyConversionContext getCurrencyConversionCtxForBankAsset()
{
CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankAsset;
if (currencyConversionContext == null)
{
currencyConversionContext = this._currencyConversionContextForBankAsset = createCurrencyConversionCtxForBankAsset();
}
return currencyConversionContext;
}
private CurrencyConversionContext createCurrencyConversionCtxForBankAsset()
{
final I_C_BankStatementLine line = getC_BankStatementLine();
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
// IMPORTANT for Bank Asset Account booking,
// * we shall NOT consider the fixed Currency Rate because we want to compute currency gain/loss
// * use default conversion types
return services.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone),
null,
ClientId.ofRepoId(line.getAD_Client_ID()));
}
CurrencyConversionContext getCurrencyConversionCtxForBankInTransit()
{
CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankInTransit;
if (currencyConversionContext == null)
{
currencyConversionContext = this._currencyConversionContextForBankInTransit = createCurrencyConversionCtxForBankInTransit();
}
return currencyConversionContext;
}
private CurrencyConversionContext createCurrencyConversionCtxForBankInTransit()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return paymentBL.extractCurrencyConversionContext(payment);
}
else
|
{
final I_C_BankStatementLine line = getC_BankStatementLine();
final PaymentCurrencyContext paymentCurrencyContext = bankStatementBL.getPaymentCurrencyContext(line);
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
CurrencyConversionContext conversionCtx = services.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone),
paymentCurrencyContext.getCurrencyConversionTypeId(),
ClientId.ofRepoId(line.getAD_Client_ID()));
final FixedConversionRate fixedCurrencyRate = paymentCurrencyContext.toFixedConversionRateOrNull();
if (fixedCurrencyRate != null)
{
conversionCtx = conversionCtx.withFixedConversionRate(fixedCurrencyRate);
}
return conversionCtx;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\DocLine_BankStatement.java
| 1
|
请完成以下Java代码
|
public I_R_IssueStatus getR_IssueStatus() throws RuntimeException
{
return (I_R_IssueStatus)MTable.get(getCtx(), I_R_IssueStatus.Table_Name)
.getPO(getR_IssueStatus_ID(), get_TrxName()); }
/** Set Issue Status.
@param R_IssueStatus_ID
Status of an Issue
*/
public void setR_IssueStatus_ID (int R_IssueStatus_ID)
{
if (R_IssueStatus_ID < 1)
set_Value (COLUMNNAME_R_IssueStatus_ID, null);
else
set_Value (COLUMNNAME_R_IssueStatus_ID, Integer.valueOf(R_IssueStatus_ID));
}
/** Get Issue Status.
@return Status of an Issue
*/
public int getR_IssueStatus_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueStatus_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_Request getR_Request() throws RuntimeException
{
return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name)
.getPO(getR_Request_ID(), get_TrxName()); }
/** Set Request.
@param R_Request_ID
Request from a Business Partner or Prospect
*/
public void setR_Request_ID (int R_Request_ID)
{
if (R_Request_ID < 1)
set_Value (COLUMNNAME_R_Request_ID, null);
else
set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID));
}
/** Get Request.
@return Request from a Business Partner or Prospect
*/
|
public int getR_Request_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Source Class.
@param SourceClassName
Source Class Name
*/
public void setSourceClassName (String SourceClassName)
{
set_Value (COLUMNNAME_SourceClassName, SourceClassName);
}
/** Get Source Class.
@return Source Class Name
*/
public String getSourceClassName ()
{
return (String)get_Value(COLUMNNAME_SourceClassName);
}
/** Set Source Method.
@param SourceMethodName
Source Method Name
*/
public void setSourceMethodName (String SourceMethodName)
{
set_Value (COLUMNNAME_SourceMethodName, SourceMethodName);
}
/** Get Source Method.
@return Source Method Name
*/
public String getSourceMethodName ()
{
return (String)get_Value(COLUMNNAME_SourceMethodName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueKnown.java
| 1
|
请完成以下Java代码
|
public long count(Predicate<T> predicate) {return getRowsIndex().count(predicate);}
public boolean anyMatch(final Predicate<T> predicate) {return getRowsIndex().anyMatch(predicate);}
public List<T> list() {return getRowsIndex().list();}
public void compute(@NonNull final UnaryOperator<ImmutableRowsIndex<T>> remappingFunction)
{
holder.compute(remappingFunction);
}
public void addRow(@NonNull final T row)
{
compute(rows -> rows.addingRow(row));
}
@SuppressWarnings("unused")
public void removeRowsById(@NonNull final DocumentIdsSelection rowIds)
{
if (rowIds.isEmpty())
{
return;
}
compute(rows -> rows.removingRowIds(rowIds));
}
@SuppressWarnings("unused")
public void removingIf(@NonNull final Predicate<T> predicate)
{
compute(rows -> rows.removingIf(predicate));
}
public void changeRowById(@NonNull DocumentId rowId, @NonNull final UnaryOperator<T> rowMapper)
{
compute(rows -> rows.changingRow(rowId, rowMapper));
}
|
public void changeRowsByIds(@NonNull DocumentIdsSelection rowIds, @NonNull final UnaryOperator<T> rowMapper)
{
compute(rows -> rows.changingRows(rowIds, rowMapper));
}
public void setRows(@NonNull final List<T> rows)
{
holder.setValue(ImmutableRowsIndex.of(rows));
}
@NonNull
private ImmutableRowsIndex<T> getRowsIndex()
{
final ImmutableRowsIndex<T> rowsIndex = holder.getValue();
// shall not happen
if (rowsIndex == null)
{
throw new AdempiereException("rowsIndex shall be set");
}
return rowsIndex;
}
public Predicate<DocumentId> isRelevantForRefreshingByDocumentId()
{
final ImmutableRowsIndex<T> rows = getRowsIndex();
return rows::isRelevantForRefreshing;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\SynchronizedRowsIndexHolder.java
| 1
|
请完成以下Java代码
|
public class EDIMissingDependencyException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = 2710688915672646730L;
public EDIMissingDependencyException(final String dependencyMessage, final String recordName, final String recordIdentifier)
{
super(buildMessage(dependencyMessage, recordName, recordIdentifier));
}
public EDIMissingDependencyException(final String dependencyMessage)
{
this(dependencyMessage, null, null);
}
private static String buildMessage(final String dependencyMessage, final String recordName, final String recordIdentifier)
{
final StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("@").append(dependencyMessage).append("@");
|
if (!Check.isEmpty(recordName))
{
messageBuilder.append(" [@").append(recordName).append("@");
if (!Check.isEmpty(recordIdentifier))
{
messageBuilder.append(" (").append(recordIdentifier).append(")]");
}
else
{
messageBuilder.append("]");
}
}
return messageBuilder.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\exception\EDIMissingDependencyException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setCycles(long currentCycleTs, long nextCycleTs) {
this.currentCycleTs = currentCycleTs;
this.nextCycleTs = nextCycleTs;
currentCycleValues.clear();
}
public void onRepartitionEvent() {
lastGaugesByServiceId.clear();
gaugesReportCycles.clear();
}
public ApiUsageStateValue getFeatureValue(ApiFeature feature) {
switch (feature) {
case TRANSPORT:
return apiUsageState.getTransportState();
case RE:
return apiUsageState.getReExecState();
case DB:
return apiUsageState.getDbStorageState();
case JS:
return apiUsageState.getJsExecState();
case TBEL:
return apiUsageState.getTbelExecState();
case EMAIL:
return apiUsageState.getEmailExecState();
case SMS:
return apiUsageState.getSmsExecState();
case ALARM:
return apiUsageState.getAlarmExecState();
default:
return ApiUsageStateValue.ENABLED;
}
}
public boolean setFeatureValue(ApiFeature feature, ApiUsageStateValue value) {
ApiUsageStateValue currentValue = getFeatureValue(feature);
switch (feature) {
case TRANSPORT:
apiUsageState.setTransportState(value);
break;
case RE:
apiUsageState.setReExecState(value);
break;
case DB:
apiUsageState.setDbStorageState(value);
break;
case JS:
apiUsageState.setJsExecState(value);
break;
case TBEL:
apiUsageState.setTbelExecState(value);
break;
case EMAIL:
apiUsageState.setEmailExecState(value);
break;
case SMS:
apiUsageState.setSmsExecState(value);
break;
|
case ALARM:
apiUsageState.setAlarmExecState(value);
break;
}
return !currentValue.equals(value);
}
public abstract EntityType getEntityType();
public TenantId getTenantId() {
return getApiUsageState().getTenantId();
}
public EntityId getEntityId() {
return getApiUsageState().getEntityId();
}
@Override
public String toString() {
return "BaseApiUsageState{" +
"apiUsageState=" + apiUsageState +
", currentCycleTs=" + currentCycleTs +
", nextCycleTs=" + nextCycleTs +
", currentHourTs=" + currentHourTs +
'}';
}
@Data
@Builder
public static class StatsCalculationResult {
private final long newValue;
private final boolean valueChanged;
private final long newHourlyValue;
private final boolean hourlyValueChanged;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\BaseApiUsageState.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getCONTROLQUAL() {
return controlqual;
}
/**
* Sets the value of the controlqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCONTROLQUAL(String value) {
this.controlqual = value;
}
/**
* Gets the value of the controlvalue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCONTROLVALUE() {
return controlvalue;
}
/**
* Sets the value of the controlvalue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCONTROLVALUE(String value) {
this.controlvalue = value;
}
/**
* Gets the value of the measurementunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMEASUREMENTUNIT() {
return measurementunit;
}
/**
* Sets the value of the measurementunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMEASUREMENTUNIT(String value) {
this.measurementunit = value;
}
/**
* Gets the value of the tamou1 property.
*
* @return
* possible object is
* {@link TAMOU1 }
*
*/
public TAMOU1 getTAMOU1() {
return tamou1;
}
/**
* Sets the value of the tamou1 property.
*
|
* @param value
* allowed object is
* {@link TAMOU1 }
*
*/
public void setTAMOU1(TAMOU1 value) {
this.tamou1 = value;
}
/**
* Gets the value of the ttaxi1 property.
*
* @return
* possible object is
* {@link TTAXI1 }
*
*/
public TTAXI1 getTTAXI1() {
return ttaxi1;
}
/**
* Sets the value of the ttaxi1 property.
*
* @param value
* allowed object is
* {@link TTAXI1 }
*
*/
public void setTTAXI1(TTAXI1 value) {
this.ttaxi1 = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\TRAILR.java
| 2
|
请完成以下Java代码
|
public <T> T parse(final ISiscCmd cmd, final String stringToParse, final String elementName, final Class<T> clazz)
{
try
{
// sometimes the scale returns "SI I" instead of the expected weigh string;
// we don't know why, but it happens so frequently that we don't throw an exception in that case
// in order not to clutter the log
if ("SI I".equals(stringToParse))
{
logger.warn("The scale returned {} for cmd={}; consider rebooting the scale", stringToParse, cmd);
return (T)ZERO.toString();
}
final SiscResultStringElement elementInfo = cmd.getResultElements().get(elementName);
final String[] tokens = stringToParse.split(" *"); // split string around spaces
final String resultToken = tokens[elementInfo.getPosition() - 1];
final Format format = elementInfo.getFormat();
|
if (format == null)
{
return (T)resultToken;
}
return (T)format.parseObject(resultToken);
}
catch (final Exception e)
{
throw new ParserException(cmd, stringToParse, elementName, clazz, e);
}
}
@Override
public String toString()
{
return String.format("SicsResponseStringParser []");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\sics\SicsResponseStringParser.java
| 1
|
请完成以下Java代码
|
public Q put() {
return method(HttpPut.METHOD_NAME);
}
public Q delete() {
return method(HttpDelete.METHOD_NAME);
}
public Q patch() {
return method(HttpPatch.METHOD_NAME);
}
public Q head() {
return method(HttpHead.METHOD_NAME);
}
public Q options() {
return method(HttpOptions.METHOD_NAME);
}
public Q trace() {
return method(HttpTrace.METHOD_NAME);
}
public Map<String, Object> getConfigOptions() {
return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG);
|
}
public Object getConfigOption(String field) {
Map<String, Object> config = getConfigOptions();
if (config != null) {
return config.get(field);
}
return null;
}
@SuppressWarnings("unchecked")
public Q configOption(String field, Object value) {
if (field == null || field.isEmpty() || value == null) {
LOG.ignoreConfig(field, value);
} else {
Map<String, Object> config = getConfigOptions();
if (config == null) {
config = new HashMap<>();
setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config);
}
config.put(field, value);
}
return (Q) this;
}
}
|
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java
| 1
|
请完成以下Java代码
|
protected void deleteInternal(String id, HistoricTaskInstanceEntity historicTaskInstance) {
List<HistoricTaskInstanceEntity> subTasks = historicTaskInstanceDataManager.findHistoricTasksByParentTaskId(
historicTaskInstance.getId()
);
for (HistoricTaskInstance subTask : subTasks) {
delete(subTask.getId());
}
getHistoricDetailEntityManager().deleteHistoricDetailsByTaskId(id);
getHistoricVariableInstanceEntityManager().deleteHistoricVariableInstancesByTaskId(id);
getCommentEntityManager().deleteCommentsByTaskId(id);
getAttachmentEntityManager().deleteAttachmentsByTaskId(id);
getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByTaskId(id);
delete(historicTaskInstance);
}
@Override
public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicTaskInstanceDataManager.findHistoricTaskInstancesByNativeQuery(
|
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicTaskInstanceDataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap);
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return historicTaskInstanceDataManager;
}
public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.historicTaskInstanceDataManager = historicTaskInstanceDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityManagerImpl.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.