instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String toString() { return "ConnectionCustomizerService [permanentCustomizers=" + permanentCustomizers + ", (thread-local-)temporaryCustomizers=" + temporaryCustomizers.get() + ", (thread-local-)currentlyInvokedCustomizers=" + currentlyInvokedCustomizers + "]"; } private List<IConnectionCustomizer> getRegisteredCustomizers() { return new ImmutableList.Builder<IConnectionCustomizer>() .addAll(permanentCustomizers) .addAll(temporaryCustomizers.get()) .build(); } /** * Invoke {@link IConnectionCustomizer#customizeConnection(Connection)} with the given parameters, unless the customizer was already invoked within this thread and that invocation did not yet finish. * So the goal is to avoid recursive invocations on the same customizer. Also see {@link IConnectionCustomizerService#fireRegisteredCustomizers(Connection)}. * * @param customizer * @param connection */ private void invokeIfNotYetInvoked(@NonNull final IConnectionCustomizer customizer, @NonNull final Connection connection)
{ try { if (currentlyInvokedCustomizers.get().add(customizer)) { customizer.customizeConnection(connection); currentlyInvokedCustomizers.get().remove(customizer); } } finally { currentlyInvokedCustomizers.get().remove(customizer); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\ConnectionCustomizerService.java
1
请完成以下Java代码
public CaseInstanceBuilder referenceType(String referenceType) { this.referenceType = referenceType; return this; } @Override public CaseInstanceBuilder parentId(String parentCaseInstanceId) { this.parentId = parentCaseInstanceId; return this; } @Override public CaseInstanceBuilder fallbackToDefaultTenant() { this.fallbackToDefaultTenant = true; return this; } @Override public CaseInstance start() { return cmmnRuntimeService.startCaseInstance(this); } @Override public CaseInstance startAsync() { return cmmnRuntimeService.startCaseInstanceAsync(this); } @Override public CaseInstance startWithForm() { this.startWithForm = true; return cmmnRuntimeService.startCaseInstance(this); } @Override public String getCaseDefinitionId() { return caseDefinitionId; } @Override public String getCaseDefinitionKey() { return caseDefinitionKey; } @Override public String getCaseDefinitionParentDeploymentId() { return caseDefinitionParentDeploymentId; } @Override public String getPredefinedCaseInstanceId() { return predefinedCaseInstanceId; } @Override public String getName() { return name; } @Override public String getBusinessKey() { return businessKey; } @Override public String getBusinessStatus() { return businessStatus; } @Override public Map<String, Object> getVariables() { return variables; } @Override public Map<String, Object> getTransientVariables() { return transientVariables; } @Override public String getTenantId() { return tenantId; } @Override public String getOwner() { return ownerId; } @Override public String getAssignee() { return assigneeId; }
@Override public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } @Override public String getOutcome() { return outcome; } @Override public Map<String, Object> getStartFormVariables() { return startFormVariables; } @Override public String getCallbackId() { return this.callbackId; } @Override public String getCallbackType() { return this.callbackType; } @Override public String getReferenceId() { return referenceId; } @Override public String getReferenceType() { return referenceType; } @Override public String getParentId() { return this.parentId; } @Override public boolean isFallbackToDefaultTenant() { return this.fallbackToDefaultTenant; } @Override public boolean isStartWithForm() { return this.startWithForm; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotEmpty(message = "First name is required.") private String firstName; @NotEmpty(message = "Last name is required.") private String lastName; @Email(message = "Please provide a valid email address.") @NotEmpty(message = "Email is required.") @Column(unique = true, nullable = false) private String email; @NotEmpty(message = "Password is required.") private String password; public User() { } public User(User user) { this.id = user.id; this.firstName = user.firstName; this.lastName = user.lastName; this.email = user.email; this.password = user.password; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; }
public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } private static final long serialVersionUID = 2738859149330833739L; }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\data\User.java
2
请完成以下Java代码
public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception { final boolean afterNewOrChange = changeType.isNewOrChange() && changeType.isAfter(); if (!afterNewOrChange) { // Note that currently we are not interested in splitting a partition if the only linking record gets deleted. return; // Nothing to do. } final ImmutableSet<String> columnNames = ImmutableSet.of(ITableRecordReference.COLUMNNAME_AD_Table_ID, ITableRecordReference.COLUMNNAME_Record_ID); if (!InterfaceWrapperHelper.isValueChanged(model, columnNames)) { return; } final IPartitionerService partitionerService = Services.get(IPartitionerService.class); final IDLMService dlmService = Services.get(IDLMService.class); final PartitionConfig config = dlmService.loadDefaultPartitionConfig(); final ITableRecordReference recordReference = TableRecordReference.ofReferencedOrNull(model); final Optional<PartitionerConfigLine> referencedLine = config.getLine(recordReference.getTableName()); if (!referencedLine.isPresent()) { return; // the table we are referencing is not part of DLM; nothing to do } final String modelTableName = InterfaceWrapperHelper.getModelTableName(model); final TableRecordIdDescriptor descriptor = TableRecordIdDescriptor.of(modelTableName, ITableRecordReference.COLUMNNAME_Record_ID, recordReference.getTableName()); final PartitionConfig augmentedConfig = partitionerService.augmentPartitionerConfig(config, Collections.singletonList(descriptor)); if (!augmentedConfig.isChanged()) { return; // we are done
} // now that the augmented config is stored, further changes will be handeled by AddToPartitionInterceptor. dlmService.storePartitionConfig(augmentedConfig); // however, for the current 'model', we need to enqueue it ourselves final CreatePartitionAsyncRequest request = PartitionRequestFactory.asyncBuilder() .setConfig(config) .setRecordToAttach(TableRecordReference.ofOrNull(model)) .build(); final PInstanceId pinstanceId = null; DLMPartitionerWorkpackageProcessor.schedule(request, pinstanceId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\PartitionerInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getOfflineAppId() { return offlineAppId; } public void setOfflineAppId(String offlineAppId) { this.offlineAppId = offlineAppId; } public String getRsaPrivateKey() { return rsaPrivateKey; } public void setRsaPrivateKey(String rsaPrivateKey) { this.rsaPrivateKey = rsaPrivateKey; } public String getRsaPublicKey() { return rsaPublicKey; } public void setRsaPublicKey(String rsaPublicKey) { this.rsaPublicKey = rsaPublicKey; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode; } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName; } public String getPartnerKey() { return partnerKey; } public void setPartnerKey(String partnerKey) { this.partnerKey = partnerKey; } private static final long serialVersionUID = 1L; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId == null ? null : appId.trim(); } public String getAppSectet() { return appSectet; } public void setAppSectet(String appSectet) {
this.appSectet = appSectet == null ? null : appSectet.trim(); } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId == null ? null : merchantId.trim(); } public String getAppType() { return appType; } public void setAppType(String appType) { this.appType = appType == null ? null : appType.trim(); } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayInfo.java
2
请完成以下Java代码
public boolean isPlaceBPAccountsOnCredit() { return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit); } /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); } @Override public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo) {
set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo); } @Override public boolean isSwitchCreditMemo() { return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
1
请在Spring Boot框架中完成以下Java代码
public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); return dataSource; } @Bean public PlatformTransactionManager hibernateTransactionManager() { final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", "false"); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\PersistenceConfig.java
2
请完成以下Java代码
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_C_ChargeType[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Charge Type. @param C_ChargeType_ID Charge Type */ public void setC_ChargeType_ID (int C_ChargeType_ID) { if (C_ChargeType_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, Integer.valueOf(C_ChargeType_ID)); } /** Get Charge Type. @return Charge Type */ public int getC_ChargeType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_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); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType.java
1
请完成以下Java代码
public int getRuleNumber() { return ruleNumber; } public Boolean isValid() { return valid; } public void setValid() { this.valid = Boolean.TRUE; } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; }
public String getValidationMessage() { return validationMessage; } public void setValidationMessage(String validationMessage) { this.validationMessage = validationMessage; } public List<ExpressionExecution> getConditionResults() { return conditionResults; } public List<ExpressionExecution> getConclusionResults() { return conclusionResults; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\RuleExecutionAuditContainer.java
1
请完成以下Java代码
public class ParallelGatewayImpl extends GatewayImpl implements ParallelGateway { protected static Attribute<Boolean> camundaAsyncAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ParallelGateway.class, BPMN_ELEMENT_PARALLEL_GATEWAY) .namespaceUri(BPMN20_NS) .extendsType(Gateway.class) .instanceProvider(new ModelTypeInstanceProvider<ParallelGateway>() { public ParallelGateway newInstance(ModelTypeInstanceContext instanceContext) { return new ParallelGatewayImpl(instanceContext); } }); /** camunda extensions */ camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC) .namespace(CAMUNDA_NS) .defaultValue(false) .build(); typeBuilder.build(); } @Override public ParallelGatewayBuilder builder() { return new ParallelGatewayBuilder((BpmnModelInstance) modelInstance, this); }
/** camunda extensions */ /** * @deprecated use isCamundaAsyncBefore() instead. */ @Deprecated public boolean isCamundaAsync() { return camundaAsyncAttribute.getValue(this); } /** * @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead. */ @Deprecated public void setCamundaAsync(boolean isCamundaAsync) { camundaAsyncAttribute.setValue(this, isCamundaAsync); } public ParallelGatewayImpl(ModelTypeInstanceContext context) { super(context); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ParallelGatewayImpl.java
1
请完成以下Java代码
public final class PublicKeyCredentialType implements Serializable { @Serial private static final long serialVersionUID = 7025333122210061679L; /** * The only credential type that currently exists. */ public static final PublicKeyCredentialType PUBLIC_KEY = new PublicKeyCredentialType("public-key"); private final String value; private PublicKeyCredentialType(String value) { this.value = value; }
/** * Gets the value. * @return the value */ public String getValue() { return this.value; } public static PublicKeyCredentialType valueOf(String value) { if (PUBLIC_KEY.getValue().equals(value)) { return PUBLIC_KEY; } return new PublicKeyCredentialType(value); } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialType.java
1
请完成以下Java代码
public void setReplenishmentClass (final @Nullable java.lang.String ReplenishmentClass) { set_Value (COLUMNNAME_ReplenishmentClass, ReplenishmentClass); } @Override public java.lang.String getReplenishmentClass() { return get_ValueAsString(COLUMNNAME_ReplenishmentClass); } @Override public void setSeparator (final java.lang.String Separator) { set_Value (COLUMNNAME_Separator, Separator); } @Override public java.lang.String getSeparator() { return get_ValueAsString(COLUMNNAME_Separator); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() {
return get_ValueAsString(COLUMNNAME_Value); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse.java
1
请完成以下Java代码
public void unassignHUs(@NonNull final Object model, @NonNull final Collection<HuId> husToUnassign, final String trxName) { final Properties ctx = InterfaceWrapperHelper.getCtx(model); final TableRecordReference modelRef = TableRecordReference.of(model); huAssignmentDAO.deleteHUAssignments(ctx, modelRef, husToUnassign, trxName); } @Override public void unassignHUs(@NonNull final TableRecordReference modelRef, @NonNull final Collection<HuId> husToUnassign) { huAssignmentDAO.deleteHUAssignments(Env.getCtx(), modelRef, husToUnassign, ITrx.TRXNAME_ThreadInherited); } @Override public IHUAssignmentBuilder createHUAssignmentBuilder() { return new HUAssignmentBuilder(); } @Override public void copyHUAssignments( @NonNull final Object sourceModel, @NonNull final Object targetModel) { final List<I_M_HU_Assignment> // huAssignmentsForSource = huAssignmentDAO.retrieveTopLevelHUAssignmentsForModel(sourceModel);
for (final I_M_HU_Assignment huAssignment : huAssignmentsForSource) { createHUAssignmentBuilder() .setTemplateForNewRecord(huAssignment) .setModel(targetModel) .build(); } } @Override public ImmutableSetMultimap<TableRecordReference, HuId> getHUsByRecordRefs(@NonNull final TableRecordReferenceSet recordRefs) { return huAssignmentDAO.retrieveHUsByRecordRefs(recordRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBL.java
1
请在Spring Boot框架中完成以下Java代码
class YourBusinessClass { Dependency1 dependency1; Dependency2 dependency2; //@Autowired public YourBusinessClass(Dependency1 dependency1, Dependency2 dependency2) { super(); System.out.println("Constructor Injection - YourBusinessClass "); this.dependency1 = dependency1; this.dependency2 = dependency2; } // @Autowired // public void setDependency1(Dependency1 dependency1) { // System.out.println("Setter Injection - setDependency1 "); // this.dependency1 = dependency1; // } // // @Autowired // public void setDependency2(Dependency2 dependency2) { // System.out.println("Setter Injection - setDependency2 "); // this.dependency2 = dependency2; // } public String toString() { return "Using " + dependency1 + " and " + dependency2; }
} @Component class Dependency1 { } @Component class Dependency2 { } @Configuration @ComponentScan public class DepInjectionLauncherApplication { public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext(DepInjectionLauncherApplication.class)) { Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println); System.out.println(context.getBean(YourBusinessClass.class)); } } }
repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\a1\DepInjectionLauncherApplication.java
2
请完成以下Java代码
public List<AbstractProcessInstanceModificationCommand> getInstructions() { return instructions; } public List<String> getProcessInstanceIds() { return processInstanceIds; } @Override public RestartProcessInstanceBuilder processInstanceIds(String... processInstanceIds) { this.processInstanceIds.addAll(Arrays.asList(processInstanceIds)); return this; } @Override public RestartProcessInstanceBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery query) { this.query = query; return this; } public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() { return query; } public String getProcessDefinitionId() { return processDefinitionId; } public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) { this.instructions = instructions; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public RestartProcessInstanceBuilder processInstanceIds(List<String> processInstanceIds) { this.processInstanceIds.addAll(processInstanceIds); return this; } @Override public RestartProcessInstanceBuilder initialSetOfVariables() { this.initialVariables = true; return this; } public boolean isInitialVariables() { return initialVariables;
} @Override public RestartProcessInstanceBuilder skipCustomListeners() { this.skipCustomListeners = true; return this; } @Override public RestartProcessInstanceBuilder skipIoMappings() { this.skipIoMappings = true; return this; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; } @Override public RestartProcessInstanceBuilder withoutBusinessKey() { withoutBusinessKey = true; return this; } public boolean isWithoutBusinessKey() { return withoutBusinessKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstanceBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { CommonAPI commonAPI = null; log.info("低代码模式,拦截请求路径:" + request.getRequestURI()); //1、验证是否开启低代码开发模式控制 if (jeecgBaseConfig == null) { jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class); } if (commonAPI == null) { commonAPI = SpringContextUtils.getBean(CommonAPI.class); } if (jeecgBaseConfig.getFirewall()!=null && LowCodeModeInterceptor.LOW_CODE_MODE_PROD.equals(jeecgBaseConfig.getFirewall().getLowCodeMode())) { String requestURI = request.getRequestURI().substring(request.getContextPath().length()); log.info("低代码模式,拦截请求路径:" + requestURI); LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); Set<String> hasRoles = null; if (loginUser == null) { loginUser = commonAPI.getUserByName(JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest())); } if (loginUser != null) { //当前登录人拥有的角色 hasRoles = commonAPI.queryUserRolesById(loginUser.getId()); } log.info("get loginUser info: {}", loginUser); log.info("get loginRoles info: {}", hasRoles != null ? hasRoles.toArray() : "空"); //拥有的角色 和 允许开发角色存在交集 boolean hasIntersection = CommonUtils.hasIntersection(hasRoles, CommonConstant.allowDevRoles); //如果是超级管理员 或者 允许开发的角色,则不做限制 if (loginUser!=null && ("admin".equals(loginUser.getUsername()) || hasIntersection)) {
return true; } this.returnErrorMessage(response); return false; } return true; } /** * 返回结果 * * @param response */ private void returnErrorMessage(HttpServletResponse response) { //校验失败返回前端 response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); Result<?> result = Result.error("低代码开发模式为发布模式,不允许使用在线配置!!"); out.print(JSON.toJSON(result)); } catch (IOException e) { e.printStackTrace(); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\firewall\interceptor\LowCodeModeInterceptor.java
2
请在Spring Boot框架中完成以下Java代码
public Device getDeviceById(DeviceId id) { TransportProtos.GetDeviceResponseMsg deviceProto = transportService.getDevice(TransportProtos.GetDeviceRequestMsg.newBuilder() .setDeviceIdMSB(id.getId().getMostSignificantBits()) .setDeviceIdLSB(id.getId().getLeastSignificantBits()) .build()); if (deviceProto == null) { return null; } DeviceProfileId deviceProfileId = new DeviceProfileId(new UUID( deviceProto.getDeviceProfileIdMSB(), deviceProto.getDeviceProfileIdLSB()) ); Device device = new Device(); device.setId(id); device.setDeviceProfileId(deviceProfileId); DeviceTransportConfiguration deviceTransportConfiguration = JacksonUtil.fromBytes( deviceProto.getDeviceTransportConfiguration().toByteArray(), DeviceTransportConfiguration.class); DeviceData deviceData = new DeviceData(); deviceData.setTransportConfiguration(deviceTransportConfiguration); device.setDeviceData(deviceData); return device; } public DeviceCredentials getDeviceCredentialsByDeviceId(DeviceId deviceId) {
TransportProtos.GetDeviceCredentialsResponseMsg deviceCredentialsResponse = transportService.getDeviceCredentials( TransportProtos.GetDeviceCredentialsRequestMsg.newBuilder() .setDeviceIdMSB(deviceId.getId().getMostSignificantBits()) .setDeviceIdLSB(deviceId.getId().getLeastSignificantBits()) .build() ); if (deviceCredentialsResponse.hasDeviceCredentialsData()) { return ProtoUtils.fromProto(deviceCredentialsResponse.getDeviceCredentialsData()); } else { throw new IllegalArgumentException("Device credentials not found"); } } public TransportProtos.GetSnmpDevicesResponseMsg getSnmpDevicesIds(int page, int pageSize) { TransportProtos.GetSnmpDevicesRequestMsg requestMsg = TransportProtos.GetSnmpDevicesRequestMsg.newBuilder() .setPage(page) .setPageSize(pageSize) .build(); return transportService.getSnmpDevicesIds(requestMsg); } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\ProtoTransportEntityService.java
2
请完成以下Java代码
public class DbPublicKeyCredentialUserEntityRepository implements PublicKeyCredentialUserEntityRepository { private final PasskeyUserRepository userRepository; @Override public PublicKeyCredentialUserEntity findById(Bytes id) { log.info("findById: id={}", id.toBase64UrlString()); var externalId = id.toBase64UrlString(); return userRepository.findByExternalId(externalId) .map(DbPublicKeyCredentialUserEntityRepository::mapToUserEntity) .orElse(null); } @Override public PublicKeyCredentialUserEntity findByUsername(String username) { log.info("findByUsername: username={}", username); return userRepository.findByName(username) .map(DbPublicKeyCredentialUserEntityRepository::mapToUserEntity) .orElse(null); } @Override public void save(PublicKeyCredentialUserEntity userEntity) { log.info("save: username={}, externalId={}", userEntity.getName(),userEntity.getId().toBase64UrlString()); var entity = userRepository.findByExternalId(userEntity.getId().toBase64UrlString()) .orElse(new PasskeyUser()); entity.setExternalId(userEntity.getId().toBase64UrlString()); entity.setName(userEntity.getName());
entity.setDisplayName(userEntity.getDisplayName()); userRepository.save(entity); } @Override public void delete(Bytes id) { log.info("delete: id={}", id.toBase64UrlString()); userRepository.findByExternalId(id.toBase64UrlString()) .ifPresent(userRepository::delete); } private static PublicKeyCredentialUserEntity mapToUserEntity(PasskeyUser user) { return ImmutablePublicKeyCredentialUserEntity.builder() .id(Bytes.fromBase64(user.getExternalId())) .name(user.getName()) .displayName(user.getDisplayName()) .build(); } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\repository\DbPublicKeyCredentialUserEntityRepository.java
1
请在Spring Boot框架中完成以下Java代码
public final class WellKnownChangePasswordBeanDefinitionParser implements BeanDefinitionParser { private static final String WELL_KNOWN_CHANGE_PASSWORD_PATTERN = "/.well-known/change-password"; private static final String DEFAULT_CHANGE_PASSWORD_PAGE = "/change-password"; private static final String ATT_CHANGE_PASSWORD_PAGE = "change-password-page"; /** * {@inheritDoc} */ @Override public BeanDefinition parse(Element element, ParserContext parserContext) { BeanDefinition requestMatcher = BeanDefinitionBuilder.rootBeanDefinition(RequestMatcherFactoryBean.class) .addConstructorArgValue(WELL_KNOWN_CHANGE_PASSWORD_PATTERN) .getBeanDefinition();
BeanDefinition changePasswordFilter = BeanDefinitionBuilder .rootBeanDefinition(RequestMatcherRedirectFilter.class) .addConstructorArgValue(requestMatcher) .addConstructorArgValue(getChangePasswordPage(element)) .getBeanDefinition(); parserContext.getReaderContext().registerWithGeneratedName(changePasswordFilter); return changePasswordFilter; } private String getChangePasswordPage(Element element) { String changePasswordPage = element.getAttribute(ATT_CHANGE_PASSWORD_PAGE); return (StringUtils.hasText(changePasswordPage) ? changePasswordPage : DEFAULT_CHANGE_PASSWORD_PAGE); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\WellKnownChangePasswordBeanDefinitionParser.java
2
请完成以下Java代码
public class Main { public static void main(String[] args) { Media media = new Media(); media.setId(001); media.setTitle("Media1"); media.setArtist("Artist001"); AudioMedia audioMedia = new AudioMedia(); audioMedia.setId(101); audioMedia.setTitle("Audio1"); audioMedia.setArtist("Artist101"); audioMedia.setBitrate(3500); audioMedia.setFrequency("256kbps"); VideoMedia videoMedia = new VideoMedia(); videoMedia.setId(201); videoMedia.setTitle("Video1"); videoMedia.setArtist("Artist201"); videoMedia.setResolution("1024x768"); videoMedia.setAspectRatio("16:9"); System.out.println(media); System.out.println(audioMedia); System.out.println(videoMedia); AudioMediaPlayer audioMediaPlayer = new AudioMediaPlayer();
audioMediaPlayer.play(); audioMediaPlayer.pause(); VideoMediaPlayer videoMediaPlayer = new VideoMediaPlayer(); videoMediaPlayer.play(); videoMediaPlayer.pause(); MultiMediaPlayer multiMediaPlayer = new MultiMediaPlayer(); multiMediaPlayer.play(); multiMediaPlayer.pause(); multiMediaPlayer.seek(); multiMediaPlayer.fastForward(); CustomMediaPlayer customMediaPlayer = new CustomMediaPlayer(); customMediaPlayer.play(); customMediaPlayer.pause(); customMediaPlayer.setId(301); customMediaPlayer.setTitle("Custom1"); customMediaPlayer.setArtist("Artist301"); System.out.println(customMediaPlayer); } }
repos\tutorials-master\core-java-modules\core-java-lang-4\src\main\java\com\baeldung\implementsvsextends\Main.java
1
请完成以下Java代码
public String getImportTableName() { return I_I_BPartner_GlobalID.Table_Name; } @Override protected String getTargetTableName() { return I_C_BPartner.Table_Name; } @Override protected void updateAndValidateImportRecordsImpl() { final ImportRecordsSelection selection = getImportRecordsSelection(); BPartnerGlobalIDImportTableSqlUpdater.updateBPartnerGlobalIDImortTable(selection); } @Override protected String getImportOrderBySql() { return I_I_BPartner_GlobalID.COLUMNNAME_GlobalId; } @Override public I_I_BPartner_GlobalID retrieveImportRecord(Properties ctx, ResultSet rs) throws SQLException
{ return new X_I_BPartner_GlobalID(ctx, rs, ITrx.TRXNAME_ThreadInherited); } /* * @param isInsertOnly ignored. This import is only for updates. */ @Override protected ImportRecordResult importRecord(@NonNull IMutable<Object> state, @NonNull I_I_BPartner_GlobalID importRecord, final boolean isInsertOnly) { final IBPartnerDAO partnerDAO = Services.get(IBPartnerDAO.class); if (importRecord.getC_BPartner_ID() > 0 && !Check.isEmpty(importRecord.getURL3(), true)) { final I_C_BPartner bpartner = partnerDAO.getById(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID())); bpartner.setURL3(importRecord.getURL3()); InterfaceWrapperHelper.save(bpartner); return ImportRecordResult.Updated; } return ImportRecordResult.Nothing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\globalid\impexp\BPartnerGlobalIDImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { http. authorizeRequests().antMatchers("/**").permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("123456").roles("USER"); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }
@Bean public PasswordEncoder passwordEncoder() { return new PasswordEncoder() { @Override public String encode(CharSequence charSequence) { return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return Objects.equals(charSequence.toString(),s); } }; } }
repos\SpringBootLearning-master (1)\springboot-security-oauth2-jwt\jwt-authserver\src\main\java\com\gf\config\WebSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
protected List<String> getLocations(@Nullable ClassLoader classLoader) { List<String> classpathLocations = new ArrayList<>(); for (ConfigDataLocation candidate : ConfigDataEnvironment.DEFAULT_SEARCH_LOCATIONS) { for (ConfigDataLocation configDataLocation : candidate.split()) { String location = configDataLocation.getValue(); if (location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { classpathLocations.add(location); } } } return classpathLocations; } /** * Get the application file extensions to consider. A valid extension starts with a * dot. * @param classLoader the classloader to use * @return the configuration file extensions */
protected List<String> getExtensions(@Nullable ClassLoader classLoader) { List<String> extensions = new ArrayList<>(); List<PropertySourceLoader> propertySourceLoaders = getSpringFactoriesLoader(classLoader) .load(PropertySourceLoader.class); for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { for (String fileExtension : propertySourceLoader.getFileExtensions()) { String candidate = "." + fileExtension; if (!extensions.contains(candidate)) { extensions.add(candidate); } } } return extensions; } protected SpringFactoriesLoader getSpringFactoriesLoader(@Nullable ClassLoader classLoader) { return SpringFactoriesLoader.forDefaultResourceLocation(classLoader); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationRuntimeHints.java
2
请在Spring Boot框架中完成以下Java代码
public JsonSessionInfo getSessionInfo() { final User user = loginService.getLoggedInUser(); final Locale locale = loginService.getLocale(); final long countUnconfirmed = userConfirmationService.getCountUnconfirmed(user); final LocalDate today = LocalDate.now(); final YearWeek week = YearWeekUtil.ofLocalDate(today); return JsonSessionInfo.builder() .loggedIn(true) .email(user.getEmail()) .language(LanguageKey.ofLocale(locale).getAsString()) // .date(today) .dayCaption(DateUtils.getDayName(today, locale)) .week(YearWeekUtil.toJsonString(week)) .weekCaption(YearWeekUtil.toDisplayName(week)) // .countUnconfirmed(countUnconfirmed) .build(); } @PostMapping("/login") public JsonSessionInfo login(@RequestBody @NonNull final JsonLoginRequest request) { try { loginService.login(request.getEmail(), request.getPassword()); return getSessionInfo(); } catch (final Exception ex) { return JsonSessionInfo.builder() .loggedIn(false) .loginError(ex.getLocalizedMessage()) .build(); }
} @GetMapping("/logout") public void logout() { loginService.logout(); } @GetMapping("/resetUserPassword") public void resetUserPasswordRequest(@RequestParam("email") final String email) { final String passwordResetToken = loginService.generatePasswordResetKey(email); loginService.sendPasswordResetKey(email, passwordResetToken); } @GetMapping("/resetUserPasswordConfirm") public JsonPasswordResetResponse resetUserPasswordConfirm(@RequestParam("token") final String token) { final User user = loginService.resetPassword(token); loginService.login(user); return JsonPasswordResetResponse.builder() .email(user.getEmail()) .language(user.getLanguageKeyOrDefault().getAsString()) .newPassword(user.getPassword()) .build(); } @PostMapping("/confirmDataEntry") public ConfirmDataEntryResponse confirmDataEntry() { final User user = loginService.getLoggedInUser(); userConfirmationService.confirmUserEntries(user); return ConfirmDataEntryResponse.builder() .countUnconfirmed(userConfirmationService.getCountUnconfirmed(user)) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\session\SessionRestController.java
2
请完成以下Java代码
public DocumentNoBuilder createDocumentNoBuilder() { return new DocumentNoBuilder(); } @Override public IDocumentNoBuilder createValueBuilderFor(@NonNull final Object modelRecord) { final IClientOrgAware clientOrg = create(modelRecord, IClientOrgAware.class); final ClientId clientId = ClientId.ofRepoId(clientOrg.getAD_Client_ID()); final ProviderResult providerResult = getDocumentSequenceInfo(modelRecord); return createDocumentNoBuilder() .setDocumentSequenceInfo(providerResult.getInfoOrNull()) .setClientId(clientId)
.setDocumentModel(modelRecord) .setFailOnError(false); } private ProviderResult getDocumentSequenceInfo(@NonNull final Object modelRecord) { for (final ValueSequenceInfoProvider provider : additionalProviders) { final ProviderResult result = provider.computeValueInfo(modelRecord); if (result.hasInfo()) { return result; } } return tableNameBasedProvider.computeValueInfo(modelRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilderFactory.java
1
请完成以下Java代码
public FlowableScriptEvaluationRequest language(String language) { if (StringUtils.isEmpty(language)) { throw new FlowableIllegalArgumentException("language is empty"); } this.language = language; return this; } @Override public FlowableScriptEvaluationRequest script(String script) { if (StringUtils.isEmpty(script)) { throw new FlowableIllegalArgumentException("script is empty"); } this.script = script; return this; } @Override public FlowableScriptEvaluationRequest resolver(Resolver resolver) { this.resolver = resolver; return this; } @Override public FlowableScriptEvaluationRequest scopeContainer(VariableContainer scopeContainer) { this.scopeContainer = scopeContainer; return this; } @Override public FlowableScriptEvaluationRequest inputVariableContainer(VariableContainer inputVariableContainer) { this.inputVariableContainer = inputVariableContainer; return this; } @Override public FlowableScriptEvaluationRequest storeScriptVariables() { this.storeScriptVariables = true; return this; }
@Override public ScriptEvaluation evaluate() throws FlowableScriptException { if (StringUtils.isEmpty(language)) { throw new FlowableIllegalArgumentException("language is required"); } if (StringUtils.isEmpty(script)) { throw new FlowableIllegalArgumentException("script is required"); } ScriptEngine scriptEngine = getEngineByName(language); Bindings bindings = createBindings(); try { Object result = scriptEngine.eval(script, bindings); return new ScriptEvaluationImpl(resolver, result); } catch (ScriptException e) { throw new FlowableScriptException(e.getMessage(), e); } } protected Bindings createBindings() { return new ScriptBindings(Collections.singletonList(resolver), scopeContainer, inputVariableContainer, storeScriptVariables); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\JSR223FlowableScriptEngine.java
1
请完成以下Java代码
public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @Override public boolean isAnalytics() { return analytics; } public void setAnalytics(boolean analytics) { this.analytics = analytics; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VariableDefinitionImpl that = (VariableDefinitionImpl) o; return ( required == that.required && Objects.equals(display, that.display) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(type, that.type) && Objects.equals(displayName, that.displayName) && Objects.equals(analytics, that.analytics) ); } @Override public int hashCode() { return Objects.hash(id, name, description, type, required, display, displayName, analytics); } @Override public String toString() { return ( "VariableDefinitionImpl{" + "id='" +
id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type='" + type + '\'' + ", required=" + required + ", display=" + display + ", displayName='" + displayName + '\'' + ", analytics='" + analytics + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\VariableDefinitionImpl.java
1
请完成以下Java代码
class UsernamePasswordAuthenticationTokenDeserializer extends ValueDeserializer<UsernamePasswordAuthenticationToken> { private static final TypeReference<List<GrantedAuthority>> GRANTED_AUTHORITY_LIST = new TypeReference<>() { }; /** * This method construct {@link UsernamePasswordAuthenticationToken} object from * serialized json. * @param jp the JsonParser * @param ctxt the DeserializationContext * @return the user * @throws JacksonException if an error during JSON processing occurs */ @Override public UsernamePasswordAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws JacksonException { JsonNode jsonNode = ctxt.readTree(jp); boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean(); JsonNode principalNode = readJsonNode(jsonNode, "principal"); Object principal = getPrincipal(ctxt, principalNode); JsonNode credentialsNode = readJsonNode(jsonNode, "credentials"); Object credentials = getCredentials(credentialsNode); JsonNode authoritiesNode = readJsonNode(jsonNode, "authorities"); List<GrantedAuthority> authorities = ctxt.readTreeAsValue(authoritiesNode, ctxt.getTypeFactory().constructType(GRANTED_AUTHORITY_LIST)); UsernamePasswordAuthenticationToken token = (!authenticated) ? UsernamePasswordAuthenticationToken.unauthenticated(principal, credentials) : UsernamePasswordAuthenticationToken.authenticated(principal, credentials, authorities); JsonNode detailsNode = readJsonNode(jsonNode, "details"); if (detailsNode.isNull() || detailsNode.isMissingNode()) { token.setDetails(null); } else { Object details = ctxt.readTreeAsValue(detailsNode, Object.class); token.setDetails(details);
} return token; } private @Nullable Object getCredentials(JsonNode credentialsNode) { if (credentialsNode.isNull() || credentialsNode.isMissingNode()) { return null; } return credentialsNode.asString(); } private Object getPrincipal(DeserializationContext ctxt, JsonNode principalNode) throws StreamReadException, DatabindException { if (principalNode.isObject()) { return ctxt.readTreeAsValue(principalNode, Object.class); } return principalNode.asString(); } private JsonNode readJsonNode(JsonNode jsonNode, String field) { return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\jackson\UsernamePasswordAuthenticationTokenDeserializer.java
1
请完成以下Java代码
public Boolean getProcessed() { return processed; } /** * @param processed the processed to set */ public WorkPackageQuery setProcessed(final Boolean processed) { this.processed = processed; return this; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getReadyForProcessing() */ @Override public Boolean getReadyForProcessing() { return readyForProcessing; } /** * @param readyForProcessing the readyForProcessing to set */ public WorkPackageQuery setReadyForProcessing(final Boolean readyForProcessing) { this.readyForProcessing = readyForProcessing; return this; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getError() */ @Override public Boolean getError() { return error; } /** * @param error the error to set */ public void setError(final Boolean error) { this.error = error; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getSkippedTimeoutMillis() */ @Override public long getSkippedTimeoutMillis() { return skippedTimeoutMillis; } /** * @param skippedTimeoutMillis the skippedTimeoutMillis to set */ public void setSkippedTimeoutMillis(final long skippedTimeoutMillis) { Check.assume(skippedTimeoutMillis >= 0, "skippedTimeoutMillis >= 0"); this.skippedTimeoutMillis = skippedTimeoutMillis; } /*
* (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getPackageProcessorIds() */ @Override @Nullable public Set<QueuePackageProcessorId> getPackageProcessorIds() { return packageProcessorIds; } /** * @param packageProcessorIds the packageProcessorIds to set */ public void setPackageProcessorIds(@Nullable final Set<QueuePackageProcessorId> packageProcessorIds) { if (packageProcessorIds != null) { Check.assumeNotEmpty(packageProcessorIds, "packageProcessorIds cannot be empty!"); } this.packageProcessorIds = packageProcessorIds; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getPriorityFrom() */ @Override public String getPriorityFrom() { return priorityFrom; } /** * @param priorityFrom the priorityFrom to set */ public void setPriorityFrom(final String priorityFrom) { this.priorityFrom = priorityFrom; } @Override public String toString() { return "WorkPackageQuery [" + "processed=" + processed + ", readyForProcessing=" + readyForProcessing + ", error=" + error + ", skippedTimeoutMillis=" + skippedTimeoutMillis + ", packageProcessorIds=" + packageProcessorIds + ", priorityFrom=" + priorityFrom + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQuery.java
1
请完成以下Java代码
public static <T> T withProcessApplicationContext(Callable<T> callable, String processApplicationName) throws Exception { try { setCurrentProcessApplication(processApplicationName); return callable.call(); } finally { clear(); } } /** * <p>Takes a callable and executes all engine API invocations within that callable in the context * of the given process application * * <p>Equivalent to * <pre> * try { * ProcessApplicationContext.setCurrentProcessApplication("someProcessApplication"); * callable.call(); * } finally { * ProcessApplicationContext.clear(); * } * </pre> * * @param callable the callable to execute * @param reference a reference of the process application to switch into */ public static <T> T withProcessApplicationContext(Callable<T> callable, ProcessApplicationReference reference) throws Exception { try { setCurrentProcessApplication(reference); return callable.call(); } finally { clear(); } }
/** * <p>Takes a callable and executes all engine API invocations within that callable in the context * of the given process application * * <p>Equivalent to * <pre> * try { * ProcessApplicationContext.setCurrentProcessApplication("someProcessApplication"); * callable.call(); * } finally { * ProcessApplicationContext.clear(); * } * </pre> * * @param callable the callable to execute * @param processApplication the process application to switch into */ public static <T> T withProcessApplicationContext(Callable<T> callable, ProcessApplicationInterface processApplication) throws Exception { try { setCurrentProcessApplication(processApplication); return callable.call(); } finally { clear(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\ProcessApplicationContext.java
1
请完成以下Java代码
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { //Open price System.out.println("@Start Init ..."); stockNames.forEach(stockName -> { stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); }); Runnable runnable = new Runnable() { @Override public void run() { //Simulate Change price and put every x seconds while (true) { int indx = new Random().nextInt(stockNames.size()); String stockName = stockNames.get(indx); BigDecimal price = getLastPrice(stockName); BigDecimal newprice = changePrice(price); Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); stocksDB.add(stock); int r = new Random().nextInt(30); try { Thread.currentThread().sleep(r*1000); } catch (InterruptedException ex) { // ... } } }
}; new Thread(runnable).start(); System.out.println("@End Init ..."); } public Stock getNextTransaction(Integer lastEventId) { return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); } BigDecimal generateOpenPrice() { float min = 70; float max = 120; return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); } BigDecimal changePrice(BigDecimal price) { return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); } private BigDecimal getLastPrice(String stockName) { return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); } }
repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-server\src\main\java\com\baeldung\sse\jaxrs\StockService.java
1
请完成以下Java代码
public PaymentTermId getPaymentTermId(@NonNull final JsonOLCandCreateRequest request, @NonNull final OrgId orgId) { final String paymentTermCode = request.getPaymentTerm(); if (Check.isEmpty(paymentTermCode)) { return null; } final IdentifierString paymentTerm = IdentifierString.of(paymentTermCode); final PaymentTermQueryBuilder queryBuilder = PaymentTermQuery.builder(); queryBuilder.orgId(orgId); switch (paymentTerm.getType()) { case EXTERNAL_ID: queryBuilder.externalId(paymentTerm.asExternalId()); break;
case VALUE: queryBuilder.value(paymentTerm.asValue()); break; default: throw new InvalidIdentifierException(paymentTerm); } final Optional<PaymentTermId> paymentTermId = paymentTermRepo.firstIdOnly(queryBuilder.build()); return paymentTermId.orElseThrow(() -> MissingResourceException.builder() .resourceName("PaymentTerm") .resourceIdentifier(paymentTermCode) .parentResource(request).build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\MasterdataProvider.java
1
请完成以下Java代码
public boolean isStateNotChanged(String oldState, String newState) { // if the old and new state are the same, leave the operation as we don't execute any transition return oldState != null && oldState.equals(newState) && abortOperationIfNewStateEqualsOldState(); } protected abstract void internalExecute(); protected PlanItemLifeCycleEvent createPlanItemLifeCycleEvent() { return new PlanItemLifeCycleEvent(planItemInstanceEntity, getLifeCycleTransition()); } public abstract String getNewState(); public abstract String getLifeCycleTransition(); /** * Overwrite this default implemented hook, if the operation should be aborted on a void transition which might be the case, if the old and new state * will be the same. * * @return true, if this operation should be aborted, if the new plan item state is the same as the old one, false, if the operation is to be executed in any case */ public boolean abortOperationIfNewStateEqualsOldState() { return false; } public abstract String getOperationName(); @Override public String toString() { PlanItem planItem = planItemInstanceEntity.getPlanItem(); StringBuilder stringBuilder = new StringBuilder(); String operationName = getOperationName(); stringBuilder.append(operationName != null ? operationName : "[Change plan item state]").append(" "); if (planItem != null) { stringBuilder.append(planItem); }
stringBuilder.append(" (CaseInstance id: "); stringBuilder.append(planItemInstanceEntity.getCaseInstanceId()); stringBuilder.append(", PlanItemInstance id: "); stringBuilder.append(planItemInstanceEntity.getId()); stringBuilder.append("), "); String currentState = planItemInstanceEntity.getState(); String newState = getNewState(); if (!Objects.equals(currentState, newState)) { stringBuilder.append("from [").append(currentState).append("] to new state: [").append(getNewState()).append("]"); stringBuilder.append(" with transition ["); stringBuilder.append(getLifeCycleTransition()); stringBuilder.append("]"); } else { stringBuilder.append("will remain in state [").append(newState).append("]"); } return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\AbstractChangePlanItemInstanceStateOperation.java
1
请完成以下Spring Boot application配置
management.endpoints.web.exposure.include=startup # JPA is not required for startup actuator endpoint spring.autoconfigure.exclude= org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \ org.springframework.boot.autoconfigure.orm.jpa.Hibernate
JpaAutoConfiguration, \ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\resources\application-startup.properties
2
请完成以下Java代码
private static String substringBeforeLast(String str, String separator) { if (ObjectUtils.isEmpty(str) || ObjectUtils.isEmpty(separator)) { return str; } int pos = str.lastIndexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } private void write(HttpHeaders headers, String name, String value, boolean append) { write(headers, name, value, append, s -> true); } private void write(HttpHeaders headers, String name, @Nullable String value, boolean append, Predicate<String> shouldWrite) { if (append) { if (value != null) { headers.add(name, value); } // these headers should be treated as a single comma separated header List<String> headerValues = headers.get(name); if (headerValues != null) { List<String> values = headerValues.stream().filter(shouldWrite).toList(); String delimitedValue = StringUtils.collectionToCommaDelimitedString(values); headers.set(name, delimitedValue); } } else if (value != null && shouldWrite.test(value)) { headers.set(name, value); } } private int getDefaultPort(String scheme) { return HTTPS_SCHEME.equals(scheme) ? HTTPS_PORT : HTTP_PORT;
} private String toHostHeader(ServerHttpRequest request) { int port = request.getURI().getPort(); String host = request.getURI().getHost(); String scheme = request.getURI().getScheme(); if (port < 0 || (port == HTTP_PORT && HTTP_SCHEME.equals(scheme)) || (port == HTTPS_PORT && HTTPS_SCHEME.equals(scheme))) { return host; } else { return host + ":" + port; } } private String stripTrailingSlash(URI uri) { String path = uri.getPath(); if (path != null && path.endsWith("/")) { return path.substring(0, path.length() - 1); } else { return path; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\XForwardedHeadersFilter.java
1
请在Spring Boot框架中完成以下Java代码
public Double getDoubleValue() { if (valueField != null) { return valueField.getDoubleValue(); } return null; } public String getTextValue2() { if (valueField != null) { return valueField.getTextValue2(); } return null; } public String getType() { if (valueType != null) { return valueType.getTypeName(); } return null; } public boolean needsTypeCheck() { // When operator is not-equals or type of value is null, type doesn't matter! if (operator == QueryOperator.NOT_EQUALS || operator == QueryOperator.NOT_EQUALS_IGNORE_CASE) {
return false; } if (valueField != null) { return !NullType.TYPE_NAME.equals(valueType.getTypeName()); } return false; } public boolean isLocal() { return local; } public String getScopeType() { return scopeType; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\QueryVariableValue.java
2
请完成以下Spring Boot application配置
management.endpoints.web.exposure.include=* management.metrics.enable.root=true management.metrics.enable.jvm=true management.endpoint.restart.enabled=true spring.datasource.jmx-enabled=false spring.jmx.enabled=true management.endpoint.shutdown.enabled=true ## Access logs configuration server.tomcat.accesslog.enabled=true server.tomcat.accesslog.directory=logs server.tomcat.accesslog.file-date-format=yyyy-MM-dd server.tomcat.accesslog.prefix=access_log server.tomcat.accesslog.suffix=.log server.tomcat.acce
sslog.pattern=common server.tomcat.basedir=tomcat ## Tomcat internal server logs logging.level.org.apache.tomcat=DEBUG logging.level.org.apache.catalina=DEBUG ## Trace app management.trace.http.include=RESPONSE_HEADERS
repos\tutorials-master\spring-boot-modules\spring-boot-runtime-2\src\main\resources\application.properties
2
请完成以下Java代码
public void setIMP_Processor_Type_ID (int IMP_Processor_Type_ID) { if (IMP_Processor_Type_ID < 1) set_Value (COLUMNNAME_IMP_Processor_Type_ID, null); else set_Value (COLUMNNAME_IMP_Processor_Type_ID, Integer.valueOf(IMP_Processor_Type_ID)); } /** Get Import Processor Type. @return Import Processor Type */ public int getIMP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Days to keep Log. @param KeepLogDays Number of days to keep the log entries */ public void setKeepLogDays (int KeepLogDays) { set_Value (COLUMNNAME_KeepLogDays, Integer.valueOf(KeepLogDays)); } /** Get Days to keep Log. @return Number of days to keep the log entries */ public int getKeepLogDays () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Password Info. @param PasswordInfo Password Info */ public void setPasswordInfo (String PasswordInfo) { set_Value (COLUMNNAME_PasswordInfo, PasswordInfo); } /** Get Password Info. @return Password Info */ public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port);
if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_Processor.java
1
请完成以下Java代码
public boolean isTransferable(final IHUAttributeTransferRequest request, final I_M_Attribute attribute) { // This strategy does only apply on VHU-to-VHU attributes transfer because it involves calculations if (!request.isVHUTransfer()) { return false; } final BigDecimal transferRatio = getTransferRatio(request, attribute); final boolean isTransferrable = BigDecimal.ZERO.compareTo(transferRatio) < 0 // transferRatio > 0 && BigDecimal.ONE.compareTo(transferRatio) >= 0; // transferRatio <= 1 return isTransferrable; } /** * @return a value between 0 and 1, resulted by the division of the requestQty (qty) and storageQty (source) for given attribute */ private BigDecimal getTransferRatio(final IHUAttributeTransferRequest request, final I_M_Attribute attribute) { // // The qty which is to be subtracted divided by the full qty is our division ratio // (will return a value which is numerically less than 1, and greater or equal to 0) final ProductId requestProductId = request.getProductId(); final IHUStorage huStorageFrom = request.getHUStorageFrom(); I_C_UOM uomToUse = request.getC_UOM(); if (uomToUse == null) { uomToUse = huStorageFrom.getProductStorage(requestProductId).getC_UOM(); // fallback and consider using the request UOM } final BigDecimal requestQty = request.getQty(); final BigDecimal existingStorageQtyOnSource; if (huStorageFrom != null) { final BigDecimal storageQty = huStorageFrom.getQty(requestProductId, uomToUse); final BigDecimal qtyUnloaded = request.getQtyUnloaded(); // // Treat the case where the transfer does nothing if (storageQty == null || qtyUnloaded == null)
{ existingStorageQtyOnSource = BigDecimal.ONE; } else { existingStorageQtyOnSource = storageQty // // Subtract qty already unloaded (at the moment of the attribute transfer, the trxLines are not processed, so the ProductStorage changes are not persisted yet) // .subtract(qtyUnloaded); } } else { existingStorageQtyOnSource = requestQty; // no HU storage => transfer all (TODO check if this adds inconsistencies to overall calculation) } if (existingStorageQtyOnSource == null || existingStorageQtyOnSource.signum() <= 0) { return BigDecimal.ZERO; } // // Do not use math context; instead, force a high scale and rounding mode to get the lowest possible error for the ratio final int scale = 12; final RoundingMode roundingMode = RoundingMode.HALF_UP; final BigDecimal transferRatio = requestQty.divide(existingStorageQtyOnSource, scale, roundingMode); return transferRatio; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\RedistributeQtyHUAttributeTransferStrategy.java
1
请完成以下Java代码
public int getGL_JournalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Manuell. @param IsManual This is a manual process */ @Override public void setIsManual (boolean IsManual) { set_ValueNoCheck (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return This is a manual process */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ @Override public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); }
/** Set Steuerbetrag. @param TaxAmt Tax Amount for a document */ @Override public void setTaxAmt (java.math.BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Steuerbetrag. @return Tax Amount for a document */ @Override public java.math.BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Bezugswert. @param TaxBaseAmt Base for calculating the tax amount */ @Override public void setTaxBaseAmt (java.math.BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } /** Get Bezugswert. @return Base for calculating the tax amount */ @Override public java.math.BigDecimal getTaxBaseAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxBaseAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationLine.java
1
请在Spring Boot框架中完成以下Java代码
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 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 String getAuthCode() { return authCode; } public void setAuthCode(String authCode) { this.authCode = authCode; } @Override public String toString() { return "F2FPayRequestBo{" + "payKey='" + payKey + '\'' + ", authCode='" + authCode + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\F2FPayRequestBo.java
2
请完成以下Java代码
public void printTargetLabel(@NonNull final HUConsolidationJobId jobId, @NotNull final UserId callerId) { final HUConsolidationJob job = jobRepository.getById(jobId); final HUConsolidationTarget currentTarget = job.getCurrentTargetNotNull(); labelPrinter.printLabel(currentTarget); } public HUConsolidationJob consolidate(@NonNull final ConsolidateRequest request) { return ConsolidateCommand.builder() .jobRepository(jobRepository) .huQRCodesService(huQRCodesService) .pickingSlotService(pickingSlotService) .request(request) .build()
.execute(); } public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId) { return GetPickingSlotContentCommand.builder() .jobRepository(jobRepository) .huQRCodesService(huQRCodesService) .pickingSlotService(pickingSlotService) .jobId(jobId) .pickingSlotId(pickingSlotId) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobService.java
1
请完成以下Java代码
public void setParamName (String ParamName) { set_Value (COLUMNNAME_ParamName, ParamName); } /** Get Parameter-Name. @return Parameter-Name */ public String getParamName () { return (String)get_Value(COLUMNNAME_ParamName); } /** Set Parameterwert. @param ParamValue Parameterwert */ public void setParamValue (String ParamValue) { set_Value (COLUMNNAME_ParamValue, ParamValue); } /** Get Parameterwert. @return Parameterwert */ public String getParamValue () {
return (String)get_Value(COLUMNNAME_ParamValue); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_Impex_ConnectorParam.java
1
请完成以下Java代码
public class C_Invoice_Candidate_Order_FacetCollector extends SingleFacetCategoryCollectorTemplate<I_C_Invoice_Candidate> { public C_Invoice_Candidate_Order_FacetCollector() { super(FacetCategory.builder() .setDisplayName(Services.get(IMsgBL.class).translate(Env.getCtx(), I_C_Invoice_Candidate.COLUMNNAME_C_Order_ID, true) + " / " + Services.get(IMsgBL.class).translate(Env.getCtx(), I_C_Invoice_Candidate.COLUMNNAME_C_Order_ID, false)) .setCollapsed(true) // 08755: default collapsed .build()); } @Override protected List<IFacet<I_C_Invoice_Candidate>> collectFacets(final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder) { // FRESH-560: Add default filter final IQueryBuilder<I_C_Invoice_Candidate> queryBuilderWithDefaultFilters = Services.get(IInvoiceCandDAO.class).applyDefaultFilter(queryBuilder); final List<Map<String, Object>> orders = queryBuilderWithDefaultFilters .andCollect(I_C_Invoice_Candidate.COLUMN_C_Order_ID) .create() .listDistinct(I_C_Order.COLUMNNAME_C_Order_ID, I_C_Order.COLUMNNAME_DocumentNo); final List<IFacet<I_C_Invoice_Candidate>> facets = new ArrayList<>(orders.size()); for (final Map<String, Object> row : orders) { final IFacet<I_C_Invoice_Candidate> facet = createFacet(row); facets.add(facet); } return facets; }
private IFacet<I_C_Invoice_Candidate> createFacet(final Map<String, Object> row) { final IFacetCategory facetCategoryOrders = getFacetCategory(); final int orderId = (int)row.get(I_C_Order.COLUMNNAME_C_Order_ID); final String documentNo = (String)row.get(I_C_Order.COLUMNNAME_DocumentNo); return Facet.<I_C_Invoice_Candidate> builder() .setFacetCategory(facetCategoryOrders) .setDisplayName(documentNo) .setFilter(TypedSqlQueryFilter.of(I_C_Invoice_Candidate.COLUMNNAME_C_Order_ID + "=" + orderId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\facet\impl\C_Invoice_Candidate_Order_FacetCollector.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { final I_C_Order order = context.getSelectedModel(I_C_Order.class); if (order == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no order"); } // Make sure this feature is enabled (sysconfig) if (!sysConfigBL.getBooleanValue(SYSCONFIG_EnableProcessGear, false, order.getAD_Client_ID(), order.getAD_Org_ID())) { return ProcessPreconditionsResolution.rejectWithInternalReason("not enabled"); } // Only completed/closed orders
if (!docActionBL.isDocumentCompletedOrClosed(order)) { logger.debug("{} has DocStatus={}; nothing to do", new Object[] { order, order.getDocStatus() }); return ProcessPreconditionsResolution.reject("only completed/closed orders are allowed"); } // Only eligible orders if (!orderCheckupBL.isEligibleForReporting(order)) { return ProcessPreconditionsResolution.reject("not eligible for reporting"); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\process\C_Order_MFGWarehouse_Report_Generate.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(idStr); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof StringDocumentId)) { return false; } final StringDocumentId other = (StringDocumentId)obj; return Objects.equals(idStr, other.idStr); } @Override public boolean isInt() { return false; } @Override public int toInt() { if (isComposedKey()) { throw new AdempiereException("Composed keys cannot be converted to int: " + this); } else { throw new AdempiereException("String document IDs cannot be converted to int: " + this); } }
@Override public boolean isNew() { return false; } @Override public boolean isComposedKey() { return idStr.contains(COMPOSED_KEY_SEPARATOR); } @Override public List<Object> toComposedKeyParts() { final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder(); COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add); return composedKeyParts.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java
1
请在Spring Boot框架中完成以下Java代码
public class DbConfig { @Autowired private Environment env; @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("driverClassName")); dataSource.setUrl(env.getProperty("url")); dataSource.setUsername(env.getProperty("user")); dataSource.setPassword(env.getProperty("password")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.books.models" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); if (env.getProperty("hibernate.hbm2ddl.auto") != null) { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); } if (env.getProperty("hibernate.dialect") != null) { hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); } if (env.getProperty("hibernate.show_sql") != null) { hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); } return hibernateProperties; } }
@Configuration @Profile("h2") @PropertySource("classpath:persistence-h2.properties") class H2Config { } @Configuration @Profile("hsqldb") @PropertySource("classpath:persistence-hsqldb.properties") class HsqldbConfig { } @Configuration @Profile("derby") @PropertySource("classpath:persistence-derby.properties") class DerbyConfig { } @Configuration @Profile("sqlite") @PropertySource("classpath:persistence-sqlite.properties") class SqliteConfig { }
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\books\config\DbConfig.java
2
请完成以下Java代码
public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setC_BP_PrintFormat_ID (final int C_BP_PrintFormat_ID) { if (C_BP_PrintFormat_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, C_BP_PrintFormat_ID); } @Override public int getC_BP_PrintFormat_ID() { return get_ValueAsInt(COLUMNNAME_C_BP_PrintFormat_ID); } @Override public void setC_DocType_ID (final int C_DocType_ID) {
if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID); } @Override public int getC_DocType_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_ID); } @Override public void setDocumentCopies_Override (final int DocumentCopies_Override) { set_Value (COLUMNNAME_DocumentCopies_Override, DocumentCopies_Override); } @Override public int getDocumentCopies_Override() { return get_ValueAsInt(COLUMNNAME_DocumentCopies_Override); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_PrintFormat.java
1
请完成以下Java代码
public class CachePurgeReport implements PurgeReporting<Set<String>> { public static final String PROCESS_DEF_CACHE = "PROC_DEF_CACHE"; public static final String BPMN_MODEL_INST_CACHE = "BPMN_MODEL_INST_CACHE"; public static final String CASE_DEF_CACHE = "CASE_DEF_CACHE"; public static final String CASE_MODEL_INST_CACHE = "CASE_MODEL_INST_CACHE"; public static final String DMN_DEF_CACHE = "DMN_DEF_CACHE"; public static final String DMN_REQ_DEF_CACHE = "DMN_REQ_DEF_CACHE"; public static final String DMN_MODEL_INST_CACHE = "DMN_MODEL_INST_CACHE"; /** * Key: cache name * Value: values */ Map<String, Set<String>> deletedCache = new HashMap<String, Set<String>>(); @Override public void addPurgeInformation(String key, Set<String> value) { deletedCache.put(key, new HashSet<String>(value)); } @Override public Map<String, Set<String>> getPurgeReport() { return deletedCache; } @Override public String getPurgeReportAsString() { StringBuilder builder = new StringBuilder(); for (String key : deletedCache.keySet()) { builder.append("Cache: ").append(key) .append(" contains: ").append(getReportValue(key)) .append("\n");
} return builder.toString(); } @Override public Set<String> getReportValue(String key) { return deletedCache.get(key); } @Override public boolean containsReport(String key) { return deletedCache.containsKey(key); } public boolean isEmpty() { return deletedCache.isEmpty(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CachePurgeReport.java
1
请完成以下Java代码
public void setType (java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */
@Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_Log.java
1
请完成以下Java代码
public void setConfigSummary (final @Nullable java.lang.String ConfigSummary) { set_Value (COLUMNNAME_ConfigSummary, ConfigSummary); } @Override public java.lang.String getConfigSummary() { return get_ValueAsString(COLUMNNAME_ConfigSummary); } @Override public void setDhl_ShipmentOrder_Log_ID (final int Dhl_ShipmentOrder_Log_ID) { if (Dhl_ShipmentOrder_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Dhl_ShipmentOrder_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Dhl_ShipmentOrder_Log_ID, Dhl_ShipmentOrder_Log_ID); } @Override public int getDhl_ShipmentOrder_Log_ID() { return get_ValueAsInt(COLUMNNAME_Dhl_ShipmentOrder_Log_ID); } @Override public de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest getDHL_ShipmentOrderRequest() { return get_ValueAsPO(COLUMNNAME_DHL_ShipmentOrderRequest_ID, de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest.class); } @Override public void setDHL_ShipmentOrderRequest(final de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest DHL_ShipmentOrderRequest) { set_ValueFromPO(COLUMNNAME_DHL_ShipmentOrderRequest_ID, de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest.class, DHL_ShipmentOrderRequest); } @Override public void setDHL_ShipmentOrderRequest_ID (final int DHL_ShipmentOrderRequest_ID) { if (DHL_ShipmentOrderRequest_ID < 1) set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, null); else set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, DHL_ShipmentOrderRequest_ID); } @Override public int getDHL_ShipmentOrderRequest_ID() { return get_ValueAsInt(COLUMNNAME_DHL_ShipmentOrderRequest_ID); } @Override public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override
public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setRequestMessage (final @Nullable java.lang.String RequestMessage) { set_Value (COLUMNNAME_RequestMessage, RequestMessage); } @Override public java.lang.String getRequestMessage() { return get_ValueAsString(COLUMNNAME_RequestMessage); } @Override public void setResponseMessage (final @Nullable java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } @Override public java.lang.String getResponseMessage() { return get_ValueAsString(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_Dhl_ShipmentOrder_Log.java
1
请完成以下Java代码
public Set<MachineInfo> getMachines() { return new HashSet<>(machines); } @Override public String toString() { return "AppInfo{" + "app='" + app + ", machines=" + machines + '}'; } public boolean addMachine(MachineInfo machineInfo) { machines.remove(machineInfo); return machines.add(machineInfo); } public synchronized boolean removeMachine(String ip, int port) { Iterator<MachineInfo> it = machines.iterator(); while (it.hasNext()) { MachineInfo machine = it.next(); if (machine.getIp().equals(ip) && machine.getPort() == port) { it.remove(); return true; } } return false; } public Optional<MachineInfo> getMachine(String ip, int port) { return machines.stream() .filter(e -> e.getIp().equals(ip) && e.getPort().equals(port)) .findFirst(); } private boolean heartbeatJudge(final int threshold) { if (machines.size() == 0) { return false; } if (threshold > 0) {
long healthyCount = machines.stream() .filter(MachineInfo::isHealthy) .count(); if (healthyCount == 0) { // No healthy machines. return machines.stream() .max(Comparator.comparingLong(MachineInfo::getLastHeartbeat)) .map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold) .orElse(false); } } return true; } /** * Check whether current application has no healthy machines and should not be displayed. * * @return true if the application should be displayed in the sidebar, otherwise false */ public boolean isShown() { return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis()); } /** * Check whether current application has no healthy machines and should be removed. * * @return true if the application is dead and should be removed, otherwise false */ public boolean isDead() { return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis()); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\AppInfo.java
1
请完成以下Java代码
public String getSystemName() { return systemName; } @Override public String getUserFriendlyName() { return userFriendlyName; } @Override public String getDefaultValue() { return defaultValue; } @Override public String getValue()
{ return value; } @Override public void setValue(String value) { this.value = value; } @Override public String toString() { return "DeviceConfigParamPojo [systemName=" + systemName + ", userFriendlyName=" + userFriendlyName + ", defaultValue=" + defaultValue + ", value=" + value + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\util\DeviceConfigParam.java
1
请完成以下Java代码
public static MActivity get(Properties ctx, int C_Activity_ID) { if (C_Activity_ID <= 0) { return null; } // Try cache MActivity activity = s_cache.get(C_Activity_ID); if (activity != null) { return activity; } // Load from DB activity = new MActivity(ctx, C_Activity_ID, null); if (activity.get_ID() == C_Activity_ID) { s_cache.put(C_Activity_ID, activity); } else { activity = null; } return activity; } /** * Standard Constructor * @param ctx context * @param C_Activity_ID id * @param trxName transaction */ public MActivity (Properties ctx, int C_Activity_ID, String trxName) { super (ctx, C_Activity_ID, trxName); } // MActivity /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MActivity (Properties ctx, ResultSet rs, String trxName)
{ super(ctx, rs, trxName); } // MActivity /** * After Save. * Insert * - create tree * @param newRecord insert * @param success save success * @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (newRecord) insert_Tree(MTree_Base.TREETYPE_Activity); // Value/Name change if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) MAccount.updateValueDescription(getCtx(), "C_Activity_ID=" + getC_Activity_ID(), get_TrxName()); return true; } // afterSave /** * After Delete * @param success * @return deleted */ protected boolean afterDelete (boolean success) { if (success) delete_Tree(MTree_Base.TREETYPE_Activity); return success; } // afterDelete } // MActivity
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MActivity.java
1
请完成以下Java代码
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 Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info
*/ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Reply. @param Reply Reply or Answer */ public void setReply (String Reply) { set_Value (COLUMNNAME_Reply, Reply); } /** Get Reply. @return Reply or Answer */ public String getReply () { return (String)get_Value(COLUMNNAME_Reply); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AccessLog.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public void setDeploymentIds(List<String> deploymentIds) { this.deploymentIds = deploymentIds; } public String getActiveActivityId() { return activeActivityId; } public void setActiveActivityId(String activeActivityId) { this.activeActivityId = activeActivityId; } public Set<String> getActiveActivityIds() { return activeActivityIds; } public void setActiveActivityIds(Set<String> activeActivityIds) { this.activeActivityIds = activeActivityIds; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public String getLocale() { return locale; }
public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public String getCallbackId() { return callbackId; } public Set<String> getCallBackIds() { return callbackIds; } public String getCallbackType() { return callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public List<ExecutionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return null; } public String getParentScopeId() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public EventBasedGateway newInstance(ModelTypeInstanceContext instanceContext) { return new EventBasedGatewayImpl(instanceContext); } }); instantiateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_INSTANTIATE) .defaultValue(false) .build(); eventGatewayTypeAttribute = typeBuilder.enumAttribute(BPMN_ATTRIBUTE_EVENT_GATEWAY_TYPE, EventBasedGatewayType.class) .defaultValue(EventBasedGatewayType.Exclusive) .build(); typeBuilder.build(); } public EventBasedGatewayImpl(ModelTypeInstanceContext context) { super(context); } @Override public EventBasedGatewayBuilder builder() { return new EventBasedGatewayBuilder((BpmnModelInstance) modelInstance, this); } public boolean isInstantiate() { return instantiateAttribute.getValue(this); }
public void setInstantiate(boolean isInstantiate) { instantiateAttribute.setValue(this, isInstantiate); } public EventBasedGatewayType getEventGatewayType() { return eventGatewayTypeAttribute.getValue(this); } public void setEventGatewayType(EventBasedGatewayType eventGatewayType) { eventGatewayTypeAttribute.setValue(this, eventGatewayType); } @Override public boolean isCamundaAsyncAfter() { throw new UnsupportedOperationException("'asyncAfter' is not supported for 'Event Based Gateway'"); } @Override public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) { throw new UnsupportedOperationException("'asyncAfter' is not supported for 'Event Based Gateway'"); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\EventBasedGatewayImpl.java
1
请完成以下Java代码
public static MoneySourceAndAcct ofSourceAndAcct(@NonNull final Money source, @NonNull final Money acct) { return new MoneySourceAndAcct(source, acct); } public String toString() { return source + "/" + acct; } public int signum() {return source.signum();} public CurrencyId getSourceCurrencyId() {return source.getCurrencyId();} private MoneySourceAndAcct newOfSourceAndAcct(@NonNull final Money newSource, @NonNull final Money newAcct) { if (Money.equals(this.source, newSource) && Money.equals(this.acct, newAcct)) { return this; } return ofSourceAndAcct(newSource, newAcct); } public MoneySourceAndAcct divide(@NonNull final MoneySourceAndAcct divisor, @NonNull final CurrencyPrecision precision) { return newOfSourceAndAcct(source.divide(divisor.source, precision), acct.divide(divisor.acct, precision)); }
public MoneySourceAndAcct multiply(@NonNull final BigDecimal multiplicand) { return newOfSourceAndAcct(source.multiply(multiplicand), acct.multiply(multiplicand)); } public MoneySourceAndAcct negate() { return newOfSourceAndAcct(source.negate(), acct.negate()); } public MoneySourceAndAcct negateIf(final boolean condition) { return condition ? negate() : this; } public MoneySourceAndAcct toZero() { return newOfSourceAndAcct(source.toZero(), acct.toZero()); } public MoneySourceAndAcct roundIfNeeded(@NonNull final CurrencyPrecision sourcePrecision, @NonNull final CurrencyPrecision acctPrecision) { return newOfSourceAndAcct(source.roundIfNeeded(sourcePrecision), acct.roundIfNeeded(acctPrecision)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\MoneySourceAndAcct.java
1
请完成以下Java代码
DancingNode hookRight(DancingNode node) { node.R = this.R; node.R.L = node; node.L = this; this.R = node; return node; } void unlinkLR() { this.L.R = this.R; this.R.L = this.L; } void relinkLR() { this.L.R = this.R.L = this; }
void unlinkUD() { this.U.D = this.D; this.D.U = this.U; } void relinkUD() { this.U.D = this.D.U = this; } DancingNode() { L = R = U = D = this; } DancingNode(ColumnNode c) { this(); C = c; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\DancingNode.java
1
请在Spring Boot框架中完成以下Java代码
private void handleFutureSync(Tuple2<String, CompletableFuture<Void>> t, Set<String> failedSet) { try { t.r2.get(10, TimeUnit.SECONDS); } catch (Exception ex) { if (ex instanceof ExecutionException) { LOGGER.error("Request for <{}> failed", t.r1, ex.getCause()); } else { LOGGER.error("Request for <{}> failed", t.r1, ex); } failedSet.add(t.r1); } } private CompletableFuture<Void> applyServerConfigChange(String app, String ip, int commandPort, ClusterAppAssignMap assignMap) { ServerTransportConfig transportConfig = new ServerTransportConfig() .setPort(assignMap.getPort()) .setIdleSeconds(600); return sentinelApiClient.modifyClusterServerTransportConfig(app, ip, commandPort, transportConfig) .thenCompose(v -> applyServerFlowConfigChange(app, ip, commandPort, assignMap)) .thenCompose(v -> applyServerNamespaceSetConfig(app, ip, commandPort, assignMap)); } private CompletableFuture<Void> applyServerFlowConfigChange(String app, String ip, int commandPort, ClusterAppAssignMap assignMap) { Double maxAllowedQps = assignMap.getMaxAllowedQps(); if (maxAllowedQps == null || maxAllowedQps <= 0 || maxAllowedQps > 20_0000) { return CompletableFuture.completedFuture(null); } return sentinelApiClient.modifyClusterServerFlowConfig(app, ip, commandPort, new ServerFlowConfig().setMaxAllowedQps(maxAllowedQps)); } private CompletableFuture<Void> applyServerNamespaceSetConfig(String app, String ip, int commandPort, ClusterAppAssignMap assignMap) {
Set<String> namespaceSet = assignMap.getNamespaceSet(); if (namespaceSet == null || namespaceSet.isEmpty()) { return CompletableFuture.completedFuture(null); } return sentinelApiClient.modifyClusterServerNamespaceSet(app, ip, commandPort, namespaceSet); } private CompletableFuture<Void> modifyMode(String ip, int port, int mode) { return sentinelApiClient.modifyClusterMode(ip, port, mode); } private int parsePort(ClusterAppAssignMap assignMap) { return MachineUtils.parseCommandPort(assignMap.getMachineId()) .orElse(ServerTransportConfig.DEFAULT_PORT); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\service\ClusterAssignServiceImpl.java
2
请完成以下Java代码
public Quantity getQtyInternalUse() { assertInternalUseInventory(); return qtyInternalUse; } public Quantity getQtyCount() { assertPhysicalInventory(); return qtyCount; } public Quantity getQtyBook() { assertPhysicalInventory(); return qtyBook; } public Quantity getQtyCountMinusBooked() { return getQtyCount().subtract(getQtyBook()); } /** * @param qtyCountToAdd needs to have the same UOM as this instance's current qtyCount. */ public InventoryLineHU withAddingQtyCount(@NonNull final Quantity qtyCountToAdd) { return withQtyCount(getQtyCount().add(qtyCountToAdd)); } public InventoryLineHU withZeroQtyCount() { return withQtyCount(getQtyCount().toZero()); } public InventoryLineHU withQtyCount(@NonNull final Quantity newQtyCount) { assertPhysicalInventory(); return toBuilder().qtyCount(newQtyCount).build(); } public static ImmutableSet<HuId> extractHuIds(@NonNull final Collection<InventoryLineHU> lineHUs) { return extractHuIds(lineHUs.stream()); } static ImmutableSet<HuId> extractHuIds(@NonNull final Stream<InventoryLineHU> lineHUs) { return lineHUs .map(InventoryLineHU::getHuId) .filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet()); } public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter) { return toBuilder() .qtyCount(qtyConverter.apply(getQtyCount())) .qtyBook(qtyConverter.apply(getQtyBook())) .build(); } public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request) { return toBuilder().updatingFrom(request).build(); } public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request) { return builder().updatingFrom(request).build(); } // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder { InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToDispose (final BigDecimal QtyToDispose) { set_Value (COLUMNNAME_QtyToDispose, QtyToDispose); } @Override public BigDecimal getQtyToDispose() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToDispose); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Inventory_Candidate.java
1
请在Spring Boot框架中完成以下Java代码
public class PrimaryDataSourceConfig { /** * 扫描spring.datasource.primary开头的配置信息 * * @return 数据源配置信息 */ @Primary @Bean(name = "primaryDataSourceProperties") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } /** * 获取主库数据源对象 * * @param dataSourceProperties 注入名为primaryDataSourceProperties的bean * @return 数据源对象
*/ @Primary @Bean(name = "primaryDataSource") public DataSource dataSource(@Qualifier("primaryDataSourceProperties") DataSourceProperties dataSourceProperties) { return dataSourceProperties.initializeDataSourceBuilder().build(); } /** * 该方法仅在需要使用JdbcTemplate对象时选用 * * @param dataSource 注入名为primaryDataSource的bean * @return 数据源JdbcTemplate对象 */ @Primary @Bean(name = "primaryJdbcTemplate") public JdbcTemplate jdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) { return new JdbcTemplate(dataSource); } }
repos\spring-boot-demo-master\demo-multi-datasource-jpa\src\main\java\com\xkcoding\multi\datasource\jpa\config\PrimaryDataSourceConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class OrderFilterProcessor implements Processor { protected Logger log = LoggerFactory.getLogger(getClass()); @Override public void process(Exchange exchange) throws Exception { log.info("Filter order by state"); final EbayImportOrdersRouteContext importOrdersRouteContext = getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_ORDERS_CONTEXT, EbayImportOrdersRouteContext.class); final Order order = exchange.getIn().getBody(Order.class); if (order == null) { throw new RuntimeException("Empty body!"); } log.debug("Checking order {} for further steps", order.getOrderId()); //only import new orders. if( OrderFulfillmentStatus.NOT_STARTED.name().equalsIgnoreCase(order.getOrderFulfillmentStatus()) ) { importOrdersRouteContext.setOrder(order); exchange.getIn().setBody(order); //remember order TS for future calls. LocalDate created = order.getCreationDate() != null ? EbayUtils.toLocalDate(order.getCreationDate()) : null;
if(created != null) { importOrdersRouteContext.setNextImportStartingTimestamp(DateAndImportStatus.of(true, created.atStartOfDay(ZoneId.systemDefault()).toInstant())); } } else { // order was filtered exchange.getIn().setBody(null); //remember order TS for future calls. LocalDate created = order.getCreationDate() != null ? EbayUtils.toLocalDate(order.getCreationDate()) : null; if(created != null) { importOrdersRouteContext.setNextImportStartingTimestamp(DateAndImportStatus.of(true, created.atStartOfDay(ZoneId.systemDefault()).toInstant())); } } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\order\OrderFilterProcessor.java
2
请完成以下Java代码
public class GenericFile { private String name; private String extension; private Date dateCreated; private String version; private byte[] content; public GenericFile() { this.setDateCreated(new Date()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } public Date getDateCreated() { return dateCreated;
} public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getFileInfo() { return "Generic File Impl"; } public Object read() { return content; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\polymorphism\GenericFile.java
1
请完成以下Java代码
public void destroyDB() throws SQLException { String destroy = "DROP table IF EXISTS CUSTOMER"; connection.prepareStatement(destroy) .execute(); connection.close(); } public void inefficientUsage() throws SQLException { for (int i = 0; i < 10000; i++) { PreparedStatement preparedStatement = connection.prepareStatement(SQL); preparedStatement.setInt(1, i); preparedStatement.setString(2, "firstname" + i); preparedStatement.setString(3, "secondname" + i); preparedStatement.executeUpdate(); preparedStatement.close(); } } public void betterUsage() { try (PreparedStatement preparedStatement = connection.prepareStatement(SQL)) { for (int i = 0; i < 10000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "firstname" + i); preparedStatement.setString(3, "secondname" + i); preparedStatement.executeUpdate(); } } catch (SQLException e) { throw new RuntimeException(e); } } public void bestUsage() { try (PreparedStatement preparedStatement = connection.prepareStatement(SQL)) { connection.setAutoCommit(false); for (int i = 0; i < 10000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "firstname" + i); preparedStatement.setString(3, "secondname" + i); preparedStatement.addBatch();
} preparedStatement.executeBatch(); try { connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } } catch (SQLException e) { throw new RuntimeException(e); } } public int checkRowCount() { try (PreparedStatement counter = connection.prepareStatement("SELECT COUNT(*) AS customers FROM CUSTOMER")) { ResultSet resultSet = counter.executeQuery(); resultSet.next(); int count = resultSet.getInt("customers"); resultSet.close(); return count; } catch (SQLException e) { return -1; } } }
repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\resusepreparedstatement\ReusePreparedStatement.java
1
请完成以下Java代码
public class JsonDeserializeBenchmark { /** * 反序列化次数参数 */ @Param({"1000", "10000", "100000"}) private int count; private String jsonStr; public static void main(String[] args) throws Exception { Options opt = new OptionsBuilder() .include(JsonDeserializeBenchmark.class.getSimpleName()) .forks(1) .warmupIterations(0) .build(); Collection<RunResult> results = new Runner(opt).run(); ResultExporter.exportResult("JSON反序列化性能", results, "count", "秒"); } @Benchmark public void JsonLib() { for (int i = 0; i < count; i++) { JsonLibUtil.json2Bean(jsonStr, Person.class); } } @Benchmark public void Gson() { for (int i = 0; i < count; i++) { GsonUtil.json2Bean(jsonStr, Person.class); } } @Benchmark public void FastJson() { for (int i = 0; i < count; i++) { FastJsonUtil.json2Bean(jsonStr, Person.class); } }
@Benchmark public void Jackson() { for (int i = 0; i < count; i++) { JacksonUtil.json2Bean(jsonStr, Person.class); } } @Setup public void prepare() { jsonStr="{\"name\":\"邵同学\",\"fullName\":{\"firstName\":\"zjj_first\",\"middleName\":\"zjj_middle\",\"lastName\":\"zjj_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":[{\"name\":\"小明\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"Tony\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"陈小二\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null}]}"; } @TearDown public void shutdown() { } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\JsonDeserializeBenchmark.java
1
请在Spring Boot框架中完成以下Java代码
public Job job1(Step step1, Step step2) { return new JobBuilder("job1", jobRepository).incrementer(new RunIdIncrementer()) .start(step1) .next(step2) .build(); } @Bean public Step step1() { return new StepBuilder("job1step1", jobRepository).tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { LOGGER.info("Tasklet has run"); return RepeatStatus.FINISHED; } }, transactionManager) .build(); } @Bean public Step step2() { return new StepBuilder("job1step2", jobRepository).<String, String> chunk(3, transactionManager) .reader(new ListItemReader<>(Arrays.asList("7", "2", "3", "10", "5", "6"))) .processor(new ItemProcessor<String, String>() { @Override public String process(String item) throws Exception { LOGGER.info("Processing of chunks"); return String.valueOf(Integer.parseInt(item) * -1); } }) .writer(new ItemWriter<String>() { @Override public void write(Chunk<? extends String> items) throws Exception { for (String item : items) { LOGGER.info(">> " + item); } } }) .build(); }
@Bean public Job job2(Step job2step1) { return new JobBuilder("job2", jobRepository).incrementer(new RunIdIncrementer()) .start(job2step1) .build(); } @Bean public Step job2step1() { return new StepBuilder("job2step1", jobRepository).tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { LOGGER.info("This job is from Baeldung"); return RepeatStatus.FINISHED; } }, transactionManager) .build(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-task\springcloudtaskbatch\src\main\java\com\baeldung\task\JobConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
class SyncContractListImportService extends AbstractSyncImportService { private final ContractRepository contractsRepo; private final SyncContractImportService contractsImportService; public SyncContractListImportService( @NonNull final ContractRepository contractsRepo, @NonNull final SyncContractImportService contractsImportService) { this.contractsRepo = contractsRepo; this.contractsImportService = contractsImportService; } public void importContracts(final BPartner bpartner, final List<SyncContract> syncContracts) { final Map<String, Contract> contracts = mapByUuid(contractsRepo.findByBpartnerAndDeletedFalse(bpartner)); final List<Entry<SyncContract, Contract>> contractsToImport = new ArrayList<>(); for (final SyncContract syncContract : syncContracts) { // If delete request, skip importing the contract. // As a result, if there is a contract for this sync-contract, it will be deleted below. if (syncContract.isDeleted()) { continue; } final Contract contract = contracts.remove(syncContract.getUuid()); contractsToImport.add(Maps.immutableEntry(syncContract, contract)); } // // Delete contracts for (final Contract contract : contracts.values()) { try
{ contractsImportService.deleteContract(contract); } catch (final Exception ex) { logger.error("Failed deleting contract {}. Ignored.", contract, ex); } } // // Import contracts for (final Entry<SyncContract, Contract> e : contractsToImport) { final SyncContract syncContract = e.getKey(); final Contract contract = e.getValue(); try { contractsImportService.importContract(bpartner, syncContract, contract); } catch (final Exception ex) { logger.error("Failed importing contract {} for {}. Skipped.", contract, bpartner, ex); } } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncContractListImportService.java
2
请在Spring Boot框架中完成以下Java代码
public class PublicApplicationController { static final String ENDPOINT = MetasfreshRestAPIConstants.ENDPOINT_API_V2 + "/public/mobile"; private static final String MSG_PREFIX = "mobileui.frontend."; private final IMsgBL msgBL = Services.get(IMsgBL.class); private final MobileConfigService configService; public PublicApplicationController( @NonNull final MobileConfigService configService, @NonNull final UserAuthTokenFilterConfiguration userAuthTokenFilterConfiguration) { this.configService = configService; userAuthTokenFilterConfiguration.addAuthResolutionForPathsContaining(ENDPOINT, AuthResolution.AUTHENTICATE_IF_TOKEN_AVAILABLE); } @GetMapping("/config") public JsonMobileConfigResponse getConfig() { final MobileConfig config = configService.getConfig().orElse(MobileConfig.DEFAULT); return JsonMobileConfigResponse.builder()
.defaultAuthMethod(config.getDefaultAuthMethod()) .availableAuthMethods(MobileAuthMethod.all()) .build(); } @GetMapping("/messages") public JsonMessages getMessages( @RequestParam(name = "lang", required = false) @Nullable final String adLanguageParam) { final String adLanguage = StringUtils.trimBlankToOptional(adLanguageParam).orElseGet(Env::getADLanguageOrBaseLanguage); return msgBL.messagesTree() .adMessagePrefix(MSG_PREFIX) .removePrefix(true) .load(adLanguage) .toJson(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\mobile\PublicApplicationController.java
2
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(TEMPLATE_KEY); } @Override public GatewayFilter apply(Config config) { String template = Objects.requireNonNull(config.template, "template must not be null"); UriTemplate uriTemplate = new UriTemplate(template); return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest req = exchange.getRequest(); addOriginalRequestUrl(exchange, req.getURI()); Map<String, String> uriVariables = getUriTemplateVariables(exchange); URI uri = uriTemplate.expand(uriVariables); String newPath = uri.getRawPath(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri); ServerHttpRequest request = req.mutate().path(newPath).build(); return chain.filter(exchange.mutate().request(request).build()); }
@Override public String toString() { return filterToStringCreator(SetPathGatewayFilterFactory.this).append("template", config.getTemplate()) .toString(); } }; } public static class Config { private @Nullable String template; public @Nullable String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetPathGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public List<HistoricIdentityLinkEntity> getQueryIdentityLinks() { if (queryIdentityLinks == null) { queryIdentityLinks = new LinkedList<>(); } return queryIdentityLinks; } public void setQueryIdentityLinks(List<HistoricIdentityLinkEntity> identityLinks) { queryIdentityLinks = identityLinks; } protected TaskServiceConfiguration getTaskServiceConfiguration() { return (TaskServiceConfiguration) getTaskEngineConfiguration().getServiceConfigurations().get(EngineConfigurationConstants.KEY_TASK_SERVICE_CONFIG); } protected IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() { return (IdentityLinkServiceConfiguration) getTaskEngineConfiguration().getServiceConfigurations().get(EngineConfigurationConstants.KEY_IDENTITY_LINK_SERVICE_CONFIG); } protected AbstractEngineConfiguration getTaskEngineConfiguration() { Map<String, AbstractEngineConfiguration> engineConfigurations = CommandContextUtil.getCommandContext().getEngineConfigurations(); AbstractEngineConfiguration engineConfiguration = null; if (ScopeTypes.CMMN.equals(scopeType)) { engineConfiguration = engineConfigurations.get(EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG); } else { engineConfiguration = engineConfigurations.get(EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); if (engineConfiguration == null) { engineConfiguration = engineConfigurations.get(EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG); } }
return engineConfiguration; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("HistoricTaskInstanceEntity["); strb.append("id=").append(id); strb.append(", key=").append(taskDefinitionKey); if (executionId != null) { strb.append(", processInstanceId=").append(processInstanceId) .append(", executionId=").append(executionId) .append(", processDefinitionId=").append(processDefinitionId); } else if (scopeId != null) { strb.append(", scopeInstanceId=").append(scopeId) .append(", subScopeId=").append(subScopeId) .append(", scopeDefinitionId=").append(scopeDefinitionId); } strb.append("]"); return strb.toString(); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskInstanceEntityImpl.java
2
请完成以下Java代码
public void showPopup() { final JPopupMenu popup = getPopupMenu(); if (popup == null) { return; } final AbstractButton button = action.getButton(); if (button.isShowing()) { popup.show(button, 0, button.getHeight()); // below button } } private CMenuItem createProcessMenuItem(final SwingRelatedProcessDescriptor process, final String adLanguage) { final CMenuItem mi = new CMenuItem(process.getCaption(adLanguage)); mi.setIcon(process.getIcon()); mi.setToolTipText(process.getDescription(adLanguage)); if (process.isEnabled()) { mi.setEnabled(true); mi.addActionListener(event -> startProcess(process)); } else { mi.setEnabled(false);
mi.setToolTipText(process.getDisabledReason(adLanguage)); } return mi; } private void startProcess(final SwingRelatedProcessDescriptor process) { final String adLanguage = Env.getAD_Language(getCtx()); final VButton button = new VButton( "StartProcess", // columnName, false, // mandatory, false, // isReadOnly, true, // isUpdateable, process.getCaption(adLanguage), process.getDescription(adLanguage), process.getHelp(adLanguage), process.getAD_Process_ID()); // Invoke action parent.actionButton(button); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\AProcess.java
1
请完成以下Java代码
private List<DocumentLayoutElementLineDescriptor> buildElementLines() { return elementLinesBuilders .stream() .map(elementLinesBuilder -> elementLinesBuilder.build()) .collect(GuavaCollectors.toImmutableList()); } public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder setLayoutType(final LayoutType layoutType) { this.layoutType = layoutType; return this; } public Builder setLayoutType(final String layoutTypeStr) { layoutType = LayoutType.fromNullable(layoutTypeStr); return this; } public Builder setColumnCount(final int columnCount) { this.columnCount = CoalesceUtil.firstGreaterThanZero(columnCount, 1); return this; } public Builder addElementLine(@NonNull final DocumentLayoutElementLineDescriptor.Builder elementLineBuilder) { elementLinesBuilders.add(elementLineBuilder); return this;
} public Builder addElementLines(@NonNull final List<DocumentLayoutElementLineDescriptor.Builder> elementLineBuilders) { elementLinesBuilders.addAll(elementLineBuilders); return this; } public boolean hasElementLines() { return !elementLinesBuilders.isEmpty(); } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementLinesBuilders.stream().flatMap(DocumentLayoutElementLineDescriptor.Builder::streamElementBuilders); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementGroupDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getStatus() { return status; } public String getScopeId() { return scopeId; } public String getSubScopeId() { return subScopeId; } public String getScopeType() { return scopeType; } public String getTenantId() {
return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isCompleted() { return completed; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchPartQueryImpl.java
2
请完成以下Java代码
public void setQtyReceivedUOM(final I_C_UOM qtyReceivedUOM) { this.qtyReceivedUOM = qtyReceivedUOM; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } /** * This method does nothing! */ @Override public void add(final Object IGNORED) { } /** * This method returns the empty list. */ @Override
public List<Object> getModels() { return Collections.emptyList(); } @Override public I_M_PriceList_Version getPLV() { return plv; } public void setPlv(I_M_PriceList_Version plv) { this.plv = plv; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainVendorReceipt.java
1
请完成以下Java代码
record TitlesBoundedSumOfLikes(String titles, int boundedSumOfLikes) {}; public BlogPost(String title, String author, BlogPostType type, int likes) { this.title = title; this.author = author; this.type = type; this.likes = likes; } public String getTitle() { return title; } public String getAuthor() { return author;
} public BlogPostType getType() { return type; } public int getLikes() { return likes; } @Override public String toString() { return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}'; } }
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\groupingby\BlogPost.java
1
请在Spring Boot框架中完成以下Java代码
class JpaOrder { private String currencyUnit; @Id @GeneratedValue private Long id; @ElementCollection(fetch = FetchType.EAGER) private final List<JpaOrderLine> orderLines; private BigDecimal totalCost; JpaOrder() { totalCost = null; orderLines = new ArrayList<>(); } JpaOrder(List<JpaOrderLine> orderLines) { checkNotNull(orderLines); if (orderLines.isEmpty()) { throw new IllegalArgumentException("Order must have at least one order line item"); } this.orderLines = new ArrayList<>(orderLines); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } JpaOrder other = (JpaOrder) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public String toString() { return "JpaOrder [currencyUnit=" + currencyUnit + ", id=" + id + ", orderLines=" + orderLines + ", totalCost=" + totalCost + "]"; }
void addLineItem(JpaOrderLine orderLine) { checkNotNull(orderLine); orderLines.add(orderLine); } String getCurrencyUnit() { return currencyUnit; } Long getId() { return id; } List<JpaOrderLine> getOrderLines() { return new ArrayList<>(orderLines); } BigDecimal getTotalCost() { return totalCost; } void removeLineItem(int line) { orderLines.remove(line); } void setCurrencyUnit(String currencyUnit) { this.currencyUnit = currencyUnit; } void setTotalCost(BigDecimal totalCost) { this.totalCost = totalCost; } private static void checkNotNull(Object par) { if (par == null) { throw new NullPointerException("Parameter cannot be null"); } } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\jpa\JpaOrder.java
2
请完成以下Java代码
private Quantity extractQty(@NonNull final RemotePOSOrderLine remoteOrderLine) { return Quantitys.of(remoteOrderLine.getQty(), remoteOrderLine.getUomId()); } @Nullable private Quantity extractCatchWeight(final @NonNull RemotePOSOrderLine remoteOrderLine) { return remoteOrderLine.getCatchWeight() != null && remoteOrderLine.getCatchWeightUomId() != null ? Quantitys.of(remoteOrderLine.getCatchWeight(), remoteOrderLine.getCatchWeightUomId()) : null; } private Tax findTax(final POSOrder order, final TaxCategoryId taxCategoryId) { final TaxQuery taxQuery = TaxQuery.builder() .fromCountryId(order.getShipFrom().getCountryId()) .orgId(order.getShipFrom().getOrgId()) .bPartnerLocationId(order.getShipToCustomerAndLocationId()) .dateOfInterest(Timestamp.from(order.getDate())) .taxCategoryId(taxCategoryId) .soTrx(SOTrx.SALES) .build(); final Tax tax = taxDAO.getByIfPresent(taxQuery).orElseThrow(() -> TaxNotFoundException.ofQuery(taxQuery)); if (tax.isDocumentLevel()) { throw new AdempiereException("POS tax shall be all line level") .setParameter("tax", tax); } return tax; } private void createOrUpdatePaymentFromRemote(final RemotePOSPayment remotePayment)
{ order.createOrUpdatePayment(remotePayment.getUuid(), existingPayment -> { final Money amount = toMoney(currencyPrecision.round(remotePayment.getAmount())); if (existingPayment != null) { // don't update Check.assumeEquals(existingPayment.getPaymentMethod(), remotePayment.getPaymentMethod(), "paymentMethod"); Check.assumeEquals(existingPayment.getAmount(), amount, "amount"); return existingPayment; } else { return POSPayment.builder() .externalId(remotePayment.getUuid()) .paymentMethod(remotePayment.getPaymentMethod()) .amount(amount) .paymentProcessingStatus(POSPaymentProcessingStatus.NEW) .build(); } }); } private Money toMoney(final BigDecimal amount) { return Money.of(amount, order.getCurrencyId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderUpdateFromRemoteCommand.java
1
请完成以下Java代码
public final boolean isIncludeWhenIncompleteInOutExists() { return isIncludeWhenIncompleteInOutExists; } public final void setIncludeWhenIncompleteInOutExists(boolean isUnconfirmedInOut) { this.isIncludeWhenIncompleteInOutExists = isUnconfirmedInOut; } public final boolean isConsolidateDocument() { return consolidateDocument; } public final void setConsolidateDocument(boolean consolidateDocument) { this.consolidateDocument = consolidateDocument; } public final Timestamp getMovementDate() { return movementDate; } public final void setMovementDate(Timestamp dateShipped) { this.movementDate = dateShipped; } public final boolean isPreferBPartner() { return preferBPartner; }
public final void setPreferBPartner(boolean preferBPartner) { this.preferBPartner = preferBPartner; } public final boolean isIgnorePostageFreeamount() { return ignorePostageFreeamount; } public final void setIgnorePostageFreeamount(boolean ignorePostageFreeamount) { this.ignorePostageFreeamount = ignorePostageFreeamount; } public Set<Integer> getSelectedOrderLineIds() { return selectedOrderLineIds; } public void setSelectedOrderLineIds(Set<Integer> selectedOrderLineIds) { this.selectedOrderLineIds = selectedOrderLineIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\shipment\ShipmentParams.java
1
请完成以下Java代码
public class CmsTopicComment implements Serializable { private Long id; private String memberNickName; private Long topicId; private String memberIcon; private String content; private Date createTime; private Integer showStatus; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMemberNickName() { return memberNickName; } public void setMemberNickName(String memberNickName) { this.memberNickName = memberNickName; } public Long getTopicId() { return topicId; } public void setTopicId(Long topicId) { this.topicId = topicId; } public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public String getContent() { return content; } public void setContent(String content) { this.content = content; }
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberNickName=").append(memberNickName); sb.append(", topicId=").append(topicId); sb.append(", memberIcon=").append(memberIcon); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopicComment.java
1
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { if (!success) return success; final I_M_Product product = getProduct(); if(updateProductFromExpenseType(product, this)) { InterfaceWrapperHelper.save(product); } return success; } /** * Set Expense Type * * @param parent expense type * @return true if changed */ private static boolean updateProductFromExpenseType(final I_M_Product product, final I_S_ExpenseType parent) { boolean changed = false; if (!X_M_Product.PRODUCTTYPE_ExpenseType.equals(product.getProductType())) { product.setProductType(X_M_Product.PRODUCTTYPE_ExpenseType); changed = true; } if (parent.getS_ExpenseType_ID() != product.getS_ExpenseType_ID()) { product.setS_ExpenseType_ID(parent.getS_ExpenseType_ID()); changed = true; } if (parent.isActive() != product.isActive()) { product.setIsActive(parent.isActive());
changed = true; } // if (!parent.getValue().equals(product.getValue())) { product.setValue(parent.getValue()); changed = true; } if (!parent.getName().equals(product.getName())) { product.setName(parent.getName()); changed = true; } if ((parent.getDescription() == null && product.getDescription() != null) || (parent.getDescription() != null && !parent.getDescription().equals(product.getDescription()))) { product.setDescription(parent.getDescription()); changed = true; } if (parent.getC_UOM_ID() != product.getC_UOM_ID()) { product.setC_UOM_ID(parent.getC_UOM_ID()); changed = true; } if (parent.getM_Product_Category_ID() != product.getM_Product_Category_ID()) { product.setM_Product_Category_ID(parent.getM_Product_Category_ID()); changed = true; } // metas 05129 end return changed; } } // MExpenseType
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MExpenseType.java
1
请完成以下Java代码
public class DelegatingAppender<T> extends AppenderBase<T> { @SuppressWarnings("rawtypes") protected static final Appender DEFAULT_APPENDER = new NOPAppender<>(); protected static final String DEFAULT_NAME = "delegate"; public DelegatingAppender() { Optional.ofNullable(LoggerFactory.getILoggerFactory()) .filter(it -> Objects.isNull(DEFAULT_APPENDER.getContext())) .filter(Context.class::isInstance) .map(Context.class::cast) .ifPresent(DEFAULT_APPENDER::setContext); this.name = DEFAULT_NAME; } private volatile Appender<T> appender;
public void setAppender(Appender<T> appender) { this.appender = appender; } @SuppressWarnings("unchecked") protected Appender<T> getAppender() { Appender<T> configuredAppender = this.appender; return configuredAppender != null ? configuredAppender : DEFAULT_APPENDER; } @Override protected void append(T eventObject) { getAppender().doAppend(eventObject); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\DelegatingAppender.java
1
请完成以下Java代码
private AdWindowId getTargetWindowId() { return _targetWindowId; } @Override protected String doIt() throws Exception { final I_M_ReceiptSchedule receiptSchedule = getProcessInfo().getRecordIfApplies(I_M_ReceiptSchedule.class, ITrx.TRXNAME_ThreadInherited).orElse(null); final int emptiesInOutId; if (receiptSchedule == null) { emptiesInOutId = createDraftEmptiesDocument(); } else { final I_M_InOut emptiesInOut = huEmptiesService.createDraftEmptiesInOutFromReceiptSchedule(receiptSchedule, getReturnMovementType()); emptiesInOutId = emptiesInOut == null ? -1 : emptiesInOut.getM_InOut_ID(); } // // Notify frontend that the empties document shall be opened in single document layout (not grid) if (emptiesInOutId > 0) { getResult().setRecordToOpen(TableRecordReference.of(I_M_InOut.Table_Name, emptiesInOutId), getTargetWindowId(), OpenTarget.SingleDocument); } return MSG_OK;
} private int createDraftEmptiesDocument() { final DocumentPath documentPath = DocumentPath.builder() .setDocumentType(WindowId.of(getTargetWindowId())) .setDocumentId(DocumentId.NEW_ID_STRING) .allowNewDocumentId() .build(); final DocumentId documentId = documentsRepo.forDocumentWritable(documentPath, NullDocumentChangesCollector.instance, document -> { huEmptiesService.newReturnsInOutProducer(getCtx()) .setMovementType(getReturnMovementType()) .setMovementDate(de.metas.common.util.time.SystemTime.asDayTimestamp()) .fillReturnsInOutHeader(InterfaceWrapperHelper.create(document, I_M_InOut.class)); return document.getDocumentId(); }); return documentId.toInt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_CreateEmptiesReturns_Base.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer("WStore["); sb.append(getWebContext(true)) .append("]"); return sb.toString(); } // toString @Override protected boolean beforeSave(boolean newRecord) { // Context to start with / if (!getWebContext().startsWith("/")) setWebContext("/" + getWebContext()); // Org to Warehouse if (newRecord || is_ValueChanged("M_Warehouse_ID") || getAD_Org_ID() <= 0) { final I_M_Warehouse wh = Services.get(IWarehouseDAO.class).getById(WarehouseId.ofRepoId(getM_Warehouse_ID()));
setAD_Org_ID(wh.getAD_Org_ID()); } String url = getURL(); if (url == null) url = ""; boolean urlOK = url.startsWith("http://") || url.startsWith("https://"); if (!urlOK) // || url.indexOf("localhost") != -1) { throw new FillMandatoryException("URL"); } return true; } // beforeSave } // MWStore
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MStore.java
1
请完成以下Java代码
public boolean isMatching(@NonNull final DataEntrySection section) { return isMatching(section.getInternalName()) || isMatching(section.getCaption()); } public boolean isMatching(@NonNull final DataEntryLine line) { return isMatching(String.valueOf(line.getSeqNo())); } public boolean isMatching(@NonNull final DataEntryField field) { return isAny() || isMatching(field.getCaption()); } private boolean isMatching(final ITranslatableString trl) { if (isAny()) { return true; } if (isMatching(trl.getDefaultValue())) { return true; } for (final String adLanguage : trl.getAD_Languages()) { if (isMatching(trl.translate(adLanguage))) { return true; } } return false;
} @VisibleForTesting boolean isMatching(final String name) { if (isAny()) { return true; } final String nameNorm = normalizeString(name); if (nameNorm == null) { return false; } return pattern.equalsIgnoreCase(nameNorm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\NamePattern.java
1
请完成以下Java代码
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { SecurityContext result = SecurityContextHolder.createEmptyContext(); for (SecurityContextRepository delegate : this.delegates) { SecurityContext delegateResult = delegate.loadContext(requestResponseHolder); if (result == null || delegate.containsContext(requestResponseHolder.getRequest())) { result = delegateResult; } } return result; } @Override public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) { DeferredSecurityContext deferredSecurityContext = null; for (SecurityContextRepository delegate : this.delegates) { if (deferredSecurityContext == null) { deferredSecurityContext = delegate.loadDeferredContext(request); } else { DeferredSecurityContext next = delegate.loadDeferredContext(request); deferredSecurityContext = new DelegatingDeferredSecurityContext(deferredSecurityContext, next); } } if (deferredSecurityContext == null) { throw new IllegalStateException("No deferredSecurityContext found"); } return deferredSecurityContext; } @Override public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { for (SecurityContextRepository delegate : this.delegates) { delegate.saveContext(context, request, response); } } @Override public boolean containsContext(HttpServletRequest request) { for (SecurityContextRepository delegate : this.delegates) { if (delegate.containsContext(request)) { return true; } } return false; } static final class DelegatingDeferredSecurityContext implements DeferredSecurityContext {
private final DeferredSecurityContext previous; private final DeferredSecurityContext next; DelegatingDeferredSecurityContext(DeferredSecurityContext previous, DeferredSecurityContext next) { this.previous = previous; this.next = next; } @Override public SecurityContext get() { SecurityContext securityContext = this.previous.get(); if (!this.previous.isGenerated()) { return securityContext; } return this.next.get(); } @Override public boolean isGenerated() { return this.previous.isGenerated() && this.next.isGenerated(); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\DelegatingSecurityContextRepository.java
1
请在Spring Boot框架中完成以下Java代码
public static class DefaultLogoutConfiguration { @Bean public SecurityFilterChain filterChainDefaultLogout(HttpSecurity http) throws Exception { http.securityMatcher("/basic/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/basic/basiclogout")); return http.build(); } } @Order(2) @Configuration public static class AllCookieClearingLogoutConfiguration { @Bean public SecurityFilterChain filterChainAllCookieClearing(HttpSecurity http) throws Exception { http.securityMatcher("/cookies/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/cookies/cookielogout") .addLogoutHandler(new SecurityContextLogoutHandler()) .addLogoutHandler((request, response, auth) -> { for (Cookie cookie : request.getCookies()) { String cookieName = cookie.getName(); Cookie cookieToDelete = new Cookie(cookieName, null); cookieToDelete.setMaxAge(0); response.addCookie(cookieToDelete); } })); return http.build(); } } @Order(1)
@Configuration public static class ClearSiteDataHeaderLogoutConfiguration { private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS }; @Bean public SecurityFilterChain filterChainClearSiteDataHeader(HttpSecurity http) throws Exception { http.securityMatcher("/csd/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/csd/csdlogout") .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)))); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\manuallogout\SimpleSecurityConfiguration.java
2
请完成以下Java代码
private boolean isHelpShown(Command command) { return !(command instanceof HelpCommand) && !(command instanceof HintCommand); } @Override public ExitStatus run(String... args) throws Exception { if (args.length == 0) { throw new NoHelpCommandArgumentsException(); } String commandName = args[0]; for (Command command : this.commandRunner) { if (command.getName().equals(commandName)) { Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription()); Log.info(""); if (command.getUsageHelp() != null) { Log.info("usage: " + this.commandRunner.getName() + command.getName() + " " + command.getUsageHelp()); Log.info(""); } if (command.getHelp() != null) { Log.info(command.getHelp()); } Collection<HelpExample> examples = command.getExamples(); if (examples != null) { Log.info((examples.size() != 1) ? "examples:" : "example:");
Log.info(""); for (HelpExample example : examples) { Log.info(" " + example.getDescription() + ":"); Log.info(" $ " + example.getExample()); Log.info(""); } Log.info(""); } return ExitStatus.OK; } } throw new NoSuchCommandException(commandName); } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\core\HelpCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class TargetCurrencyType { @XmlElement(name = "CurrencyCode") protected String currencyCode; @XmlElement(name = "ExchangeRate") protected BigDecimal exchangeRate; @XmlElement(name = "ExchangeDate") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar exchangeDate; /** * Gets the value of the currencyCode property. * * @return * possible object is * {@link String } * */ public String getCurrencyCode() { return currencyCode; } /** * Sets the value of the currencyCode property. * * @param value * allowed object is * {@link String } * */ public void setCurrencyCode(String value) { this.currencyCode = value; } /** * Gets the value of the exchangeRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getExchangeRate() { return exchangeRate; } /** * Sets the value of the exchangeRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setExchangeRate(BigDecimal value) {
this.exchangeRate = value; } /** * Gets the value of the exchangeDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getExchangeDate() { return exchangeDate; } /** * Sets the value of the exchangeDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setExchangeDate(XMLGregorianCalendar value) { this.exchangeDate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\TargetCurrencyType.java
2
请完成以下Java代码
public class CompositeHttpSessionIdResolver implements HttpSessionIdResolver { private final HttpSessionIdResolver[] resolvers; public CompositeHttpSessionIdResolver(HttpSessionIdResolver... resolvers) { this.resolvers = resolvers; } /** * {@inheritDoc} */ @Override public List<String> resolveSessionIds(HttpServletRequest request) { return Stream.of(this.resolvers) .flatMap((resolver) -> resolver.resolveSessionIds(request).stream()) .distinct() .toList(); } /** * {@inheritDoc}
*/ @Override public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) { for (HttpSessionIdResolver resolver : this.resolvers) { resolver.setSessionId(request, response, sessionId); } } /** * {@inheritDoc} */ @Override public void expireSession(HttpServletRequest request, HttpServletResponse response) { for (HttpSessionIdResolver resolver : this.resolvers) { resolver.expireSession(request, response); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\CompositeHttpSessionIdResolver.java
1
请在Spring Boot框架中完成以下Java代码
public List<JobProcessor> getJobProcessors() { return jobProcessors; } public JobServiceConfiguration setJobProcessors(List<JobProcessor> jobProcessors) { this.jobProcessors = Collections.unmodifiableList(jobProcessors); return this; } public List<HistoryJobProcessor> getHistoryJobProcessors() { return historyJobProcessors; } public JobServiceConfiguration setHistoryJobProcessors(List<HistoryJobProcessor> historyJobProcessors) { this.historyJobProcessors = Collections.unmodifiableList(historyJobProcessors); return this; } public void setJobParentStateResolver(InternalJobParentStateResolver jobParentStateResolver) { this.jobParentStateResolver = jobParentStateResolver; }
public InternalJobParentStateResolver getJobParentStateResolver() { return jobParentStateResolver; } public List<String> getEnabledJobCategories() { return enabledJobCategories; } public void setEnabledJobCategories(List<String> enabledJobCategories) { this.enabledJobCategories = enabledJobCategories; } public void addEnabledJobCategory(String jobCategory) { if (enabledJobCategories == null) { enabledJobCategories = new ArrayList<>(); } enabledJobCategories.add(jobCategory); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\JobServiceConfiguration.java
2
请完成以下Java代码
private int extractId(@NonNull final SearchHit hit) { final Object value = hit .getFields() .get(esKeyColumnName) .getValue(); return NumberUtils.asInt(value, -1); } private QueryBuilder createElasticsearchQuery(final LookupDataSourceContext evalCtx) { final String text = evalCtx.getFilter(); return QueryBuilders.multiMatchQuery(text, esSearchFieldNames); } @Override public boolean isCached() { return true; } @Override public String getCachePrefix() { return null; } @Override public Optional<String> getLookupTableName() { return Optional.of(modelTableName); } @Override public void cacheInvalidate() { // nothing } @Override public LookupDataSourceFetcher getLookupDataSourceFetcher() { return this; } @Override public boolean isHighVolume() { return true;
} @Override public LookupSource getLookupSourceType() { return LookupSource.lookup; } @Override public boolean hasParameters() { return true; } @Override public boolean isNumericKey() { return true; } @Override public Set<String> getDependsOnFieldNames() { return null; } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } @Override public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression() { return sqlLookupDescriptor != null ? sqlLookupDescriptor.getSqlForFetchingLookupByIdExpression() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptor.java
1
请完成以下Java代码
public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) { String configuration = eventSubscription.getConfiguration(); if (configuration == null) { throw new ActivitiException( "Compensating execution not set for compensate event subscription with id " + eventSubscription.getId() ); } ExecutionEntity compensatingExecution = commandContext.getExecutionEntityManager().findById(configuration); String processDefinitionId = compensatingExecution.getProcessDefinitionId(); Process process = ProcessDefinitionUtil.getProcess(processDefinitionId); if (process == null) { throw new ActivitiException( "Cannot start process instance. Process model (id = " + processDefinitionId + ") could not be found" ); } FlowElement flowElement = process.getFlowElement(eventSubscription.getActivityId(), true); if (flowElement instanceof SubProcess && !((SubProcess) flowElement).isForCompensation()) { // descend into scope: compensatingExecution.setScope(true); List<CompensateEventSubscriptionEntity> eventsForThisScope = commandContext .getEventSubscriptionEntityManager() .findCompensateEventSubscriptionsByExecutionId(compensatingExecution.getId()); ScopeUtil.throwCompensationEvent(eventsForThisScope, compensatingExecution, false); } else {
try { if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createActivityEvent( ActivitiEventType.ACTIVITY_COMPENSATE, compensatingExecution, flowElement ) ); } compensatingExecution.setCurrentFlowElement(flowElement); Context.getAgenda().planContinueProcessInCompensation(compensatingExecution); } catch (Exception e) { throw new ActivitiException("Error while handling compensation event " + eventSubscription, e); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\CompensationEventHandler.java
1
请完成以下Java代码
public void dispatchEvent(ActivitiEvent event) { if (enabled) { eventSupport.dispatchEvent(event); } if (event.getType() == ActivitiEventType.ENTITY_DELETED && event instanceof ActivitiEntityEvent) { ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event; if (entityEvent.getEntity() instanceof ProcessDefinition) { // process definition deleted event doesn't need to be dispatched to event listeners return; } } // Try getting hold of the Process definition, based on the process definition key, if a context is active CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { BpmnModel bpmnModel = extractBpmnModelFromEvent(event); if (bpmnModel != null) { ((ActivitiEventSupport) bpmnModel.getEventSupport()).dispatchEvent(event); } } } /** * In case no process-context is active, this method attempts to extract a process-definition based on the event. In case it's an event related to an entity, this can be deducted by inspecting the * entity, without additional queries to the database. * * If not an entity-related event, the process-definition will be retrieved based on the processDefinitionId (if filled in). This requires an additional query to the database in case not already * cached. However, queries will only occur when the definition is not yet in the cache, which is very unlikely to happen, unless evicted. * * @param event * @return */ protected BpmnModel extractBpmnModelFromEvent(ActivitiEvent event) {
BpmnModel result = null; if (result == null && event.getProcessDefinitionId() != null) { ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition( event.getProcessDefinitionId(), true ); if (processDefinition != null) { result = Context.getProcessEngineConfiguration() .getDeploymentManager() .resolveProcessDefinition(processDefinition) .getBpmnModel(); } } return result; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventDispatcherImpl.java
1
请完成以下Java代码
public String getPAPeriodType () { return (String)get_Value(COLUMNNAME_PAPeriodType); } /** Set Report Line. @param PA_ReportLine_ID Report Line */ public void setPA_ReportLine_ID (int PA_ReportLine_ID) { if (PA_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID)); } /** Get Report Line. @return Report Line */ public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_ReportLineSet getPA_ReportLineSet() throws RuntimeException { return (I_PA_ReportLineSet)MTable.get(getCtx(), I_PA_ReportLineSet.Table_Name) .getPO(getPA_ReportLineSet_ID(), get_TrxName()); } /** Set Report Line Set. @param PA_ReportLineSet_ID Report Line Set */ public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID) { if (PA_ReportLineSet_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID)); } /** Get Report Line Set. @return Report Line Set */ public int getPA_ReportLineSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) {
set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportLine.java
1
请在Spring Boot框架中完成以下Java代码
public class CourseRepository { private Map<Integer, Course> courses = new HashMap<>(); { Student student1 = new Student(); Student student2 = new Student(); student1.setId(1); student1.setName("Student A"); student2.setId(2); student2.setName("Student B"); List<Student> course1Students = new ArrayList<>(); course1Students.add(student1); course1Students.add(student2); Course course1 = new Course(); Course course2 = new Course(); course1.setId(1); course1.setName("REST with Spring"); course1.setStudents(course1Students); course2.setId(2); course2.setName("Learn Spring Security"); courses.put(1, course1); courses.put(2, course2); } @GET @Path("courses/{courseId}") public Course getCourse(@PathParam("courseId") int courseId) { return findById(courseId); }
@PUT @Path("courses/{courseId}") public Response updateCourse(@PathParam("courseId") int courseId, Course course) { Course existingCourse = findById(courseId); if (existingCourse == null) { return Response.status(Response.Status.NOT_FOUND).build(); } if (existingCourse.equals(course)) { return Response.notModified().build(); } courses.put(courseId, course); return Response.ok().build(); } @Path("courses/{courseId}/students") public Course pathToStudent(@PathParam("courseId") int courseId) { return findById(courseId); } private Course findById(int id) { for (Map.Entry<Integer, Course> course : courses.entrySet()) { if (course.getKey() == id) { return course.getValue(); } } return null; } }
repos\tutorials-master\apache-cxf-modules\cxf-jaxrs-implementation\src\main\java\com\baeldung\cxf\jaxrs\implementation\CourseRepository.java
2
请完成以下Java代码
public org.compiere.model.I_S_ResourceType getS_ResourceType() { return get_ValueAsPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class); } @Override public void setS_ResourceType(final org.compiere.model.I_S_ResourceType S_ResourceType) { set_ValueFromPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class, S_ResourceType); } @Override public void setS_ResourceType_ID (final int S_ResourceType_ID) { if (S_ResourceType_ID < 1) set_Value (COLUMNNAME_S_ResourceType_ID, null); else set_Value (COLUMNNAME_S_ResourceType_ID, S_ResourceType_ID); } @Override public int getS_ResourceType_ID() { return get_ValueAsInt(COLUMNNAME_S_ResourceType_ID); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override
public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWaitingTime (final @Nullable BigDecimal WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public BigDecimal getWaitingTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WaitingTime); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Resource.java
1
请完成以下Java代码
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 Reporting Hierarchy.
@param PA_Hierarchy_ID Optional Reporting Hierarchy - If not selected the default hierarchy trees are used. */ public void setPA_Hierarchy_ID (int PA_Hierarchy_ID) { if (PA_Hierarchy_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Hierarchy_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Hierarchy_ID, Integer.valueOf(PA_Hierarchy_ID)); } /** Get Reporting Hierarchy. @return Optional Reporting Hierarchy - If not selected the default hierarchy trees are used. */ public int getPA_Hierarchy_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Hierarchy_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_PA_Hierarchy.java
1
请完成以下Java代码
private PPOrderQuantities getQuantities(final UomId targetUOMId) { return ppOrderBOMBL.getQuantities(ppOrder, targetUOMId); } @Override public I_C_UOM getC_UOM() { return uomDAO.getById(getUomId()); } @NonNull public UomId getUomId() { return UomId.ofRepoId(ppOrder.getC_UOM_ID()); } @Override public ProductionMaterialType getType() { return ProductionMaterialType.PRODUCED; } @Override public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw) { ppOrder.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw); } @Override public BigDecimal getQM_QtyDeliveredPercOfRaw() { return ppOrder.getQM_QtyDeliveredPercOfRaw(); } @Override public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg) { ppOrder.setQM_QtyDeliveredAvg(qtyDeliveredAvg); } @Override public BigDecimal getQM_QtyDeliveredAvg() { return ppOrder.getQM_QtyDeliveredAvg(); } @Override public Object getModel() { return ppOrder; }
@Override public String getVariantGroup() { return null; } @Override public BOMComponentType getComponentType() { return null; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { if (!_handlingUnitsInfoLoaded) { _handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder); _handlingUnitsInfoLoaded = true; } return _handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { // there is no substitute for a produced material return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java
1