instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class LocatorQRCodeJsonConverter { // note to dev: keep in sync with misc/services/mobile-webui/mobile-webui-frontend/src/utils/qrCode/locator.js public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("LOC"); public static String toGlobalQRCodeJsonString(final LocatorQRCode qrCode) { return toGlobalQRCode(qrCode).getAsString(); } public static GlobalQRCode toGlobalQRCode(final LocatorQRCode qrCode) { return JsonConverterV1.toGlobalQRCode(qrCode); } public static LocatorQRCode fromGlobalQRCodeJsonString(final String qrCodeString) { return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString)); } public static LocatorQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode) { if (!isTypeMatching(globalQRCode)) { throw new AdempiereException("Invalid QR Code") .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
} final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION)) { return JsonConverterV1.fromGlobalQRCode(globalQRCode); } else { throw new AdempiereException("Invalid QR Code version: " + version); } } public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode) { return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCodeJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public void setMessagesPerAck(Integer messagesPerAck) { this.messagesPerAck = messagesPerAck; } /** * An approximate timeout; when {@link #setMessagesPerAck(Integer) messagesPerAck} is * greater than 1, and this time elapses since the last ack, the pending acks will be * sent either when the next message arrives, or a short time later if no additional * messages arrive. In that case, the actual time depends on the * {@link #setMonitorInterval(long) monitorInterval}. * @param ackTimeout the timeout in milliseconds (default 20000); * @see #setMessagesPerAck(Integer) */ public void setAckTimeout(Long ackTimeout) { this.ackTimeout = ackTimeout; } @Override protected DirectMessageListenerContainer createContainerInstance() { return new DirectMessageListenerContainer(); } @Override protected void initializeContainer(DirectMessageListenerContainer instance, @Nullable RabbitListenerEndpoint endpoint) { super.initializeContainer(instance, endpoint); JavaUtils javaUtils = JavaUtils.INSTANCE.acceptIfNotNull(this.taskScheduler, instance::setTaskScheduler) .acceptIfNotNull(this.monitorInterval, instance::setMonitorInterval)
.acceptIfNotNull(this.messagesPerAck, instance::setMessagesPerAck) .acceptIfNotNull(this.ackTimeout, instance::setAckTimeout); if (endpoint != null && endpoint.getConcurrency() != null) { try { instance.setConsumersPerQueue(Integer.parseInt(endpoint.getConcurrency())); } catch (NumberFormatException e) { throw new IllegalStateException("Failed to parse concurrency: " + e.getMessage(), e); } } else { javaUtils.acceptIfNotNull(this.consumersPerQueue, instance::setConsumersPerQueue); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\DirectRabbitListenerContainerFactory.java
2
请完成以下Java代码
public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } /** Get System-Problem. @return Automatically created or manually entered System Issue */ @Override public int getAD_Issue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_WorkPackage getC_Queue_WorkPackage() { return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class); } @Override public void setC_Queue_WorkPackage(de.metas.async.model.I_C_Queue_WorkPackage C_Queue_WorkPackage) { set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, C_Queue_WorkPackage); } /** Set WorkPackage Queue. @param C_Queue_WorkPackage_ID WorkPackage Queue */ @Override public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID) { if (C_Queue_WorkPackage_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, Integer.valueOf(C_Queue_WorkPackage_ID)); } /** Get WorkPackage Queue. @return WorkPackage Queue */ @Override public int getC_Queue_WorkPackage_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Workpackage audit/log table. @param C_Queue_WorkPackage_Log_ID Workpackage audit/log table */ @Override public void setC_Queue_WorkPackage_Log_ID (int C_Queue_WorkPackage_Log_ID) { if (C_Queue_WorkPackage_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, Integer.valueOf(C_Queue_WorkPackage_Log_ID)); } /** Get Workpackage audit/log table. @return Workpackage audit/log table */ @Override public int getC_Queue_WorkPackage_Log_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Log_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Log.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getPersonNumber() { return personNumber; } public void setPersonNumber(Long personNumber) { this.personNumber = personNumber; } public Boolean getIsActive() { return isActive; }
public void setIsActive(Boolean isActive) { this.isActive = isActive; } public String getScode() { return securityNumber; } public void setScode(String scode) { this.securityNumber = scode; } public String getDcode() { return departmentCode; } public void setDcode(String dcode) { this.departmentCode = dcode; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\uniqueconstraints\Person.java
1
请完成以下Java代码
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) { HttpServletRequest req = (HttpServletRequest) request; String token = req.getHeader(TOKEN); return token != null; } @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String token = httpServletRequest.getHeader(TOKEN); JWTToken jwtToken = new JWTToken(token); try { getSubject(request, response).login(jwtToken); return true; } catch (Exception e) { log.error(e.getMessage()); return false; } }
/** * 对跨域提供支持 */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域时会首先发送一个 option请求,这里我们给 option请求直接返回正常状态 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { httpServletResponse.setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\JWTFilter.java
1
请完成以下Java代码
protected void init() { // nothing } public void setDefaultResult(@NonNull final Result defaultResult) { _defaultResult = defaultResult; } /** * Gets default result to be returned by all methods which were not implemented by extending class. * * @return default result * @see #setDefaultResult(de.metas.handlingunits.IHUIteratorListener.Result) */ protected Result getDefaultResult() { return _defaultResult; } @Override public void setHUIterator(final IHUIterator iterator) { if (this.iterator != null && iterator != null && this.iterator != iterator) { throw new AdempiereException("Changing the iterator from " + this.iterator + " to " + iterator + " is not allowed for " + this + "." + " You need to explicitelly set it to null first and then set it again."); } this.iterator = iterator; } public final IHUIterator getHUIterator() { return iterator; } @Override public Result beforeHU(final IMutable<I_M_HU> hu) { return getDefaultResult(); } @Override public Result afterHU(final I_M_HU hu) { return getDefaultResult();
} @Override public Result beforeHUItem(final IMutable<I_M_HU_Item> item) { return getDefaultResult(); } @Override public Result afterHUItem(final I_M_HU_Item item) { return getDefaultResult(); } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return getDefaultResult(); } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return getDefaultResult(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUIteratorListenerAdapter.java
1
请完成以下Java代码
public PickingJobStepPickFromMap reduceWithPickedEvent( @NonNull PickingJobStepPickFromKey key, @NonNull PickingJobStepPickedTo pickedTo) { return withChangedPickFrom(key, pickFrom -> pickFrom.withPickedEvent(pickedTo)); } public PickingJobStepPickFromMap reduceWithUnpickEvent( @NonNull PickingJobStepPickFromKey key, @NonNull PickingJobStepUnpickInfo unpicked) { return withChangedPickFrom(key, pickFrom -> pickFrom.withUnPickedEvent(unpicked)); } private PickingJobStepPickFromMap withChangedPickFrom( @NonNull PickingJobStepPickFromKey key, @NonNull UnaryOperator<PickingJobStepPickFrom> pickFromMapper) { if (!map.containsKey(key)) { throw new AdempiereException("No PickFrom " + key + " found in " + this); } final ImmutableMap<PickingJobStepPickFromKey, PickingJobStepPickFrom> newMap = CollectionUtils.mapValue(map, key, pickFromMapper); return !Objects.equals(this.map, newMap) ? new PickingJobStepPickFromMap(newMap) : this; } public Optional<Quantity> getQtyPicked() { return map.values() .stream() .map(pickFrom -> pickFrom.getQtyPicked().orElse(null)) .filter(Objects::nonNull) .reduce(Quantity::add); } public Optional<Quantity> getQtyRejected() { // returning only from mainPickFrom because I wanted to keep the same logic we already have in misc/services/mobile-webui/mobile-webui-frontend/src/utils/picking.js, getQtyPickedOrRejectedTotalForLine
return getMainPickFrom().getQtyRejected(); } @NonNull public List<HuId> getPickedHUIds() { return map.values() .stream() .map(PickingJobStepPickFrom::getPickedTo) .filter(Objects::nonNull) .filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0) .map(PickingJobStepPickedTo::getPickedHuIds) .flatMap(List::stream) .collect(ImmutableList.toImmutableList()); } @NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHU() { return map.values() .stream() .map(PickingJobStepPickFrom::getPickedTo) .filter(Objects::nonNull) .filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0) .map(PickingJobStepPickedTo::getLastPickedHu) .filter(Optional::isPresent) .map(Optional::get) .max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFromMap.java
1
请完成以下Java代码
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 setPrintName (final java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } @Override public java.lang.String getPrintName() { return get_ValueAsString(COLUMNNAME_PrintName); } @Override public org.compiere.model.I_R_RequestType getR_RequestType() { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType);
} @Override public void setR_RequestType_ID (final int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID); } @Override public int getR_RequestType_ID() { return get_ValueAsInt(COLUMNNAME_R_RequestType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
1
请在Spring Boot框架中完成以下Java代码
protected Publisher<Void> handle(Flux<InstanceEvent> publisher) { return publisher .filter((event) -> event instanceof InstanceEndpointsDetectedEvent || event instanceof InstanceStatusChangedEvent || event instanceof InstanceRegistrationUpdatedEvent) .flatMap((event) -> this.updateInfo(event.getInstance())); } protected Mono<Void> updateInfo(InstanceId instanceId) { return this.infoUpdater.updateInfo(instanceId).onErrorResume((e) -> { log.warn("Unexpected error while updating info for {}", instanceId, e); return Mono.empty(); }).doFinally((s) -> this.intervalCheck.markAsChecked(instanceId)); } @Override public void start() { super.start();
this.intervalCheck.start(); } @Override public void stop() { super.stop(); this.intervalCheck.stop(); } public void setInterval(Duration updateInterval) { this.intervalCheck.setInterval(updateInterval); } public void setLifetime(Duration infoLifetime) { this.intervalCheck.setMinRetention(infoLifetime); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\InfoUpdateTrigger.java
2
请在Spring Boot框架中完成以下Java代码
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer { @Autowired private BeanFactory beanFactory; @Bean public Executor executor() { ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(1); threadPoolTaskExecutor.setMaxPoolSize(1); threadPoolTaskExecutor.initialize(); return new LazyTraceExecutor(beanFactory, threadPoolTaskExecutor); } @Override public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(1); threadPoolTaskExecutor.setMaxPoolSize(1); threadPoolTaskExecutor.initialize(); return new LazyTraceExecutor(beanFactory, threadPoolTaskExecutor); } @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(schedulingExecutor()); } @Bean(destroyMethod = "shutdown") public Executor schedulingExecutor() { return Executors.newScheduledThreadPool(1); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-sleuth\src\main\java\com\baeldung\spring\session\ThreadConfig.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public Long getMobile() { return mobile; } public void setMobile(Long mobile) { this.mobile = mobile; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } }
repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\hibernatejfr\entity\PersonEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class SyncContractLine implements IConfirmableDTO { String uuid; boolean deleted; long syncConfirmationId; SyncProduct product; @JsonCreator @Builder(toBuilder = true) public SyncContractLine( @JsonProperty("uuid") final String uuid, @JsonProperty("deleted") final boolean deleted, @JsonProperty("syncConfirmationId") final long syncConfirmationId, @JsonProperty("product") final SyncProduct product) { this.uuid = uuid; this.deleted = deleted;
this.syncConfirmationId = syncConfirmationId; this.product = product; } @Override public String toString() { return "SyncContractLine [product=" + product + "]"; } @Override public IConfirmableDTO withNotDeleted() { return toBuilder().deleted(false).build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncContractLine.java
2
请完成以下Java代码
public DmnHistoricDecisionExecutionQuery orderByTenantId() { return orderBy(HistoricDecisionExecutionQueryProperty.TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getHistoricDecisionExecutionEntityManager().findHistoricDecisionExecutionCountByQueryCriteria(this); } @Override public List<DmnHistoricDecisionExecution> executeList(CommandContext commandContext) { return CommandContextUtil.getHistoricDecisionExecutionEntityManager().findHistoricDecisionExecutionsByQueryCriteria(this); } @Override public void delete() { if (commandExecutor != null) { commandExecutor.execute(new DeleteHistoricDecisionExecutionsByQueryCmd(this)); } else { new DeleteHistoricDecisionExecutionsByQueryCmd(this).execute(Context.getCommandContext()); } } @Override @Deprecated public void deleteWithRelatedData() { delete(); } // getters //////////////////////////////////////////// @Override public String getId() { return id; } public Set<String> getIds() { return ids; } public String getDecisionDefinitionId() { return decisionDefinitionId; } public String getDeploymentId() { return deploymentId; } public String getDecisionKey() { return decisionKey; } public String getInstanceId() { return instanceId; } public String getExecutionId() { return executionId; }
public String getActivityId() { return activityId; } public String getScopeType() { return scopeType; } public boolean isWithoutScopeType() { return withoutScopeType; } public String getProcessInstanceIdWithChildren() { return processInstanceIdWithChildren; } public String getCaseInstanceIdWithChildren() { return caseInstanceIdWithChildren; } public Boolean getFailed() { return failed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\HistoricDecisionExecutionQueryImpl.java
1
请完成以下Java代码
public I_C_Doc_Responsible createDocResponsible(@NonNull final Object doc, int adOrgId) { final Properties ctx = InterfaceWrapperHelper.getCtx(doc); final String trxName = InterfaceWrapperHelper.getTrxName(doc); final String tableName = InterfaceWrapperHelper.getModelTableName(doc); final int tableId = Services.get(IADTableDAO.class).retrieveTableId(tableName); final int recordId = InterfaceWrapperHelper.getId(doc); final WFResponsible wfResponsible = getOrgWFResponsible(OrgId.ofRepoIdOrAny(adOrgId)); I_C_Doc_Responsible docResponsible = Services.get(IWorkflowDAO.class).retrieveDocResponsible(doc); if (docResponsible == null) { docResponsible = InterfaceWrapperHelper.create(ctx, I_C_Doc_Responsible.class, trxName); } docResponsible.setAD_Org_ID(adOrgId); docResponsible.setAD_Table_ID(tableId); docResponsible.setRecord_ID(recordId); docResponsible.setAD_WF_Responsible_ID(wfResponsible.getId().getRepoId()); final IUserDAO userDAO = Services.get(IUserDAO.class); if (wfResponsible.isInvoker()) { final UserId userResponsibleId = Env.getLoggedUserId(ctx); // logged user docResponsible.setAD_User_Responsible_ID(userResponsibleId.getRepoId()); docResponsible.setAD_WF_Responsible_Name(userDAO.retrieveUserFullName(userResponsibleId)); } else if (wfResponsible.isHuman()) { final UserId userResponsibleId = wfResponsible.getUserId(); docResponsible.setAD_User_Responsible_ID(userResponsibleId.getRepoId()); docResponsible.setAD_WF_Responsible_Name(userDAO.retrieveUserFullName(userResponsibleId)); } else { docResponsible.setAD_User_Responsible_ID(-1); // no user responsible docResponsible.setAD_WF_Responsible_Name(wfResponsible.getName()); } InterfaceWrapperHelper.save(docResponsible); return docResponsible;
} private WFResponsible getOrgWFResponsible(@NonNull final OrgId orgId) { final IOrgDAO orgDAO = Services.get(IOrgDAO.class); final IADWorkflowDAO workflowDAO = Services.get(IADWorkflowDAO.class); final OrgInfo orgInfo = orgDAO.getOrgInfoById(orgId); final WFResponsibleId wfResponsibleId = orgInfo.getWorkflowResponsibleId(); final WFResponsible wfResponsible = wfResponsibleId != null ? workflowDAO.getWFResponsibleById(wfResponsibleId) : null; if (wfResponsible != null) { return wfResponsible; } // // Default: Invoker return workflowDAO.getWFResponsibleById(WFResponsibleId.Invoker); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\workflow\api\impl\WorkflowBL.java
1
请完成以下Java代码
public int getNotificationCount() { return this.notifications.size(); } @Override public List<I_AD_Note> getNotifications() { return this.notifications; } @Override public void addNotifications(final List<I_AD_Note> list) { if (list != null && !list.isEmpty()) { this.notifications.addAll(list); this.notificationsWhereClause = null; } } @Override public String getNotificationsWhereClause() { if (this.notificationsWhereClause == null) { final Accessor accessor = new Accessor() { @Override public Object getValue(Object o) { return ((I_AD_Note)o).getAD_Note_ID(); } }; this.notificationsWhereClause = buildSqlInArrayWhereClause( I_AD_Note.COLUMNNAME_AD_Note_ID, this.notifications, accessor, null // params ); } return this.notificationsWhereClause; } private String buildSqlInArrayWhereClause(String columnName, List<?> values, Accessor accessor, List<Object> params) { if (values == null || values.isEmpty()) return ""; boolean hasNull = false; StringBuffer whereClause = new StringBuffer(); StringBuffer whereClauseCurrent = new StringBuffer(); int count = 0; for (Object v : values) { final Object value; if (accessor != null) value = accessor.getValue(v); else value = v; if (value == null) { hasNull = true; continue; } if (whereClauseCurrent.length() > 0) whereClauseCurrent.append(","); if (params == null) { whereClauseCurrent.append(value); } else { whereClauseCurrent.append("?"); params.add(value); } if (count >= 30) { if (whereClause.length() > 0) whereClause.append(" OR "); whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")"); whereClauseCurrent = new StringBuffer(); count = 0; } } if (whereClauseCurrent.length() > 0) { if (whereClause.length() > 0) whereClause.append(" OR "); whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")"); whereClauseCurrent = null; }
if (hasNull) { if (whereClause.length() > 0) whereClause.append(" OR "); whereClause.append(columnName).append(" IS NULL"); } if (whereClause.length() > 0) whereClause.insert(0, "(").append(")"); return whereClause.toString(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("InvoiceGenerateResult ["); sb.append("invoiceCount=").append(getInvoiceCount()); if (storeInvoices) { sb.append(", invoices=").append(invoices); } if (notifications != null && !notifications.isEmpty()) { sb.append(", notifications=").append(notifications); } sb.append("]"); return sb.toString(); } @Override public String getSummary(final Properties ctx) { return Services.get(IMsgBL.class).getMsg(ctx, MSG_Summary, new Object[] { getInvoiceCount(), getNotificationCount() }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceGenerateResult.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getDunningDate())); } /** 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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
} /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Send. @param SendIt Send */ public void setSendIt (String SendIt) { set_Value (COLUMNNAME_SendIt, SendIt); } /** Get Send. @return Send */ public String getSendIt () { return (String)get_Value(COLUMNNAME_SendIt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult<List<UmsResourceCategory>> listAll() { List<UmsResourceCategory> resourceList = resourceCategoryService.listAll(); return CommonResult.success(resourceList); } @ApiOperation("添加后台资源分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsResourceCategory umsResourceCategory) { int count = resourceCategoryService.create(umsResourceCategory); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台资源分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsResourceCategory umsResourceCategory) { int count = resourceCategoryService.update(id, umsResourceCategory); if (count > 0) { return CommonResult.success(count); } else {
return CommonResult.failed(); } } @ApiOperation("根据ID删除后台资源分类") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = resourceCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsResourceCategoryController.java
2
请完成以下Java代码
public OidcProviderConfiguration build() { validate(); return new OidcProviderConfiguration(getClaims()); } @Override protected void validate() { super.validate(); Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.JWKS_URI), "jwksUri cannot be null"); Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED), "subjectTypes cannot be null"); Assert.isInstanceOf(List.class, getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED), "subjectTypes must be of type List"); Assert.notEmpty((List<?>) getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED), "subjectTypes cannot be empty"); Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED), "idTokenSigningAlgorithms cannot be null"); Assert.isInstanceOf(List.class, getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED), "idTokenSigningAlgorithms must be of type List"); Assert.notEmpty( (List<?>) getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED), "idTokenSigningAlgorithms cannot be empty"); if (getClaims().get(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT) != null) { validateURL(getClaims().get(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT), "userInfoEndpoint must be a valid URL"); } if (getClaims().get(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT) != null) { validateURL(getClaims().get(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT), "endSessionEndpoint must be a valid URL"); }
} @SuppressWarnings("unchecked") private void addClaimToClaimList(String name, String value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>()); ((List<String>) getClaims().get(name)).add(value); } @SuppressWarnings("unchecked") private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(valuesConsumer, "valuesConsumer cannot be null"); getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>()); List<String> values = (List<String>) getClaims().get(name); valuesConsumer.accept(values); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcProviderConfiguration.java
1
请完成以下Java代码
public class CanalClient { private final static Logger logger = LoggerFactory.getLogger(CanalClient.class); private volatile boolean running = false; private Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { logger.error("parse events has an error", e); } }; private Thread thread = null; private CanalConnector connector; private static String canal_get = "get_message batchId : {} , entrySize : {}"; private static String canal_ack = "ack_message batchId : {} "; private String destination; public String getDestination() { return destination; } public CanalClient(String destination, CanalConnector connector) { this.destination = destination; this.connector = connector; } public void start() { Assert.notNull(connector, "connector is null"); thread = new Thread(new Runnable() { public void run() { logger.info("destination:{} running", destination); process(); } }); thread.setUncaughtExceptionHandler(handler); thread.start(); running = true; } public void stop() { if (!running) { return; } running = false; } private void process() {
int batchSize = 4 * 1024; while (running) { try { MDC.put("destination", destination); connector.connect(); connector.subscribe(); while (running) { Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据 long batchId = message.getId(); int size = message.getEntries().size(); if (batchId != -1 && size > 0) { logger.info(canal_get, batchId, size); // for (CanalEntry.Entry entry : message.getEntries()) { // logger.info("parse event has an data:" + entry.toString()); // } MessageHandler messageHandler = SpringUtil.getBean("messageHandler", MessageHandler.class); messageHandler.execute(message.getEntries()); logger.info(canal_ack, batchId); } connector.ack(batchId); // 提交确认 } } catch (Exception e) { logger.error("process error!", e); } finally { connector.disconnect(); MDC.remove("destination"); } } } }
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\canal\CanalClient.java
1
请完成以下Java代码
public static final class Builder { private int AD_Session_ID; private String trxName; private int AD_Table_ID; private int AD_Column_ID; private int record_ID; private int AD_Client_ID; private int AD_Org_ID; private Object oldValue; private Object newValue; private String eventType; private int AD_User_ID; private PInstanceId AD_PInstance_ID; private Builder() { super(); } public ChangeLogRecord build() { return new ChangeLogRecord(this); } public Builder setAD_Session_ID(final int AD_Session_ID) { this.AD_Session_ID = AD_Session_ID; return this; } public Builder setTrxName(final String trxName) { this.trxName = trxName; return this; } public Builder setAD_Table_ID(final int AD_Table_ID) { this.AD_Table_ID = AD_Table_ID; return this; } public Builder setAD_Column_ID(final int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public Builder setRecord_ID(final int record_ID) { this.record_ID = record_ID;
return this; } public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) { this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请完成以下Java代码
public ResponseEntity<BaseResponse> doJoin(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestHeader(name="Authorization", defaultValue="token") String token, @RequestBody PosParam posParam) { _logger.info("请求入网接口 start...."); BaseResponse result = new BaseResponse(); result.setSuccess(true); result.setMsg("入网成功"); return new ResponseEntity<>(result, HttpStatus.CREATED); } /** * 请求绑定网点接口 * * @return 处理结果 */ @ApiOperation(value = "请求绑定网点接口", notes = "POS机重新绑定新的网点", produces = "application/json") @RequestMapping(value = "/bind", method = RequestMethod.POST) public ResponseEntity<BaseResponse> doBind(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestHeader(name="Authorization", defaultValue="token") String token, @RequestBody BindParam bindParam) { _logger.info("请求绑定网点接口 start...."); BaseResponse result = new BaseResponse(); result.setSuccess(true); result.setMsg("绑定网点成功"); return new ResponseEntity<>(result, HttpStatus.OK); } /** * 报告位置接口 * * @return 报告结果 */ @ApiOperation(value = "报告位置接口", notes = "终端设备定时报告位置信息", produces = "application/json") @RequestMapping(value = "/report", method = RequestMethod.POST) public BaseResponse report(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestHeader(name="Authorization", defaultValue="token") String token, @RequestBody ReportParam param) { _logger.info("定时报告接口 start...."); BaseResponse result = new BaseResponse(); result.setSuccess(true); result.setMsg("心跳报告成功"); return result;
} /** * 版本检查接口 * * @return 版本检查结果 */ @ApiOperation(value = "APP版本更新检查", notes = "APP版本更新检查", produces = "application/json") @RequestMapping(value = "/version", method = RequestMethod.POST) public VersionResult version(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestHeader(name="Authorization", defaultValue="token") String token, @RequestBody VersionParam param) { _logger.info("版本检查接口 start...."); VersionResult result = new VersionResult(); result.setAppName("AppName"); result.setDownloadUrl("http://www.baidu.com/"); result.setFindNew(true); result.setPublishtime(new Date()); result.setTips("tips"); result.setVersion("v1.2"); return result; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\PublicController.java
1
请在Spring Boot框架中完成以下Java代码
public class CalculatorService { @Tool(description = "Add two numbers") public CalculationResult add(@ToolParam(description = "First number") double a, @ToolParam(description = "Second number") double b) { double result = a + b; return new CalculationResult("addition", a, b, result); } @Tool(description = "Subtract two numbers") public CalculationResult subtract(@ToolParam(description = "First number") double a, @ToolParam(description = "Second number") double b) { double result = a - b; return new CalculationResult("subtraction", a, b, result); } @Tool(description = "Multiply two numbers")
public CalculationResult multiply(@ToolParam(description = "First number") double a, @ToolParam(description = "Second number") double b) { double result = a * b; return new CalculationResult("multiplication", a, b, result); } @Tool(description = "Divide two numbers") public CalculationResult divide(@ToolParam(description = "First number") double a, @ToolParam(description = "Second number") double b) { if (b == 0) { throw new IllegalArgumentException("Cannot divide by zero"); } double result = a / b; return new CalculationResult("division", a, b, result); } }
repos\tutorials-master\spring-ai-modules\spring-ai-mcp-oauth\mcp-server-oauth2\src\main\java\com\baeldung\mcp\mcpserveroauth2\CalculatorService.java
2
请完成以下Java代码
public void removeValidator(Validator<AbstractQuery<?, ?>> validator) { validators.remove(validator); } @SuppressWarnings("unchecked") public List<String> listIds() { this.resultType = ResultType.LIST_IDS; List<String> ids = null; if (commandExecutor != null) { ids = (List<String>) commandExecutor.execute(this); } else { ids = evaluateExpressionsAndExecuteIdsList(Context.getCommandContext()); } if (ids != null) { QueryMaxResultsLimitUtil.checkMaxResultsLimit(ids.size()); } return ids; } @SuppressWarnings("unchecked") public List<ImmutablePair<String, String>> listDeploymentIdMappings() { this.resultType = ResultType.LIST_DEPLOYMENT_ID_MAPPINGS; List<ImmutablePair<String, String>> ids = null; if (commandExecutor != null) { ids = (List<ImmutablePair<String, String>>) commandExecutor.execute(this); } else { ids = evaluateExpressionsAndExecuteDeploymentIdMappingsList(Context.getCommandContext()); } if (ids != null) { QueryMaxResultsLimitUtil.checkMaxResultsLimit(ids.size()); } return ids; } public List<String> evaluateExpressionsAndExecuteIdsList(CommandContext commandContext) { validate(); evaluateExpressions(); return !hasExcludingConditions() ? executeIdsList(commandContext) : new ArrayList<>(); } public List<String> executeIdsList(CommandContext commandContext) { throw new UnsupportedOperationException("executeIdsList not supported by " + getClass().getCanonicalName()); }
public List<ImmutablePair<String, String>> evaluateExpressionsAndExecuteDeploymentIdMappingsList(CommandContext commandContext) { validate(); evaluateExpressions(); return !hasExcludingConditions() ? executeDeploymentIdMappingsList(commandContext) : new ArrayList<>(); } public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) { throw new UnsupportedOperationException("executeDeploymentIdMappingsList not supported by " + getClass().getCanonicalName()); } protected void checkMaxResultsLimit() { if (maxResultsLimitEnabled) { QueryMaxResultsLimitUtil.checkMaxResultsLimit(maxResults); } } public void enableMaxResultsLimit() { maxResultsLimitEnabled = true; } public void disableMaxResultsLimit() { maxResultsLimitEnabled = false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractQuery.java
1
请在Spring Boot框架中完成以下Java代码
public CommentCollectionResource getComments() { return comments; } /** * @param comments the comments to set */ public void setComments(CommentCollectionResource comments) { this.comments = comments; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((comments == null) ? 0 : comments.hashCode()); result = prime * result + (completed ? 1231 : 1237); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); 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;
TaskDTO other = (TaskDTO) obj; if (comments == null) { if (other.comments != null) return false; } else if (!comments.equals(other.comments)) return false; if (completed != other.completed) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (taskId == null) { if (other.taskId != null) return false; } else if (!taskId.equals(other.taskId)) return false; if (userName == null) { if (other.userName != null) return false; } else if (!userName.equals(other.userName)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "TaskDTO [taskId=" + taskId + ", description=" + description + ", completed=" + completed + ", userName=" + userName + ", comments=" + comments + "]"; } }
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\dtos\TaskDTO.java
2
请完成以下Java代码
public class Book { private Integer id; private String author; private String title; public Book(Integer id, String author, String title) { this.id = id; this.author = author; this.title = title; } public Book() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; return id.equals(book.id); } @Override public int hashCode() { return Objects.hash(id); } }
repos\tutorials-master\graphql-modules\graphql-spqr\src\main\java\com\baeldung\spqr\Book.java
1
请在Spring Boot框架中完成以下Java代码
public final class GrantedAuthorityFromAssertionAttributesUserDetailsService extends AbstractCasAssertionUserDetailsService { private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD"; private final String[] attributes; private boolean convertToUpperCase = true; public GrantedAuthorityFromAssertionAttributesUserDetailsService(final String[] attributes) { Assert.notNull(attributes, "attributes cannot be null."); Assert.isTrue(attributes.length > 0, "At least one attribute is required to retrieve roles from."); this.attributes = attributes; } @SuppressWarnings("unchecked") @Override protected UserDetails loadUserDetails(final Assertion assertion) { List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String attribute : this.attributes) { Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value != null) { if (value instanceof List) { for (Object o : (List<?>) value) { grantedAuthorities.add(createSimpleGrantedAuthority(o)); } } else {
grantedAuthorities.add(createSimpleGrantedAuthority(value)); } } } return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities); } private SimpleGrantedAuthority createSimpleGrantedAuthority(Object o) { return new SimpleGrantedAuthority( this.convertToUpperCase ? o.toString().toUpperCase(Locale.ROOT) : o.toString()); } /** * Converts the returned attribute values to uppercase values. * @param convertToUpperCase true if it should convert, false otherwise. */ public void setConvertToUpperCase(final boolean convertToUpperCase) { this.convertToUpperCase = convertToUpperCase; } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\userdetails\GrantedAuthorityFromAssertionAttributesUserDetailsService.java
2
请完成以下Java代码
public void changeRowById(@NonNull DocumentId rowId, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRow(rowId, rowMapper)); } public void changeRowsByIds(@NonNull DocumentIdsSelection rowIds, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRows(rowIds, rowMapper)); } public void setRows(@NonNull final List<T> rows) { holder.setValue(ImmutableRowsIndex.of(rows)); } @NonNull private ImmutableRowsIndex<T> getRowsIndex() {
final ImmutableRowsIndex<T> rowsIndex = holder.getValue(); // shall not happen if (rowsIndex == null) { throw new AdempiereException("rowsIndex shall be set"); } return rowsIndex; } public Predicate<DocumentId> isRelevantForRefreshingByDocumentId() { final ImmutableRowsIndex<T> rows = getRowsIndex(); return rows::isRelevantForRefreshing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\SynchronizedRowsIndexHolder.java
1
请在Spring Boot框架中完成以下Java代码
public static JsonWorkflowLaunchersList of( @NonNull final WorkflowLaunchersList result, @NonNull final JsonLaunchersQuery query, @NonNull final JsonOpts jsonOpts) { return of(result, query.isCountOnly(), jsonOpts); } public static JsonWorkflowLaunchersList of( @NonNull final WorkflowLaunchersList result, final boolean countOnly, @NonNull final JsonOpts jsonOpts) { final JsonWorkflowLaunchersListBuilder builder = builder() .count(result.size()) .filterByQRCode(result.getFilterByQRCode() != null ? result.getFilterByQRCode().toJson() : null) .computedTime(result.getTimestamp()); if (!countOnly)
{ final String adLanguage = jsonOpts.getAdLanguage(); builder.launchers(result.stream() .sorted(Comparator.comparing( WorkflowLauncher::getCaption, WorkflowLauncherCaption.orderBy(adLanguage, result.getOrderByFields()))) .map(launcher -> JsonWorkflowLauncher.of(launcher, jsonOpts)) .collect(ImmutableList.toImmutableList())); builder.actions(result.getActions()); } return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\json\JsonWorkflowLaunchersList.java
2
请在Spring Boot框架中完成以下Java代码
public class DefaultTbOauth2ClientService extends AbstractTbEntityService implements TbOauth2ClientService { private final OAuth2ClientService oAuth2ClientService; @Override public OAuth2Client save(OAuth2Client oAuth2Client, User user) throws Exception { ActionType actionType = oAuth2Client.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = oAuth2Client.getTenantId(); try { OAuth2Client savedClient = checkNotNull(oAuth2ClientService.saveOAuth2Client(tenantId, oAuth2Client)); logEntityActionService.logEntityAction(tenantId, savedClient.getId(), savedClient, actionType, user); return savedClient; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.OAUTH2_CLIENT), oAuth2Client, actionType, user, e); throw e; }
} @Override public void delete(OAuth2Client oAuth2Client, User user) { ActionType actionType = ActionType.DELETED; TenantId tenantId = oAuth2Client.getTenantId(); OAuth2ClientId oAuth2ClientId = oAuth2Client.getId(); try { oAuth2ClientService.deleteOAuth2ClientById(tenantId, oAuth2ClientId); logEntityActionService.logEntityAction(tenantId, oAuth2ClientId, oAuth2Client, actionType, user); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, oAuth2ClientId, oAuth2Client, actionType, user, e); throw e; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\oauth2client\DefaultTbOauth2ClientService.java
2
请完成以下Java代码
private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // don't check } @Override
public void checkServerTrusted(X509Certificate[] certs, String authType) { // don't check } } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustAllCerts, null); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\CasServiceUtil.java
1
请完成以下Java代码
public void setAnonymousAuthentication(Authentication authentication) { Assert.notNull(authentication, "authentication cannot be null"); this.anonymous = authentication; } @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); if (authentication == null) { authentication = this.anonymous; } return MessageBuilder.fromMessage(message).setHeader(this.authenticationHeaderName, authentication).build(); } @Override public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { return postReceive(message, channel); } @Override public Message<?> postReceive(Message<?> message, MessageChannel channel) { setup(message); return message; } @Override public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, @Nullable Exception ex) { cleanup(); } private void setup(Message<?> message) { Authentication authentication = message.getHeaders().get(this.authenticationHeaderName, Authentication.class); SecurityContext currentContext = this.securityContextHolderStrategy.getContext(); Stack<SecurityContext> contextStack = originalContext.get(); if (contextStack == null) { contextStack = new Stack<>(); originalContext.set(contextStack); } contextStack.push(currentContext); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context); } private void cleanup() { Stack<SecurityContext> contextStack = originalContext.get(); if (contextStack == null || contextStack.isEmpty()) { this.securityContextHolderStrategy.clearContext(); originalContext.remove(); return; } SecurityContext context = contextStack.pop(); try { if (this.empty.equals(context)) { this.securityContextHolderStrategy.clearContext(); originalContext.remove(); } else { this.securityContextHolderStrategy.setContext(context); } } catch (Throwable ex) { this.securityContextHolderStrategy.clearContext(); } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextPropagationChannelInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public InternalEntityLinkQueryImpl<E> getParameter() { return this; } @Override public boolean isRetained(E entity, Object param) { return isRetained(entity, (InternalEntityLinkQueryImpl<?>) param); } @Override public boolean isRetained(Collection<E> databaseEntities, Collection<CachedEntity> cachedEntities, E entity, Object param) { return isRetained(entity, (InternalEntityLinkQueryImpl<?>) param); } public boolean isRetained(E entity, InternalEntityLinkQueryImpl<?> param) { if (param.scopeId != null && !param.scopeId.equals(entity.getScopeId())) { return false; } if (param.scopeIds != null && !param.scopeIds.contains(entity.getScopeId())) { return false; } if (param.scopeDefinitionId != null && !param.scopeDefinitionId.equals(entity.getScopeDefinitionId())) { return false; } if (param.scopeType != null && !param.scopeType.equals(entity.getScopeType())) { return false; } if (param.referenceScopeId != null && !param.referenceScopeId.equals(entity.getReferenceScopeId())) { return false; } if (param.referenceScopeDefinitionId != null && !param.referenceScopeDefinitionId.equals(entity.getReferenceScopeDefinitionId())) { return false; } if (param.referenceScopeType != null && !param.referenceScopeType.equals(entity.getReferenceScopeType())) { return false; }
if (param.rootScopeId != null && !param.rootScopeId.equals(entity.getRootScopeId())) { return false; } if (param.rootScopeType != null && !param.rootScopeType.equals(entity.getRootScopeType())) { return false; } if (param.linkType != null && !param.linkType.equals(entity.getLinkType())) { return false; } if (param.hierarchyType != null && !param.hierarchyType.equals(entity.getHierarchyType())) { return false; } return true; } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\InternalEntityLinkQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public ProdStateEnum getProdStateEnum() { return prodStateEnum; } public void setProdStateEnum(ProdStateEnum prodStateEnum) { this.prodStateEnum = prodStateEnum; } public List<ProdImageEntity> getProdImageEntityList() { return prodImageEntityList; } public void setProdImageEntityList(List<ProdImageEntity> prodImageEntityList) { this.prodImageEntityList = prodImageEntityList; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public UserEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(UserEntity companyEntity) { this.companyEntity = companyEntity; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; }
@Override public String toString() { return "ProductEntity{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntity=" + topCateEntity + ", subCategEntity=" + subCategEntity + ", brandEntity=" + brandEntity + ", prodStateEnum=" + prodStateEnum + ", prodImageEntityList=" + prodImageEntityList + ", content='" + content + '\'' + ", companyEntity=" + companyEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java
2
请完成以下Java代码
public void deleteAttachment(String attachmentId) { commandExecutor.execute(new DeleteAttachmentCmd(attachmentId)); } @Override public void deleteComments(String taskId, String processInstanceId) { commandExecutor.execute(new DeleteCommentCmd(taskId, processInstanceId, null)); } @Override public void deleteComment(String commentId) { commandExecutor.execute(new DeleteCommentCmd(null, null, commentId)); } @Override public Attachment getAttachment(String attachmentId) { return commandExecutor.execute(new GetAttachmentCmd(attachmentId)); } @Override public List<Attachment> getTaskAttachments(String taskId) { return commandExecutor.execute(new GetTaskAttachmentsCmd(taskId)); }
@Override public List<Attachment> getProcessInstanceAttachments(String processInstanceId) { return commandExecutor.execute(new GetProcessInstanceAttachmentsCmd(processInstanceId)); } @Override public void saveAttachment(Attachment attachment) { commandExecutor.execute(new SaveAttachmentCmd(attachment)); } @Override public List<Task> getSubTasks(String parentTaskId) { return commandExecutor.execute(new GetSubTasksCmd(parentTaskId)); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java
1
请完成以下Java代码
public void removeChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) { this.childCompensationSubscriptionInstances.remove(migratingEventSubscription); } @Override public boolean migrates() { return targetScope != null; } @Override public void detachChildren() { Set<MigratingProcessElementInstance> childrenCopy = new HashSet<MigratingProcessElementInstance>(getChildren()); for (MigratingProcessElementInstance child : childrenCopy) { child.detachState(); } } @Override public void remove(boolean skipCustomListeners, boolean skipIoMappings) { // never invokes listeners and io mappings because this does not remove an active // activity instance eventScopeExecution.remove(); migratingEventSubscription.remove(); setParent(null); }
@Override public Collection<MigratingProcessElementInstance> getChildren() { Set<MigratingProcessElementInstance> children = new HashSet<MigratingProcessElementInstance>(childInstances); children.addAll(childCompensationSubscriptionInstances); return children; } @Override public Collection<MigratingScopeInstance> getChildScopeInstances() { return new HashSet<MigratingScopeInstance>(childInstances); } @Override public void removeUnmappedDependentInstances() { } public MigratingCompensationEventSubscriptionInstance getEventSubscription() { return migratingEventSubscription; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingEventScopeInstance.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-consumer-application cloud: # Spring Cloud Stream 配置项,对应 BindingServiceProperties 类 stream: # Binder 配置项,对应 BinderProperties Map # binders: # Binding 配置项,对应 BindingProperties Map bindings: demo01-input: destination: DEMO-TOPIC-01 # 目的地。这里使用 Kafka Topic content-type: application/json # 内容格式。这里使用 JSON group: demo01-consumer-group # 消费者分组 # Consumer 配置项,对应 ConsumerProperties 类 consumer: max-attempts: 3 # 重试次数,默认为 3 次。 back-off-initial-interval: 3000 # 重试间隔的初始值,单位毫秒,默认为 1000 back-off-multiplier: 2.0 # 重试间隔的递乘系数,默认为 2.0 back-off-max-interval: 10000 # 重试间隔的最大值,单位毫秒,默认为 10000 # Spring Cloud Stream Kafka 配置项 kafka: # Kafka Binder 配置项,对应 KafkaBinderConfigurationProperties 类 binder: brokers: 127.0.0.1:9092 # 指定 K
afka Broker 地址,可以设置多个,以逗号分隔 # Kafka Binding 配置项,对应 KafkaBindingProperties 类 bindings: demo01-input: # Kafka Consumer 配置项,对应 KafkaConsumerProperties 类 consumer: enable-dlq: true # 是否开启死信队列,默认为 false 关闭 dlq-name: # 死信队列名,默认为 `errors.{topicName}.{consumerGroup}` server: port: ${random.int[10000,19999]} # 随机端口,方便启动多个消费者
repos\SpringBoot-Labs-master\labx-11-spring-cloud-stream-kafka\labx-11-sc-stream-kafka-consumer-error-handler\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin") .password(passwordEncoder().encode("admin123")) .roles("ADMIN"); } /** * Enable HTTPS/SSL in Spring Boot * **/ @Override
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // .anyRequest().permitAll() if you fix all permission values, then remove all conditions. .antMatchers("/index").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\5.0.1 SpringHttpToHttps\src\main\java\spring\security\SecurityConfiguration.java
2
请完成以下Java代码
public class TableRecordMDC { public MDCCloseable putTableRecordReference(@NonNull final String tableName, @Nullable final RepoIdAware id) { final String key = tableName + "_ID"; final String value = id == null ? "null" : Integer.toString(id.getRepoId()); return putKeyAndValue(key, value); } public MDCCloseable putTableRecordReference(@NonNull final Object recordModel) { return putTableRecordReference(TableRecordReference.of(recordModel)); } /** * @return {@code null} if the given {@code tableRecordReference} was put already. * Thx to https://stackoverflow.com/a/35372185/1012103
*/ public MDCCloseable putTableRecordReference(@NonNull final TableRecordReference tableRecordReference) { final String key = tableRecordReference.getTableName() + "_ID"; final String value = Integer.toString(tableRecordReference.getRecord_ID()); return putKeyAndValue(key, value); } private MDCCloseable putKeyAndValue(final String key, final String value) { if (Objects.equals(MDC.get(key), value)) { return null; } return MDC.putCloseable(key, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\TableRecordMDC.java
1
请完成以下Java代码
public IAutoCloseable switchContext(@NonNull final Properties ctx) { // If we were asked to set the context proxy (the one which we are returning everytime), // then it's better to do nothing because this could end in a StackOverflowException. if (ctx == ctxProxy) { logger.trace("Not switching context because the given temporary context it's actually our context proxy: {}", ctx); return NullAutoCloseable.instance; } final Properties previousTempCtx = temporaryCtxHolder.get(); temporaryCtxHolder.set(ctx); logger.trace("Switched to temporary context. \n New temporary context: {} \n Previous temporary context: {}", ctx, previousTempCtx); return new IAutoCloseable() { private boolean closed = false; @Override public void close() { if (closed) { return; } if (previousTempCtx != null) { temporaryCtxHolder.set(previousTempCtx); }
else { temporaryCtxHolder.remove(); } closed = true; logger.trace("Switched back from temporary context"); } }; } @Override public void reset() { temporaryCtxHolder.remove(); serverCtx.clear(); logger.debug("Reset done"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\WebRestApiContextProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class PeriodType { @XmlElement(name = "FromDate", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar fromDate; @XmlElement(name = "ToDate", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar toDate; /** * Delivery period - from date. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getFromDate() { return fromDate; } /** * Sets the value of the fromDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setFromDate(XMLGregorianCalendar value) { this.fromDate = value; } /** * Delivery period - to date. * * @return * possible object is * {@link XMLGregorianCalendar }
* */ public XMLGregorianCalendar getToDate() { return toDate; } /** * Sets the value of the toDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setToDate(XMLGregorianCalendar value) { this.toDate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PeriodType.java
2
请完成以下Java代码
public final class CsrfRequestDataValueProcessor implements RequestDataValueProcessor { private Pattern DISABLE_CSRF_TOKEN_PATTERN = Pattern.compile("(?i)^(GET|HEAD|TRACE|OPTIONS)$"); private String DISABLE_CSRF_TOKEN_ATTR = "DISABLE_CSRF_TOKEN_ATTR"; public String processAction(HttpServletRequest request, String action) { return action; } @Override public String processAction(HttpServletRequest request, String action, String method) { if (method != null && this.DISABLE_CSRF_TOKEN_PATTERN.matcher(method).matches()) { request.setAttribute(this.DISABLE_CSRF_TOKEN_ATTR, Boolean.TRUE); } else { request.removeAttribute(this.DISABLE_CSRF_TOKEN_ATTR); } return action; } @Override public String processFormFieldValue(HttpServletRequest request, @Nullable String name, String value, String type) { return value; } @Override public Map<String, String> getExtraHiddenFields(HttpServletRequest request) { if (Boolean.TRUE.equals(request.getAttribute(this.DISABLE_CSRF_TOKEN_ATTR))) { request.removeAttribute(this.DISABLE_CSRF_TOKEN_ATTR); return Collections.emptyMap(); }
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (token == null) { return Collections.emptyMap(); } Map<String, String> hiddenFields = new HashMap<>(1); hiddenFields.put(token.getParameterName(), token.getToken()); return hiddenFields; } @Override public String processUrl(HttpServletRequest request, String url) { return url; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servlet\support\csrf\CsrfRequestDataValueProcessor.java
1
请完成以下Java代码
public class OpenApiLog implements Serializable { private static final long serialVersionUID = -5870384488947863579L; /** * id */ @TableId(type = IdType.ASSIGN_ID) private String id; /** * 接口ID */ private String apiId; /** * 调用ID */ private String callAuthId;
/** * 调用时间 */ private Date callTime; /** * 耗时 */ private Long usedTime; /** * 响应时间 */ private Date responseTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\entity\OpenApiLog.java
1
请在Spring Boot框架中完成以下Java代码
private void checkWsUpdates(WsClient wsClient, String testValue) { stopWatch.start(); wsClient.waitForUpdates(resultCheckTimeoutMs); log.trace("[{}] Waited for WS update. Last WS msgs: {}", info, wsClient.lastMsgs); Map<String, String> latest = wsClient.getLatest(target.getDeviceId()); if (latest.isEmpty()) { throw new ServiceFailureException(info, "No WS update arrived within " + resultCheckTimeoutMs + " ms"); } String actualValue = latest.get(TEST_TELEMETRY_KEY); if (!testValue.equals(actualValue)) { throw new ServiceFailureException(info, "Was expecting value " + testValue + " but got " + actualValue); } if (isCfMonitoringEnabled()) { String cfTestValue = testValue + "-cf"; String actualCfValue = latest.get(TEST_CF_TELEMETRY_KEY); if (actualCfValue == null) { throw new ServiceFailureException(info, "No calculated field value arrived"); } else if (!cfTestValue.equals(actualCfValue)) { throw new ServiceFailureException(info, "Was expecting calculated field value " + cfTestValue + " but got " + actualCfValue); } }
reporter.reportLatency(Latencies.wsUpdate(getKey()), stopWatch.getTime()); } protected abstract void initClient() throws Exception; protected abstract String createTestPayload(String testValue); protected abstract void sendTestPayload(String payload) throws Exception; @PreDestroy protected abstract void destroyClient() throws Exception; protected abstract Object getInfo(); protected abstract String getKey(); protected abstract boolean isCfMonitoringEnabled(); }
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\BaseHealthChecker.java
2
请完成以下Java代码
private Stream<ScaleDevice> streamAvailableScaleDevices(final @NonNull WFProcess wfProcess) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); return manufacturingJobService.streamAvailableScaleDevices(job); } private static JsonQRCode toJsonQRCode(final ScaleDevice scaleDevice, final String adLanguage) { final DeviceQRCode qrCode = DeviceQRCode.builder() .deviceId(scaleDevice.getDeviceId()) .caption(scaleDevice.getCaption().translate(adLanguage)) .build(); return JsonQRCode.builder() .qrCode(qrCode.toGlobalQRCodeJsonString()) .caption(qrCode.getCaption()) .build(); }
@Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return getCurrentScaleDevice(wfProcess).isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(final @NonNull SetScannedBarcodeRequest request) { final DeviceId newScaleDeviceId = DeviceQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode()).getDeviceId(); return ManufacturingMobileApplication.mapDocument( request.getWfProcess(), job -> manufacturingJobService.withCurrentScaleDevice(job, newScaleDeviceId) ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\scanScaleDevice\ScanScaleDeviceActivityHandler.java
1
请在Spring Boot框架中完成以下Java代码
public AsyncReporter<Span> spanReporter() { // 异步 Reporter return AsyncReporter.create(sender()); } /** * Controls aspects of tracing such as the service name that shows up in the UI */ @Bean public Tracing tracing(@Value("${spring.application.name}") String serviceName) { return Tracing.newBuilder() .localServiceName(serviceName) // 应用名 .spanReporter(this.spanReporter()).build(); } /** * Allows someone to add tags to a span if a trace is in progress */ @Bean public SpanCustomizer spanCustomizer(Tracing tracing) { return CurrentSpanCustomizer.create(tracing); } // ==================== HTTP 相关 ==================== /** * Decides how to name and tag spans. By default they are named the same as the http method */ @Bean public HttpTracing httpTracing(Tracing tracing) { return HttpTracing.create(tracing); } /** * Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { // 拦截请求,记录 HTTP 请求的链路信息 return TracingFilter.create(httpTracing); }
// ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) 。因为 SpanCustomizingAsyncHandlerInterceptor 未提供 public 构造方法 // ==================== RabbitMQ 相关 ==================== @Bean public JmsTracing jmsTracing(Tracing tracing) { return JmsTracing.newBuilder(tracing) .remoteServiceName("demo-mq-activemq") // 远程 ActiveMQ 服务名,可自定义 .build(); } @Bean public BeanPostProcessor activeMQBeanPostProcessor(JmsTracing jmsTracing) { return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // 如果是 ConnectionFactory ,针对 ActiveMQ Producer 和 Consumer if (bean instanceof ConnectionFactory) { return jmsTracing.connectionFactory((ConnectionFactory) bean); } return bean; } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-activemq\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public void onApplicationReady(ApplicationReadyEvent event) { if (autoRegister) { startRegisterTask(); } } @EventListener @Order(Ordered.LOWEST_PRECEDENCE) public void onClosedContext(ContextClosedEvent event) { if (event.getApplicationContext().getParent() == null || "bootstrap".equals(event.getApplicationContext().getParent().getId())) { stopRegisterTask(); if (autoDeregister) { registrator.deregister(); } } } public void startRegisterTask() { if (scheduledTask != null && !scheduledTask.isDone()) { return; } scheduledTask = taskScheduler.scheduleAtFixedRate(registrator::register, registerPeriod); LOGGER.debug("Scheduled registration task for every {}ms", registerPeriod.toMillis()); } public void stopRegisterTask() { if (scheduledTask != null && !scheduledTask.isDone()) { scheduledTask.cancel(true); LOGGER.debug("Canceled registration task"); } } public void setAutoDeregister(boolean autoDeregister) { this.autoDeregister = autoDeregister; } public void setAutoRegister(boolean autoRegister) {
this.autoRegister = autoRegister; } public void setRegisterPeriod(Duration registerPeriod) { this.registerPeriod = registerPeriod; } @Override public void afterPropertiesSet() { taskScheduler.afterPropertiesSet(); } @Override public void destroy() { taskScheduler.destroy(); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\RegistrationApplicationListener.java
1
请完成以下Java代码
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; } @Override public String modelChange(final PO po, final int type) throws Exception { if (type != ModelValidator.TYPE_AFTER_CHANGE && type != ModelValidator.TYPE_AFTER_NEW && type != ModelValidator.TYPE_BEFORE_DELETE) { return null; } if (!po.is_ManualUserAction()) { return null; } final I_M_ProductPrice productPrice = create(po, I_M_ProductPrice.class); final String useScalePrice = productPrice.getUseScalePrice(); if (Objects.equals(useScalePrice, X_M_ProductPrice.USESCALEPRICE_DonTUseScalePrice)) { return null; } if (type == ModelValidator.TYPE_BEFORE_DELETE) { productPriceDelete(productPrice); } else { final IProductPA productPA = Services.get(IProductPA.class); if (!Objects.equals(useScalePrice, X_M_ProductPrice.USESCALEPRICE_DonTUseScalePrice)) { final String trxName = getTrxName(productPrice); final I_M_ProductScalePrice productScalePrice = productPA.retrieveOrCreateScalePrices( productPrice.getM_ProductPrice_ID(), BigDecimal.ONE, // Qty true, // createNew=true => if the scalePrice doesn't exist yet, create a new one trxName); // copy the price from the productPrice productScalePrice.setM_ProductPrice_ID(productPrice.getM_ProductPrice_ID());
productScalePrice.setPriceLimit(productPrice.getPriceLimit()); productScalePrice.setPriceList(productPrice.getPriceList()); productScalePrice.setPriceStd(productPrice.getPriceStd()); save(productScalePrice); } } return null; } private void productPriceDelete(final I_M_ProductPrice productPrice) { if (productPrice.getM_ProductPrice_ID() <= 0) { return; } final String trxName = getTrxName(productPrice); for (final I_M_ProductScalePrice psp : productPA.retrieveScalePrices(productPrice.getM_ProductPrice_ID(), trxName)) { if (psp.getM_ProductPrice_ID() != productPrice.getM_ProductPrice_ID()) { // the psp comes from cache and is stale // NOTE: i think this problem does not apply anymore, so we can safely delete this check continue; } delete(psp); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\modelvalidator\MProductPriceValidator.java
1
请完成以下Java代码
public ConfigurationPropertyName getName() { return this.name; } /** * Return the target being bound. * @return the bind target */ public Bindable<?> getTarget() { return this.target; } /** * Return the configuration property name of the item that was being bound. * @return the configuration property name */ public @Nullable ConfigurationProperty getProperty() { return this.property;
} @Override public @Nullable Origin getOrigin() { return Origin.from(this.name); } private static String buildMessage(@Nullable ConfigurationPropertyName name, Bindable<?> target) { StringBuilder message = new StringBuilder(); message.append("Failed to bind properties"); message.append((name != null) ? " under '" + name + "'" : ""); message.append(" to ").append(target.getType()); return message.toString(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\BindException.java
1
请完成以下Java代码
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { String rememberMe = request.getParameter(parameter); if (rememberMe != null) { if (rememberMe.equalsIgnoreCase("true") || rememberMe.equalsIgnoreCase("on") || rememberMe.equalsIgnoreCase("yes") || rememberMe.equals("1")) { return true; } } if (logger.isDebugEnabled()) { logger.debug("Did not send remember-me cookie (principal did not set " + "parameter '" + parameter + "')"); } return false; } /** * Set the name of the parameter which should be checked for to see if a remember-me * has been requested during a login request. This should be the same name you assign * to the checkbox in your login form. * @param rememberMeParameterName the request parameter */ public void setRememberMeParameterName(String rememberMeParameterName) { Assert.hasText(rememberMeParameterName, "rememberMeParameterName cannot be empty or null"); this.rememberMeParameterName = rememberMeParameterName; }
public void setAlwaysRemember(boolean alwaysRemember) { this.alwaysRemember = alwaysRemember; } public void setValiditySeconds(int validitySeconds) { this.validitySeconds = validitySeconds; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { logout(request); } private void logout(HttpServletRequest request) { logger.debug("Interactive login attempt was unsuccessful."); HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\web\authentication\SpringSessionRememberMeServices.java
1
请完成以下Java代码
public class C_AllocationHdr extends MaterialTrackableDocumentByASIInterceptor<I_C_AllocationHdr, I_C_AllocationLine> { @Init public void init() { final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class); materialTrackingBL.addModelTrackingListener( PaymentAllocationLineMaterialTrackingListener.LISTENER_TableName, PaymentAllocationLineMaterialTrackingListener.instance); } @Override protected boolean isEligibleForMaterialTracking(final I_C_AllocationHdr document) { // NOTE: at this point we don't know if is eligible or not, so we consider everything as eligible // and we will decide it later, on Allocation Line if (Services.get(IAllocationBL.class).isReversal(document)) { // .. at any rate, we don't link reversals, because the original allocation is also unlinked. return false; } return true; } @Override protected List<I_C_AllocationLine> retrieveDocumentLines(final I_C_AllocationHdr document) { return Services.get(IAllocationDAO.class).retrieveLines(document); } @Override protected AttributeSetInstanceId getM_AttributeSetInstance(final I_C_AllocationLine documentLine) { // shall not be called because we implement "getMaterialTrackingFromDocumentLineASI" throw new IllegalStateException("shall not be called"); } /** * Loads and returns the material tracking of the invoice referenced by the given {@code documentLine}, if there is any. If there is none, it returns {@code null}.
* Analog to {@link C_Invoice#isEligibleForMaterialTracking(I_C_Invoice)}, if the invoice is a sales invoice or if it is reversed, then we don't bother trying to get its material tracking and directly return {@code null}. */ @Override protected I_M_Material_Tracking getMaterialTrackingFromDocumentLineASI(final I_C_AllocationLine documentLine) { if (documentLine.getC_Invoice_ID() <= 0) { return null; } final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final I_C_Invoice invoice = documentLine.getC_Invoice(); // please keep in sync with the isEligible method mentioned in the javadoc. if (Services.get(IInvoiceBL.class).isReversal(invoice)) { return null; } if (invoice.isSOTrx()) { return null; } final I_M_Material_Tracking materialTracking = materialTrackingDAO.retrieveSingleMaterialTrackingForModel(invoice); return materialTracking; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_AllocationHdr.java
1
请完成以下Java代码
public void assertReActivationAllowed(final I_C_Order order) { if (order.isSOTrx()) { shipmentScheduleBL.assertSalesOrderCanBeReactivated(OrderId.ofRepoId(order.getC_Order_ID())); } else { if (receiptScheduleDAO.existsExportedReceiptScheduleForOrder(OrderId.ofRepoId(order.getC_Order_ID()))) { throw new AdempiereException(MSG_PO_REACTIVATION_VOID_NOT_ALLOWED) .markAsUserValidationError(); } } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ignoreColumnsChanged = { I_C_Order.COLUMNNAME_DocStatus, I_C_Order.COLUMNNAME_DocAction, I_C_Order.COLUMNNAME_Processing, I_C_Order.COLUMNNAME_Processed, I_C_Order.COLUMNNAME_IsApproved, I_C_Order.COLUMNNAME_QtyOrdered, I_C_Order.COLUMNNAME_QtyInvoiced, I_C_Order.COLUMNNAME_InvoiceDate, I_C_Order.COLUMNNAME_QtyMoved,
I_C_Order.COLUMNNAME_GrandTotal, I_C_Order.COLUMNNAME_TotalLines, I_C_Order.COLUMNNAME_Weight, I_C_Order.COLUMNNAME_Posted, I_C_Order.COLUMNNAME_Updated, I_C_Order.COLUMNNAME_UpdatedBy }) public void assertChangeAllowed(@NonNull final I_C_Order order) { if (order.getQtyMoved().signum() == 0 || orderBL.isSalesOrder(order)) { return; } throw new AdempiereException(ERR_ORDER_MODIFICATION_NOT_ALLOWED_RECEIPT_EXISTS) .markAsUserValidationError(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\C_Order.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCreateBOMLine { @ApiModelProperty(position = 10, value = PRODUCT_IDENTIFIER_DOC, required = true) String productIdentifier; @ApiModelProperty(position = 20, value = "Corresponding to 'PP_Product_BOMLine.QtyBom' and 'PP_Product_BOMLine.C_UOM_ID' ", required = true) JsonQuantity qtyBom; @ApiModelProperty(position = 30, value = "Corresponding to 'PP_Product_BOMLine.Line") Integer line; @ApiModelProperty(position = 40, value = "Corresponding to 'PP_Product_BOMLine.IsQtyPercentage") Boolean isQtyPercentage; @ApiModelProperty(position = 50, value = "Corresponding to 'PP_Product_BOMLine.Scrap") BigDecimal scrap; @ApiModelProperty(position = 60, value = "Corresponding to 'PP_Product_BOMLine.IssueMethod") String issueMethod; @ApiModelProperty(position = 70, value = "Corresponding to `M_AttributeSetInstance`") JsonAttributeSetInstance attributeSetInstance; @Builder @JsonCreator public JsonCreateBOMLine( @JsonProperty("productIdentifier") @NonNull final String productIdentifier, @JsonProperty("qtyBom") @NonNull final JsonQuantity qtyBom, @JsonProperty("line") @Nullable final Integer line,
@JsonProperty("isQtyPercentage") @Nullable final Boolean isQtyPercentage, @JsonProperty("scrap") final BigDecimal scrap, @JsonProperty("issueMethod") @Nullable final String issueMethod, @JsonProperty("attributeSetInstance") @Nullable final JsonAttributeSetInstance attributeSetInstance) { this.productIdentifier = productIdentifier; this.qtyBom = qtyBom; this.line = line; this.isQtyPercentage = isQtyPercentage; this.scrap = scrap; this.issueMethod = issueMethod; this.attributeSetInstance = attributeSetInstance; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\bom\JsonCreateBOMLine.java
2
请完成以下Java代码
public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setResult (final int Result) { set_Value (COLUMNNAME_Result, Result); } @Override public int getResult() {
return get_ValueAsInt(COLUMNNAME_Result); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
1
请完成以下Java代码
public void contribute(Info.Builder builder) { Map<String, Object> details = new LinkedHashMap<>(); this.metadataProvider.get().getDependencies().getAll().forEach((dependency) -> { if (dependency.getBom() == null) { contribute(details, dependency); } }); if (!details.isEmpty()) { builder.withDetail("dependency-ranges", details); } } private void contribute(Map<String, Object> details, Dependency dependency) { if (!ObjectUtils.isEmpty(dependency.getMappings())) { Map<String, VersionRange> dep = new LinkedHashMap<>(); dependency.getMappings().forEach((it) -> { if (it.getRange() != null && it.getVersion() != null) { dep.put(it.getVersion(), it.getRange()); } }); if (!dep.isEmpty()) { if (dependency.getRange() == null) { boolean openRange = dep.values().stream().anyMatch((v) -> v.getHigherVersion() == null); if (!openRange) { Version higher = getHigher(dep); dep.put("managed", new VersionRange(higher)); } } Map<String, Object> depInfo = new LinkedHashMap<>(); dep.forEach((k, r) -> depInfo.put(k, "Spring Boot " + r)); details.put(dependency.getId(), depInfo); } } else if (dependency.getVersion() != null && dependency.getRange() != null) {
Map<String, Object> dep = new LinkedHashMap<>(); String requirement = "Spring Boot " + dependency.getRange(); dep.put(dependency.getVersion(), requirement); details.put(dependency.getId(), dep); } } private Version getHigher(Map<String, VersionRange> dep) { Version higher = null; for (VersionRange versionRange : dep.values()) { Version candidate = versionRange.getHigherVersion(); if (higher == null) { higher = candidate; } else if (candidate.compareTo(higher) > 0) { higher = candidate; } } return higher; } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\info\DependencyRangesInfoContributor.java
1
请完成以下Java代码
public RoleId getLoggedRoleId() { return Env.getLoggedRoleId(getCtx()); } public String getUserName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_User_Name); } public String getRoleName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Role_Name); } String getAdLanguage() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Language); } Language getLanguage() { return Env.getLanguage(getCtx()); } /** * @return previous language */
String verifyLanguageAndSet(final Language lang) { final Properties ctx = getCtx(); final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language); // // Check the language (and update it if needed) final Language validLang = Env.verifyLanguageFallbackToBase(lang); // // Actual update final String adLanguageNew = validLang.getAD_Language(); Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew); this.locale = validLang.getLocale(); UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang); return adLanguageOld; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\InternalUserSessionData.java
1
请完成以下Java代码
/* package */final Optional<IncludedDetailInfo> includedDetailInfoIfExists(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return Optional.ofNullable(includedDetailInfos.get(detailId)); } /* package */void collectEvent(final IDocumentFieldChangedEvent event) { final boolean init_isKey = false; final boolean init_publicField = true; final boolean init_advancedField = false; final DocumentFieldWidgetType init_widgetType = event.getWidgetType(); fieldChangesOf(event.getFieldName(), init_isKey, init_publicField, init_advancedField, init_widgetType) .mergeFrom(event); } /* package */ void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning) { fieldChangesOf(documentField).setFieldWarning(fieldWarning); } public static final class IncludedDetailInfo { private final DetailId detailId; private boolean stale = false; private LogicExpressionResult allowNew; private LogicExpressionResult allowDelete; private IncludedDetailInfo(final DetailId detailId) { this.detailId = detailId; } public DetailId getDetailId() { return detailId; } IncludedDetailInfo setStale() { stale = true; return this; } public boolean isStale() { return stale; } public LogicExpressionResult getAllowNew() { return allowNew; } IncludedDetailInfo setAllowNew(final LogicExpressionResult allowNew) { this.allowNew = allowNew; return this; }
public LogicExpressionResult getAllowDelete() { return allowDelete; } IncludedDetailInfo setAllowDelete(final LogicExpressionResult allowDelete) { this.allowDelete = allowDelete; return this; } private void collectFrom(final IncludedDetailInfo from) { if (from.stale) { stale = from.stale; } if (from.allowNew != null) { allowNew = from.allowNew; } if (from.allowDelete != null) { allowDelete = from.allowDelete; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChanges.java
1
请完成以下Java代码
public void setRefundInvoiceType (java.lang.String RefundInvoiceType) { set_Value (COLUMNNAME_RefundInvoiceType, RefundInvoiceType); } /** Get Rückvergütung per. @return Rückvergütung per */ @Override public java.lang.String getRefundInvoiceType () { return (java.lang.String)get_Value(COLUMNNAME_RefundInvoiceType); } /** * RefundMode AD_Reference_ID=540903 * Reference name: RefundMode */ public static final int REFUNDMODE_AD_Reference_ID=540903; /** Tiered = T */ public static final String REFUNDMODE_Tiered = "T"; /** Accumulated = A */ public static final String REFUNDMODE_Accumulated = "A"; /** Set Staffel-Modus. @param RefundMode Staffel-Modus */ @Override public void setRefundMode (java.lang.String RefundMode) { set_Value (COLUMNNAME_RefundMode, RefundMode);
} /** Get Staffel-Modus. @return Staffel-Modus */ @Override public java.lang.String getRefundMode () { return (java.lang.String)get_Value(COLUMNNAME_RefundMode); } /** Set Rückvergütung %. @param RefundPercent Rückvergütung % */ @Override public void setRefundPercent (java.math.BigDecimal RefundPercent) { set_Value (COLUMNNAME_RefundPercent, RefundPercent); } /** Get Rückvergütung %. @return Rückvergütung % */ @Override public java.math.BigDecimal getRefundPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RefundPercent); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_RefundConfig.java
1
请在Spring Boot框架中完成以下Java代码
public final void clearJobScopeLock(Job job) { InternalJobManager internalJobManager = findInternalJobManager(job); if (internalJobManager == null) { clearJobScopeLockInternal(job); } else { internalJobManager.clearJobScopeLock(job); } } protected abstract void clearJobScopeLockInternal(Job job); @Override public final void preTimerJobDelete(JobEntity jobEntity, VariableScope variableScope) { InternalJobManager internalJobManager = findInternalJobManager(jobEntity); if (internalJobManager == null) { preTimerJobDeleteInternal(jobEntity, variableScope); } else { internalJobManager.preTimerJobDelete(jobEntity, variableScope); } } protected abstract void preTimerJobDeleteInternal(JobEntity jobEntity, VariableScope variableScope); @Override public final void preRepeatedTimerSchedule(TimerJobEntity timerJobEntity, VariableScope variableScope) { InternalJobManager internalJobManager = findInternalJobManager(timerJobEntity); if (internalJobManager == null) { preRepeatedTimerScheduleInternal(timerJobEntity, variableScope);
} else { internalJobManager.preRepeatedTimerSchedule(timerJobEntity, variableScope); } } protected abstract void preRepeatedTimerScheduleInternal(TimerJobEntity timerJobEntity, VariableScope variableScope); protected InternalJobManager findInternalJobManager(Job job) { if (internalJobManagerByScopeType == null || internalJobManagerByScopeType.isEmpty()) { return null; } String scopeType = job.getScopeType(); if (scopeType == null && job.getProcessInstanceId() != null) { scopeType = ScopeTypes.BPMN; } return internalJobManagerByScopeType.get(scopeType); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\ScopeAwareInternalJobManager.java
2
请完成以下Java代码
public String getServerInfo() { return "#" + getRunCount() + " - Last=" + m_summary.toString(); } // getServerInfo /** * metas: c.ghita@metas.ro * notify trough mail in case of abnormal termination */ private void notify( final boolean ok, final String subject, final String summary, final String logInfo, final int adTableId, final int recordId) { final Properties ctx = getCtx(); // notify supervisor if error final INotificationBL notificationBL = Services.get(INotificationBL.class); final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx); if (!ok) { if (sysConfigBL.getBooleanValue(SYSCONFIG_NOTIFY_ON_NOT_OK, false, adClientId, adOrgId)) { final UserId supervisorId = m_model.getSupervisor_ID() > 0 ? UserId.ofRepoId(m_model.getSupervisor_ID()) : null; if (supervisorId != null) { notificationBL.send(UserNotificationRequest.builder() .recipientUserId(supervisorId) .subjectADMessage(MSG_PROCESS_RUN_ERROR) .contentPlain(summary + " " + logInfo) .targetAction(TargetRecordAction.of(TableRecordReference.of(adTableId, recordId))) .build()); } } } else if (sysConfigBL.getBooleanValue(SYSCONFIG_NOTIFY_ON_OK, false, adClientId, adOrgId)) { for (final UserId userId : m_model.getRecipientAD_User_IDs()) { notificationBL.send(UserNotificationRequest.builder() .recipientUserId(userId) .subjectADMessage(MSG_PROCESS_OK) .contentPlain(summary + " " + logInfo) .targetAction(TargetRecordAction.of(TableRecordReference.of(adTableId, recordId))) .build()); }
} } /** * This implementation evaluated a cron pattern to do the scheduling. If the model's scheduling type is not "cron", * then the super classe's scheduling is used instead. */ @Override public void run() { if (!X_AD_Scheduler.SCHEDULETYPE_CronSchedulingPattern.equals(m_model.getScheduleType())) { super.run(); return; } final String cronPattern = m_model.getCronPattern(); if (Check.isNotBlank(cronPattern) && SchedulingPattern.validate(cronPattern)) { cronScheduler = new it.sauronsoftware.cron4j.Scheduler(); cronScheduler.schedule(cronPattern, () -> { runNow(); final long next = predictor.nextMatchingTime(); setDateNextRun(new Timestamp(next)); }); predictor = new Predictor(cronPattern); final long next = predictor.nextMatchingTime(); setDateNextRun(new Timestamp(next)); cronScheduler.start(); while (true) { if (!sleep()) { cronScheduler.stop(); break; } else if (!cronScheduler.isStarted()) { break; } } } else { super.run(); } } } // Scheduler
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\Scheduler.java
1
请完成以下Java代码
class SqlServerJdbcDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<JdbcConnectionDetails> { protected SqlServerJdbcDockerComposeConnectionDetailsFactory() { super("mssql/server"); } @Override protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new SqlServerJdbcDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link JdbcConnectionDetails} backed by a {@code mssql/server} * {@link RunningService}. */ static class SqlServerJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements JdbcConnectionDetails { private static final JdbcUrlBuilder jdbcUrlBuilder = new SqlServerJdbcUrlBuilder("sqlserver", 1433); private final SqlServerEnvironment environment; private final String jdbcUrl; SqlServerJdbcDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new SqlServerEnvironment(service.env()); this.jdbcUrl = disableEncryptionIfNecessary(jdbcUrlBuilder.build(service)); } private String disableEncryptionIfNecessary(String jdbcUrl) { if (jdbcUrl.contains(";encrypt=false;")) { return jdbcUrl; } StringBuilder jdbcUrlBuilder = new StringBuilder(jdbcUrl); if (!jdbcUrl.endsWith(";")) { jdbcUrlBuilder.append(";"); } jdbcUrlBuilder.append("encrypt=false;"); return jdbcUrlBuilder.toString(); } @Override public String getUsername() { return this.environment.getUsername();
} @Override public String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } private static final class SqlServerJdbcUrlBuilder extends JdbcUrlBuilder { private SqlServerJdbcUrlBuilder(String driverProtocol, int containerPort) { super(driverProtocol, containerPort); } @Override protected void appendParameters(StringBuilder url, String parameters) { url.append(";").append(parameters); } } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\SqlServerJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public class GrpcCodecDefinition { /** * The codec definition for gzip. */ public static final GrpcCodecDefinition GZIP_DEFINITION = new GrpcCodecDefinition(new Codec.Gzip(), true, CodecType.ALL); /** * The codec definition for identity (no-op). */ public static final GrpcCodecDefinition IDENTITY_DEFINITION = new GrpcCodecDefinition(Codec.Identity.NONE, false, CodecType.ALL); /** * The default encodings used by gRPC. */ public static final Collection<GrpcCodecDefinition> DEFAULT_DEFINITIONS = ImmutableList.<GrpcCodecDefinition>builder() .add(GZIP_DEFINITION) .add(IDENTITY_DEFINITION) .build();
private final Codec codec; private final boolean advertised; private final CodecType codecType; /** * Creates a new GrpcCodecDefinition. * * @param codec The codec bean. * @param advertised Whether the codec should be advertised in the headers. * @param codecType The type of the codec. */ public GrpcCodecDefinition(final Codec codec, final boolean advertised, final CodecType codecType) { this.codec = codec; this.advertised = advertised; this.codecType = codecType; } }
repos\grpc-spring-master\grpc-common-spring-boot\src\main\java\net\devh\boot\grpc\common\codec\GrpcCodecDefinition.java
1
请完成以下Java代码
public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Package getM_Package() throws RuntimeException { return (I_M_Package)MTable.get(getCtx(), I_M_Package.Table_Name) .getPO(getM_Package_ID(), get_TrxName()); } /** Set Package. @param M_Package_ID Shipment Package */ public void setM_Package_ID (int M_Package_ID) { if (M_Package_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Package_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID)); } /** Get Package. @return Shipment Package */ public int getM_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_Package_ID())); } /** Set Package Line. @param M_PackageLine_ID The detail content of the Package */ public void setM_PackageLine_ID (int M_PackageLine_ID) { if (M_PackageLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PackageLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PackageLine_ID, Integer.valueOf(M_PackageLine_ID)); } /** Get Package Line. @return The detail content of the Package
*/ public int getM_PackageLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackageLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quantity. @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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackageLine.java
1
请在Spring Boot框架中完成以下Java代码
static class RunTask implements Runnable { int time; boolean stop = false; String name; boolean slow = false; public RunTask(String name, int time, boolean slow) { super(); this.time = time; this.name = name; this.slow = slow; } @Override public void run() { long startTime = System.currentTimeMillis(); ContextUtil.enter(String.valueOf(startTime)); while (!stop) { long now = System.currentTimeMillis(); if (now - startTime > time * 1000) { stop = true; } Entry e1 = null; try { e1 = SphU.entry(name);
if (slow == true) { TimeUnit.MILLISECONDS.sleep(3000); } } catch (Exception e) { } finally { if (e1 != null) { e1.exit(); } } Random random2 = new Random(); try { TimeUnit.MILLISECONDS.sleep(random2.nextInt(200)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ContextUtil.exit(); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\DemoController.java
2
请完成以下Java代码
public boolean isProviderNeededForOLCand(@NonNull final I_C_OLCand olCand) { final ProductId productId = ProductId.ofRepoIdOrNull(olCand.getM_Product_ID()); if (productId == null) { return false; // nothing to do } if (!isNull(olCand, I_C_OLCand.COLUMNNAME_QtyItemCapacityInternal)) { return false; // already set; nothing to do } final UomId uomId = olCandEffectiveValuesBL.getEffectiveUomId(olCand); return uomDAO.isUOMForTUs(uomId); } @NonNull @Override public Optional<Quantity> computeQtyItemCapacity(@NonNull final I_C_OLCand olCand) {
final OLCandHUPackingAware huPackingAware = new OLCandHUPackingAware(olCand); final Capacity capacity = huPackingAwareBL.calculateCapacity(huPackingAware); if (capacity == null) { return Optional.empty(); } final ProductId productId = ProductId.ofRepoId(olCand.getM_Product_ID()); // note that the product's stocking UOM is never a TU-UOM if (capacity.isInfiniteCapacity()) { return Optional.of(Quantity.infinite(capacity.getC_UOM())); } return Optional.of(uomConversionBL.convertToProductUOM(capacity.toQuantity(), productId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\ordercandidate\spi\impl\OLCandWithUOMForTUsCapacityProvider.java
1
请完成以下Java代码
protected static class CacheRegisteredChannel implements RegisteredChannel { protected final CacheValue value; protected CacheRegisteredChannel(CacheValue value) { this.value = value; } @Override public int getChannelDefinitionVersion() { return value.version; } @Override public String getChannelDefinitionId() { return value.definitionId; } } protected class ChannelRegistrationImpl implements ChannelRegistration { protected final boolean registered; protected final CacheRegisteredChannel previousChannel; protected final CacheKey cacheKey; public ChannelRegistrationImpl(boolean registered, CacheRegisteredChannel previousChannel, CacheKey cacheKey) { this.registered = registered; this.previousChannel = previousChannel; this.cacheKey = cacheKey; } @Override public boolean registered() {
return registered; } @Override public RegisteredChannel previousChannel() { return previousChannel; } @Override public void rollback() { CacheValue cacheValue = previousChannel != null ? previousChannel.value : null; if (cacheValue == null) { cache.remove(cacheKey); } else { cache.put(cacheKey, cacheValue); } } } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\DefaultInboundChannelModelCacheManager.java
1
请完成以下Java代码
public static byte[] decrypt(byte[] encrypted, byte[] aesKey) { return Pkcs7Encoder.decode(aes(encrypted, aesKey, Cipher.DECRYPT_MODE)); } /** * ase加密 * * @param encrypted 内容 * @param aesKey 密钥 * @param mode 模式 * @return byte[] */ @SneakyThrows private static byte[] aes(byte[] encrypted, byte[] aesKey, int mode) { Assert.isTrue(aesKey.length == 32, "IllegalAesKey, aesKey's length must be 32"); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); cipher.init(mode, keySpec, iv); return cipher.doFinal(encrypted); } /** * 提供基于PKCS7算法的加解密接口. */ private static class Pkcs7Encoder { private static final int BLOCK_SIZE = 32; private static byte[] encode(byte[] src) { int count = src.length; // 计算需要填充的位数 int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
// 获得补位所用的字符 byte pad = (byte) (amountToPad & 0xFF); byte[] pads = new byte[amountToPad]; for (int index = 0; index < amountToPad; index++) { pads[index] = pad; } int length = count + amountToPad; byte[] dest = new byte[length]; System.arraycopy(src, 0, dest, 0, count); System.arraycopy(pads, 0, dest, count, amountToPad); return dest; } private static byte[] decode(byte[] decrypted) { int pad = decrypted[decrypted.length - 1]; if (pad < 1 || pad > BLOCK_SIZE) { pad = 0; } if (pad > 0) { return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); } return decrypted; } } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\utils\JwtCrypto.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCheckInvoiceCandidatesStatusResponseItem { @ApiModelProperty(position = 10, dataType = "java.lang.String") JsonExternalId externalHeaderId; @ApiModelProperty(position = 20, dataType = "java.lang.String") JsonExternalId externalLineId; @ApiModelProperty(position = 30, dataType = "java.lang.String") MetasfreshId metasfreshId; @ApiModelProperty(position = 40) @Nullable BigDecimal qtyEntered; @ApiModelProperty(position = 50) @Nullable BigDecimal qtyToInvoice; @ApiModelProperty(position = 60) @Nullable BigDecimal qtyInvoiced; @ApiModelProperty(position = 70) @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) LocalDate dateInvoiced; @ApiModelProperty(position = 80) @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) LocalDate dateToInvoice; @ApiModelProperty(position = 90) boolean processed; @ApiModelProperty(position = 100) @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY)
List<JsonInvoiceStatus> invoices; @ApiModelProperty(position = 110) @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) List<JsonWorkPackageStatus> workPackages; @Builder @JsonCreator public JsonCheckInvoiceCandidatesStatusResponseItem( @JsonProperty("externalHeaderId") final JsonExternalId externalHeaderId, @JsonProperty("externalLineId") final JsonExternalId externalLineId, @JsonProperty("metasfreshId") final MetasfreshId metasfreshId, @JsonProperty("qtyEntered") @Nullable final BigDecimal qtyEntered, @JsonProperty("qtyToInvoice") @Nullable final BigDecimal qtyToInvoice, @JsonProperty("qtyInvoiced") @Nullable final BigDecimal qtyInvoiced, @JsonProperty("dateInvoiced") @Nullable final LocalDate dateInvoiced, @JsonProperty("dateToInvoice") @Nullable final LocalDate dateToInvoice, @JsonProperty("processed") final boolean processed, @JsonProperty("invoices") @Nullable final List<JsonInvoiceStatus> invoices, @JsonProperty("workPackages") @Nullable final List<JsonWorkPackageStatus> workPackages) { this.externalHeaderId = externalHeaderId; this.externalLineId = externalLineId; this.metasfreshId = metasfreshId; this.qtyEntered = qtyEntered; this.qtyToInvoice = qtyToInvoice; this.qtyInvoiced = qtyInvoiced; this.dateInvoiced = dateInvoiced; this.dateToInvoice = dateToInvoice; this.processed = processed; this.invoices = invoices; this.workPackages = workPackages; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api\src\main\java\de\metas\rest_api\invoicecandidates\response\JsonCheckInvoiceCandidatesStatusResponseItem.java
2
请完成以下Java代码
private void setDocTypeInvoiceId(@NonNull final InvoiceHeaderImpl invoiceHeader) { final boolean invoiceIsSOTrx = invoiceHeader.isSOTrx(); final boolean isTakeDocTypeFromPool = invoiceHeader.isTakeDocTypeFromPool(); final DocTypeId docTypeIdToBeUsed; final Optional<DocTypeId> docTypeInvoiceId = invoiceHeader.getDocTypeInvoiceId(); if (docTypeInvoiceId.isPresent() && !isTakeDocTypeFromPool) { docTypeIdToBeUsed = docTypeInvoiceId.get(); } else if (invoiceHeader.getDocTypeInvoicingPoolId().isPresent()) { final DocTypeInvoicingPool docTypeInvoicingPool = docTypeInvoicingPoolService.getById(invoiceHeader.getDocTypeInvoicingPoolId().get()); final Money totalAmt = invoiceHeader.calculateTotalNetAmtFromLines(); docTypeIdToBeUsed = docTypeInvoicingPool.getDocTypeId(totalAmt); final I_C_DocType docTypeToBeUsedRecord = docTypeBL.getById(docTypeIdToBeUsed);
Check.assume(invoiceIsSOTrx == docTypeToBeUsedRecord.isSOTrx(), "InvoiceHeader's IsSOTrx={} shall match document type {}", invoiceIsSOTrx, docTypeToBeUsedRecord); } else { docTypeIdToBeUsed = null; } invoiceHeader.setDocTypeInvoiceId(docTypeIdToBeUsed); } private Optional<DocTypeInvoicingPool> getDocTypeInvoicingPool(@NonNull final DocTypeId docTypeId) { final I_C_DocType docTypeInvoice = docTypeBL.getByIdInTrx(docTypeId); return Optional.ofNullable(DocTypeInvoicingPoolId.ofRepoIdOrNull(docTypeInvoice.getC_DocType_Invoicing_Pool_ID())) .map(docTypeInvoicingPoolService::getById); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationEngine.java
1
请完成以下Java代码
public class X_R_IssueRecommendation extends PO implements I_R_IssueRecommendation, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_R_IssueRecommendation (Properties ctx, int R_IssueRecommendation_ID, String trxName) { super (ctx, R_IssueRecommendation_ID, trxName); /** if (R_IssueRecommendation_ID == 0) { setName (null); setR_IssueRecommendation_ID (0); } */ } /** Load Constructor */ public X_R_IssueRecommendation (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_R_IssueRecommendation[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help);
} /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Issue Recommendation. @param R_IssueRecommendation_ID Recommendations how to fix an Issue */ public void setR_IssueRecommendation_ID (int R_IssueRecommendation_ID) { if (R_IssueRecommendation_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, Integer.valueOf(R_IssueRecommendation_ID)); } /** Get Issue Recommendation. @return Recommendations how to fix an Issue */ public int getR_IssueRecommendation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueRecommendation_ID); 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_R_IssueRecommendation.java
1
请在Spring Boot框架中完成以下Java代码
public String getDISCREPANCYREASON() { return discrepancyreason; } /** * Sets the value of the discrepancyreason property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYREASON(String value) { this.discrepancyreason = value; } /** * Gets the value of the discrepancydesc property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYDESC() { return discrepancydesc; } /** * Sets the value of the discrepancydesc property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYDESC(String value) { this.discrepancydesc = value; } /** * Gets the value of the discrepancydate1 property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYDATE1() { return discrepancydate1; } /** * Sets the value of the discrepancydate1 property. * * @param value * allowed object is * {@link String }
* */ public void setDISCREPANCYDATE1(String value) { this.discrepancydate1 = value; } /** * Gets the value of the discrepancydate2 property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYDATE2() { return discrepancydate2; } /** * Sets the value of the discrepancydate2 property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYDATE2(String value) { this.discrepancydate2 = 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\DQVAR1.java
2
请完成以下Java代码
public Builder tenantId(TenantId tenantId) { this.tenantId = tenantId; return this; } public Builder entityId(EntityId entityId) { this.entityId = entityId; return this; } public Builder scope(AttributeScope scope) { this.scope = scope; return this; } @Deprecated public Builder scope(String scope) { try { this.scope = AttributeScope.valueOf(scope); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid attribute scope '" + scope + "'"); } return this; } public Builder keys(List<String> keys) { this.keys = keys; return this; } public Builder notifyDevice(boolean notifyDevice) { this.notifyDevice = notifyDevice; return this; } public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = previousCalculatedFieldIds; return this; } public Builder tbMsgId(UUID tbMsgId) { this.tbMsgId = tbMsgId; return this; } public Builder tbMsgType(TbMsgType tbMsgType) { this.tbMsgType = tbMsgType; return this; } public Builder callback(FutureCallback<Void> callback) { this.callback = callback;
return this; } public Builder future(SettableFuture<Void> future) { return callback(new FutureCallback<>() { @Override public void onSuccess(Void result) { future.set(result); } @Override public void onFailure(Throwable t) { future.setException(t); } }); } public AttributesDeleteRequest build() { return new AttributesDeleteRequest( tenantId, entityId, scope, keys, notifyDevice, previousCalculatedFieldIds, tbMsgId, tbMsgType, requireNonNullElse(callback, NoOpFutureCallback.instance()) ); } } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\AttributesDeleteRequest.java
1
请完成以下Java代码
public void setC_Queue_Processor_Assign_ID (int C_Queue_Processor_Assign_ID) { if (C_Queue_Processor_Assign_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_Assign_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_Assign_ID, Integer.valueOf(C_Queue_Processor_Assign_ID)); } /** Get Assigned Workpackage Processors. @return Assigned Workpackage Processors */ @Override public int getC_Queue_Processor_Assign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_Assign_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_Processor getC_Queue_Processor() { return get_ValueAsPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class); } @Override public void setC_Queue_Processor(de.metas.async.model.I_C_Queue_Processor C_Queue_Processor) { set_ValueFromPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class, C_Queue_Processor); } /** Set Queue Processor Definition.
@param C_Queue_Processor_ID Queue Processor Definition */ @Override public void setC_Queue_Processor_ID (int C_Queue_Processor_ID) { if (C_Queue_Processor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, Integer.valueOf(C_Queue_Processor_ID)); } /** Get Queue Processor Definition. @return Queue Processor Definition */ @Override public int getC_Queue_Processor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor_Assign.java
1
请完成以下Java代码
public static DocumentValidStatus invalid(@NonNull final Exception error) { return new DocumentValidStatus(false, AdempiereException.extractMessageTrl(error), error, null, null, AdempiereException.extractErrorCodeOrNull(error)); } private static final DocumentValidStatus STATE_InitialInvalid = new DocumentValidStatus(false, TranslatableStrings.anyLanguage("not validated yet"), null, null, Boolean.TRUE, null); private static final DocumentValidStatus STATE_Valid = new DocumentValidStatus(true, null, null, null, null, null); @Getter private final boolean valid; @Nullable @Getter private final Boolean initialValue; @Nullable @Getter private final ITranslatableString reason; @Nullable @Getter private final Exception exception; @Nullable @Getter private final String fieldName; private transient Integer _hashcode; // lazy private transient String _toString; // lazy @Getter private final String errorCode; private DocumentValidStatus( final boolean valid, @Nullable final ITranslatableString reason, @Nullable final Exception exception, @Nullable final String fieldName, @Nullable final Boolean isInitialValue, @Nullable final String errorCode) { this.valid = valid; this.initialValue = isInitialValue; this.reason = reason; this.exception = exception; this.fieldName = fieldName; this.errorCode = errorCode; } @Override public String toString() { String toString = this._toString; if (toString == null) { final StringBuilder sb = new StringBuilder(); sb.append(valid ? "Valid" : "Invalid"); if (initialValue != null && initialValue) { sb.append("-Initial"); } if (!TranslatableStrings.isBlank(reason)) { sb.append("('").append(reason).append("')"); } toString = this._toString = sb.toString(); } return toString; } @Override public int hashCode() { Integer hashcode = this._hashcode; if (hashcode == null) { hashcode = this._hashcode = Objects.hash(valid, initialValue, reason, fieldName); } return hashcode; }
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof DocumentValidStatus)) { return false; } final DocumentValidStatus other = (DocumentValidStatus)obj; return valid == other.valid && Objects.equals(initialValue, other.initialValue) && Objects.equals(reason, other.reason) && Objects.equals(fieldName, other.fieldName) && Objects.equals(errorCode, other.errorCode); } public boolean isInitialInvalid() { return this == STATE_InitialInvalid; } public void throwIfInvalid() { if (isValid()) { return; } if (exception != null) { throw AdempiereException.wrapIfNeeded(exception); } else { throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Invalid")); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentValidStatus.java
1
请完成以下Java代码
public class State { private List<Stack<String>> state; private int heuristics; public State(List<Stack<String>> state) { this.state = state; } State(List<Stack<String>> state, int heuristics) { this.state = state; this.heuristics = heuristics; } State(State state) { if (state != null) { this.state = new ArrayList<>(); for (Stack s : state.getState()) { Stack s1;
s1 = (Stack) s.clone(); this.state.add(s1); } this.heuristics = state.getHeuristics(); } } public List<Stack<String>> getState() { return state; } public int getHeuristics() { return heuristics; } public void setHeuristics(int heuristics) { this.heuristics = heuristics; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\hillclimbing\State.java
1
请完成以下Java代码
public class Param extends BaseEntity { @Serial private static final long serialVersionUID = 1L; /** * 主键id */ @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 参数名 */ @Schema(description = "参数名") private String paramName; /** * 参数键 */ @Schema(description = "参数键") private String paramKey;
/** * 参数值 */ @Schema(description = "参数值") private String paramValue; /** * 备注 */ @Schema(description = "备注") private String remark; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Param.java
1
请完成以下Java代码
public static void writeIncomingAndOutgoingFlowElement(FlowNode flowNode, XMLStreamWriter xtw) throws Exception { if (!flowNode.getIncomingFlows().isEmpty()) { for (SequenceFlow incomingSequence : flowNode.getIncomingFlows()) { writeIncomingElementChild(xtw, incomingSequence); } } if (!flowNode.getOutgoingFlows().isEmpty()) { for (SequenceFlow outgoingSequence : flowNode.getOutgoingFlows()) { writeOutgoingElementChild(xtw, outgoingSequence); } } } public static void writeIncomingElementChild(XMLStreamWriter xtw, SequenceFlow incomingSequence) throws Exception { xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_GATEWAY_INCOMING, BPMN2_NAMESPACE); xtw.writeCharacters(incomingSequence.getId()); xtw.writeEndElement(); } public static void writeOutgoingElementChild(XMLStreamWriter xtw, SequenceFlow outgoingSequence) throws Exception { xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_GATEWAY_OUTGOING, BPMN2_NAMESPACE); xtw.writeCharacters(outgoingSequence.getId()); xtw.writeEndElement(); } /**
* 'safe' is here reflecting: * http://activiti.org/userguide/index.html#advanced.safe.bpmn.xml */ public static XMLInputFactory createSafeXmlInputFactory() { XMLInputFactory xif = XMLInputFactory.newInstance(); if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) { xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); } if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) { xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) { xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); } return xif; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\util\BpmnXMLUtil.java
1
请完成以下Java代码
public void put(Object name, Object value) { Assert.notNull(name, "'name' must not be null"); this.source.put(name.toString(), value); } @Override public Object getUnderlyingSource() { return this.source; } @Override public @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { return this.delegate.getConfigurationProperty(name); } @Override public Iterator<ConfigurationPropertyName> iterator() {
return this.delegate.iterator(); } @Override public Stream<ConfigurationPropertyName> stream() { return this.delegate.stream(); } private void assertNotReadOnlySystemAttributesMap(Map<?, ?> map) { try { map.size(); } catch (UnsupportedOperationException ex) { throw new IllegalArgumentException("Security restricted maps are not supported", ex); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\MapConfigurationPropertySource.java
1
请在Spring Boot框架中完成以下Java代码
public LookupValuesList getProducts() { final ImmutableSet<ProductId> sparePartIds = getSparePartsCalculation().getAllowedSparePartIds(); return lookupDataSourceFactory.searchInTableLookup(I_M_Product.Table_Name).findByIdsOrdered(sparePartIds); } @Override public void onParameterChanged(@NonNull final String parameterName) { if (PARAM_M_Product_ID.equals(parameterName)) { final ProductId sparePartId = this.sparePartId; if (sparePartId != null) { final Quantity qty = getSparePartsCalculation().computeQtyOfSparePartsRequiredNet(sparePartId, uomConversionBL).orElse(null); this.qtyBD = qty != null ? qty.toBigDecimal() : null; this.uomId = qty != null ? qty.getUomId() : null; } } } @Override protected String doIt() { final InOutId customerReturnId = getCustomerReturnId(); final Quantity qtyReturned = getQtyReturned(); repairCustomerReturnsService.prepareAddSparePartsToCustomerReturn() .customerReturnId(customerReturnId) .productId(sparePartId) .qtyReturned(qtyReturned) .build(); return MSG_OK; } private Quantity getQtyReturned() { if (qtyBD == null) {
throw new FillMandatoryException("Qty"); } if (uomId == null) { throw new FillMandatoryException("C_UOM_ID"); } final I_C_UOM uom = uomDAO.getById(uomId); return Quantity.of(qtyBD, uom); } private SparePartsReturnCalculation getSparePartsCalculation() { SparePartsReturnCalculation sparePartsCalculation = _sparePartsCalculation; if (sparePartsCalculation == null) { sparePartsCalculation = _sparePartsCalculation = repairCustomerReturnsService.getSparePartsCalculation(getCustomerReturnId()); } return sparePartsCalculation; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\CustomerReturns_AddSpareParts.java
2
请完成以下Java代码
private boolean canStopEditing() { // nothing atm return true; } @Override public boolean stopCellEditing() { if (!canStopEditing()) { return false; } if (!super.stopCellEditing()) { return false; } clearCurrentEditing(); return true; } @Override public void cancelCellEditing() { if (!canStopEditing()) { return ;
} clearCurrentEditing(); super.cancelCellEditing(); } private void clearCurrentEditing() { // metas: reset editing coordinates editingRowIndexModel = -1; editingColumnIndexModel = -1; editingKeyId = -100; if (m_editor instanceof VLookup) { ((VLookup)m_editor).setStopEditing(true); } } public void setActionListener(final ActionListener listener) { actionListener = listener; } } // VCellEditor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCellEditor.java
1
请完成以下Java代码
public I_C_ElementValue getC_ElementValue() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getC_ElementValue_ID(), get_TrxName()); } /** Set Account Element. @param C_ElementValue_ID Account Element */ public void setC_ElementValue_ID (int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ElementValue_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ElementValue_ID, Integer.valueOf(C_ElementValue_ID)); } /** Get Account Element. @return Account Element */ public int getC_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sub Account. @param C_SubAcct_ID Sub account for Element Value */ public void setC_SubAcct_ID (int C_SubAcct_ID) { if (C_SubAcct_ID < 1) set_ValueNoCheck (COLUMNNAME_C_SubAcct_ID, null); else set_ValueNoCheck (COLUMNNAME_C_SubAcct_ID, Integer.valueOf(C_SubAcct_ID)); } /** Get Sub Account. @return Sub account for Element Value */ public int getC_SubAcct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_SubAcct_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 Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help.
@return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SubAcct.java
1
请完成以下Java代码
public class GroovyStaticScriptEngineFactory extends GroovyScriptEngineFactory { /** * Returns the full name of the <code>ScriptEngine</code>. * * @return The name of the engine implementation. */ @Override public String getEngineName() { return "groovy-static"; } @Override public List<String> getNames() { return Collections.singletonList("groovy-static"); } /** * Returns the version of the <code>ScriptEngine</code>.
* * @return The <code>ScriptEngine</code> implementation version. */ @Override public String getEngineVersion() { return "1.0"; } /** * Returns an instance of the <code>ScriptEngine</code> associated with this * <code>ScriptEngineFactory</code>. A new ScriptEngine is generally * returned, but implementations may pool, share or reuse engines. * * @return A new <code>ScriptEngine</code> instance. */ @Override public ScriptEngine getScriptEngine() { return new GroovyStaticScriptEngine(this); } }
repos\flowable-engine-main\modules\flowable-groovy-script-static-engine\src\main\java\org\flowable\engine\impl\scripting\GroovyStaticScriptEngineFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public BigDecimal getOrderPrice() { return orderPrice; } public void setOrderPrice(BigDecimal orderPrice) { this.orderPrice = orderPrice; } public String getOrderIp() { return orderIp; } public void setOrderIp(String orderIp) { this.orderIp = orderIp; } public String getOrderDate() { return orderDate; } public void setOrderDate(String orderDate) { this.orderDate = orderDate; } public String getOrderTime() { return orderTime; } public void setOrderTime(String orderTime) { this.orderTime = orderTime; } public Integer getOrderPeriod() { return orderPeriod; } public void setOrderPeriod(Integer orderPeriod) { this.orderPeriod = orderPeriod; } public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getRemark() {
return remark; } public void setRemark(String remark) { this.remark = remark; } public String getPayType() { return payType; } public void setPayType(String payType) { this.payType = payType; } public Integer getNumberOfStages() { return numberOfStages; } public void setNumberOfStages(Integer numberOfStages) { this.numberOfStages = numberOfStages; } @Override public String toString() { return "ScanPayRequestBo{" + "payKey='" + payKey + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", orderPeriod=" + orderPeriod + ", returnUrl='" + returnUrl + '\'' + ", notifyUrl='" + notifyUrl + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + ", numberOfStages=" + numberOfStages + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ScanPayRequestBo.java
2
请完成以下Java代码
public boolean isThreadLocalContextAware() { return this.threadLocalContextAware; } @SuppressWarnings({"unused", "try"}) @Override public final Mono<List<GraphQLError>> resolveException(Throwable exception) { if (this.threadLocalContextAware) { return Mono.deferContextual((contextView) -> { ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(contextView); try { List<GraphQLError> errors = snapshot.wrap(() -> resolveToMultipleErrors(exception)).call(); return Mono.justOrEmpty(errors); } catch (Exception ex2) { this.logger.warn("Failed to resolve " + exception, ex2); return Mono.empty(); } }); } else { return Mono.justOrEmpty(resolveToMultipleErrors(exception)); }
} /** * Override this method to resolve the Exception to multiple GraphQL errors. * @param exception the exception to resolve * @return the resolved errors or {@code null} if unresolved */ protected @Nullable List<GraphQLError> resolveToMultipleErrors(Throwable exception) { GraphQLError error = resolveToSingleError(exception); return (error != null) ? Collections.singletonList(error) : null; } /** * Override this method to resolve the Exception to a single GraphQL error. * @param exception the exception to resolve * @return the resolved error or {@code null} if unresolved */ protected @Nullable GraphQLError resolveToSingleError(Throwable exception) { return null; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SubscriptionExceptionResolverAdapter.java
1
请完成以下Java代码
public void processPhoto(Long photoId) { System.out.println("processing photo#" + photoId); } public void launchPhotoProcess(String... photoLabels) { List<Photo> photos = new ArrayList<>(); for (String l : photoLabels) { Photo x = this.photoRepository.save(new Photo(l)); photos.add(x); } Map<String, Object> procVars = new HashMap<>(); procVars.put("photos", photos); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dogeProcess", procVars); List<Execution> waitingExecutions = runtimeService.createExecutionQuery().activityId("wait").list(); System.out.println("--> # executions = " + waitingExecutions.size()); for (Execution execution : waitingExecutions) { runtimeService.trigger(execution.getId()); } Task reviewTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(reviewTask.getId(), Collections.singletonMap("approved", (Object) true)); long count = runtimeService.createProcessInstanceQuery().count(); System.out.println("Proc count " + count); } }
interface PhotoRepository extends JpaRepository<Photo, Long> { } @Entity class Photo { @Id @GeneratedValue private Long id; Photo() { } Photo(String username) { this.username = username; } private String username; public Long getId() { return id; } public String getUsername() { return username; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-jpa\src\main\java\flowable\Application.java
1
请完成以下Java代码
static private class KeySetIterable<KEY, VALUE> implements Iterable<Iterable<KEY>> { final private Iterator<Map<KEY, VALUE>> maps; public KeySetIterable(Iterable<Map<KEY, VALUE>> maps) { this.maps = maps.iterator(); } @Override public Iterator<Iterable<KEY>> iterator() { return new Iterator<Iterable<KEY>>() { @Override public boolean hasNext() { return maps.hasNext(); }
@Override public Iterable<KEY> next() { return maps.next().keySet(); } @Override public void remove() { } }; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TfIdf.java
1
请在Spring Boot框架中完成以下Java代码
public class X_S_FailedTimeBooking extends org.compiere.model.PO implements I_S_FailedTimeBooking, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1002982304L; /** Standard Constructor */ public X_S_FailedTimeBooking (final Properties ctx, final int S_FailedTimeBooking_ID, @Nullable final String trxName) { super (ctx, S_FailedTimeBooking_ID, trxName); } /** Load Constructor */ public X_S_FailedTimeBooking (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setImportErrorMsg (final @Nullable java.lang.String ImportErrorMsg) { set_Value (COLUMNNAME_ImportErrorMsg, ImportErrorMsg); } @Override public java.lang.String getImportErrorMsg() { return get_ValueAsString(COLUMNNAME_ImportErrorMsg);
} @Override public void setJSONValue (final @Nullable java.lang.String JSONValue) { set_Value (COLUMNNAME_JSONValue, JSONValue); } @Override public java.lang.String getJSONValue() { return get_ValueAsString(COLUMNNAME_JSONValue); } @Override public void setS_FailedTimeBooking_ID (final int S_FailedTimeBooking_ID) { if (S_FailedTimeBooking_ID < 1) set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, null); else set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, S_FailedTimeBooking_ID); } @Override public int getS_FailedTimeBooking_ID() { return get_ValueAsInt(COLUMNNAME_S_FailedTimeBooking_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_FailedTimeBooking.java
2
请完成以下Java代码
private DocumentQueryOrderByList getOrderBys() { return DocumentQueryOrderByList.ofList(orderBys); } public HUEditorViewBuilder setParameter(final String name, @Nullable final Object value) { if (value == null) { if (parameters != null) { parameters.remove(name); } } else { if (parameters == null) { parameters = new LinkedHashMap<>(); } parameters.put(name, value); } return this; } public HUEditorViewBuilder setParameters(final Map<String, Object> parameters) { parameters.forEach(this::setParameter); return this; } ImmutableMap<String, Object> getParameters() { return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of(); } @Nullable public <T> T getParameter(@NonNull final String name) { if (parameters == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)parameters.get(name); return value; } public void assertParameterSet(final String name) { final Object value = getParameter(name); if (value == null) { throw new AdempiereException("Parameter " + name + " is expected to be set in " + parameters + " for " + this); }
} public HUEditorViewBuilder setHUEditorViewRepository(final HUEditorViewRepository huEditorViewRepository) { this.huEditorViewRepository = huEditorViewRepository; return this; } HUEditorViewBuffer createRowsBuffer(@NonNull final SqlDocumentFilterConverterContext context) { final ViewId viewId = getViewId(); final DocumentFilterList stickyFilters = getStickyFilters(); final DocumentFilterList filters = getFilters(); if (HUEditorViewBuffer_HighVolume.isHighVolume(stickyFilters)) { return new HUEditorViewBuffer_HighVolume(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context); } else { return new HUEditorViewBuffer_FullyCached(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context); } } public HUEditorViewBuilder setUseAutoFilters(final boolean useAutoFilters) { this.useAutoFilters = useAutoFilters; return this; } public boolean isUseAutoFilters() { return useAutoFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuilder.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getExecutionId() { return executionId; } public Long getLongValue() { return longValue; } public void setLongValue(Long longValue) { this.longValue = longValue; } public Double getDoubleValue() { return doubleValue; } public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } public String getTextValue() { return textValue; } public void setTextValue(String textValue) { this.textValue = textValue; } public String getTextValue2() { return textValue2; } public void setTextValue2(String textValue2) { this.textValue2 = textValue2; }
public Object getCachedValue() { return cachedValue; } public void setCachedValue(Object cachedValue) { this.cachedValue = cachedValue; } // misc methods /////////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("VariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(type != null ? type.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableInstanceEntityImpl.java
1
请完成以下Java代码
public boolean isMandatory() { return false; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } /** * @return our attribute instance's {@code M_Attribute_ID}. */ @Override public int getDisplaySeqNo() { return attributeInstance.getM_Attribute_ID(); } /**
* @return {@code true} */ @Override public boolean isUseInASI() { return true; } /** * @return {@code false}, since no HU-PI attribute is involved. */ @Override public boolean isDefinedByTemplate() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java
1
请完成以下Spring Boot application配置
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/demo?createDatabaseIfNotExist=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false spring.datasource.username = root spring.datasource.password = root spring.datasource.driver-class-na
me = com.mysql.cj.jdbc.Driver spring.liquibase.change-log = classpath:liquibase/master.xml spring.liquibase.contexts = dev
repos\springboot-demo-master\Liquibase\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class StockDataAggregateItem { int productCategoryId; int productId; String productValue; int warehouseId; BigDecimal qtyOnHand; @Builder private StockDataAggregateItem( final int productCategoryId, final int productId, final String productValue, final int warehouseId,
@NonNull final BigDecimal qtyOnHand, @Singular final Map<AttributesKey, BigDecimal> qtyOnHandDetails) { Check.assumeGreaterThanZero(productCategoryId, "productCategoryId"); Check.assumeGreaterThanZero(productId, "productId"); Check.assumeNotEmpty(productValue, "productValue is not empty"); // Check.assumeGreaterThanZero(warehouseId, "warehouseId"); this.productCategoryId = productCategoryId; this.productId = productId; this.productValue = productValue; this.warehouseId = warehouseId > 0 ? warehouseId : -1; this.qtyOnHand = qtyOnHand; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\StockDataAggregateItem.java
2
请完成以下Java代码
private static DocumentEntityDescriptor findNewRecordEntityDescriptor( @NonNull final DocumentLayoutElementFieldDescriptor fieldDescriptor, final JSONDocumentLayoutOptions jsonOpts) { if (fieldDescriptor.isForbidNewRecordCreation()) { return null; } final String lookupTableName = fieldDescriptor.getLookupTableName().orElse(null); if (lookupTableName == null) { return null; } final NewRecordDescriptorsProvider newRecordDescriptorsProvider = jsonOpts.getNewRecordDescriptorsProvider(); if (newRecordDescriptorsProvider == null) { return null; } return newRecordDescriptorsProvider.getNewRecordEntityDescriptorIfAvailable(lookupTableName); } void setAdvSearchWindow( final @NonNull WindowId windowId, final @Nullable DetailId tabId, final @NonNull JSONDocumentLayoutOptions jsonOpts) { if (lookupTableName == null) {
return; } // avoid enabling advanced search assistant for included tabs, // because atm frontend does not support it. if (tabId != null) { return; } final AdvancedSearchDescriptorsProvider provider = jsonOpts.getAdvancedSearchDescriptorsProvider(); if (provider == null) { return; } final DocumentEntityDescriptor advancedSearchEntityDescriptor = provider.getAdvancedSearchDescriptorIfAvailable(lookupTableName); if (advancedSearchEntityDescriptor != null) { advSearchWindowId = advancedSearchEntityDescriptor.getDocumentTypeId().toJson(); advSearchCaption = advancedSearchEntityDescriptor.getCaption().translate(jsonOpts.getAdLanguage()); } else { advSearchWindowId = null; advSearchCaption = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutElementField.java
1
请完成以下Java代码
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceId(String caseInstanceId) { return dataManager.findSentryPartInstancesByCaseInstanceId(caseInstanceId); } @Override public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(String caseInstanceId) { return dataManager.findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(caseInstanceId); } @Override public List<SentryPartInstanceEntity> findSentryPartInstancesByPlanItemInstanceId(String planItemId) { return dataManager.findSentryPartInstancesByPlanItemInstanceId(planItemId); } @Override
public void updateSentryPartInstancesCaseDefinitionId(String caseInstanceId, String caseDefinitionId) { List<SentryPartInstanceEntity> sentryPartInstances = findSentryPartInstancesByCaseInstanceId(caseInstanceId); if (sentryPartInstances != null && !sentryPartInstances.isEmpty()) { for (SentryPartInstanceEntity sentryPartInstanceEntity : sentryPartInstances) { sentryPartInstanceEntity.setCaseDefinitionId(caseDefinitionId); update(sentryPartInstanceEntity); } } } @Override public void deleteByCaseInstanceId(String caseInstanceId) { dataManager.deleteByCaseInstanceId(caseInstanceId); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\SentryPartInstanceEntityManagerImpl.java
1
请完成以下Java代码
public acronym removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } /** * The onclick event occurs when the pointing device button is clicked over * an element. This attribute may be used with most elements. * * @param script script */ public void setOnClick (String script) { addAttribute ("onclick", script); } /** * The ondblclick event occurs when the pointing device button is double * clicked over an element. This attribute may be used with most elements. * * @param script script */ public void setOnDblClick (String script) { addAttribute ("ondblclick", script); } /** * The onmousedown event occurs when the pointing device button is pressed * over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseDown (String script) { addAttribute ("onmousedown", script); } /** * The onmouseup event occurs when the pointing device button is released * over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseUp (String script) { addAttribute ("onmouseup", script); } /** * The onmouseover event occurs when the pointing device is moved onto an * element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOver (String script) { addAttribute ("onmouseover", script); } /** * The onmousemove event occurs when the pointing device is moved while it * is over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseMove (String script) { addAttribute ("onmousemove", script); } /**
* The onmouseout event occurs when the pointing device is moved away from * an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOut (String script) { addAttribute ("onmouseout", script); } /** * The onkeypress event occurs when a key is pressed and released over an * element. This attribute may be used with most elements. * * @param script script */ public void setOnKeyPress (String script) { addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements. * * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\acronym.java
1
请在Spring Boot框架中完成以下Java代码
public class Swagger2DemoRestController { // List<Student> students = new ArrayList<Student>(); { students.add(new Student("Hamdamboy", "V", "Uzbekistan")); students.add(new Student("Babam", "VI", "Uzbekistan")); students.add(new Student("Anajonim", "v", "Uzbekistan")); students.add(new Student("Azamat", "V", "Uzbekistan")); } @RequestMapping(value = "/getStudents") public List<Student> getStudents(){ return students; } @RequestMapping(value = "/getStudent/{name}") public Student getStudent(@PathVariable(value = "name") String name) { return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); }
@RequestMapping(value = "/getStudentByCountry/{country}") public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) { System.out.println("Searching Student in country : " + country); List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)) .collect(Collectors.toList()); System.out.println(studentsByCountry); return studentsByCountry; } @RequestMapping(value = "/getStudentByClass/{cls}") public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) { return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList()); } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringSwagger2Project\src\main\java\spring\swagger2\Swagger2DemoRestController.java
2
请完成以下Java代码
public ReferredDocumentType1Choice getCdOrPrtry() { return cdOrPrtry; } /** * Sets the value of the cdOrPrtry property. * * @param value * allowed object is * {@link ReferredDocumentType1Choice } * */ public void setCdOrPrtry(ReferredDocumentType1Choice value) { this.cdOrPrtry = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String } * */
public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = 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\ReferredDocumentType2.java
1
请完成以下Java代码
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getSourceCaseDefinitionId() { return sourceProcessDefinitionId; } public void setSourceCaseDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetCaseDefinitionId() { return targetProcessDefinitionId; } public void setTargetCaseDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public List<CaseInstanceBatchMigrationPartResult> getAllMigrationParts() { return allMigrationParts; } public void addMigrationPart(CaseInstanceBatchMigrationPartResult migrationPart) { if (allMigrationParts == null) { allMigrationParts = new ArrayList<>(); } allMigrationParts.add(migrationPart); if (!STATUS_COMPLETED.equals(migrationPart.getStatus())) { if (waitingMigrationParts == null) { waitingMigrationParts = new ArrayList<>(); } waitingMigrationParts.add(migrationPart); } else { if (RESULT_SUCCESS.equals(migrationPart.getResult())) { if (succesfulMigrationParts == null) {
succesfulMigrationParts = new ArrayList<>(); } succesfulMigrationParts.add(migrationPart); } else { if (failedMigrationParts == null) { failedMigrationParts = new ArrayList<>(); } failedMigrationParts.add(migrationPart); } } } public List<CaseInstanceBatchMigrationPartResult> getSuccessfulMigrationParts() { return succesfulMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getFailedMigrationParts() { return failedMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getWaitingMigrationParts() { return waitingMigrationParts; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationResult.java
1
请完成以下Java代码
public Properties getAddonProperties() { return props; } private static void startAddon(final String className) { try { final Class<?> clazz = Class.forName(className); final Class<? extends IAddOn> clazzVC = clazz .asSubclass(IAddOn.class); final IAddOn instance = clazzVC.newInstance(); instance.beforeConnection(); } catch (ClassNotFoundException e) { MetasfreshLastError.saveError(logger, "Addon not available: " + className, e); }
catch (ClassCastException e) { MetasfreshLastError.saveError(logger, "Addon class " + className + " doesn't implement " + IAddOn.class.getName(), e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\addon\impl\AddonStarter.java
1
请在Spring Boot框架中完成以下Java代码
public Candidate toCandidateWithQtyDelta() { return candidate.withQuantity(getQtyDelta()); } /** * Convenience method that returns a new instance whose included {@link Candidate} has the given id. */ public CandidateSaveResult withCandidateId(@Nullable final CandidateId candidateId) { return toBuilder() .candidate(candidate.withId(candidateId)) .build(); } /**
* Convenience method that returns a new instance with negated candidate quantity and previousQty */ public CandidateSaveResult withNegatedQuantity() { return toBuilder() .candidate(candidate.withNegatedQuantity()) .previousQty(previousQty == null ? null : previousQty.negate()) .build(); } public CandidateSaveResult withParentId(@Nullable final CandidateId parentId) { return toBuilder() .candidate(candidate.withParentId(parentId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateSaveResult.java
2
请完成以下Java代码
public String getTextValue() { if (variableInstanceEntity != null) { return variableInstanceEntity.getTextValue(); } return null; } public Long getLongValue() { if (variableInstanceEntity != null) { return variableInstanceEntity.getLongValue(); } return null; } public Double getDoubleValue() { if (variableInstanceEntity != null) { return variableInstanceEntity.getDoubleValue(); } return null; } public String getTextValue2() {
if (variableInstanceEntity != null) { return variableInstanceEntity.getTextValue2(); } return null; } public String getType() { if (variableInstanceEntity != null) { return variableInstanceEntity.getType().getTypeName(); } return null; } public boolean isLocal() { return local; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\QueryVariableValue.java
1