instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public int getM_TargetDistribution_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_TargetDistribution_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Menge. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** RewardMode AD_Reference_ID=53389 */ public static final int REWARDMODE_AD_Reference_ID=53389; /** Charge = CH */ public static final String REWARDMODE_Charge = "CH"; /** Split Quantity = SQ */ public static final String REWARDMODE_SplitQuantity = "SQ"; /** Set Reward Mode. @param RewardMode Reward Mode */ public void setRewardMode (String RewardMode) { set_Value (COLUMNNAME_RewardMode, RewardMode); } /** Get Reward Mode. @return Reward Mode */ public String getRewardMode () { return (String)get_Value(COLUMNNAME_RewardMode); } /** RewardType AD_Reference_ID=53298 */ public static final int REWARDTYPE_AD_Reference_ID=53298; /** Percentage = P */ public static final String REWARDTYPE_Percentage = "P"; /** Flat Discount = F */ public static final String REWARDTYPE_FlatDiscount = "F"; /** Absolute Amount = A */ public static final String REWARDTYPE_AbsoluteAmount = "A"; /** Set Reward Type. @param RewardType Type of reward which consists of percentage discount, flat discount or absolute amount */ public void setRewardType (String RewardType) { set_Value (COLUMNNAME_RewardType, RewardType); }
/** Get Reward Type. @return Type of reward which consists of percentage discount, flat discount or absolute amount */ public String getRewardType () { return (String)get_Value(COLUMNNAME_RewardType); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionReward.java
1
请在Spring Boot框架中完成以下Java代码
public String toString() { return "AuthenticationManagerDelegator [delegate=" + this.delegate + "]"; } } static class DefaultPasswordEncoderAuthenticationManagerBuilder extends AuthenticationManagerBuilder { private PasswordEncoder defaultPasswordEncoder; /** * Creates a new instance * @param objectPostProcessor the {@link ObjectPostProcessor} instance to use. */ DefaultPasswordEncoderAuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor, PasswordEncoder defaultPasswordEncoder) { super(objectPostProcessor); this.defaultPasswordEncoder = defaultPasswordEncoder; } @Override public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication() { return super.inMemoryAuthentication().passwordEncoder(this.defaultPasswordEncoder); } @Override public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() { return super.jdbcAuthentication().passwordEncoder(this.defaultPasswordEncoder); } @Override public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService( T userDetailsService) { return super.userDetailsService(userDetailsService).passwordEncoder(this.defaultPasswordEncoder); } } static class LazyPasswordEncoder implements PasswordEncoder { private ApplicationContext applicationContext; private PasswordEncoder passwordEncoder; LazyPasswordEncoder(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public String encode(CharSequence rawPassword) { return getPasswordEncoder().encode(rawPassword); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) {
return getPasswordEncoder().matches(rawPassword, encodedPassword); } @Override public boolean upgradeEncoding(String encodedPassword) { return getPasswordEncoder().upgradeEncoding(encodedPassword); } private PasswordEncoder getPasswordEncoder() { if (this.passwordEncoder != null) { return this.passwordEncoder; } this.passwordEncoder = this.applicationContext.getBeanProvider(PasswordEncoder.class) .getIfUnique(PasswordEncoderFactories::createDelegatingPasswordEncoder); return this.passwordEncoder; } @Override public String toString() { return getPasswordEncoder().toString(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configuration\AuthenticationConfiguration.java
2
请完成以下Java代码
public class ProductionSimulationRows implements IEditableRowsData<ProductionSimulationRow> { public static ProductionSimulationRows cast(final IRowsData<ProductionSimulationRow> rowsData) { return (ProductionSimulationRows)rowsData; } private final ImmutableList<DocumentId> rowIds; private final ConcurrentHashMap<DocumentId, ProductionSimulationRow> rowsById; @Builder private ProductionSimulationRows(@NonNull final List<ProductionSimulationRow> rows) { rowIds = rows.stream() .map(ProductionSimulationRow::getId) .collect(ImmutableList.toImmutableList()); rowsById = new ConcurrentHashMap<>(Maps.uniqueIndex(rows, ProductionSimulationRow::getId)); } @Override public void patchRow(final IEditableView.RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests) { throw new UnsupportedOperationException("ProductionSimulationRows are read-only!"); } @Override public Map<DocumentId, ProductionSimulationRow> getDocumentId2TopLevelRows() { return rowIds.stream() .map(rowsById::get) .collect(GuavaCollectors.toImmutableMapByKey(ProductionSimulationRow::getId)); }
@Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs) { return DocumentIdsSelection.EMPTY; } @Override public void invalidateAll() { } @NonNull public ImmutableList<DocumentId> getRowIds() { return rowIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationRows.java
1
请完成以下Java代码
public boolean isRfQResponseAccepted () { Object oo = get_Value(COLUMNNAME_IsRfQResponseAccepted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_ValueNoCheck (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); } /** * QuoteType AD_Reference_ID=314 * Reference name: C_RfQ QuoteType */ public static final int QUOTETYPE_AD_Reference_ID=314; /** Quote Total only = T */ public static final String QUOTETYPE_QuoteTotalOnly = "T"; /** Quote Selected Lines = S */ public static final String QUOTETYPE_QuoteSelectedLines = "S"; /** Quote All Lines = A */ public static final String QUOTETYPE_QuoteAllLines = "A"; /** Set RfQ Type. @param QuoteType Request for Quotation Type */ @Override public void setQuoteType (java.lang.String QuoteType) { set_ValueNoCheck (COLUMNNAME_QuoteType, QuoteType); } /** Get RfQ Type. @return Request for Quotation Type */ @Override public java.lang.String getQuoteType () { return (java.lang.String)get_Value(COLUMNNAME_QuoteType);
} @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_RV_C_RfQ_UnAnswered.java
1
请完成以下Java代码
public class SysLog implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId(type = IdType.ASSIGN_ID) private String id; /** * 创建人 */ private String createBy; /** * 创建时间 */ @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 更新人 */ private String updateBy; /** * 更新时间 */ private Date updateTime; /** * 耗时 */ @Excel(name = "耗时(毫秒)", width = 15) private Long costTime; /** * IP */ @Excel(name = "IP", width = 15) private String ip; /** * 请求参数 */ private String requestParam; /** * 请求类型 */ private String requestType; /** * 请求路径 */ private String requestUrl; /** * 请求方法 */ private String method;
/** * 操作人用户名称 */ private String username; /** * 操作人用户账户 */ @Excel(name = "操作人", width = 15) private String userid; /** * 操作详细日志 */ @Excel(name = "日志内容", width = 50) private String logContent; /** * 日志类型(1登录日志,2操作日志) */ @Dict(dicCode = "log_type") private Integer logType; /** * 操作类型(1查询,2添加,3修改,4删除,5导入,6导出) */ @Dict(dicCode = "operate_type") private Integer operateType; /** * 客户终端类型 pc:电脑端 app:手机端 h5:移动网页端 */ @Excel(name = "客户端类型", width = 15, dicCode = "client_type") @Dict(dicCode = "client_type") private String clientType; /** * 租户ID */ private Integer tenantId; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysLog.java
1
请完成以下Java代码
public void enqueuePurchaseCandidates( @NonNull final I_PMM_PurchaseCandidate purchaseCandidateRecord, @NonNull final ModelChangeType type) { final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(purchaseCandidateRecord); final AbstractPurchaseOfferEvent event; final boolean deleted = type.isDelete() || ModelChangeUtil.isJustDeactivated(purchaseCandidateRecord); final boolean created = type.isNew() || ModelChangeUtil.isJustActivated(purchaseCandidateRecord); final BigDecimal qtyPromised = purchaseCandidateRecord.getQtyPromised(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(purchaseCandidateRecord.getAD_Client_ID(), purchaseCandidateRecord.getAD_Org_ID()); final UserId userId = UserId.ofRepoId(purchaseCandidateRecord.getUpdatedBy()); if (deleted) { event = PurchaseOfferDeletedEvent.builder() .date(TimeUtil.asInstant(purchaseCandidateRecord.getDatePromised())) .eventDescriptor(EventDescriptor.ofClientOrgAndUserId(clientAndOrgId, userId)) .procurementCandidateId(purchaseCandidateRecord.getPMM_PurchaseCandidate_ID()) .productDescriptor(productDescriptor) .qty(qtyPromised) .build(); } else if (created) { event = PurchaseOfferCreatedEvent.builder() .date(TimeUtil.asInstant(purchaseCandidateRecord.getDatePromised())) .eventDescriptor(EventDescriptor.ofClientOrgAndUserId(clientAndOrgId, userId)) .procurementCandidateId(purchaseCandidateRecord.getPMM_PurchaseCandidate_ID()) .productDescriptor(productDescriptor) .qty(qtyPromised) .build(); }
else { final I_PMM_PurchaseCandidate oldPurchaseCandidate = InterfaceWrapperHelper.createOld(purchaseCandidateRecord, I_PMM_PurchaseCandidate.class); final BigDecimal oldQtyPromised = oldPurchaseCandidate.getQtyPromised(); event = PurchaseOfferUpdatedEvent.builder() .date(TimeUtil.asInstant(purchaseCandidateRecord.getDatePromised())) .eventDescriptor(EventDescriptor.ofClientAndOrg(purchaseCandidateRecord.getAD_Client_ID(), purchaseCandidateRecord.getAD_Org_ID())) .procurementCandidateId(purchaseCandidateRecord.getPMM_PurchaseCandidate_ID()) .productDescriptor(productDescriptor) .qty(qtyPromised) .qtyDelta(qtyPromised.subtract(oldQtyPromised)) .build(); } materialEventService.enqueueEventAfterNextCommit(event); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\material\interceptor\PMM_PurchaseCandidate.java
1
请完成以下Java代码
public class BPMNActivityImpl extends BPMNElementImpl implements BPMNActivity { private String activityName; private String activityType; private String executionId; public BPMNActivityImpl() {} public BPMNActivityImpl(String elementId, String activityName, String activityType) { this.setElementId(elementId); this.activityName = activityName; this.activityType = activityType; } @Override public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } @Override public String getActivityType() { return activityType; } public void setActivityType(String activityType) { this.activityType = activityType; } @Override public String getExecutionId() { return this.executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) {
return false; } if (getClass() != obj.getClass()) { return false; } BPMNActivityImpl other = (BPMNActivityImpl) obj; return ( Objects.equals(activityName, other.activityName) && Objects.equals(activityType, other.activityType) && Objects.equals(executionId, other.executionId) ); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(activityName, activityType, executionId); return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder .append("BPMNActivityImpl [activityName=") .append(activityName) .append(", activityType=") .append(activityType) .append(", executionId=") .append(executionId) .append(", toString()=") .append(super.toString()) .append("]"); return builder.toString(); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNActivityImpl.java
1
请完成以下Java代码
private static class LoggableAsGraphLoggerAdapter implements ILogger { @NonNull private final ILoggable loggable; @NonNull @Getter @Setter private LoggerLevel loggingLevel = LoggerLevel.DEBUG; @Override public void logDebug(@NonNull final String message) { loggable.addLog(message); } @Override public void logError(@NonNull final String message, @Nullable final Throwable throwable) { final StringBuilder finalMessage = new StringBuilder("ERROR: ").append(message); if (throwable != null) { finalMessage.append("\n").append(Util.dumpStackTraceToString(throwable)); } loggable.addLog(finalMessage.toString()); } } @RequiredArgsConstructor private static class SLF4JAsGraphLoggerAdapter implements ILogger { @NonNull private final Logger logger; @Override public void setLoggingLevel(@NonNull final LoggerLevel level) { switch (level) { case ERROR: LogManager.setLoggerLevel(logger, Level.WARN); break; case DEBUG: default: LogManager.setLoggerLevel(logger, Level.DEBUG); break; } } @Override public @NonNull LoggerLevel getLoggingLevel() { final Level level = LogManager.getLoggerLevel(logger); if (level == null) { return LoggerLevel.DEBUG; }
else if (Level.ERROR.equals(level) || Level.WARN.equals(level)) { return LoggerLevel.ERROR; } else { return LoggerLevel.DEBUG; } } @Override public void logDebug(@NonNull final String message) { logger.debug(message); } @Override public void logError(@NonNull final String message, @Nullable final Throwable throwable) { logger.warn(message, throwable); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\sender\MicrosoftGraphMailSender.java
1
请在Spring Boot框架中完成以下Java代码
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) { exeTimeThreadLocal.set(System.currentTimeMillis()); statisticsInterceptor.startCounter(); return true; } @Override public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView modelAndView) { Long queryCount = statisticsInterceptor.getQueryCount(); if (modelAndView != null) { //to display to the View modelAndView.addObject("_queryCount", queryCount); } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse resp, Object handler, Exception ex) { long duration = System.currentTimeMillis() - exeTimeThreadLocal.get(); Long queryCount = statisticsInterceptor.getQueryCount();
statisticsInterceptor.clearCounter(); exeTimeThreadLocal.remove(); log.debug("Queries executed: {}, Request Url: {}, Time: {} ms", queryCount, request.getRequestURI(), duration); } @Override public void afterConcurrentHandlingStarted(HttpServletRequest req, HttpServletResponse resp, Object handler) { //concurrent handling cannot be supported here statisticsInterceptor.clearCounter(); exeTimeThreadLocal.remove(); } }
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\config\logging\WebRequestInterceptor.java
2
请完成以下Java代码
public InvalidRequestException setupActionNotAvailable() { return new InvalidRequestException(Status.FORBIDDEN, "Setup action not available"); } public RestException processEngineProviderNotFound() { return new RestException(Status.BAD_REQUEST, "Could not find an implementation of the " + ProcessEngineProvider.class + "- SPI"); } public void infoWebappSuccessfulLogin(String username) { logInfo("001", "Successful login for user {}.", username); } public void infoWebappFailedLogin(String username, String reason) { logInfo("002", "Failed login attempt for user {}. Reason: {}", username, reason); } public void infoWebappLogout(String username) { logInfo("003", "Successful logout for user {}.", username); } public void traceCacheValidationTime(Date cacheValidationTime) { logTrace("004", "Cache validation time: {}", cacheValidationTime); }
public void traceCacheValidationTimeUpdated(Date cacheValidationTime, Date newCacheValidationTime) { logTrace("005", "Cache validation time updated from: {} to: {}", cacheValidationTime, newCacheValidationTime); } public void traceAuthenticationUpdated(String engineName) { logTrace("006", "Authentication updated: {}", engineName); } public void traceAuthenticationRemoved(String engineName) { logTrace("007", "Authentication removed: {}", engineName); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\WebappLogger.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getCaseExecutionId() { return caseExecutionId; } public String getCaseInstanceId() { return caseInstanceId;
} public String getTenantId() { return tenantId; } public static VariableInstanceDto fromVariableInstance(VariableInstance variableInstance) { VariableInstanceDto dto = new VariableInstanceDto(); dto.id = variableInstance.getId(); dto.name = variableInstance.getName(); dto.processDefinitionId = variableInstance.getProcessDefinitionId(); dto.processInstanceId = variableInstance.getProcessInstanceId(); dto.executionId = variableInstance.getExecutionId(); dto.caseExecutionId = variableInstance.getCaseExecutionId(); dto.caseInstanceId = variableInstance.getCaseInstanceId(); dto.taskId = variableInstance.getTaskId(); dto.batchId = variableInstance.getBatchId(); dto.activityInstanceId = variableInstance.getActivityInstanceId(); dto.tenantId = variableInstance.getTenantId(); if(variableInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, variableInstance.getTypedValue()); } else { dto.errorMessage = variableInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(variableInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\VariableInstanceDto.java
1
请完成以下Java代码
public EntityImpl update(EntityImpl entity) { return update(entity, true); } @Override public EntityImpl update(EntityImpl entity, boolean fireUpdateEvent) { EntityImpl updatedEntity = getDataManager().update(entity); if (fireUpdateEvent) { fireEntityUpdatedEvent(entity); } return updatedEntity; } protected void fireEntityUpdatedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { getEventDispatcher().dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, entity), engineType); } } @Override public void delete(String id) { EntityImpl entity = findById(id); delete(entity); } @Override public void delete(EntityImpl entity) { delete(entity, true); } @Override public void delete(EntityImpl entity, boolean fireDeleteEvent) { getDataManager().delete(entity); FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (fireDeleteEvent && eventDispatcher != null && eventDispatcher.isEnabled()) { fireEntityDeletedEvent(entity); } } protected void fireEntityDeletedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, entity), engineType); } } protected FlowableEntityEvent createEntityEvent(FlowableEngineEventType eventType, Entity entity) { return new FlowableEntityEventImpl(entity, eventType); } protected DM getDataManager() { return dataManager; } protected void setDataManager(DM dataManager) { this.dataManager = dataManager; } protected abstract FlowableEventDispatcher getEventDispatcher(); }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntityManager.java
1
请完成以下Java代码
public boolean supportsParameter(MethodParameter parameter) { return (getArgumentResolver(parameter) != null); } /** * Iterate over registered * {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} * and invoke the one that supports it. * @throws IllegalArgumentException if no suitable argument resolver is found */ @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); if (resolver == null) { throw new IllegalArgumentException("Unsupported parameter [%s].".formatted(parameter)); } return resolver.resolveArgument(parameter, environment); }
/** * Find a registered {@link HandlerMethodArgumentResolver} that supports * the given method parameter. * @param parameter the method parameter */ public @Nullable HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) { return this.argumentResolverCache.computeIfAbsent(parameter, (p) -> { for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) { if (resolver.supportsParameter(parameter)) { return resolver; } } return null; }); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\HandlerMethodArgumentResolverComposite.java
1
请完成以下Java代码
public class BusinessRuleTaskActivityBehavior extends TaskActivityBehavior implements BusinessRuleTaskDelegate { private static final long serialVersionUID = 1L; protected Set<Expression> variablesInputExpressions = new HashSet<>(); protected Set<Expression> rulesExpressions = new HashSet<>(); protected boolean exclude; protected String resultVariable; public BusinessRuleTaskActivityBehavior() { } @Override public void execute(DelegateExecution execution) { ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(execution.getProcessDefinitionId()); String deploymentId = processDefinition.getDeploymentId(); KieBase knowledgeBase = RulesHelper.findKnowledgeBaseByDeploymentId(deploymentId); KieSession ksession = knowledgeBase.newKieSession(); if (variablesInputExpressions != null) { Iterator<Expression> itVariable = variablesInputExpressions.iterator(); while (itVariable.hasNext()) { Expression variable = itVariable.next(); ksession.insert(variable.getValue(execution)); } } if (!rulesExpressions.isEmpty()) { RulesAgendaFilter filter = new RulesAgendaFilter(); Iterator<Expression> itRuleNames = rulesExpressions.iterator(); while (itRuleNames.hasNext()) { Expression ruleName = itRuleNames.next(); filter.addSuffic(ruleName.getValue(execution).toString()); } filter.setAccept(!exclude);
ksession.fireAllRules(filter); } else { ksession.fireAllRules(); } Collection<? extends Object> ruleOutputObjects = ksession.getObjects(); if (ruleOutputObjects != null && !ruleOutputObjects.isEmpty()) { Collection<Object> outputVariables = new ArrayList<>(ruleOutputObjects); execution.setVariable(resultVariable, outputVariables); } ksession.dispose(); leave(execution); } @Override public void addRuleVariableInputIdExpression(Expression inputId) { this.variablesInputExpressions.add(inputId); } @Override public void addRuleIdExpression(Expression inputId) { this.rulesExpressions.add(inputId); } @Override public void setExclude(boolean exclude) { this.exclude = exclude; } @Override public void setResultVariable(String resultVariableName) { this.resultVariable = resultVariableName; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\BusinessRuleTaskActivityBehavior.java
1
请完成以下Java代码
public void setFeature_id_(int feature_id_) { this.feature_id_ = feature_id_; } public int getThread_id_() { return thread_id_; } public void setThread_id_(int thread_id_) { this.thread_id_ = thread_id_; } public FeatureIndex getFeature_index_() { return feature_index_; } public void setFeature_index_(FeatureIndex feature_index_) { this.feature_index_ = feature_index_; } public List<List<String>> getX_() { return x_; } public void setX_(List<List<String>> x_) { this.x_ = x_; } public List<List<Node>> getNode_() { return node_; } public void setNode_(List<List<Node>> node_) { this.node_ = node_; } public List<Integer> getAnswer_() { return answer_; } public void setAnswer_(List<Integer> answer_) { this.answer_ = answer_; } public List<Integer> getResult_() { return result_; } public void setResult_(List<Integer> result_) { this.result_ = result_; } public static void main(String[] args) throws Exception { if (args.length < 1) { return; } TaggerImpl tagger = new TaggerImpl(Mode.TEST); InputStream stream = null; try { stream = IOUtil.newInputStream(args[0]); } catch (IOException e) {
System.err.printf("model not exits for %s", args[0]); return; } if (stream != null && !tagger.open(stream, 2, 0, 1.0)) { System.err.println("open error"); return; } System.out.println("Done reading model"); if (args.length >= 2) { InputStream fis = IOUtil.newInputStream(args[1]); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); while (true) { ReadStatus status = tagger.read(br); if (ReadStatus.ERROR == status) { System.err.println("read error"); return; } else if (ReadStatus.EOF == status) { break; } if (tagger.getX_().isEmpty()) { break; } if (!tagger.parse()) { System.err.println("parse error"); return; } System.out.print(tagger.toString()); } br.close(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java
1
请完成以下Java代码
public static AdMessageKey ofNullable(@Nullable final String value) { return value != null && Check.isNotBlank(value) ? of(value) : null; } private final String value; private AdMessageKey(final String value) { Check.assumeNotEmpty(value, "value is not empty"); this.value = value; } @Override public String toString() {
return toAD_Message(); } @JsonValue public String toAD_Message() { return value; } public String toAD_MessageWithMarkers() { return "@" + toAD_Message() + "@"; } public boolean startsWith(final String prefix) {return value.startsWith(prefix);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessageKey.java
1
请完成以下Java代码
public class BaseEntity { @Id @Column(name = "Id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Transient private Integer page = 1; @Transient private Integer rows = 10; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; }
public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } }
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\model\BaseEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class ArrayOfDocuments extends ArrayList<Document> { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append("class ArrayOfDocuments {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\ArrayOfDocuments.java
2
请完成以下Java代码
public double getFitness() { return fitness; } /** * Gets the {@link #bestPosition}. * * @return the {@link #bestPosition} */ public long[] getBestPosition() { return bestPosition; } /** * Gets the {@link #bestFitness}. * * @return the {@link #bestFitness} */ public double getBestFitness() { return bestFitness; } /** * Sets the {@link #position}. * * @param position * the new {@link #position} */ public void setPosition(long[] position) { this.position = position; } /** * Sets the {@link #speed}. * * @param speed * the new {@link #speed} */ public void setSpeed(long[] speed) { this.speed = speed; } /** * Sets the {@link #fitness}. * * @param fitness * the new {@link #fitness} */ public void setFitness(double fitness) { this.fitness = fitness; } /** * Sets the {@link #bestPosition}. * * @param bestPosition * the new {@link #bestPosition} */ public void setBestPosition(long[] bestPosition) { this.bestPosition = bestPosition; } /** * Sets the {@link #bestFitness}. * * @param bestFitness * the new {@link #bestFitness} */ public void setBestFitness(double bestFitness) { this.bestFitness = bestFitness; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override
public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(bestFitness); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(bestPosition); temp = Double.doubleToLongBits(fitness); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(position); result = prime * result + Arrays.hashCode(speed); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Particle other = (Particle) obj; if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness)) return false; if (!Arrays.equals(bestPosition, other.bestPosition)) return false; if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness)) return false; if (!Arrays.equals(position, other.position)) return false; if (!Arrays.equals(speed, other.speed)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness=" + fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]"; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Particle.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof AttachmentEntryItem) { final AttachmentEntryItem other = (AttachmentEntryItem)obj; return attachmentEntryId == other.attachmentEntryId; } else { return false; } } } /************************************************************************** * Graphic Image Panel */ class GImage extends JPanel { /** * */ private static final long serialVersionUID = 4991225210651641722L; /** * Graphic Image */ public GImage() { super(); } // GImage /** The Image */ private Image m_image = null; /** * Set Image * * @param image image */ public void setImage(final Image image) { m_image = image;
if (m_image == null) { return; } MediaTracker mt = new MediaTracker(this); mt.addImage(m_image, 0); try { mt.waitForID(0); } catch (Exception e) { } Dimension dim = new Dimension(m_image.getWidth(this), m_image.getHeight(this)); this.setPreferredSize(dim); } // setImage /** * Paint * * @param g graphics */ @Override public void paint(final Graphics g) { Insets in = getInsets(); if (m_image != null) { g.drawImage(m_image, in.left, in.top, this); } } // paint /** * Update * * @param g graphics */ @Override public void update(final Graphics g) { paint(g); } // update } // GImage } // Attachment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\Attachment.java
1
请完成以下Java代码
public boolean isFileSystem() { return get_ValueAsBoolean(COLUMNNAME_IsFileSystem); } @Override public void setIsReport (final boolean IsReport) { set_Value (COLUMNNAME_IsReport, IsReport); } @Override public boolean isReport() { return get_ValueAsBoolean(COLUMNNAME_IsReport); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); }
@Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java
1
请在Spring Boot框架中完成以下Java代码
public String getPOReference() { return POReference; } public Date getDateCandidate() { return dateCandidate; } public Date getDatePromised() { return datePromised; } public int getM_Product_ID() { return M_Product_ID; } public String getProductDescription() { return productDescription; } public String getProductAttributes() { return productAttributes; } public int getM_ProductPrice_ID() {
return M_ProductPrice_ID; } public int getM_ProductPrice_Attribute_ID() { return M_ProductPrice_Attribute_ID; } public int getM_HU_PI_Item_Product_ID() { return M_HU_PI_Item_Product_ID; } public int getC_BPartner_ID() { return C_BPartner_ID; } public int getC_BPartner_Location_ID() { return C_BPartner_Location_ID; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\Excel_OLCand_Row.java
2
请完成以下Java代码
public class AstLambdaParameters extends AstRightValue { private final List<String> parameterNames; public AstLambdaParameters(List<String> parameterNames) { this.parameterNames = parameterNames; } public List<String> getParameterNames() { return parameterNames; } @Override public void appendStructure(StringBuilder builder, Bindings bindings) { if (parameterNames.size() == 1) { builder.append(parameterNames.get(0)); } else { builder.append("("); for (int i = 0; i < parameterNames.size(); i++) { if (i > 0) { builder.append(", "); } builder.append(parameterNames.get(i)); } builder.append(")"); } } @Override public Object eval(Bindings bindings, ELContext context) { // Lambda parameters don't evaluate to a value return parameterNames;
} @Override public int getCardinality() { return 0; } @Override public AstNode getChild(int i) { return null; } @Override public String toString() { return parameterNames.size() == 1 ? parameterNames.get(0) : parameterNames.toString(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstLambdaParameters.java
1
请完成以下Java代码
private FlatrateTerm getById0(@NonNull final FlatrateTermId id) { final I_C_Flatrate_Term term = flatrateDAO.getById(id); final OrgId orgId = OrgId.ofRepoId(term.getAD_Org_ID()); final I_C_Flatrate_Conditions flatrateConditionsRecord = term.getC_Flatrate_Conditions(); final ProductId productId = ProductId.ofRepoId(term.getM_Product_ID()); final I_C_UOM termUom = uomDAO.getById(CoalesceUtil.coalesceSuppliersNotNull( () -> UomId.ofRepoIdOrNull(term.getC_UOM_ID()), () -> productBL.getStockUOMId(productId))); final BPartnerLocationAndCaptureId billPartnerLocationAndCaptureId = ContractLocationHelper.extractBillToLocationId(term); final DocumentLocation billLocation = ContractLocationHelper.extractBillLocation(term); final BPartnerLocationAndCaptureId dropshipLPartnerLocationAndCaptureId = ContractLocationHelper.extractDropshipLocationId(term); return FlatrateTerm.builder() .id(id)
.orgId(orgId) .billPartnerLocationAndCaptureId(billPartnerLocationAndCaptureId) .billLocation(billLocation) .dropshipPartnerLocationAndCaptureId(dropshipLPartnerLocationAndCaptureId) .productId(productId) .flatrateConditionsId(ConditionsId.ofRepoId(term.getC_Flatrate_Conditions_ID())) .pricingSystemId(PricingSystemId.ofRepoIdOrNull(term.getM_PricingSystem_ID())) .isSimulation(term.isSimulation()) .status(FlatrateTermStatus.ofNullableCode(term.getContractStatus())) .userInChargeId(UserId.ofRepoIdOrNull(term.getAD_User_InCharge_ID())) .startDate(TimeUtil.asInstant(term.getStartDate())) .endDate(TimeUtil.asInstant(term.getEndDate())) .masterStartDate(TimeUtil.asInstant(term.getMasterStartDate())) .masterEndDate(TimeUtil.asInstant(term.getMasterEndDate())) .plannedQtyPerUnit(Quantity.of(term.getPlannedQtyPerUnit(), termUom)) .deliveryRule(DeliveryRule.ofNullableCode(term.getDeliveryRule())) .deliveryViaRule(DeliveryViaRule.ofNullableCode(term.getDeliveryViaRule())) .invoiceRule(InvoiceRule.ofCode(flatrateConditionsRecord.getInvoiceRule())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\FlatrateTermRepo.java
1
请完成以下Java代码
public class FindWithObjectId { private static final String OBJECT_ID_FIELD = "_id"; private static MongoClient mongoClient; private static MongoDatabase database; private static MongoCollection<Document> collection; private static String collectionName; private static String databaseName; public static void setUp() { if (mongoClient == null) { mongoClient = new MongoClient("localhost", 27017); databaseName = "baeldung"; collectionName = "vehicle"; database = mongoClient.getDatabase(databaseName); collection = database.getCollection(collectionName); } } public static void retrieveAllDocumentsUsingFindWithObjectId() { Document document = collection.find() .first(); System.out.println(document); FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, document.get(OBJECT_ID_FIELD))); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void retrieveFirstDocumentWithObjectId() { Document document = collection.find() .first();
System.out.println(document); FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, document.get(OBJECT_ID_FIELD))); Document queriedDocument = documents.first(); System.out.println(queriedDocument); } public static void retrieveDocumentWithRandomObjectId() { FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, new ObjectId())); Document queriedDocument = documents.first(); if (queriedDocument != null) { System.out.println(queriedDocument); } else { System.out.println("No documents found"); } } public static void main(String args[]) { setUp(); retrieveAllDocumentsUsingFindWithObjectId(); retrieveFirstDocumentWithObjectId(); retrieveDocumentWithRandomObjectId(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\find\FindWithObjectId.java
1
请完成以下Java代码
private Iterable<I_C_Invoice_Candidate> retrieveSelection(@NonNull final PInstanceId pinstanceId) { return () -> invoiceCandDAO.retrieveIcForSelection(pinstanceId, PlainContextAware.newWithThreadInheritedTrx(getCtx())); } @Override public IInvoiceCandidateEnqueuer setContext(@NonNull final Properties ctx) { this._ctx = ctx; return this; } /** * @return context; never returns null */ private Properties getCtx() { return _ctx; } @Override public InvoiceCandidateEnqueuer setFailIfNothingEnqueued(final boolean failIfNothingEnqueued) { this._failIfNothingEnqueued = failIfNothingEnqueued; return this; } private boolean isFailIfNothingEnqueued() { return _failIfNothingEnqueued; } private boolean isFailOnInvoiceCandidateError() { return _failOnInvoiceCandidateError; } @Override public IInvoiceCandidateEnqueuer setInvoicingParams(final IInvoicingParams invoicingParams) { this._invoicingParams = invoicingParams; return this; } private IInvoicingParams getInvoicingParams() { Check.assumeNotNull(_invoicingParams, "invoicingParams not null"); return _invoicingParams; } @Override public final InvoiceCandidateEnqueuer setFailOnChanges(final boolean failOnChanges) { this._failOnChanges = failOnChanges; return this; } private boolean isFailOnChanges() { // Use the explicit setting if available if (_failOnChanges != null) { return _failOnChanges; } // Use the sysconfig setting return sysConfigBL.getBooleanValue(SYSCONFIG_FailOnChanges, DEFAULT_FailOnChanges); } private IInvoiceCandidatesChangesChecker newInvoiceCandidatesChangesChecker() {
if (isFailOnChanges()) { return new InvoiceCandidatesChangesChecker() .setTotalNetAmtToInvoiceChecksum(_totalNetAmtToInvoiceChecksum); } else { return IInvoiceCandidatesChangesChecker.NULL; } } @Override public IInvoiceCandidateEnqueuer setTotalNetAmtToInvoiceChecksum(final BigDecimal totalNetAmtToInvoiceChecksum) { this._totalNetAmtToInvoiceChecksum = totalNetAmtToInvoiceChecksum; return this; } @Override public IInvoiceCandidateEnqueuer setAsyncBatchId(final AsyncBatchId asyncBatchId) { _asyncBatchId = asyncBatchId; return this; } @Override public IInvoiceCandidateEnqueuer setPriority(final IWorkpackagePrioStrategy priority) { _priority = priority; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateEnqueuer.java
1
请在Spring Boot框架中完成以下Java代码
public class MenuWrapper extends BaseEntityWrapper<Menu, MenuVO> { private static IMenuService menuService; private static IDictClient dictClient; static { menuService = SpringUtil.getBean(IMenuService.class); dictClient = SpringUtil.getBean(IDictClient.class); } public static MenuWrapper build() { return new MenuWrapper(); } @Override public MenuVO entityVO(Menu menu) { MenuVO menuVO = BeanUtil.copyProperties(menu, MenuVO.class); if (Func.equals(menu.getParentId(), CommonConstant.TOP_PARENT_ID)) { menuVO.setParentName(CommonConstant.TOP_PARENT_NAME); } else { Menu parent = menuService.getById(menu.getParentId()); menuVO.setParentName(parent.getName()); } R<String> d1 = dictClient.getValue("menu_category", Func.toInt(menuVO.getCategory())); R<String> d2 = dictClient.getValue("button_func", Func.toInt(menuVO.getAction())); R<String> d3 = dictClient.getValue("yes_no", Func.toInt(menuVO.getIsOpen()));
if (d1.isSuccess()) { menuVO.setCategoryName(d1.getData()); } if (d2.isSuccess()) { menuVO.setActionName(d2.getData()); } if (d3.isSuccess()) { menuVO.setIsOpenName(d3.getData()); } return menuVO; } public List<MenuVO> listNodeVO(List<Menu> list) { List<MenuVO> collect = list.stream().map(menu -> BeanUtil.copyProperties(menu, MenuVO.class)).collect(Collectors.toList()); return ForestNodeMerger.merge(collect); } public List<MenuVO> listNodeLazyVO(List<MenuVO> list) { return ForestNodeMerger.merge(list); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\wrapper\MenuWrapper.java
2
请完成以下Java代码
private PackageDimensions extractDimensionsInCM(@Nullable final JsonDimensions dimensions) { if (dimensions == null) { return PackageDimensions.UNSPECIFIED; } return PackageDimensions.builder() .lengthInCM(dimensions.getLength()) .widthInCM(dimensions.getWidth()) .heightInCM(dimensions.getHeight()) .build(); } @Nullable private String createTrackingURLOrNull( @Nullable final String trackingBaseURL, @NonNull final JsonPackage jsonPackage) { if (Check.isNotBlank(trackingBaseURL) && Check.isNotBlank(jsonPackage.getTrackingCode())) { return trackingBaseURL + jsonPackage.getTrackingCode(); } else if (Check.isNotBlank(trackingBaseURL)) { return trackingBaseURL; } return null; }
private void createTransportationOrderAndPackages(@NonNull final HashMap<GenerateShippingPackagesGroupingKey, HashSet<PackageInfo>> groupingKey2PackageInfoList) { groupingKey2PackageInfoList.entrySet() .stream() .map(entry -> AddTrackingInfosForInOutWithoutHUReq.builder() .inOutId(entry.getKey().getInOutId()) .shipperId(entry.getKey().getShipperId()) .packageInfos(ImmutableList.copyOf(entry.getValue())) .build()) .map(huShipperTransportationBL::addTrackingInfosForInOutWithoutHU) .forEach(huShipperTransportationBL::processShipperTransportation); } @Value @Builder private static class GenerateShippingPackagesGroupingKey { @NonNull InOutId inOutId; @NonNull ShipperId shipperId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\mpackage\ShippingPackageService.java
1
请完成以下Java代码
public void removeLast() { if (isEmpty()) { return; } else if (size() == 1) { tail = null; head = null; } else { Node<S> secondToLast = null; Node<S> last = head; while (last.next != null) { secondToLast = last; last = last.next; } secondToLast.next = null; } --size; } public boolean contains(S element) { if (isEmpty()) { return false; } Node<S> current = head; while (current != null) { if (Objects.equals(element, current.element)) return true; current = current.next; } return false;
} private boolean isLastNode(Node<S> node) { return tail == node; } private boolean isFistNode(Node<S> node) { return head == node; } public static class Node<T> { private T element; private Node<T> next; public Node(T element) { this.element = element; } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\linkedlistremove\SinglyLinkedList.java
1
请完成以下Java代码
public class LogListener extends LogBaseListener { private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.ENGLISH); private List<LogEntry> entries = new ArrayList<>(); private LogEntry currentLogEntry; @Override public void enterEntry(LogParser.EntryContext ctx) { this.currentLogEntry = new LogEntry(); } @Override public void exitEntry(LogParser.EntryContext ctx) { entries.add(currentLogEntry); } @Override public void enterTimestamp(LogParser.TimestampContext ctx) { currentLogEntry.setTimestamp(LocalDateTime.parse(ctx.getText(), DEFAULT_DATETIME_FORMATTER));
} @Override public void enterMessage(LogParser.MessageContext ctx) { currentLogEntry.setMessage(ctx.getText()); } @Override public void enterLevel(LogParser.LevelContext ctx) { currentLogEntry.setLevel(LogLevel.valueOf(ctx.getText())); } public List<LogEntry> getEntries() { return Collections.unmodifiableList(entries); } }
repos\tutorials-master\text-processing-libraries-modules\antlr\src\main\java\com\baeldung\antlr\log\LogListener.java
1
请完成以下Java代码
public I_C_Calendar getC_Calendar() throws RuntimeException { return (I_C_Calendar)MTable.get(getCtx(), I_C_Calendar.Table_Name) .getPO(getC_Calendar_ID(), get_TrxName()); } /** Set Calendar. @param C_Calendar_ID Accounting Calendar Name */ public void setC_Calendar_ID (int C_Calendar_ID) { if (C_Calendar_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, Integer.valueOf(C_Calendar_ID)); } /** Get Calendar. @return Accounting Calendar Name */ public int getC_Calendar_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Calendar_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Year. @param C_Year_ID Calendar Year */ public void setC_Year_ID (int C_Year_ID) { if (C_Year_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Year_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID)); } /** Get Year. @return Calendar Year */ public int getC_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Year. @param FiscalYear The Fiscal Year */ public void setFiscalYear (String FiscalYear) { set_Value (COLUMNNAME_FiscalYear, FiscalYear);
} /** Get Year. @return The Fiscal Year */ public String getFiscalYear () { return (String)get_Value(COLUMNNAME_FiscalYear); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getFiscalYear()); } /** 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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Year.java
1
请在Spring Boot框架中完成以下Java代码
private StatsCounter register(StatsCounter counter) { counters.add(counter); return counter; } public void log(ToEdgeNotificationMsg msg) { totalCounter.increment(); if (msg.hasEdgeHighPriority()) { edgeHighPriorityCounter.increment(); } else if (msg.hasEdgeEventUpdate()) { edgeEventUpdateCounter.increment(); } else if (msg.hasToEdgeSyncRequest()) { edgeSyncRequestCounter.increment(); } else if (msg.hasFromEdgeSyncResponse()) { edgeSyncResponseCounter.increment(); } else if (msg.hasComponentLifecycle()) { edgeComponentLifecycle.increment(); } } public void log(ToEdgeMsg msg) { totalCounter.increment();
edgeNotificationsCounter.increment(); } public void printStats() { int total = totalCounter.get(); if (total > 0) { StringBuilder stats = new StringBuilder(); counters.forEach(counter -> stats.append(counter.getName()).append(" = [").append(counter.get()).append("] ")); log.info("Edge Stats: {}", stats); } } public void reset() { counters.forEach(StatsCounter::clear); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\EdgeConsumerStats.java
2
请完成以下Java代码
public boolean isFinishedGoods() { return !isBOMLine(); } public boolean isBOMLine() { return ppOrderBOMLineId != null; } public PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { final PPOrderId ppOrderIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getPpOrderId() : null; final PPOrderBOMLineId lineIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getLineId() : null; return PPOrderId.equals(this.ppOrderId, ppOrderIdNew) && PPOrderBOMLineId.equals(this.ppOrderBOMLineId, lineIdNew) ? this : toBuilder().ppOrderId(ppOrderIdNew).ppOrderBOMLineId(lineIdNew).build(); } public PPOrderRef withPPOrderId(@Nullable final PPOrderId ppOrderId) { if (PPOrderId.equals(this.ppOrderId, ppOrderId)) { return this; } return toBuilder().ppOrderId(ppOrderId).build(); } @Nullable public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderId(newPPOrderId); } else if (newPPOrderId != null) { return ofPPOrderId(newPPOrderId); } else { return null; } }
@Nullable public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId); } else if (newPPOrderAndBOMLineId != null) { return ofPPOrderBOMLineId(newPPOrderAndBOMLineId); } else { return null; } } @Nullable public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java
1
请完成以下Java代码
protected String getHistoryRemovalTimeStrategy(CommandContext commandContext) { return commandContext.getProcessEngineConfiguration() .getHistoryRemovalTimeStrategy(); } protected boolean isDmnEnabled(CommandContext commandContext) { return commandContext.getProcessEngineConfiguration().isDmnEnabled(); } protected Date calculateRemovalTime(HistoricBatchEntity batch, CommandContext commandContext) { return commandContext.getProcessEngineConfiguration() .getHistoryRemovalTimeProvider() .calculateRemovalTime(batch); } protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) { return commandContext.getDbEntityManager() .selectById(ByteArrayEntity.class, byteArrayId); } protected HistoricBatchEntity findBatchById(String instanceId, CommandContext commandContext) { return commandContext.getHistoricBatchManager() .findHistoricBatchById(instanceId); } public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; }
protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration, List<String> batchIds) { return new SetRemovalTimeBatchConfiguration(batchIds) .setRemovalTime(configuration.getRemovalTime()) .setHasRemovalTime(configuration.hasRemovalTime()); } protected SetRemovalTimeJsonConverter getJsonConverterInstance() { return SetRemovalTimeJsonConverter.INSTANCE; } public String getType() { return Batch.TYPE_BATCH_SET_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\BatchSetRemovalTimeJobHandler.java
1
请完成以下Java代码
public boolean computeUnsetValue(@NonNull final SyncAdvise syncAdvise) { final boolean explicitlyUnsetDiscount = coalesce(this.getUnsetValue(), false); if (explicitlyUnsetDiscount) { return true; } final boolean implicitlyUnsetPrice = this.getValue() == null && syncAdvise.getIfExists().isUpdateRemove(); if (implicitlyUnsetPrice) { return true; } return false; } public boolean computeSetValue(@NonNull final SyncAdvise syncAdvise) { final IfExists isExistsAdvise = syncAdvise.getIfExists(); final boolean dontChangeAtAll = !isExistsAdvise.isUpdate(); if (dontChangeAtAll) { return false;
} final boolean dontChangeIfNotSet = dontChangeAtAll || isExistsAdvise.isUpdateMerge(); final boolean implicitlyDontSetPrice = this.getValue() == null && dontChangeIfNotSet; if (implicitlyDontSetPrice) { return false; } return true; } protected abstract Object getValue(); protected abstract Boolean getUnsetValue(); }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\JsonUnsettableValue.java
1
请在Spring Boot框架中完成以下Java代码
public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Set<String> getAuthorities() { return authorities; } public void setAuthorities(Set<String> authorities) { this.authorities = authorities; } // prettier-ignore @Override public String toString() { return "AdminUserDTO{" +
"login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated=" + activated + ", langKey='" + langKey + '\'' + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", lastModifiedBy='" + lastModifiedBy + '\'' + ", lastModifiedDate=" + lastModifiedDate + ", authorities=" + authorities + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\dto\AdminUserDTO.java
2
请完成以下Java代码
public final class ShipmentCandidatesView extends AbstractCustomView<ShipmentCandidateRow> implements IEditableView { private final IShipmentScheduleBL shipmentScheduleBL; @Builder private ShipmentCandidatesView( @NonNull final IShipmentScheduleBL shipmentScheduleBL, // @NonNull final ViewId viewId, @Nullable final ITranslatableString description, @NonNull final ShipmentCandidateRows rows) { super(viewId, description, rows, NullDocumentFilterDescriptorsProvider.instance); this.shipmentScheduleBL = shipmentScheduleBL; } @Override public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override protected ShipmentCandidateRows getRowsData() { return ShipmentCandidateRows.cast(super.getRowsData());
} @Override public void close(final ViewCloseAction closeAction) { if (closeAction.isDone()) { saveChanges(); } } private void saveChanges() { final ShipmentScheduleUserChangeRequestsList userChanges = getRowsData().createShipmentScheduleUserChangeRequestsList().orElse(null); if (userChanges == null) { return; } shipmentScheduleBL.applyUserChangesInTrx(userChanges); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidatesView.java
1
请完成以下Java代码
public Integer getId() { return id; } public UserCacheObject setId(Integer id) { this.id = id; return this; } public String getName() { return name; } public UserCacheObject setName(String name) { this.name = name; return this; } public Integer getGender() {
return gender; } public UserCacheObject setGender(Integer gender) { this.gender = gender; return this; } @Override public String toString() { return "UserCacheObject{" + "id=" + id + ", name='" + name + '\'' + ", gender=" + gender + '}'; } }
repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-with-jedis\src\main\java\cn\iocoder\springboot\labs\lab10\springdatarediswithjedis\cacheobject\UserCacheObject.java
1
请完成以下Java代码
private Set<String> getCombinedParameterNames() { Set<String> names = new HashSet<>(); names.addAll(super.getParameterMap().keySet()); names.addAll(this.savedRequest.getParameterMap().keySet()); return names; } @Override public Enumeration<String> getParameterNames() { return new Enumerator<>(getCombinedParameterNames()); } @Override public String[] getParameterValues(String name) { String[] savedRequestParams = this.savedRequest.getParameterValues(name); String[] wrappedRequestParams = super.getParameterValues(name); if (savedRequestParams == null) { return wrappedRequestParams;
} if (wrappedRequestParams == null) { return savedRequestParams; } // We have parameters in both saved and wrapped requests so have to merge them List<String> wrappedParamsList = Arrays.asList(wrappedRequestParams); List<String> combinedParams = new ArrayList<>(wrappedParamsList); // We want to add all parameters of the saved request *apart from* duplicates of // those already added for (String savedRequestParam : savedRequestParams) { if (!wrappedParamsList.contains(savedRequestParam)) { combinedParams.add(savedRequestParam); } } return combinedParams.toArray(new String[0]); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SavedRequestAwareWrapper.java
1
请完成以下Java代码
public class ExternalIdsUtil { private static final String EXTERNAL_ID_DELIMITER = ";,;"; public static String joinExternalIds(@NonNull final List<String> externalIds) { return externalIds .stream() .collect(Collectors.joining(EXTERNAL_ID_DELIMITER)); } /** * @return empty list if the given parameter is null or empty. */ public static List<String> splitExternalIds(@Nullable final String externalIds) { if (Check.isBlank(externalIds)) { return ImmutableList.of(); } return Splitter .on(EXTERNAL_ID_DELIMITER) .splitToList(externalIds); } public static int extractSingleRecordId(@NonNull final List<String> externalIds)
{ if (externalIds.size() != 1) { return -1; } final String externalId = CollectionUtils.singleElement(externalIds); final List<String> externalIdSegments = Splitter .on("_") .splitToList(externalId); if (externalIdSegments.isEmpty()) { return -1; } final String recordIdStr = externalIdSegments.get(externalIdSegments.size() - 1); try { return Integer.parseInt(recordIdStr); } catch (NumberFormatException nfe) { return -1; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\lang\ExternalIdsUtil.java
1
请完成以下Java代码
private ImmutableTableNamesGroupsIndex getTableNamesToBroadcastIndex() { return _tableNamesToBroadcastIndex; } public ImmutableSet<String> getTableNamesToBroadcast() { return getTableNamesToBroadcastIndex().getTableNames(); } /** * Broadcast a cache invalidation request. */ public void postEvent(final CacheInvalidateMultiRequest request) { // Do nothing if cache invalidation broadcasting is not enabled if (!isEnabled()) { logger.trace("Skip broadcasting {} because feature is not enabled", request); return; } // Do nothing if given table name is not in our table names to broadcast list if (!isAllowBroadcast(request)) { logger.trace("Skip broadcasting {} because it's not allowed", request); return; } // Broadcast the event. final Event event = createEventFromRequest(request); try (final MDCCloseable ignored = EventMDC.putEvent(event)) { logger.debug("Broadcasting cacheInvalidateMultiRequest={}", request); getEventBusFactory() .getEventBus(TOPIC_CacheInvalidation) .enqueueEvent(event); } } private boolean isAllowBroadcast(final CacheInvalidateMultiRequest multiRequest) { return multiRequest.getRequests().stream().anyMatch(this::isAllowBroadcast); } private boolean isAllowBroadcast(final CacheInvalidateRequest request) { final ImmutableTableNamesGroupsIndex index = this.getTableNamesToBroadcastIndex(); return index.containsTableName(request.getRootTableName()) || index.containsTableName(request.getChildTableName()); } /** * Called when we got a remote cache invalidation request. It tries to invalidate local caches. */ @Override public void onEvent(final IEventBus eventBus, final Event event) { // Ignore local events because they were fired from CacheMgt.reset methods. // If we would not do so, we would have an infinite loop here. if (event.isLocalEvent()) { logger.debug("onEvent - ignoring local event={}", event); return; } final CacheInvalidateMultiRequest request = createRequestFromEvent(event); if (request == null)
{ logger.debug("onEvent - ignoring event without payload; event={}", event); return; } // // Reset cache for TableName/Record_ID logger.debug("onEvent - resetting local cache for request {} because we got remote event={}", request, event); CacheMgt.get().reset(request, CacheMgt.ResetMode.LOCAL); // don't broadcast it anymore because else we would introduce recursion } @VisibleForTesting Event createEventFromRequest(@NonNull final CacheInvalidateMultiRequest request) { return Event.builder() .putProperty(EVENT_PROPERTY, jsonSerializer.toJson(request)) .build(); } @Nullable private CacheInvalidateMultiRequest createRequestFromEvent(final Event event) { final String jsonRequest = event.getProperty(EVENT_PROPERTY); if (Check.isEmpty(jsonRequest, true)) { return null; } return jsonSerializer.fromJson(jsonRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheInvalidationRemoteHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void addInterceptors(InterceptorRegistry registry) { // Add Sentinel interceptor // addSentinelWebTotalInterceptor(registry); addSentinelWebInterceptor(registry); } private void addSentinelWebInterceptor(InterceptorRegistry registry) { // 创建 SentinelWebMvcConfig 对象 SentinelWebMvcConfig config = new SentinelWebMvcConfig(); config.setHttpMethodSpecify(true); // 是否包含请求方法。即基于 URL 创建的资源,是否包含 Method。 // config.setBlockExceptionHandler(new DefaultBlockExceptionHandler()); // 设置 BlockException 处理器。 // config.setOriginParser(new RequestOriginParser() { // 设置请求来源解析器。用于黑白名单控制功能。 // // @Override // public String parseOrigin(HttpServletRequest request) { // // 从 Header 中,获得请求来源 // String origin = request.getHeader("s-user"); // // 如果为空,给一个默认的 // if (StringUtils.isEmpty(origin)) { // origin = "default"; // } // return origin; // } //
// }); // 添加 SentinelWebInterceptor 拦截器 registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**"); } private void addSentinelWebTotalInterceptor(InterceptorRegistry registry) { // 创建 SentinelWebMvcTotalConfig 对象 SentinelWebMvcTotalConfig config = new SentinelWebMvcTotalConfig(); // 添加 SentinelWebTotalInterceptor 拦截器 registry.addInterceptor(new SentinelWebTotalInterceptor(config)).addPathPatterns("/**"); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SpringMvcConfiguration.java
2
请完成以下Java代码
public class YamlLoaderInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); private final String file; public YamlLoaderInitializer() { this.file = null; } public YamlLoaderInitializer(String file) { this.file = file; } @Override public void initialize(ConfigurableApplicationContext applicationContext) { String yamlFile = (this.file == null) ? applicationContext.getEnvironment() .getProperty("custom.configyaml.file") : this.file; Resource path = new ClassPathResource(yamlFile); PropertySource<?> propertySource = loadYaml(path);
applicationContext.getEnvironment() .getPropertySources() .addLast(propertySource); } private PropertySource<?> loadYaml(Resource path) { if (!path.exists()) { throw new IllegalArgumentException("Resource " + path + " does not exist"); } try { return this.loader.load("custom-resource", path) .get(0); } catch (IOException ex) { throw new IllegalStateException("Failed to load yaml configuration from" + path, ex); } } }
repos\tutorials-master\spring-security-modules\spring-security-oidc\src\main\java\com\baeldung\openid\oidc\utils\YamlLoaderInitializer.java
1
请完成以下Java代码
public class Fruit { @Min(value = 10, message = "Fruit weight must be 10 or greater") private Integer weight; @Size(min = 5, max = 200) private String name; @Size(min = 5, max = 200) private String colour; private String serial; public Fruit() { } public Fruit(String name, String colour) { this.name = name; this.colour = colour; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setColour(String colour) {
this.colour = colour; } public String getColour() { return colour; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } @Override public String toString() { return "Fruit [name: " + getName() + " colour: " + getColour() + "]"; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\model\Fruit.java
1
请完成以下Java代码
public int getRepoId() { return repoId; } public static boolean equals(@Nullable final CurrencyId currencyId1, @Nullable final CurrencyId currencyId2) { return Objects.equals(currencyId1, currencyId2); } @NonNull @SafeVarargs public static <T> CurrencyId getCommonCurrencyIdOfAll( @NonNull final Function<T, CurrencyId> getCurrencyId, @NonNull final String name, @Nullable final T... objects) { if (objects == null || objects.length == 0) { throw new AdempiereException("No " + name + " provided"); } else if (objects.length == 1 && objects[0] != null) { return getCurrencyId.apply(objects[0]); } else { CurrencyId commonCurrencyId = null; for (final T object : objects) { if (object == null) { continue; } final CurrencyId currencyId = getCurrencyId.apply(object); if (commonCurrencyId == null) { commonCurrencyId = currencyId; } else if (!CurrencyId.equals(commonCurrencyId, currencyId)) { throw new AdempiereException("All given " + name + "(s) shall have the same currency: " + Arrays.asList(objects)); }
} if (commonCurrencyId == null) { throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects)); } return commonCurrencyId; } } @SafeVarargs public static <T> void assertCurrencyMatching( @NonNull final Function<T, CurrencyId> getCurrencyId, @NonNull final String name, @Nullable final T... objects) { if (objects == null || objects.length <= 1) { return; } CurrencyId expectedCurrencyId = null; for (final T object : objects) { if (object == null) { continue; } final CurrencyId currencyId = getCurrencyId.apply(object); if (expectedCurrencyId == null) { expectedCurrencyId = currencyId; } else if (!CurrencyId.equals(currencyId, expectedCurrencyId)) { throw new AdempiereException("" + name + " has invalid currency: " + object + ". Expected: " + expectedCurrencyId); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\CurrencyId.java
1
请在Spring Boot框架中完成以下Java代码
public class SourceCodeProjectGenerationConfiguration { @Bean public MainApplicationTypeCustomizer<TypeDeclaration> springBootApplicationAnnotator() { return (typeDeclaration) -> typeDeclaration.annotations() .addSingle(ClassName.of("org.springframework.boot.autoconfigure.SpringBootApplication")); } @Bean public TestApplicationTypeCustomizer<TypeDeclaration> junitJupiterSpringBootTestTypeCustomizer() { return (typeDeclaration) -> typeDeclaration.annotations() .addSingle(ClassName.of("org.springframework.boot.test.context.SpringBootTest")); } /** * Language-agnostic source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { private final ProjectDescription description;
WarPackagingConfiguration(ProjectDescription description) { this.description = description; } @Bean @ConditionalOnPlatformVersion("2.0.0.M1") ServletInitializerContributor boot20ServletInitializerContributor( ObjectProvider<ServletInitializerCustomizer<?>> servletInitializerCustomizers) { return new ServletInitializerContributor(this.description.getPackageName(), "org.springframework.boot.web.servlet.support.SpringBootServletInitializer", servletInitializerCustomizers); } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\SourceCodeProjectGenerationConfiguration.java
2
请完成以下Java代码
private URL getURL(final String relativePath, final Map<String, String> params) { final String serverUrl = getServerUrl(); final StringBuilder urlStrBuf = new StringBuilder(); urlStrBuf.append(serverUrl); if (!urlStrBuf.toString().endsWith("/") && !IArchiveEndpoint.PATH_Service.startsWith("/")) { urlStrBuf.append("/"); } urlStrBuf.append(IArchiveEndpoint.PATH_Service); if (!urlStrBuf.toString().endsWith("/") && !relativePath.startsWith("/")) { urlStrBuf.append("/"); } urlStrBuf.append(relativePath); final String urlStr = MapFormat.format(urlStrBuf.toString(), params); try { return new URL(urlStr); } catch (final MalformedURLException e) { throw new RuntimeException("Invalid URL " + urlStr, e); } } private <T> T executePost(final String path, final Map<String, String> params, final Object request, final Class<T> responseClass) { final URL url = getURL(path, params); final PostMethod httpPost = new PostMethod(url.toString()); final byte[] data = beanEncoder.encode(request); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; InputStream in = null; try { result = executeHttpPost(httpPost);
in = httpPost.getResponseBodyAsStream(); if (result != 200) { final String errorMsg = in == null ? "code " + result : IOStreamUtils.toString(in); throw new AdempiereException("Error " + result + " while posting on " + url + ": " + errorMsg); } if (responseClass != null) { final T response = beanEncoder.decodeStream(in, responseClass); return response; } } catch (final Exception e) { throw new AdempiereException(e); } finally { IOStreamUtils.close(in); in = null; } return null; } private int executeHttpPost(final PostMethod httpPost) throws HttpException, IOException { final int result = httpclient.executeMethod(httpPost); RestHttpArchiveEndpoint.logger.trace("Result code: {}", result); // final DefaultMethodRetryHandler retryHandler = new DefaultMethodRetryHandler(); // retryHandler.setRetryCount(3); // httpPost.setMethodRetryHandler(retryHandler); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\RestHttpArchiveEndpoint.java
1
请完成以下Java代码
public class MethodInfo { private final String name; private final Class<?>[] paramTypes; private final Class<?> returnType; public MethodInfo(String name, Class<?> returnType, Class<?>[] paramTypes) { this.name = name; this.returnType = returnType; this.paramTypes = paramTypes; } public String getName() { return this.name; } public Class<?> getReturnType() { return this.returnType; } public Class<?>[] getParamTypes() { return this.paramTypes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + Arrays.hashCode(paramTypes); result = prime * result + ((returnType == null) ? 0 : returnType.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; } MethodInfo other = (MethodInfo) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (!Arrays.equals(paramTypes, other.paramTypes)) { return false; } if (returnType == null) { return other.returnType == null; } else { return returnType.equals(other.returnType); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MethodInfo.java
1
请完成以下Java代码
public void setIsOneAssetPerUOM (boolean IsOneAssetPerUOM) { set_Value (COLUMNNAME_IsOneAssetPerUOM, Boolean.valueOf(IsOneAssetPerUOM)); } /** Get One Asset Per UOM. @return Create one asset per UOM */ public boolean isOneAssetPerUOM () { Object oo = get_Value(COLUMNNAME_IsOneAssetPerUOM); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Owned. @param IsOwned The asset is owned by the organization */ public void setIsOwned (boolean IsOwned) { set_Value (COLUMNNAME_IsOwned, Boolean.valueOf(IsOwned)); } /** Get Owned. @return The asset is owned by the organization */ public boolean isOwned () { Object oo = get_Value(COLUMNNAME_IsOwned); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Track Issues. @param IsTrackIssues Enable tracking issues for this asset */ public void setIsTrackIssues (boolean IsTrackIssues) { set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues)); }
/** Get Track Issues. @return Enable tracking issues for this asset */ public boolean isTrackIssues () { Object oo = get_Value(COLUMNNAME_IsTrackIssues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group.java
1
请在Spring Boot框架中完成以下Java代码
public class PostMaterialEventService { private static final Logger logger = LogManager.getLogger(PostMaterialEventService.class); private final MetasfreshEventBusService materialEventService; public PostMaterialEventService(@NonNull final MetasfreshEventBusService materialEventService) { this.materialEventService = materialEventService; } /** * Adds a trx listener to make sure the given {@code event} will be fired via {@link #enqueueEventNow(MaterialEvent)} before the given {@code trxName} is committed. */ public void enqueueEventAfterNextCommit(@NonNull final MaterialEvent event) { final ITrxManager trxManager = Services.get(ITrxManager.class); trxManager.accumulateAndProcessAfterCommit(event.getEventName(), ImmutableSet.of(event), this::enqueueEventsNow);
} /** * Fires the given event using our (distributed) event framework. * <b>Important:</b> Please make sure to only use this method if you know that all the data which this event refers to is already committed to database! */ public void enqueueEventNow(final MaterialEvent event) { materialEventService.enqueueEvent(event); logger.debug("Posted MaterialEvent={}", event); } public void enqueueEventsNow(final Collection<MaterialEvent> events) { events.forEach(this::enqueueEventNow); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\PostMaterialEventService.java
2
请完成以下Java代码
private HashMap<DocumentPath, TableRecordReference> getTableRecordReferences(@NonNull final ImmutableList<IViewRow> rows) { final ImmutableSet<DocumentPath> documentPaths = rows.stream() .map(IViewRow::getDocumentPath) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); final HashMap<DocumentPath, TableRecordReference> recordRefsByDocumentPath = new HashMap<>(rows.size()); for (final DocumentPath documentPath : documentPaths) { @SuppressWarnings("SimplifyOptionalCallChains") final TableRecordReference recordRef = documentDescriptorFactory.getTableRecordReferenceIfPossible(documentPath).orElse(null); if (recordRef != null) { recordRefsByDocumentPath.put(documentPath, recordRef); } } return recordRefsByDocumentPath; } public boolean hasComments(@NonNull final DocumentPath documentPath) { final TableRecordReference reference = documentDescriptorFactory.getTableRecordReferenceIfPossible(documentPath).orElse(null); if (reference == null) { return false; } final Map<TableRecordReference, Boolean> referencesWithComments = commentsRepository.hasComments(ImmutableList.of(reference)); return referencesWithComments.getOrDefault(reference, false); } @NonNull public ImmutableList<JSONComment> getRowCommentsAsJson(@NonNull final DocumentPath documentPath, final ZoneId zoneId) {
final TableRecordReference tableRecordReference = documentDescriptorFactory.getTableRecordReference(documentPath); final List<CommentEntry> comments = commentsRepository.retrieveLastCommentEntries(tableRecordReference, 100); return comments.stream() .map(comment -> toJsonComment(comment, zoneId)) .sorted(Comparator.comparing(JSONComment::getCreated).reversed()) .collect(ImmutableList.toImmutableList()); } public void addComment(@NonNull final DocumentPath documentPath, @NonNull final JSONCommentCreateRequest jsonCommentCreateRequest) { final TableRecordReference tableRecordReference = documentDescriptorFactory.getTableRecordReference(documentPath); commentsRepository.createCommentEntry(jsonCommentCreateRequest.getText(), tableRecordReference); } @NonNull private JSONComment toJsonComment(@NonNull final CommentEntry comment, final ZoneId zoneId) { final String text = comment.getText(); final String created = DateTimeConverters.toJson(comment.getCreated(), zoneId); final String createdBy = userDAO.retrieveUserFullName(comment.getCreatedBy()); return JSONComment.builder() .text(text) .created(created) .createdBy(createdBy) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\comments\CommentsService.java
1
请完成以下Java代码
public String getSysNm() { return sysNm; } /** * Sets the value of the sysNm property. * * @param value * allowed object is * {@link String } * */ public void setSysNm(String value) { this.sysNm = value; } /** * Gets the value of the grpId property. * * @return * possible object is * {@link String } * */ public String getGrpId() { return grpId; } /** * Sets the value of the grpId property. * * @param value * allowed object is * {@link String } * */ public void setGrpId(String value) { this.grpId = value; } /** * Gets the value of the cpblties property. * * @return * possible object is * {@link PointOfInteractionCapabilities1 } * */ public PointOfInteractionCapabilities1 getCpblties() { return cpblties;
} /** * Sets the value of the cpblties property. * * @param value * allowed object is * {@link PointOfInteractionCapabilities1 } * */ public void setCpblties(PointOfInteractionCapabilities1 value) { this.cpblties = value; } /** * Gets the value of the cmpnt 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 cmpnt property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCmpnt().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PointOfInteractionComponent1 } * * */ public List<PointOfInteractionComponent1> getCmpnt() { if (cmpnt == null) { cmpnt = new ArrayList<PointOfInteractionComponent1>(); } return this.cmpnt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteraction1.java
1
请在Spring Boot框架中完成以下Java代码
public class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String slug; private String title; @Enumerated(EnumType.STRING) private Status status; public enum Status { DRAFT, PUBLISHED } public Article() { } public Article(String title) { this.title = title; this.status = Status.DRAFT; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } }
repos\tutorials-master\spring-boot-modules\spring-boot-annotations\src\main\java\com\baeldung\retryable\transactional\Article.java
2
请完成以下Java代码
public class OpenApiPermission implements Serializable { /** * id */ @TableId(type = IdType.ASSIGN_ID) private String id; /** * 接口ID */ private String apiId; /** * 认证ID */ private String apiAuthId; /**
* 创建人 */ private String createBy; /** * 创建时间 */ private Date createTime; /** * 更新人 */ private String updateBy; /** * 更新时间 */ private Date updateTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\entity\OpenApiPermission.java
1
请完成以下Java代码
public Set<String> getAllowedOrigins() { return allowedOrigins == null ? Collections.emptySet() : allowedOrigins; } public void setAllowedOrigins(Set<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public Set<String> getAllowedHeaders() { return allowedHeaders == null ? Collections.emptySet() : allowedHeaders; } public void setAllowedHeaders(Set<String> allowedHeaders) { this.allowedHeaders = allowedHeaders; } public Set<String> getExposedHeaders() {
return exposedHeaders == null ? Collections.emptySet() : exposedHeaders; } public void setExposedHeaders(Set<String> exposedHeaders) { this.exposedHeaders = exposedHeaders; } public Set<String> getAllowedMethods() { return allowedMethods == null ? Collections.emptySet() : allowedMethods; } public void setAllowedMethods(Set<String> allowedMethods) { this.allowedMethods = allowedMethods; } } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\RestAppProperties.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { if (para.getParameter() == null) { continue; } final String parameterName = para.getParameterName(); if (PARAM_DeliveryDate.equals(parameterName)) { p_deliveryDate = para.getParameterAsTimestamp(); } if (PARAM_PreparationDate.equals(parameterName)) { p_preparationDate = para.getParameterAsTimestamp(); } } final IShipmentSchedulePA shipmentSchedulePA = Services.get(IShipmentSchedulePA.class); final IQueryFilter<I_M_ShipmentSchedule> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBuilder<I_M_ShipmentSchedule> queryBuilderForShipmentSchedulesSelection = shipmentSchedulePA.createQueryForShipmentScheduleSelection(getCtx(), userSelectionFilter); // // Create selection and return how many items were added final int selectionCount = queryBuilderForShipmentSchedulesSelection .create() .createSelection(getPinstanceId()); if (selectionCount <= 0) { throw new AdempiereException("@NoSelection@"); } }
@Override protected String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); final IShipmentSchedulePA shipmentSchedulePA = Services.get(IShipmentSchedulePA.class); // update delivery date // no invalidation shipmentSchedulePA.updateDeliveryDate_Override(p_deliveryDate, pinstanceId); // In case preparation date is set as parameter, update the preparation date too if (p_preparationDate != null) { // no invalidation. Just set the preparation date that was given shipmentSchedulePA.updatePreparationDate_Override(p_preparationDate, pinstanceId); } else { // Initially, set null in preparation date. It will be calculated later, during the updating process. // This update will invalidate the selected schedules. shipmentSchedulePA.updatePreparationDate_Override(null, pinstanceId); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_ChangeDeliveryDate.java
1
请完成以下Java代码
public final class OAuth2RestClientHttpServiceGroupConfigurer implements RestClientHttpServiceGroupConfigurer { private final HttpRequestValues.Processor processor = ClientRegistrationIdProcessor.DEFAULT_INSTANCE; private final ClientHttpRequestInterceptor interceptor; private OAuth2RestClientHttpServiceGroupConfigurer(ClientHttpRequestInterceptor interceptor) { this.interceptor = interceptor; } @Override public void configureGroups(Groups<RestClient.Builder> groups) { // @formatter:off groups.forEachClient((group, client) -> client.requestInterceptor(this.interceptor)
); groups.forEachProxyFactory((group, factory) -> factory.httpRequestValuesProcessor(this.processor) ); // @formatter:on } public static OAuth2RestClientHttpServiceGroupConfigurer from( OAuth2AuthorizedClientManager authorizedClientManager) { OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor( authorizedClientManager); return new OAuth2RestClientHttpServiceGroupConfigurer(interceptor); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\client\support\OAuth2RestClientHttpServiceGroupConfigurer.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PricingSummary pricingSummary = (PricingSummary)o; return Objects.equals(this.adjustment, pricingSummary.adjustment) && Objects.equals(this.deliveryCost, pricingSummary.deliveryCost) && Objects.equals(this.deliveryDiscount, pricingSummary.deliveryDiscount) && Objects.equals(this.fee, pricingSummary.fee) && Objects.equals(this.priceDiscountSubtotal, pricingSummary.priceDiscountSubtotal) && Objects.equals(this.priceSubtotal, pricingSummary.priceSubtotal) && Objects.equals(this.tax, pricingSummary.tax) && Objects.equals(this.total, pricingSummary.total); } @Override public int hashCode() { return Objects.hash(adjustment, deliveryCost, deliveryDiscount, fee, priceDiscountSubtotal, priceSubtotal, tax, total); } @Override public String toString()
{ StringBuilder sb = new StringBuilder(); sb.append("class PricingSummary {\n"); sb.append(" adjustment: ").append(toIndentedString(adjustment)).append("\n"); sb.append(" deliveryCost: ").append(toIndentedString(deliveryCost)).append("\n"); sb.append(" deliveryDiscount: ").append(toIndentedString(deliveryDiscount)).append("\n"); sb.append(" fee: ").append(toIndentedString(fee)).append("\n"); sb.append(" priceDiscountSubtotal: ").append(toIndentedString(priceDiscountSubtotal)).append("\n"); sb.append(" priceSubtotal: ").append(toIndentedString(priceSubtotal)).append("\n"); sb.append(" tax: ").append(toIndentedString(tax)).append("\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PricingSummary.java
2
请完成以下Java代码
public String toString() { return "DocOutboundProducer [" + "tableName=" + tableName + ", isDocument=" + isDocument + "]"; } @Override public boolean accept(@Nullable final Object model) { if (model == null) { return false; } // Check tableName match final String modelTableName = InterfaceWrapperHelper.getModelTableName(model); if (!tableName.equals(modelTableName)) { return false; } if (isDocument) { return acceptDocument(model); } return true; } protected boolean acceptDocument(final Object model) { return docOutboundConfigService.retrieveConfigForModel(model) != null; } @Override public void createDocOutbound(@NonNull final Object model)
{ enqueueModelForWorkpackageProcessor(model, DocOutboundWorkpackageProcessor.class); } @Override public void voidDocOutbound(@NonNull final Object model) { enqueueModelForWorkpackageProcessor(model, ProcessPrintingQueueWorkpackageProcessor.class); } private void enqueueModelForWorkpackageProcessor( @NonNull final Object model, @NonNull final Class<? extends IWorkpackageProcessor> packageProcessorClass) { final Properties ctx = InterfaceWrapperHelper.getCtx(model); final I_C_Async_Batch asyncBatch = asyncBatchBL.getAsyncBatchId(model) .map(asyncBatchBL::getAsyncBatchById) .orElse(null); workPackageQueueFactory .getQueueForEnqueuing(ctx, packageProcessorClass) .newWorkPackage() .bindToThreadInheritedTrx() .addElement(model) .setC_Async_Batch(asyncBatch) .setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null)) .buildAndEnqueue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\AbstractDocOutboundProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class ReconciliationFileDownBiz { private static final Log LOG = LogFactory.getLog(ReconciliationFileDownBiz.class); private static final int DOWNLOAD_TRY_TIMES = 3;// 下载尝试次数 @Autowired private ReconciliationFactory reconciliationFactory; /** * 请求下载对账文件 . * * @param interfaceCode * 支付渠道 * @param billDate * 账单日 * @return */ public File downReconciliationFile(String interfaceCode, Date billDate) { // 支付渠道编码 if (StringUtil.isEmpty(interfaceCode)) { LOG.info("支付渠道编码为空"); return null; } // 对账单下载 return this.downFile(interfaceCode, billDate); } /** * 下载文件 *
* @param interfaceCode * 接口编码 * @param tradeGainCheckFileTime * 业务对账文件的获取时间 */ private File downFile(String interfaceCode, Date billDate) { LOG.info("银行渠道编号[" + interfaceCode + "],进入下载业务对账文件操作>>>"); try { File file = null; int downloadTrytimes = 0; // 默认尝试三次 while (file == null && downloadTrytimes < DOWNLOAD_TRY_TIMES) { try { downloadTrytimes++; // 使用工厂模式 file = reconciliationFactory.fileDown(interfaceCode, billDate); } catch (Exception e) { LOG.error("下载账单文件失败", e); Thread.sleep(10000); } } return file; } catch (Exception e) { LOG.error("下载微信账单文件失败", e); } return null; } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\biz\ReconciliationFileDownBiz.java
2
请在Spring Boot框架中完成以下Java代码
H2ConsoleLogger h2ConsoleLogger(ObjectProvider<DataSource> dataSources) { return new H2ConsoleLogger(dataSources, this.properties.getPath()); } private void configureH2ConsoleSettings(ServletRegistrationBean<JakartaWebServlet> registration, Settings settings) { if (settings.isTrace()) { registration.addInitParameter("trace", ""); } if (settings.isWebAllowOthers()) { registration.addInitParameter("webAllowOthers", ""); } if (settings.getWebAdminPassword() != null) { registration.addInitParameter("webAdminPassword", settings.getWebAdminPassword()); } } static class H2ConsoleLogger { H2ConsoleLogger(ObjectProvider<DataSource> dataSources, String path) { if (logger.isInfoEnabled()) { ClassLoader classLoader = getClass().getClassLoader(); withThreadContextClassLoader(classLoader, () -> log(getConnectionUrls(dataSources), path)); } } private void withThreadContextClassLoader(ClassLoader classLoader, Runnable action) { ClassLoader previous = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); action.run(); } finally { Thread.currentThread().setContextClassLoader(previous); } } private List<String> getConnectionUrls(ObjectProvider<DataSource> dataSources) { return dataSources.orderedStream(ObjectProvider.UNFILTERED) .map(this::getConnectionUrl) .filter(Objects::nonNull)
.toList(); } private @Nullable String getConnectionUrl(DataSource dataSource) { try (Connection connection = dataSource.getConnection()) { return "'" + connection.getMetaData().getURL() + "'"; } catch (Exception ex) { return null; } } private void log(List<String> urls, String path) { if (!urls.isEmpty()) { logger.info(LogMessage.format("H2 console available at '%s'. %s available at %s", path, (urls.size() > 1) ? "Databases" : "Database", String.join(", ", urls))); } } } }
repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleAutoConfiguration.java
2
请完成以下Java代码
public java.lang.String getRfQType () { return (java.lang.String)get_Value(COLUMNNAME_RfQType); } @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID)
{ if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ.java
1
请完成以下Java代码
public final String getPropagationType() { return huPIAttribute.getPropagationType(); } @Override public final IAttributeAggregationStrategy retrieveAggregationStrategy() { final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute); final int adJavaClassId = huPIAttribute.getAggregationStrategy_JavaClass_ID(); return attributeStrategyFactory.retrieveStrategy(ctx, adJavaClassId, IAttributeAggregationStrategy.class); } @Override public final IAttributeSplitterStrategy retrieveSplitterStrategy() { final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute); final int adJavaClassId = huPIAttribute.getSplitterStrategy_JavaClass_ID(); return attributeStrategyFactory.retrieveStrategy(ctx, adJavaClassId, IAttributeSplitterStrategy.class); } @Override public final IHUAttributeTransferStrategy retrieveTransferStrategy() { final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute); final int adJavaClassId = huPIAttribute.getHU_TansferStrategy_JavaClass_ID(); return attributeStrategyFactory.retrieveStrategy(ctx, adJavaClassId, IHUAttributeTransferStrategy.class); } @Override public final boolean isUseInASI() { return huPIAttribute.isUseInASI(); } @Override public final boolean isDefinedByTemplate() { if (_definedByTemplate == null) { synchronized (this) { if (_definedByTemplate == null) { _definedByTemplate = Services.get(IHUPIAttributesDAO.class).isTemplateAttribute(huPIAttribute); } } } return _definedByTemplate; } public final I_M_HU_PI_Attribute getM_HU_PI_Attribute() { return huPIAttribute; } @Override public final I_C_UOM getC_UOM() { final int uomId = huPIAttribute.getC_UOM_ID(); if (uomId > 0) { return Services.get(IUOMDAO.class).getById(uomId); } else { // fallback to M_Attribute's UOM return super.getC_UOM();
} } @Override public final boolean isReadonlyUI() { return huPIAttribute.isReadOnly(); } @Override public final boolean isDisplayedUI() { return huPIAttribute.isDisplayed(); } @Override public final boolean isMandatory() { return huPIAttribute.isMandatory(); } @Override public final int getDisplaySeqNo() { final int seqNo = huPIAttribute.getSeqNo(); if (seqNo > 0) { return seqNo; } // Fallback: if SeqNo was not set, return max int (i.e. show them last) return Integer.MAX_VALUE; } @Override public boolean isOnlyIfInProductAttributeSet() { return huPIAttribute.isOnlyIfInProductAttributeSet(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractHUAttributeValue.java
1
请完成以下Java代码
public static Json succ(String operate, String dataKey, Object dataVal) { return new Json(operate, true, DEFAULT_SUCC_CODE, DEFAULT_SUCC_MSG, null).data(dataKey, dataVal); } ////// 操作失败的: public static Json fail() { return new Json(DEFAULT_OPER_VAL, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null); } public static Json fail(String operate) { return new Json(operate, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null); } public static Json fail(String operate, String message) { return new Json(operate, false, DEFAULT_FAIL_CODE, message, null); } public static Json fail(String operate, Object data) { return new Json(operate, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, data); } public static Json fail(String operate, String dataKey, Object dataVal) { return new Json(operate, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null).data(dataKey, dataVal); } ////// 操作动态判定成功或失败的: public static Json result(String operate, boolean success) { return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE), (success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), null); } public static Json result(String operate, boolean success, Object data) { return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE), (success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), data); } public static Json result(String operate, boolean success, String dataKey, Object dataVal) { return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE), (success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), null).data(dataKey, dataVal); } /////////////////////// 各种链式调用方法 /////////////////////// /** 设置操作名称 */
public Json oper(String operate) { this.put(KEY_OPER, operate); return this; } /** 设置操作结果是否成功的标记 */ public Json succ(boolean success) { this.put(KEY_SUCC, success); return this; } /** 设置操作结果的代码 */ public Json code(int code) { this.put(KEY_CODE, code); return this; } /** 设置操作结果的信息 */ public Json msg(String message) { this.put(KEY_MSG, message); return this; } /** 设置操作返回的数据 */ public Json data(Object dataVal) { this.put(KEY_DATA, dataVal); return this; } /** 设置操作返回的数据,数据使用自定义的key存储 */ public Json data(String dataKey, Object dataVal) { this.put(dataKey, dataVal); return this; } }
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\vo\Json.java
1
请完成以下Java代码
public java.lang.String getProxyPassword () { return (java.lang.String)get_Value(COLUMNNAME_ProxyPassword); } /** Set Proxy port. @param ProxyPort Port of your proxy server */ @Override public void setProxyPort (int ProxyPort) { set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort)); } /** Get Proxy port. @return Port of your proxy server */ @Override public int getProxyPort () { Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort); if (ii == null) return 0; return ii.intValue(); } /** Set Statement Loader Class. @param StmtLoaderClass Class name of the bank statement loader */ @Override public void setStmtLoaderClass (java.lang.String StmtLoaderClass) { set_Value (COLUMNNAME_StmtLoaderClass, StmtLoaderClass); } /** Get Statement Loader Class. @return Class name of the bank statement loader
*/ @Override public java.lang.String getStmtLoaderClass () { return (java.lang.String)get_Value(COLUMNNAME_StmtLoaderClass); } /** Set User ID. @param UserID User ID or account number */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get User ID. @return User ID or account number */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLoader.java
1
请完成以下Java代码
public boolean hasTransactions() { if (trxAttributesCollector == null) { return false; } return !trxAttributesCollector.isEmpty(); } @Override public void clearTransactions() { if (trxAttributesCollector != null) { trxAttributesCollector.clearTransactions(); } } @Override public void transferAttributes(@NonNull final IHUAttributeTransferRequest request) { logger.trace("Transfering attributes for {}", request); final IAttributeSet attributesFrom = request.getAttributesFrom(); final IAttributeStorage attributesTo = request.getAttributesTo(); for (final I_M_Attribute attribute : attributesFrom.getAttributes()) { // // If "toAttributes" does not support our attribute then skip it if (!attributesTo.hasAttribute(attribute)) { logger.trace("Skip transfering attribute {} because target storage does not have it", attribute); continue; } final IHUAttributeTransferStrategy transferFromStrategy = getHUAttributeTransferStrategy(request, attribute); // // Only transfer value if the request allows it if (!transferFromStrategy.isTransferable(request, attribute)) { logger.trace("Skip transfering attribute {} because transfer strategy says so: {}", attribute, transferFromStrategy); continue; } transferFromStrategy.transferAttribute(request, attribute); logger.trace("Attribute {} was transfered to target storage", attribute); } } private IHUAttributeTransferStrategy getHUAttributeTransferStrategy(final IHUAttributeTransferRequest request, final I_M_Attribute attribute) { final IAttributeSet attributesFrom = request.getAttributesFrom(); if (attributesFrom instanceof IAttributeStorage) { return ((IAttributeStorage)attributesFrom).retrieveTransferStrategy(attribute); } final IAttributeStorage attributesTo = request.getAttributesTo(); return attributesTo.retrieveTransferStrategy(attribute); }
@Override public IAllocationResult createAllocationResult() { final List<IHUTransactionAttribute> attributeTrxs = getAndClearTransactions(); if (attributeTrxs.isEmpty()) { // no transactions, nothing to do return AllocationUtils.nullResult(); } return AllocationUtils.createQtyAllocationResult( BigDecimal.ZERO, // qtyToAllocate BigDecimal.ZERO, // qtyAllocated Collections.emptyList(), // trxs attributeTrxs // attribute transactions ); } @Override public IAllocationResult createAndProcessAllocationResult() { final IAllocationResult result = createAllocationResult(); Services.get(IHUTrxBL.class).createTrx(huContext, result); return result; } @Override public void dispose() { // Unregister the listener/collector if (attributeStorageFactory != null && trxAttributesCollector != null) { trxAttributesCollector.dispose(); attributeStorageFactory.removeAttributeStorageListener(trxAttributesCollector); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTransactionAttributeBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public List<Map<String, Object>> uploadAndQuery(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName) { List<Map<String, Object>> results = new ArrayList<>(); Connection connection = null; try { // Save the uploaded file to the server's temporary directory File tempFile = File.createTempFile("upload-", ".accdb"); file.transferTo(tempFile); // Connect to the Access database String dbUrl = "jdbc:ucanaccess://" + tempFile.getAbsolutePath(); connection = DriverManager.getConnection(dbUrl); // Query the specified table in the database Statement statement = connection.createStatement(); String query = "SELECT * FROM " + tableName; ResultSet resultSet = statement.executeQuery(query); // Store query results in a List<Map<String, Object>> while (resultSet.next()) { Map<String, Object> row = new HashMap<>(); int columnCount = resultSet.getMetaData().getColumnCount(); for (int i = 1; i <= columnCount; i++) { String columnName = resultSet.getMetaData().getColumnName(i); row.put(columnName, resultSet.getObject(i)); } results.add(row); } // Close the ResultSet and Statement resultSet.close(); statement.close(); // Mark temporary file for deletion upon JVM exit tempFile.deleteOnExit();
} catch (Exception e) { e.printStackTrace(); } finally { // Close the database connection if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } return results; } }
repos\springboot-demo-master\accessDB\src\main\java\com\demo\controller\AccessDatabaseController.java
2
请完成以下Java代码
public void updatePostCalculationAmounts(final CurrencyPrecision precision) { for (final CostElementId costElementId : getCostElementIds()) { updatePostCalculationAmountsForCostElement(precision, costElementId); } } public void updatePostCalculationAmountsForCostElement( final CurrencyPrecision precision, final CostElementId costElementId) { final List<PPOrderCost> costs = filterAndList(PPOrderCostFilter.builder() .costElementId(costElementId) .build()); final List<PPOrderCost> inboundCosts = costs.stream() .filter(PPOrderCost::isInboundCost) .collect(ImmutableList.toImmutableList()); final PPOrderCost mainProductCost = costs.stream() .filter(PPOrderCost::isMainProduct) .collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Single main product cost could not be found in " + costs))); final ImmutableList<PPOrderCost> coProductCosts = costs.stream() .filter(PPOrderCost::isCoProduct) .collect(ImmutableList.toImmutableList()); // // Update inbound costs and calculate total inbound costs inboundCosts.forEach(PPOrderCost::setPostCalculationAmountAsAccumulatedAmt); final CostAmount totalInboundCostAmount = inboundCosts.stream()
.map(PPOrderCost::getPostCalculationAmount) .reduce(CostAmount::add) .orElseThrow(() -> new AdempiereException("No inbound costs found in " + costs)); // // Update co-product costs and calculate total co-product costs coProductCosts.forEach(cost -> cost.setPostCalculationAmount(totalInboundCostAmount.multiply(cost.getCoProductCostDistributionPercent(), precision))); final CostAmount totalCoProductsCostAmount = coProductCosts.stream() .map(PPOrderCost::getPostCalculationAmount) .reduce(CostAmount::add) .orElseGet(totalInboundCostAmount::toZero); // // Update main product cost mainProductCost.setPostCalculationAmount(totalInboundCostAmount.subtract(totalCoProductsCostAmount)); // // Clear by-product costs costs.stream() .filter(PPOrderCost::isByProduct) .forEach(PPOrderCost::setPostCalculationAmountAsZero); } private Set<CostElementId> getCostElementIds() { return costs.keySet() .stream() .map(CostSegmentAndElement::getCostElementId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCosts.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public AbstractQueryDto<?> getQuery() { return query; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "resourceType", defaultImpl=TaskQueryDto.class) @JsonSubTypes(value = { @JsonSubTypes.Type(value = TaskQueryDto.class, name = EntityTypes.TASK)}) public void setQuery(AbstractQueryDto<?> query) { this.query = query; } public Map<String, Object> getProperties() { return properties; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } @JsonInclude(Include.NON_NULL) public Long getItemCount() { return itemCount;
} public void setItemCount(Long itemCount) { this.itemCount = itemCount; } public static FilterDto fromFilter(Filter filter) { FilterDto dto = new FilterDto(); dto.id = filter.getId(); dto.resourceType = filter.getResourceType(); dto.name = filter.getName(); dto.owner = filter.getOwner(); if (EntityTypes.TASK.equals(filter.getResourceType())) { dto.query = TaskQueryDto.fromQuery(filter.getQuery()); } dto.properties = filter.getProperties(); return dto; } public void updateFilter(Filter filter, ProcessEngine engine) { if (getResourceType() != null && !getResourceType().equals(filter.getResourceType())) { throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to update filter from resource type '" + filter.getResourceType() + "' to '" + getResourceType() + "'"); } filter.setName(getName()); filter.setOwner(getOwner()); filter.setQuery(query.toQuery(engine)); filter.setProperties(getProperties()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterDto.java
1
请完成以下Java代码
public class JavaClassBL implements IJavaClassBL { @Override public <T> T newInstance(@NonNull final JavaClassId javaClassId) { final I_AD_JavaClass javaClassRecord = loadOutOfTrx(javaClassId, I_AD_JavaClass.class); return newInstance(javaClassRecord); } @Override public <T> T newInstance(@NonNull final I_AD_JavaClass javaClassDef) { Check.errorIf(javaClassDef.isInterface(), "Param {} may not be an interface", javaClassDef); final Class<?> javaClass = verifyClassName(javaClassDef); final String className = javaClass.getName(); if (javaClass.isInterface()) { // shouldn't happen throw new AdempiereException("The class " + className + " is an interface, so it cannot be instantiated."); // interface: do not instantiate, only check if exists } final Class<?> typeClass = getJavaTypeClassOrNull(javaClassDef); final T classInstance; if (typeClass != null && typeClass.isAnnotation()) { classInstance = Util.getInstance(null, className); } else { @SuppressWarnings("unchecked") final Class<T> typeClassT = (Class<T>)typeClass; // typeClass might be null, which is fine classInstance = Util.getInstance(typeClassT, className); } return classInstance; } @SuppressWarnings("unchecked") @Override public Class<?> verifyClassName(final I_AD_JavaClass javaClassDef) { final String className = javaClassDef.getClassname(); final Class<?> javaClass; ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = getClass().getClassLoader(); } try { javaClass = cl.loadClass(className); } catch (final ClassNotFoundException e) {
throw new AdempiereException("Classname not found: " + className, e); } return javaClass; } private Class<?> getJavaTypeClassOrNull(final I_AD_JavaClass javaClassDef) { if (javaClassDef.getAD_JavaClass_Type_ID() <= 0) { return null; } final I_AD_JavaClass_Type javaClassTypeDef = javaClassDef.getAD_JavaClass_Type(); final String typeClassname = javaClassTypeDef.getClassname(); if (Check.isEmpty(typeClassname, true)) { return null; } final Class<?> typeClass; ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = getClass().getClassLoader(); } try { typeClass = cl.loadClass(typeClassname.trim()); } catch (final ClassNotFoundException e) { throw new AdempiereException("Classname not found: " + typeClassname, e); } return typeClass; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\impl\JavaClassBL.java
1
请完成以下Java代码
Mono<Neo4jHealthDetails> runHealthCheckQuery() { return Mono.using(this::session, this::healthDetails, ReactiveSession::close); } private ReactiveSession session() { return this.driver.session(ReactiveSession.class, Neo4jHealthIndicator.DEFAULT_SESSION_CONFIG); } private Mono<Neo4jHealthDetails> healthDetails(ReactiveSession session) { return Mono.from(session.run(Neo4jHealthIndicator.CYPHER)).flatMap(this::healthDetails); } private Mono<? extends Neo4jHealthDetails> healthDetails(ReactiveResult result) { Flux<Record> records = Flux.from(result.records()); Mono<ResultSummary> summary = Mono.from(result.consume()); Neo4jHealthDetailsBuilder builder = new Neo4jHealthDetailsBuilder(); return records.single().doOnNext(builder::record).then(summary).map(builder::build); } /** * Builder used to create a {@link Neo4jHealthDetails} from a {@link Record} and a * {@link ResultSummary}. */
private static final class Neo4jHealthDetailsBuilder { private @Nullable Record record; void record(Record record) { this.record = record; } private Neo4jHealthDetails build(ResultSummary summary) { Assert.state(this.record != null, "'record' must not be null"); return new Neo4jHealthDetails(this.record, summary); } } }
repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\health\Neo4jReactiveHealthIndicator.java
1
请完成以下Java代码
public class LdapSearchResults implements NamingEnumeration<SearchResult>, AutoCloseable { protected NamingEnumeration<SearchResult> enumeration; public LdapSearchResults(NamingEnumeration<SearchResult> enumeration) { this.enumeration = enumeration; } @Override public SearchResult next() throws NamingException { return enumeration.next(); } @Override public boolean hasMore() throws NamingException { return enumeration.hasMore(); } @Override public boolean hasMoreElements() {
return enumeration.hasMoreElements(); } @Override public SearchResult nextElement() { return enumeration.nextElement(); } @Override public void close() { try { if (enumeration != null) { enumeration.close(); } } catch (Exception e) { // ignore silently } } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapSearchResults.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa spring.datasource.password= spring.datasource.driver-class-name=org.h2.Driver spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.
show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.batch.jdbc.initialize-schema=always
repos\tutorials-master\spring-batch-2\src\main\resources\application-test.properties
2
请在Spring Boot框架中完成以下Java代码
public static class SubGroup { @XmlElement(name = "ID") protected String id; @XmlElement(name = "SubDescription") protected List<GroupDescriptionType> subDescription; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setID(String value) { this.id = value; } /** * Gets the value of the subDescription 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 subDescription property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSubDescription().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link GroupDescriptionType } * * */ public List<GroupDescriptionType> getSubDescription() { if (subDescription == null) { subDescription = new ArrayList<GroupDescriptionType>(); } return this.subDescription; } } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ProductGroupType.java
2
请完成以下Java代码
public GatewayFilter apply(Config config) { return new OrderedGatewayFilter((exchange, chain) -> { if (config.isPreLogger()) logger.info("Pre GatewayFilter logging: " + config.getBaseMessage()); return chain.filter(exchange) .then(Mono.fromRunnable(() -> { if (config.isPostLogger()) logger.info("Post GatewayFilter logging: " + config.getBaseMessage()); })); }, 1); } public static class Config { private String baseMessage; private boolean preLogger; private boolean postLogger; public Config() { }; public Config(String baseMessage, boolean preLogger, boolean postLogger) { super(); this.baseMessage = baseMessage; this.preLogger = preLogger; this.postLogger = postLogger; } public String getBaseMessage() { return this.baseMessage; } public boolean isPreLogger() { return preLogger; }
public boolean isPostLogger() { return postLogger; } public void setBaseMessage(String baseMessage) { this.baseMessage = baseMessage; } public void setPreLogger(boolean preLogger) { this.preLogger = preLogger; } public void setPostLogger(boolean postLogger) { this.postLogger = postLogger; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\LoggingGatewayFilterFactory.java
1
请完成以下Java代码
public class AuthenticationCredentialsNotFoundEvent extends AbstractAuthorizationEvent { private final AuthenticationCredentialsNotFoundException credentialsNotFoundException; private final Collection<ConfigAttribute> configAttribs; /** * Construct the event. * @param secureObject the secure object * @param attributes that apply to the secure object * @param credentialsNotFoundException exception returned to the caller (contains * reason) * */ public AuthenticationCredentialsNotFoundEvent(Object secureObject, Collection<ConfigAttribute> attributes, AuthenticationCredentialsNotFoundException credentialsNotFoundException) { super(secureObject);
Assert.isTrue(attributes != null && credentialsNotFoundException != null, "All parameters are required and cannot be null"); this.configAttribs = attributes; this.credentialsNotFoundException = credentialsNotFoundException; } public Collection<ConfigAttribute> getConfigAttributes() { return this.configAttribs; } public AuthenticationCredentialsNotFoundException getCredentialsNotFoundException() { return this.credentialsNotFoundException; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\event\AuthenticationCredentialsNotFoundEvent.java
1
请完成以下Java代码
public static Date getDate(Map<String, String> requestParams, String name) { if (requestParams != null && name != null) { return parseLongDate(requestParams.get(name)); } return null; } public static Date parseLongDate(String aDate) { OffsetDateTime offsetDateTime = OffsetDateTime.parse(aDate, longDateFormat); return Date.from(offsetDateTime.toInstant()); } public static String dateToString(Date date) { String dateString = null; if (date != null) { dateString = longDateFormatOutputFormater.format(date); } return dateString; } public static Integer parseToInteger(String integer) { Integer parsedInteger = null; try { parsedInteger = Integer.parseInt(integer); } catch (Exception e) { } return parsedInteger; } public static Date parseToDate(String date) {
Date parsedDate = null; try { parsedDate = shortDateFormat.parse(date); } catch (Exception e) { } return parsedDate; } public static List<String> parseToList(String value) { if (value == null || value.isEmpty()) { return null; } String[] valueParts = value.split(","); List<String> values = new ArrayList<>(valueParts.length); Collections.addAll(values, valueParts); return values; } public static Set<String> parseToSet(String value) { if (value == null || value.isEmpty()) { return null; } String[] valueParts = value.split(","); Set<String> values = new HashSet<>(valueParts.length); Collections.addAll(values, valueParts); return values; } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\RequestUtil.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public User getCustomer() { return customer; } public void setCustomer(User customer) { this.customer = customer; } // public List<Product> getProducts() { // return products; // } // public List<Product> getProductsByUser(int customer_id ) { // List<Product> userProducts = new ArrayList<Product>(); // for (Product product : products) { // if (product.getCustomer().getId() == customer_id) {
// userProducts.add(product); // } // } // return userProducts; // } // public void setProducts(List<Product> products) { // this.products = products; // } // public void addProduct(Product product) { // products.add(product); // } // // public void removeProduct(Product product) { // products.remove(product); // } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\Cart.java
1
请完成以下Java代码
protected ProjectGenerationRequest createProjectGenerationRequest(OptionSet options) { List<?> nonOptionArguments = new ArrayList<Object>(options.nonOptionArguments()); Assert.state(nonOptionArguments.size() <= 1, "Only the target location may be specified"); ProjectGenerationRequest request = new ProjectGenerationRequest(); request.setServiceUrl(options.valueOf(this.target)); if (options.has(this.bootVersion)) { request.setBootVersion(options.valueOf(this.bootVersion)); } if (options.has(this.dependencies)) { for (String dep : options.valueOf(this.dependencies).split(",")) { request.getDependencies().add(dep.trim()); } } if (options.has(this.javaVersion)) { request.setJavaVersion(options.valueOf(this.javaVersion)); } if (options.has(this.packageName)) { request.setPackageName(options.valueOf(this.packageName)); } request.setBuild(options.valueOf(this.build)); request.setFormat(options.valueOf(this.format)); request.setDetectType(options.has(this.build) || options.has(this.format)); if (options.has(this.type)) { request.setType(options.valueOf(this.type)); } if (options.has(this.packaging)) { request.setPackaging(options.valueOf(this.packaging)); } if (options.has(this.language)) { request.setLanguage(options.valueOf(this.language)); } if (options.has(this.groupId)) { request.setGroupId(options.valueOf(this.groupId)); } if (options.has(this.artifactId)) { request.setArtifactId(options.valueOf(this.artifactId));
} if (options.has(this.name)) { request.setName(options.valueOf(this.name)); } if (options.has(this.version)) { request.setVersion(options.valueOf(this.version)); } if (options.has(this.description)) { request.setDescription(options.valueOf(this.description)); } request.setExtract(options.has(this.extract)); if (nonOptionArguments.size() == 1) { String output = (String) nonOptionArguments.get(0); request.setOutput(output); } return request; } private static String processArgument(String argument) { for (Map.Entry<String, String> entry : CAMEL_CASE_OPTIONS.entrySet()) { String name = entry.getKey(); if (argument.startsWith(name + " ") || argument.startsWith(name + "=")) { return entry.getValue() + argument.substring(name.length()); } } return argument; } } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\init\InitCommand.java
1
请完成以下Java代码
public static HUQRCode fromGlobalQRCode(final GlobalQRCode globalQRCode) { if (!isHandled(globalQRCode)) { throw new AdempiereException(INVALID_QR_CODE_ERROR_MSG) .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long } // // IMPORTANT: keep in sync with huQRCodes.js // final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION)) { return JsonConverterV1.fromGlobalQRCode(globalQRCode); } else { throw new AdempiereException(INVALID_QR_VERSION_ERROR_MSG) .setParameter("version", version); }
} public static JsonDisplayableQRCode toRenderedJson(@NonNull final HUQRCode huQRCode) { return JsonDisplayableQRCode.builder() .code(toGlobalQRCodeJsonString(huQRCode)) .displayable(huQRCode.toDisplayableQRCode()) .build(); } public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode) { return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\json\HUQRCodeJsonConverter.java
1
请完成以下Java代码
public void process(final IT item) throws Exception { processor.process(item); } @Override public RT getResult() { return processor.getResult(); } /** * @return always return <code>false</code>. Each item is a separated chunk */ @Override public boolean isSameChunk(final IT item) { return false; } @Override
public void newChunk(final IT item) { // nothing } @Override public void completeChunk() { // nothing } @Override public void cancelChunk() { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessor2TrxItemChunkProcessorWrapper.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSitename() { return sitename; } public void setSitename(String sitename) { this.sitename = sitename; } public String getSitedomain() { return sitedomain; } public void setSitedomain(String sitedomain) { this.sitedomain = sitedomain; } public String getSitetype() { return sitetype; } public void setSitetype(String sitetype) { this.sitetype = sitetype; } public String getCdate() { return cdate; } public void setCdate(String cdate) { this.cdate = cdate; } public String getComtype() { return comtype; } public void setComtype(String comtype) { this.comtype = comtype;
} public String getComname() { return comname; } public void setComname(String comname) { this.comname = comname; } public String getComaddress() { return comaddress; } public void setComaddress(String comaddress) { this.comaddress = comaddress; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "DomainDetail{" + "id='" + id + '\'' + ", sitename='" + sitename + '\'' + ", sitedomain='" + sitedomain + '\'' + ", sitetype='" + sitetype + '\'' + ", cdate='" + cdate + '\'' + ", comtype='" + comtype + '\'' + ", comname='" + comname + '\'' + ", comaddress='" + comaddress + '\'' + ", updateTime='" + updateTime + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-feign\src\main\java\com\quick\feign\entity\DomainDetail.java
1
请完成以下Java代码
public boolean isDeleted() { return deleted; } public boolean isNotDeleted() { return notDeleted; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isWithException() { return withJobException; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId;
} public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<String> getInvolvedGroups() { return involvedGroups; } public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请完成以下Java代码
public class User { @Transient public static final String SEQUENCE_NAME = "users_sequence"; @Id private BigInteger id; private String firstName; private String lastName; private String email; public User() { } public User(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public BigInteger getId() { return id; } public void setId(BigInteger id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\mongodb\models\User.java
1
请完成以下Java代码
private static int readInt(ByteArrayInputStream result) throws IOException { byte[] b = new byte[2]; result.read(b); return ((b[0] & 0xFF) << 8) | (b[1] & 0xFF); } private static byte[] decrypt(byte[] text, @Nullable PrivateKey key, RsaAlgorithm alg, String salt, boolean gcm) { ByteArrayInputStream input = new ByteArrayInputStream(text); ByteArrayOutputStream output = new ByteArrayOutputStream(text.length); try { int length = readInt(input); byte[] random = new byte[length]; input.read(random); final Cipher cipher = Cipher.getInstance(alg.getJceName()); cipher.init(Cipher.DECRYPT_MODE, key); String secret = new String(Hex.encode(cipher.doFinal(random))); byte[] buffer = new byte[text.length - random.length - 2]; input.read(buffer); BytesEncryptor aes = gcm ? Encryptors.stronger(secret, salt) : Encryptors.standard(secret, salt); output.write(aes.decrypt(buffer)); return output.toByteArray(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Cannot decrypt", ex); } }
private static boolean isHex(String input) { try { Hex.decode(input); return true; } catch (Exception ex) { return false; } } public boolean canDecrypt() { return this.privateKey != null; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaSecretEncryptor.java
1
请完成以下Java代码
public class DeleteIdentityLinkForProcessDefinitionCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected String userId; protected String groupId; public DeleteIdentityLinkForProcessDefinitionCmd(String processDefinitionId, String userId, String groupId) { validateParams(userId, groupId, processDefinitionId); this.processDefinitionId = processDefinitionId; this.userId = userId; this.groupId = groupId; } protected void validateParams(String userId, String groupId, String processDefinitionId) { if (processDefinitionId == null) { throw new ActivitiIllegalArgumentException("processDefinitionId is null"); } if (userId == null && groupId == null) {
throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null"); } } public Void execute(CommandContext commandContext) { ProcessDefinitionEntity processDefinition = commandContext .getProcessDefinitionEntityManager() .findById(processDefinitionId); if (processDefinition == null) { throw new ActivitiObjectNotFoundException( "Cannot find process definition with id " + processDefinitionId, ProcessDefinition.class ); } executeInternal(commandContext, processDefinition); return null; } protected void executeInternal(CommandContext commandContext, ProcessDefinitionEntity processDefinition) { commandContext.getIdentityLinkEntityManager().deleteIdentityLink(processDefinition, userId, groupId); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteIdentityLinkForProcessDefinitionCmd.java
1
请在Spring Boot框架中完成以下Java代码
public void setLOCATIONQUAL(String value) { this.locationqual = value; } /** * Gets the value of the locationcode property. * * @return * possible object is * {@link String } * */ public String getLOCATIONCODE() { return locationcode; } /** * Sets the value of the locationcode property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONCODE(String value) { this.locationcode = value; } /** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the date property. * * @return * possible object is * {@link String } * */ public String getDATE() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link String } * */ public void setDATE(String value) { this.date = value; } /** * Gets the value of the quantity property. * * @return * possible object is * {@link String } * */ public String getQUANTITY() {
return quantity; } /** * Sets the value of the quantity property. * * @param value * allowed object is * {@link String } * */ public void setQUANTITY(String value) { this.quantity = value; } /** * Gets the value of the quantitymeasureunit property. * * @return * possible object is * {@link String } * */ public String getQUANTITYMEASUREUNIT() { return quantitymeasureunit; } /** * Sets the value of the quantitymeasureunit property. * * @param value * allowed object is * {@link String } * */ public void setQUANTITYMEASUREUNIT(String value) { this.quantitymeasureunit = 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\DPLAC1.java
2
请完成以下Java代码
public ReactiveAuthenticationManager customersAuthenticationManager() { return authentication -> customer(authentication) .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication .getPrincipal() .toString()))) .map(b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) ) ); } public ReactiveAuthenticationManager employeesAuthenticationManager() { return authentication -> employee(authentication) .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication .getPrincipal() .toString()))) .map( b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) ) ); } public Mono<String> customer(Authentication authentication) { return Mono.justOrEmpty(authentication .getPrincipal()
.toString() .startsWith("customer") ? authentication .getPrincipal() .toString() : null); } public Mono<String> employee(Authentication authentication) { return Mono.justOrEmpty(authentication .getPrincipal() .toString() .startsWith("employee") ? authentication .getPrincipal() .toString() : null); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-security\src\main\java\com\baeldung\reactive\authresolver\CustomWebSecurityConfig.java
1
请完成以下Java代码
public void setServiceFee_Product_ID (int ServiceFee_Product_ID) { if (ServiceFee_Product_ID < 1) set_Value (COLUMNNAME_ServiceFee_Product_ID, null); else set_Value (COLUMNNAME_ServiceFee_Product_ID, Integer.valueOf(ServiceFee_Product_ID)); } @Override public int getServiceFee_Product_ID() { return get_ValueAsInt(COLUMNNAME_ServiceFee_Product_ID); } @Override public void setServiceInvoice_DocType_ID (int ServiceInvoice_DocType_ID) { if (ServiceInvoice_DocType_ID < 1) set_Value (COLUMNNAME_ServiceInvoice_DocType_ID, null); else set_Value (COLUMNNAME_ServiceInvoice_DocType_ID, Integer.valueOf(ServiceInvoice_DocType_ID)); } @Override public int getServiceInvoice_DocType_ID()
{ return get_ValueAsInt(COLUMNNAME_ServiceInvoice_DocType_ID); } @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getApiKey() { return this.apiKey; } public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; } public @Nullable Proxy getProxy() { return this.proxy; } public void setProxy(@Nullable Proxy proxy) { this.proxy = proxy; } public static class Proxy { /** * SendGrid proxy host. */ private @Nullable String host; /** * SendGrid proxy port. */ private @Nullable Integer port; public @Nullable String getHost() {
return this.host; } public void setHost(@Nullable String host) { this.host = host; } public @Nullable Integer getPort() { return this.port; } public void setPort(@Nullable Integer port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-sendgrid\src\main\java\org\springframework\boot\sendgrid\autoconfigure\SendGridProperties.java
2
请完成以下Java代码
public I_ESR_ImportFile createESRImportFile(@NonNull final I_ESR_Import header) { final I_ESR_ImportFile esrImportFile = newInstance(I_ESR_ImportFile.class); esrImportFile.setESR_Import_ID(header.getESR_Import_ID()); esrImportFile.setAD_Org_ID(header.getAD_Org_ID()); esrImportFile.setC_BP_BankAccount_ID(header.getC_BP_BankAccount_ID()); esrImportFile.setESR_Control_Amount(BigDecimal.ZERO); saveRecord(esrImportFile); return esrImportFile; } @Override public ImmutableList<I_ESR_ImportFile> retrieveActiveESRImportFiles(@NonNull final I_ESR_Import esrImport) { return queryBL.createQueryBuilder(I_ESR_ImportFile.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ESR_ImportFile.COLUMNNAME_ESR_Import_ID, esrImport.getESR_Import_ID()) .create() .listImmutable(I_ESR_ImportFile.class); } @Override public ImmutableList<I_ESR_ImportLine> retrieveActiveESRImportLinesFromFile(@NonNull final I_ESR_ImportFile esrImportFile) { return queryBL.createQueryBuilder(I_ESR_ImportLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ESR_ImportLine.COLUMNNAME_ESR_ImportFile_ID, esrImportFile.getESR_ImportFile_ID()) .create() .listImmutable(I_ESR_ImportLine.class); } @Override public I_ESR_ImportFile getImportFileById(final int esrImportFileId) { return load(esrImportFileId, I_ESR_ImportFile.class); }
@Override public void validateEsrImport(final I_ESR_Import esrImport) { final ImmutableList<I_ESR_ImportFile> esrImportFiles = retrieveActiveESRImportFiles(esrImport); final boolean isValid = esrImportFiles.stream() .allMatch(I_ESR_ImportFile::isValid); esrImport.setIsValid(isValid); save(esrImport); } @Override public I_ESR_Import getById(final ESRImportId esrImportId) { return load(esrImportId.getRepoId(), I_ESR_Import.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRImportDAO.java
1
请完成以下Java代码
public class EdgeEventsCleanUpService extends AbstractCleanUpService { public static final String RANDOM_DELAY_INTERVAL_MS_EXPRESSION = "#{T(org.apache.commons.lang3.RandomUtils).nextLong(0, ${sql.ttl.edge_events.execution_interval_ms})}"; @Value("${sql.ttl.edge_events.edge_events_ttl}") private long ttl; @Value("${sql.edge_events.partition_size:168}") private int partitionSizeInHours; @Value("${sql.ttl.edge_events.enabled:true}") private boolean ttlTaskExecutionEnabled; private final EdgeEventService edgeEventService; private final SqlPartitioningRepository partitioningRepository;
public EdgeEventsCleanUpService(PartitionService partitionService, EdgeEventService edgeEventService, SqlPartitioningRepository partitioningRepository) { super(partitionService); this.edgeEventService = edgeEventService; this.partitioningRepository = partitioningRepository; } @Scheduled(initialDelayString = RANDOM_DELAY_INTERVAL_MS_EXPRESSION, fixedDelayString = "${sql.ttl.edge_events.execution_interval_ms}") public void cleanUp() { long edgeEventsExpTime = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(ttl); if (ttlTaskExecutionEnabled && isSystemTenantPartitionMine()) { edgeEventService.cleanupEvents(edgeEventsExpTime); } else { partitioningRepository.cleanupPartitionsCache(EDGE_EVENT_TABLE_NAME, edgeEventsExpTime, TimeUnit.HOURS.toMillis(partitionSizeInHours)); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ttl\EdgeEventsCleanUpService.java
1
请完成以下Java代码
public void setIsInDispute (boolean IsInDispute) { set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute)); } /** Get In Dispute. @return Document is in dispute */ public boolean isInDispute () { Object oo = get_Value(COLUMNNAME_IsInDispute); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open Amount. @param OpenAmt Open item amount */ public void setOpenAmt (BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Open Amount. @return Open item amount */ public BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Times Dunned. @param TimesDunned Number of times dunned previously */ public void setTimesDunned (int TimesDunned)
{ set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned)); } /** Get Times Dunned. @return Number of times dunned previously */ public int getTimesDunned () { Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned); if (ii == null) return 0; return ii.intValue(); } /** Set Total Amount. @param TotalAmt Total Amount */ public void setTotalAmt (BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Total Amount. @return Total Amount */ public BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java
1
请完成以下Java代码
protected HistoryEvent getHistoricProcessInstance(CommandContext commandContext) { String historicProcessInstanceId = authorization.getResourceId(); if (isNullOrAny(historicProcessInstanceId)) { return null; } return commandContext.getHistoricProcessInstanceManager() .findHistoricProcessInstance(historicProcessInstanceId); } protected HistoryEvent getHistoricTaskInstance(CommandContext commandContext) { String historicTaskInstanceId = authorization.getResourceId(); if (isNullOrAny(historicTaskInstanceId)) { return null; } return commandContext.getHistoricTaskInstanceManager() .findHistoricTaskInstanceById(historicTaskInstanceId);
} protected boolean isNullOrAny(String resourceId) { return resourceId == null || isAny(resourceId); } protected boolean isAny(String resourceId) { return Objects.equals(Authorization.ANY, resourceId); } protected boolean isResourceEqualTo(Resources resource) { return Objects.equals(resource.resourceType(), authorization.getResource()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SaveAuthorizationCmd.java
1
请完成以下Java代码
public PrintingQueueProcessingInfo getProcessingInfo() { final boolean createWithSpecificHostKey = !item.isPrintoutForOtherUser(); return new PrintingQueueProcessingInfo(adUserPrintJobId, AD_User_ToPrint_IDs, createWithSpecificHostKey); } @Override public Iterator<I_C_Printing_Queue> createItemsIterator() { return new SingletonIterator<I_C_Printing_Queue>(item); } @Override public Iterator<I_C_Printing_Queue> createRelatedItemsIterator(final I_C_Printing_Queue item) { final List<I_C_Printing_Queue> list = Collections.emptyList(); return list.iterator(); } @Override public String getTrxName() { return trxName; } @Override public boolean isPrinted(@NonNull final I_C_Printing_Queue item)
{ if (persistPrintedFlag) { return super.isPrinted(item); } else { return temporaryPrinted; } } @Override public void markPrinted(@NonNull final I_C_Printing_Queue item) { if (persistPrintedFlag) { super.markPrinted(item); } else { temporaryPrinted = true; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\SingletonPrintingQueueSource.java
1
请完成以下Java代码
public TransactionAgents2 createTransactionAgents2() { return new TransactionAgents2(); } /** * Create an instance of {@link TransactionDates2 } * */ public TransactionDates2 createTransactionDates2() { return new TransactionDates2(); } /** * Create an instance of {@link TransactionInterest2 } * */ public TransactionInterest2 createTransactionInterest2() { return new TransactionInterest2(); } /** * Create an instance of {@link TransactionParty2 } * */ public TransactionParty2 createTransactionParty2() { return new TransactionParty2(); } /** * Create an instance of {@link TransactionPrice2Choice } * */ public TransactionPrice2Choice createTransactionPrice2Choice() { return new TransactionPrice2Choice(); } /** * Create an instance of {@link TransactionQuantities1Choice } * */ public TransactionQuantities1Choice createTransactionQuantities1Choice() {
return new TransactionQuantities1Choice(); } /** * Create an instance of {@link TransactionReferences2 } * */ public TransactionReferences2 createTransactionReferences2() { return new TransactionReferences2(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.02", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ObjectFactory.java
1
请完成以下Java代码
public class SpringIoInitializrMetadataUpdateStrategy implements InitializrMetadataUpdateStrategy { private static final Log logger = LogFactory.getLog(SpringIoInitializrMetadataUpdateStrategy.class); private final RestTemplate restTemplate; private final ObjectMapper objectMapper; public SpringIoInitializrMetadataUpdateStrategy(RestTemplate restTemplate, ObjectMapper objectMapper) { this.restTemplate = restTemplate; this.objectMapper = objectMapper; } @Override public InitializrMetadata update(InitializrMetadata current) { String url = current.getConfiguration().getEnv().getSpringBootMetadataUrl(); List<DefaultMetadataElement> bootVersions = fetchSpringBootVersions(url); if (bootVersions != null && !bootVersions.isEmpty()) { if (bootVersions.stream().noneMatch(DefaultMetadataElement::isDefault)) { // No default specified bootVersions.get(0).setDefault(true); } current.updateSpringBootVersions(bootVersions); } return current; } /** * Fetch the available Spring Boot versions using the specified service url. * @param url the url to the spring-boot project metadata * @return the spring boot versions metadata or {@code null} if it could not be
* retrieved */ protected List<DefaultMetadataElement> fetchSpringBootVersions(String url) { if (StringUtils.hasText(url)) { try { logger.info("Fetching Spring Boot metadata from " + url); return new SpringBootMetadataReader(this.objectMapper, this.restTemplate, url).getBootVersions(); } catch (Exception ex) { logger.warn("Failed to fetch Spring Boot metadata", ex); } } return null; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\SpringIoInitializrMetadataUpdateStrategy.java
1
请完成以下Java代码
private int onCacheReset(CacheInvalidateMultiRequest multiRequest) { if (!multiRequest.isResetAll()) { return 0; } // reset defaults qualityBasedConfigProviderDefault = null; qualityInvoiceLineGroupsBuilderProviderDefault = null; return 2; } private final <T> T getInstance(final String sysConfigName, final Class<T> interfaceClass) { final String classname = Services.get(ISysConfigBL.class).getValue(sysConfigName); Check.assumeNotEmpty(classname, "AD_Sysconfig {} shall be set", sysConfigName); final T instance = Util.getInstance(interfaceClass, classname); return instance; } @Override public IQualityBasedConfigProvider getQualityBasedConfigProvider() { if (qualityBasedConfigProvider != null) { return qualityBasedConfigProvider; } if (qualityBasedConfigProviderDefault == null) { qualityBasedConfigProviderDefault = getInstance(SYSCONFIG_QualityBasedConfigProvider, IQualityBasedConfigProvider.class); } return qualityBasedConfigProviderDefault; } @Override public void setQualityBasedConfigProvider(final IQualityBasedConfigProvider provider) {
qualityBasedConfigProvider = provider; } @Override public IQualityInvoiceLineGroupsBuilderProvider getQualityInvoiceLineGroupsBuilderProvider() { if (qualityInvoiceLineGroupsBuilderProvider != null) { return qualityInvoiceLineGroupsBuilderProvider; } if (qualityInvoiceLineGroupsBuilderProviderDefault == null) { qualityInvoiceLineGroupsBuilderProviderDefault = getInstance(SYSCONFIG_QualityInvoiceLineGroupsBuilderProvider, IQualityInvoiceLineGroupsBuilderProvider.class); } return qualityInvoiceLineGroupsBuilderProviderDefault; } @Override public void setQualityInvoiceLineGroupsBuilderProvider(final IQualityInvoiceLineGroupsBuilderProvider qualityInvoiceLineGroupsBuilderProvider) { this.qualityInvoiceLineGroupsBuilderProvider = qualityInvoiceLineGroupsBuilderProvider; } @Override public void setInvoicedSumProvider(final IInvoicedSumProvider invoicedSumProvider) { this.invoicedSumProvider = invoicedSumProvider; } @Override public IInvoicedSumProvider getInvoicedSumProvider() { if (invoicedSumProvider != null) { return invoicedSumProvider; } return invoicedSumProviderDefault; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityBasedSpiProviderService.java
1
请在Spring Boot框架中完成以下Java代码
public class RestTemplateConfiguration { @Bean public RestTemplate restTemplate() { try { // Timeout configurations SocketConfig socketConfig = SocketConfig.custom() .setSoTimeout(Timeout.ofSeconds(30)) // Read timeout .build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setConnectTimeout(Timeout.ofSeconds(30)) // Connect timeout .build(); RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(Timeout.ofSeconds(30)) // Pool wait timeout .build(); // Connection pool configuration PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() .setMaxConnPerRoute(20) .setMaxConnTotal(100)
.setDefaultSocketConfig(socketConfig) .setDefaultConnectionConfig(connectionConfig) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); } catch (Exception e) { throw new IllegalStateException("Failed to configure RestTemplate", e); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\restclient\RestTemplateConfiguration.java
2
请完成以下Java代码
public static <T> CompletableFuture<T> retryUnsafe(Supplier<T> supplier, int maxRetries) { CompletableFuture<T> cf = CompletableFuture.supplyAsync(supplier); sleep(100l); for (int i = 0; i < maxRetries; i++) { cf = cf.exceptionally(__ -> supplier.get()); } return cf; } public static <T> CompletableFuture<T> retryNesting(Supplier<T> supplier, int maxRetries) { CompletableFuture<T> cf = CompletableFuture.supplyAsync(supplier); sleep(100); for (int i = 0; i < maxRetries; i++) { cf = cf.thenApply(CompletableFuture::completedFuture) .exceptionally(__ -> CompletableFuture.supplyAsync(supplier)) .thenCompose(Function.identity()); } return cf; } public static <T> CompletableFuture<T> retryExceptionallyAsync(Supplier<T> supplier, int maxRetries) { CompletableFuture<T> cf = CompletableFuture.supplyAsync(supplier);
sleep(100); for (int i = 0; i < maxRetries; i++) { cf = cf.exceptionallyAsync(__ -> supplier.get()); } return cf; } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-3\src\main\java\com\baeldung\concurrent\completablefuture\retry\RetryCompletableFuture.java
1