instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authenticationProvider() { final DaoAuthenticationProvider bean = new CustomDaoAuthenticationProvider(); bean.setUserDetailsService(customUserDetailsService); bean.setPasswordEncoder(encoder()); return bean; } /** * Order of precedence is very important. * <p> * Matching occurs from top to bottom - so, the topmost match succeeds first. */ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/", "/index", "/authenticate") .permitAll() .requestMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success") .authenticated() .anyRequest() .authenticated()) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login") .permitAll() .usernameParameter("username") .passwordParameter("password") .loginProcessingUrl("/authenticate") .successHandler(loginSuccessHandler()) .failureUrl("/denied") .permitAll()) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler())) /** * Applies to User Roles - not to login failures or unauthenticated access attempts. */ .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler()))
.authenticationProvider(authenticationProvider()); /** Disabled for local testing */ http.csrf(AbstractHttpConfigurer::disable); /** This is solely required to support H2 console viewing in Spring MVC with Spring Security */ http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin())) .authorizeHttpRequests(Customizer.withDefaults()); return http.build(); } @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .authenticationProvider(authenticationProvider()) .build(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers("/resources/**"); } }
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\config\SecurityConfig.java
2
请完成以下Java代码
public int getC_Invoice_Verification_Set_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_Set_ID); } @Override public void setC_Invoice_Verification_SetLine_ID (final int C_Invoice_Verification_SetLine_ID) { if (C_Invoice_Verification_SetLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_SetLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_SetLine_ID, C_Invoice_Verification_SetLine_ID); } @Override public int getC_Invoice_Verification_SetLine_ID() {
return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_SetLine_ID); } @Override public void setRelevantDate (final @Nullable java.sql.Timestamp RelevantDate) { set_ValueNoCheck (COLUMNNAME_RelevantDate, RelevantDate); } @Override public java.sql.Timestamp getRelevantDate() { return get_ValueAsTimestamp(COLUMNNAME_RelevantDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_SetLine.java
1
请在Spring Boot框架中完成以下Java代码
public class AbstractStockEstimateHandler implements MaterialEventHandler<AbstractStockEstimateEvent> { private final MainDataRequestHandler dataUpdateRequestHandler; private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); public AbstractStockEstimateHandler( @NonNull final MainDataRequestHandler dataUpdateRequestHandler) { this.dataUpdateRequestHandler = dataUpdateRequestHandler; } @Override public Collection<Class<? extends AbstractStockEstimateEvent>> getHandledEventType() { return ImmutableList.of(StockEstimateCreatedEvent.class, StockEstimateDeletedEvent.class); } @Override public void handleEvent(@NonNull final AbstractStockEstimateEvent event) { final UpdateMainDataRequest dataUpdateRequest = createDataUpdateRequestForEvent(event); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } private UpdateMainDataRequest createDataUpdateRequestForEvent( @NonNull final AbstractStockEstimateEvent stockEstimateEvent) { final OrgId orgId = stockEstimateEvent.getOrgId(); final ZoneId timeZone = orgDAO.getTimeZone(orgId); final MainDataRecordIdentifier identifier = MainDataRecordIdentifier.builder() .productDescriptor(stockEstimateEvent.getMaterialDescriptor()) .date(TimeUtil.getDay(stockEstimateEvent.getDate(), timeZone)) .warehouseId(stockEstimateEvent.getMaterialDescriptor().getWarehouseId()) .build();
final BigDecimal qtyStockEstimate = stockEstimateEvent instanceof StockEstimateDeletedEvent ? BigDecimal.ZERO : stockEstimateEvent.getQuantityDelta(); final Integer qtyStockSeqNo = stockEstimateEvent instanceof StockEstimateDeletedEvent ? 0 : stockEstimateEvent.getQtyStockEstimateSeqNo(); return UpdateMainDataRequest.builder() .identifier(identifier) .qtyStockEstimateSeqNo(qtyStockSeqNo) .qtyStockEstimateCount(qtyStockEstimate) .qtyStockEstimateTime(stockEstimateEvent.getDate()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\AbstractStockEstimateHandler.java
2
请在Spring Boot框架中完成以下Java代码
public void stop() { synchronized (MONITOR) { isInterrupted = true; if (isWaiting.compareAndSet(true, false)) { MONITOR.notifyAll(); } } } protected void sleep(long millisToWait) { if (millisToWait > 0) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("async job acquisition for engine {}, thread sleeping for {} millis", getEngineName(), millisToWait); } synchronized (MONITOR) { if (!isInterrupted) { isWaiting.set(true); lifecycleListener.startWaiting(getEngineName(), millisToWait); MONITOR.wait(millisToWait); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("async job acquisition for engine {}, thread woke up", getEngineName()); }
} catch (InterruptedException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("async job acquisition for engine {}, wait interrupted", getEngineName()); } } finally { isWaiting.set(false); } } } protected String getEngineName() { return asyncExecutor.getJobServiceConfiguration().getEngineName(); } public AcquireAsyncJobsDueLifecycleListener getLifecycleListener() { return lifecycleListener; } public void setLifecycleListener(AcquireAsyncJobsDueLifecycleListener lifecycleListener) { this.lifecycleListener = lifecycleListener; } public void setConfiguration(AcquireJobsRunnableConfiguration configuration) { this.configuration = configuration; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AcquireAsyncJobsDueRunnable.java
2
请完成以下Java代码
public class GetExecutionVariablesCmd implements Command<Map<String, Object>>, Serializable { private static final long serialVersionUID = 1L; protected String executionId; protected Collection<String> variableNames; protected boolean isLocal; public GetExecutionVariablesCmd(String executionId, Collection<String> variableNames, boolean isLocal) { this.executionId = executionId; this.variableNames = variableNames; this.isLocal = isLocal; } public Map<String, Object> execute(CommandContext commandContext) { // Verify existance of execution if (executionId == null) { throw new ActivitiIllegalArgumentException("executionId is null"); } ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId); if (execution == null) { throw new ActivitiObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class); } return getVariable(execution, commandContext); } public Map<String, Object> getVariable(ExecutionEntity execution, CommandContext commandContext) { if (variableNames == null || variableNames.isEmpty()) { // Fetch all
if (isLocal) { return execution.getVariablesLocal(); } else { return execution.getVariables(); } } else { // Fetch specific collection of variables if (isLocal) { return execution.getVariablesLocal(variableNames, false); } else { return execution.getVariables(variableNames, false); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetExecutionVariablesCmd.java
1
请完成以下Java代码
public class IdentityInfoEntityImpl extends AbstractIdmEngineEntity implements IdentityInfoEntity, Serializable { private static final long serialVersionUID = 1L; protected String type; protected String userId; protected String key; protected String value; protected String password; protected byte[] passwordBytes; protected String parentId; protected Map<String, String> details; public IdentityInfoEntityImpl() { } @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("value", value); persistentState.put("password", passwordBytes); return persistentState; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getUserId() { return userId; } @Override public void setUserId(String userId) { this.userId = userId; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public byte[] getPasswordBytes() { return passwordBytes;
} @Override public void setPasswordBytes(byte[] passwordBytes) { this.passwordBytes = passwordBytes; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getName() { return key; } @Override public String getUsername() { return value; } @Override public String getParentId() { return parentId; } @Override public void setParentId(String parentId) { this.parentId = parentId; } @Override public Map<String, String> getDetails() { return details; } @Override public void setDetails(Map<String, String> details) { this.details = details; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\IdentityInfoEntityImpl.java
1
请完成以下Java代码
private JsonContact toJsonContactOrNull(final @Nullable ContactPerson contact) { if (contact == null) {return null;} return JsonContact.builder() .name(contact.getName()) .phone(contact.getPhoneAsStringOrNull()) .emailAddress(contact.getEmailAddress()) .language(contact.getLanguageCode()) .build(); } private JsonDeliveryOrderParcel toJsonDeliveryOrderLine(@NonNull final DeliveryOrderParcel line) { return JsonDeliveryOrderParcel.builder() .id(line.getId() != null ? String.valueOf(line.getId().getRepoId()) : null) .content(line.getContent()) .grossWeightKg(line.getGrossWeightKg()) .packageDimensions(toJsonPackageDimensions(line.getPackageDimensions())) .packageId(line.getPackageId().toString()) .contents(java.util.Collections.emptyList()) .build(); } private JsonPackageDimensions toJsonPackageDimensions(final PackageDimensions dims) { if (dims == null) {return JsonPackageDimensions.builder().lengthInCM(0).widthInCM(0).heightInCM(0).build();} return JsonPackageDimensions.builder() .lengthInCM(dims.getLengthInCM()) .widthInCM(dims.getWidthInCM()) .heightInCM(dims.getHeightInCM()) .build(); } @NonNull private JsonMappingConfigList toJsonMappingConfigList(@NonNull final ShipperMappingConfigList configs) { if (configs == ShipperMappingConfigList.EMPTY)
{ return JsonMappingConfigList.EMPTY; } return JsonMappingConfigList.ofList( StreamSupport.stream(configs.spliterator(), false) .map(this::toJsonMappingConfig) .collect(ImmutableList.toImmutableList())); } @NonNull private JsonMappingConfig toJsonMappingConfig(@NonNull final ShipperMappingConfig config) { final CarrierProduct carrierProduct = config.getCarrierProductId() != null ? carrierProductRepository.getCachedShipperProductById(config.getCarrierProductId()) : null; return JsonMappingConfig.builder() .seqNo(config.getSeqNo().toInt()) .shipperProductExternalId(carrierProduct != null ? carrierProduct.getCode() : null) .attributeType(config.getAttributeType().getCode()) .groupKey(config.getGroupKey()) .attributeKey(config.getAttributeKey()) .attributeValue(config.getAttributeValue().getCode()) .mappingRule(config.getMappingRule() != null ? config.getMappingRule().getCode() : null) .mappingRuleValue(config.getMappingRuleValue()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\converters\v1\JsonShipperConverter.java
1
请完成以下Java代码
public void setPP_Order_IssueSchedule(final de.metas.handlingunits.model.I_PP_Order_IssueSchedule PP_Order_IssueSchedule) { set_ValueFromPO(COLUMNNAME_PP_Order_IssueSchedule_ID, de.metas.handlingunits.model.I_PP_Order_IssueSchedule.class, PP_Order_IssueSchedule); } @Override public void setPP_Order_IssueSchedule_ID (final int PP_Order_IssueSchedule_ID) { if (PP_Order_IssueSchedule_ID < 1) set_Value (COLUMNNAME_PP_Order_IssueSchedule_ID, null); else set_Value (COLUMNNAME_PP_Order_IssueSchedule_ID, PP_Order_IssueSchedule_ID); } @Override public int getPP_Order_IssueSchedule_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_IssueSchedule_ID); } @Override public void setPP_Order_Qty_ID (final int PP_Order_Qty_ID) { if (PP_Order_Qty_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Qty_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Qty_ID, PP_Order_Qty_ID); } @Override public int getPP_Order_Qty_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Qty_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 setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); 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_PP_Order_Qty.java
1
请完成以下Java代码
public void setPP_Order_Candidate_ID (final int PP_Order_Candidate_ID) { if (PP_Order_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, PP_Order_Candidate_ID); } @Override public int getPP_Order_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID); } @Override public void setPP_OrderLine_Candidate_ID (final int PP_OrderLine_Candidate_ID) { if (PP_OrderLine_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, PP_OrderLine_Candidate_ID); } @Override public int getPP_OrderLine_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_PP_OrderLine_Candidate_ID); } @Override public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class); } @Override public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine) { set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine); } @Override
public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID) { if (PP_Product_BOMLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID); } @Override public int getPP_Product_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID); } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderLine_Candidate.java
1
请完成以下Spring Boot application配置
spring: application: name: spring-cloud-eureka-client server: port: 0 eureka: client: serviceUrl: defaultZone: ${EUREKA_URI:htt
p://localhost:8761/eureka} instance: preferIpAddress: true
repos\tutorials-master\spring-cloud-modules\spring-cloud-eureka\spring-cloud-eureka-client\src\main\resources\application.yml
2
请完成以下Java代码
public Date getNextRunWithDelay(Date date) { Date result = addSeconds(date, Math.min((int)(Math.pow(2., (double)countEmptyRuns) * START_DELAY), MAX_DELAY)); return result; } private Date addSeconds(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.SECOND, amount); return c.getTime(); } public int getCountEmptyRuns() { return countEmptyRuns; } public void setCountEmptyRuns(int countEmptyRuns) { this.countEmptyRuns = countEmptyRuns; } public boolean isImmediatelyDue() { return immediatelyDue; } public void setImmediatelyDue(boolean immediatelyDue) { this.immediatelyDue = immediatelyDue; } public int getMinuteFrom() {
return minuteFrom; } public void setMinuteFrom(int minuteFrom) { this.minuteFrom = minuteFrom; } public int getMinuteTo() { return minuteTo; } public void setMinuteTo(int minuteTo) { this.minuteTo = minuteTo; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobHandlerConfiguration.java
1
请完成以下Java代码
public class PermissionServiceFactories { public PermissionServiceFactory currentContext() { return ContextPermissionServiceFactory.instance; } public PermissionServiceFactory singleton(@NonNull final PermissionService permissionService) { return new SingletonPermissionServiceFactory(permissionService); } private static final class ContextPermissionServiceFactory implements PermissionServiceFactory { public static final transient ContextPermissionServiceFactory instance = new ContextPermissionServiceFactory(); @Override public PermissionService createPermissionService() { final Properties ctx = Env.getCtx(); return PermissionService.builder() .userRolePermissionsKey(UserRolePermissionsKey.fromContext(ctx)) .defaultOrgId(Env.getOrgId(ctx)) .build(); }
} private static final class SingletonPermissionServiceFactory implements PermissionServiceFactory { private final PermissionService permissionService; public SingletonPermissionServiceFactory(@NonNull final PermissionService permissionService) { this.permissionService = permissionService; } @Override public PermissionService createPermissionService() { return permissionService; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions2\PermissionServiceFactories.java
1
请完成以下Java代码
public class ActorJackson { private String imdbId; private Date dateOfBirth; private List<String> filmography; public ActorJackson() { super(); } public ActorJackson(String imdbId, Date dateOfBirth, List<String> filmography) { super(); this.imdbId = imdbId; this.dateOfBirth = dateOfBirth; this.filmography = filmography; } @Override public String toString() { return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; } public String getImdbId() { return imdbId; } public void setImdbId(String imdbId) { this.imdbId = imdbId; } public Date getDateOfBirth() {
return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public List<String> getFilmography() { return filmography; } public void setFilmography(List<String> filmography) { this.filmography = filmography; } private String formatDateOfBirth() { final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); return formatter.format(dateOfBirth); } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\jacksonvsgson\ActorJackson.java
1
请完成以下Java代码
public void setNoMonths (int NoMonths) { set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths)); } /** Get Number of Months. @return Number of Months */ public int getNoMonths () { Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths); if (ii == null) return 0; return ii.intValue(); } /** RecognitionFrequency AD_Reference_ID=196 */ public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196; /** Month = M */ public static final String RECOGNITIONFREQUENCY_Month = "M"; /** Quarter = Q */ public static final String RECOGNITIONFREQUENCY_Quarter = "Q"; /** Year = Y */ public static final String RECOGNITIONFREQUENCY_Year = "Y";
/** Set Recognition frequency. @param RecognitionFrequency Recognition frequency */ public void setRecognitionFrequency (String RecognitionFrequency) { set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency); } /** Get Recognition frequency. @return Recognition frequency */ public String getRecognitionFrequency () { return (String)get_Value(COLUMNNAME_RecognitionFrequency); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java
1
请完成以下Java代码
public abstract class FormDataImpl implements FormData, Serializable { private static final long serialVersionUID = 1L; protected String formKey; protected CamundaFormRef camundaFormRef; protected String deploymentId; protected List<FormProperty> formProperties = new ArrayList<>(); protected List<FormField> formFields = new ArrayList<>(); // getters and setters ////////////////////////////////////////////////////// public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public CamundaFormRef getCamundaFormRef() { return camundaFormRef; } public void setCamundaFormRef(CamundaFormRef camundaFormRef) { this.camundaFormRef = camundaFormRef; }
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public List<FormProperty> getFormProperties() { return formProperties; } public void setFormProperties(List<FormProperty> formProperties) { this.formProperties = formProperties; } public List<FormField> getFormFields() { return formFields; } public void setFormFields(List<FormField> formFields) { this.formFields = formFields; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\FormDataImpl.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setExpression(DmnExpressionImpl expression) { this.expression = expression; } public DmnExpressionImpl getExpression() { return expression; } public String getInputVariable() { if (inputVariable != null) {
return inputVariable; } else { return DEFAULT_INPUT_VARIABLE_NAME; } } public void setInputVariable(String inputVariable) { this.inputVariable = inputVariable; } @Override public String toString() { return "DmnDecisionTableInputImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", expression=" + expression + ", inputVariable='" + inputVariable + '\'' + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionTableInputImpl.java
1
请完成以下Java代码
public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public Rule toRule() { return null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDefinitionEntity entity = (ApiDefinitionEntity) o; return Objects.equals(id, entity.id) && Objects.equals(app, entity.app) && Objects.equals(ip, entity.ip) &&
Objects.equals(port, entity.port) && Objects.equals(gmtCreate, entity.gmtCreate) && Objects.equals(gmtModified, entity.gmtModified) && Objects.equals(apiName, entity.apiName) && Objects.equals(predicateItems, entity.predicateItems); } @Override public int hashCode() { return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); } @Override public String toString() { return "ApiDefinitionEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", apiName='" + apiName + '\'' + ", predicateItems=" + predicateItems + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiDefinitionEntity.java
1
请完成以下Java代码
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 Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Resource Assignment. @param S_ResourceAssignment_ID Resource Assignment */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID) { if (S_ResourceAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Resource Assignment. @return Resource Assignment */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_Resource getS_Resource() throws RuntimeException { return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name)
.getPO(getS_Resource_ID(), get_TrxName()); } /** Set Resource. @param S_Resource_ID Resource */ public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } /** Get Resource. @return Resource */ public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceAssignment.java
1
请完成以下Java代码
public ShipperId getShipperId() {return getDdOrderCandidate().getShipperId();} @NonNull @JsonIgnore public SupplyRequiredDescriptor getSupplyRequiredDescriptorNotNull() {return Check.assumeNotNull(getSupplyRequiredDescriptor(), "supplyRequiredDescriptor shall be set for " + this);} @Nullable @JsonIgnore public ProductPlanningId getProductPlanningId() {return getDdOrderCandidate().getProductPlanningId();} @Nullable @JsonIgnore public DistributionNetworkAndLineId getDistributionNetworkAndLineId() {return getDdOrderCandidate().getDistributionNetworkAndLineId();} @Nullable @JsonIgnore public MaterialDispoGroupId getMaterialDispoGroupId() {return getDdOrderCandidate().getMaterialDispoGroupId();}
@Nullable @JsonIgnore public PPOrderRef getForwardPPOrderRef() {return getDdOrderCandidate().getForwardPPOrderRef();} @JsonIgnore public int getExistingDDOrderCandidateId() {return getDdOrderCandidate().getExitingDDOrderCandidateId();} @Nullable public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_DD_Order_Candidate.Table_Name,ddOrderCandidate.getExitingDDOrderCandidateId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\AbstractDDOrderCandidateEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class Dao<T, ID extends Serializable> implements GenericDao<T, ID> { @PersistenceContext private EntityManager entityManager; @Override public <S extends T> S persist(S entity) { Objects.requireNonNull(entity, "Cannot persist a null entity"); entityManager.persist(entity); return entity; } @Transactional(readOnly = true) public List<CategoryDto> fetchCategories() { Query query = entityManager.createNativeQuery( "SELECT t.name AS namet, m.name AS namem, b.name AS nameb "
+ "FROM middle_category m " + "INNER JOIN top_category t " + "ON t.id=m.top_category_id " + "INNER JOIN bottom_category b " + "ON m.id=b.middle_category_id", "CategoryDtoMapping"); List<CategoryDto> result = query.getResultList(); return result; } protected EntityManager getEntityManager() { return entityManager; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\dao\Dao.java
2
请在Spring Boot框架中完成以下Java代码
private SmsFlashPromotionSession getNextFlashPromotionSession(Date date) { SmsFlashPromotionSessionExample sessionExample = new SmsFlashPromotionSessionExample(); sessionExample.createCriteria() .andStartTimeGreaterThan(date); sessionExample.setOrderByClause("start_time asc"); List<SmsFlashPromotionSession> promotionSessionList = promotionSessionMapper.selectByExample(sessionExample); if (!CollectionUtils.isEmpty(promotionSessionList)) { return promotionSessionList.get(0); } return null; } private List<SmsHomeAdvertise> getHomeAdvertiseList() { SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample(); example.createCriteria().andTypeEqualTo(1).andStatusEqualTo(1); example.setOrderByClause("sort desc"); return advertiseMapper.selectByExample(example); } //根据时间获取秒杀活动 private SmsFlashPromotion getFlashPromotion(Date date) { Date currDate = DateUtil.getDate(date); SmsFlashPromotionExample example = new SmsFlashPromotionExample(); example.createCriteria() .andStatusEqualTo(1) .andStartDateLessThanOrEqualTo(currDate) .andEndDateGreaterThanOrEqualTo(currDate);
List<SmsFlashPromotion> flashPromotionList = flashPromotionMapper.selectByExample(example); if (!CollectionUtils.isEmpty(flashPromotionList)) { return flashPromotionList.get(0); } return null; } //根据时间获取秒杀场次 private SmsFlashPromotionSession getFlashPromotionSession(Date date) { Date currTime = DateUtil.getTime(date); SmsFlashPromotionSessionExample sessionExample = new SmsFlashPromotionSessionExample(); sessionExample.createCriteria() .andStartTimeLessThanOrEqualTo(currTime) .andEndTimeGreaterThanOrEqualTo(currTime); List<SmsFlashPromotionSession> promotionSessionList = promotionSessionMapper.selectByExample(sessionExample); if (!CollectionUtils.isEmpty(promotionSessionList)) { return promotionSessionList.get(0); } return null; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\HomeServiceImpl.java
2
请完成以下Java代码
public XmlBalance withMod(@Nullable final BalanceMod balanceMod) { if (balanceMod == null) { return this; } final XmlBalanceBuilder builder = toBuilder(); if (balanceMod.getCurrency() != null) { builder.currency(balanceMod.getCurrency()); } if (balanceMod.getAmount() != null) { builder.amount(balanceMod.getAmount()); } if (balanceMod.getAmountDue() != null) { builder.amountDue(balanceMod.getAmountDue()); } return builder .vat(vat.withMod(balanceMod.getVatMod())) .build(); }
@Value @Builder public static class BalanceMod { @Nullable String currency; @Nullable BigDecimal amount; @Nullable BigDecimal amountDue; @Nullable VatMod vatMod; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\XmlBalance.java
1
请在Spring Boot框架中完成以下Java代码
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { /** * 用户认证 Manager */ @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.checkTokenAccess("isAuthenticated()")
// .tokenKeyAccess("permitAll()") ; } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("clientapp").secret("112233") // Client 账号、密码。 .authorizedGrantTypes("authorization_code") // 授权码模式 .redirectUris("http://127.0.0.1:9090/callback") // 配置回调地址,选填。 .scopes("read_userinfo", "read_contacts") // 可授权的 Scope // .and().withClient() // 可以继续配置新的 Client ; } }
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo02-authorization-server-with-authorization-code\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\OAuth2AuthorizationServerConfig.java
2
请完成以下Java代码
public boolean isLimitHitOrExceeded(@NonNull final Collection<?> collection) { return isLimitHitOrExceeded(collection.size()); } public boolean isLimitHitOrExceeded(@NonNull final MutableInt countHolder) { return isLimitHitOrExceeded(countHolder.getValue()); } public boolean isLimitHitOrExceeded(final int count) { return isLimited() && value <= count; } public boolean isBelowLimit(@NonNull final Collection<?> collection) { return isNoLimit() || value > collection.size(); } public QueryLimit minusSizeOf(@NonNull final Collection<?> collection)
{ if (isNoLimit() || collection.isEmpty()) { return this; } else { final int collectionSize = collection.size(); final int newLimitInt = value - collectionSize; if (newLimitInt <= 0) { throw new AdempiereException("Invalid collection size. It shall be less than " + value + " but it was " + collectionSize); } return ofInt(newLimitInt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\QueryLimit.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { ensureNotNull("task", task); validateStandaloneTask(task, commandContext); String operation; if (task.getRevision() == 0) { try { checkCreateTask(task, commandContext); task.ensureParentTaskActive(); task.propagateParentTaskTenantId(); task.insert(); operation = UserOperationLogEntry.OPERATION_TYPE_CREATE; task.executeMetrics(Metrics.ACTIVTY_INSTANCE_START, commandContext); } catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } task.fireAuthorizationProvider(); task.transitionTo(TaskState.STATE_CREATED); } else { checkTaskAssign(task, commandContext); task.update(); operation = UserOperationLogEntry.OPERATION_TYPE_UPDATE; task.fireAuthorizationProvider(); task.triggerUpdateEvent();
} task.executeMetrics(Metrics.UNIQUE_TASK_WORKERS, commandContext); task.logUserOperation(operation); return null; } protected void validateStandaloneTask(TaskEntity task, CommandContext commandContext) { boolean standaloneTasksEnabled = commandContext.getProcessEngineConfiguration().isStandaloneTasksEnabled(); if (!standaloneTasksEnabled && task.isStandaloneTask()) { throw new NotAllowedException("Cannot save standalone task. They are disabled in the process engine configuration."); } } protected void checkTaskAssign(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskAssign(task); } } protected void checkCreateTask(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkCreateTask(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SaveTaskCmd.java
1
请完成以下Java代码
public void setLastProcessed_WorkPackage_ID (final int LastProcessed_WorkPackage_ID) { if (LastProcessed_WorkPackage_ID < 1) set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, null); else set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, LastProcessed_WorkPackage_ID); } @Override public int getLastProcessed_WorkPackage_ID() { return get_ValueAsInt(COLUMNNAME_LastProcessed_WorkPackage_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public de.metas.async.model.I_C_Async_Batch getParent_Async_Batch() { return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class); } @Override public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch)
{ set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch); } @Override public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID) { if (Parent_Async_Batch_ID < 1) set_Value (COLUMNNAME_Parent_Async_Batch_ID, null); else set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID); } @Override public int getParent_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID); } @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.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java
1
请在Spring Boot框架中完成以下Java代码
public PickingJobScheduleCollection deleteByIdsAndReturn(final @NonNull Set<PickingJobScheduleId> jobScheduleIds) { if (jobScheduleIds.isEmpty()) { return PickingJobScheduleCollection.EMPTY; } final List<I_M_Picking_Job_Schedule> records = queryBL.createQueryBuilder(I_M_Picking_Job_Schedule.class) .addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID, jobScheduleIds) .create() .list(); if (records.isEmpty()) { return PickingJobScheduleCollection.EMPTY; } final PickingJobScheduleCollection deletedSchedules = records.stream() .map(PickingJobScheduleRepository::fromRecord) .collect(PickingJobScheduleCollection.collect()); InterfaceWrapperHelper.deleteAll(records); return deletedSchedules; } public PickingJobScheduleCollection list(@NonNull final PickingJobScheduleQuery query) { return stream(query).collect(PickingJobScheduleCollection.collect()); } public Stream<PickingJobSchedule> stream(@NonNull final PickingJobScheduleQuery query) { return toSqlQuery(query) .stream() .map(PickingJobScheduleRepository::fromRecord); } public boolean anyMatch(@NonNull final PickingJobScheduleQuery query) { return toSqlQuery(query).anyMatch(); } private IQuery<I_M_Picking_Job_Schedule> toSqlQuery(@NonNull final PickingJobScheduleQuery query) { if (query.isAny()) { throw new AdempiereException("Any query is not allowed"); }
final IQueryBuilder<I_M_Picking_Job_Schedule> queryBuilder = queryBL.createQueryBuilder(I_M_Picking_Job_Schedule.class) .orderBy(I_M_Picking_Job_Schedule.COLUMNNAME_M_ShipmentSchedule_ID) .orderBy(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID) .addOnlyActiveRecordsFilter(); if (!query.getWorkplaceIds().isEmpty()) { queryBuilder.addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_C_Workplace_ID, query.getWorkplaceIds()); } if (!query.getExcludeJobScheduleIds().isEmpty()) { queryBuilder.addNotInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID, query.getExcludeJobScheduleIds()); } if (!query.getOnlyShipmentScheduleIds().isEmpty()) { queryBuilder.addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_ShipmentSchedule_ID, query.getOnlyShipmentScheduleIds()); } if (query.getIsProcessed() != null) { queryBuilder.addEqualsFilter(I_M_Picking_Job_Schedule.COLUMNNAME_Processed, query.getIsProcessed()); } return queryBuilder.create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\repository\PickingJobScheduleRepository.java
2
请完成以下Java代码
public boolean isEmpty() { return locks.isEmpty(); } private boolean isNotLocked(final ShipmentScheduleId shipmentScheduleId) { return getByShipmentScheduleIdOrNull(shipmentScheduleId) == null; } private ShipmentScheduleLock getByShipmentScheduleIdOrNull(@NonNull final ShipmentScheduleId shipmentScheduleId) { return locks.get(shipmentScheduleId); } public boolean isNotLockedBy(@NonNull final UserId userId) { if (isEmpty()) { return true; } return !isLockedBy(userId); } public boolean isLockedBy(@NonNull final UserId userId) { if (isEmpty()) { return false; } return locks.values() .stream() .anyMatch(lock -> lock.isLockedBy(userId)); } public void assertLockedBy(@NonNull final UserId expectedLockedBy) { if (isEmpty()) { return; } final List<ShipmentScheduleLock> locksByOtherUser = locks.values() .stream() .filter(lock -> lock.isNotLockedBy(expectedLockedBy)) .collect(ImmutableList.toImmutableList());
if (!locksByOtherUser.isEmpty()) { throw new AdempiereException("Following locks are not owned by " + expectedLockedBy + ": " + locksByOtherUser); } } public void assertLockType(@NonNull final ShipmentScheduleLockType expectedLockType) { if (isEmpty()) { return; } final List<ShipmentScheduleLock> locksWithDifferentLockType = locks.values() .stream() .filter(lock -> !lock.isLockType(expectedLockType)) .collect(ImmutableList.toImmutableList()); if (!locksWithDifferentLockType.isEmpty()) { throw new AdempiereException("Following locks are not for " + expectedLockType + ": " + locksWithDifferentLockType); } } public Set<ShipmentScheduleId> getShipmentScheduleIdsNotLocked(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIdsToCheck) { if (isEmpty()) { return shipmentScheduleIdsToCheck; } return shipmentScheduleIdsToCheck.stream() .filter(this::isNotLocked) .collect(ImmutableSet.toImmutableSet()); } public Set<ShipmentScheduleId> getShipmentScheduleIdsLocked() { return locks.keySet(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\lock\ShipmentScheduleLocksMap.java
1
请完成以下Java代码
public void setC_OrderLine_ID (final int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_Value (COLUMNNAME_C_OrderLine_ID, null); else set_Value (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID); } @Override public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setMostRecentTriggerTimestamp (final java.sql.Timestamp MostRecentTriggerTimestamp) { set_Value (COLUMNNAME_MostRecentTriggerTimestamp, MostRecentTriggerTimestamp); } @Override public java.sql.Timestamp getMostRecentTriggerTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_MostRecentTriggerTimestamp); } @Override public void setM_Product_Order_ID (final int M_Product_Order_ID) { if (M_Product_Order_ID < 1) set_Value (COLUMNNAME_M_Product_Order_ID, null); else set_Value (COLUMNNAME_M_Product_Order_ID, M_Product_Order_ID); } @Override public int getM_Product_Order_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Order_ID); } @Override public void setPointsBase_Forecasted (final BigDecimal PointsBase_Forecasted) { set_Value (COLUMNNAME_PointsBase_Forecasted, PointsBase_Forecasted); } @Override public BigDecimal getPointsBase_Forecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Forecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiceable (final BigDecimal PointsBase_Invoiceable) { set_Value (COLUMNNAME_PointsBase_Invoiceable, PointsBase_Invoiceable); } @Override public BigDecimal getPointsBase_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setPointsBase_Invoiced (final BigDecimal PointsBase_Invoiced) { set_Value (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced); } @Override public BigDecimal getPointsBase_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Instance.java
1
请完成以下Java代码
public boolean isPickQAConfirm() { return get_ValueAsBoolean(COLUMNNAME_IsPickQAConfirm); } @Override public void setIsShipConfirm (final boolean IsShipConfirm) { set_Value (COLUMNNAME_IsShipConfirm, IsShipConfirm); } @Override public boolean isShipConfirm() { return get_ValueAsBoolean(COLUMNNAME_IsShipConfirm); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setIsSplitWhenDifference (final boolean IsSplitWhenDifference) { set_Value (COLUMNNAME_IsSplitWhenDifference, IsSplitWhenDifference); } @Override public boolean isSplitWhenDifference() { return get_ValueAsBoolean(COLUMNNAME_IsSplitWhenDifference); } @Override public org.compiere.model.I_AD_Sequence getLotNo_Sequence() { return get_ValueAsPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setLotNo_Sequence(final org.compiere.model.I_AD_Sequence LotNo_Sequence) { set_ValueFromPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, LotNo_Sequence); } @Override public void setLotNo_Sequence_ID (final int LotNo_Sequence_ID) { if (LotNo_Sequence_ID < 1) set_Value (COLUMNNAME_LotNo_Sequence_ID, null); else set_Value (COLUMNNAME_LotNo_Sequence_ID, LotNo_Sequence_ID); } @Override public int getLotNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_LotNo_Sequence_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
@Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintName (final java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } @Override public java.lang.String getPrintName() { return get_ValueAsString(COLUMNNAME_PrintName); } @Override public org.compiere.model.I_R_RequestType getR_RequestType() { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); } @Override public void setR_RequestType_ID (final int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID); } @Override public int getR_RequestType_ID() { return get_ValueAsInt(COLUMNNAME_R_RequestType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
1
请完成以下Java代码
public class User { /** * 城市编号 */ private Long id; /** * 城市名称 */ private String userName; /** * 描述 */ private String description; private City city; public City getCity() { return city; } public void setCity(City city) { this.city = city; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\springboot-learning-example-master\springboot-mybatis-mutil-datasource\src\main\java\org\spring\springboot\domain\User.java
1
请完成以下Java代码
public void onCreated(TbActorCtx context) throws Exception { start(context); } public void onUpdate(TbActorCtx context) throws Exception { restart(context); } public void onActivate(TbActorCtx context) throws Exception { restart(context); } public void onSuspend(TbActorCtx context) throws Exception { stop(context); } public void onStop(TbActorCtx context) throws Exception { stop(context); } private void restart(TbActorCtx context) throws Exception { stop(context); start(context); } public ScheduledFuture<?> scheduleStatsPersistTick(TbActorCtx context, long statsPersistFrequency) { return schedulePeriodicMsgWithDelay(context, StatsPersistTick.INSTANCE, statsPersistFrequency, statsPersistFrequency); } protected boolean checkMsgValid(TbMsg tbMsg) { var valid = tbMsg.isValid(); if (!valid) { if (log.isTraceEnabled()) { log.trace("Skip processing of message: {} because it is no longer valid!", tbMsg); } } return valid;
} protected void checkComponentStateActive(TbMsg tbMsg) throws RuleNodeException { if (state != ComponentLifecycleState.ACTIVE) { log.debug("Component is not active. Current state [{}] for processor [{}][{}] tenant [{}]", state, entityId.getEntityType(), entityId, tenantId); RuleNodeException ruleNodeException = getInactiveException(); if (tbMsg != null) { tbMsg.getCallback().onFailure(ruleNodeException); } throw ruleNodeException; } } abstract protected RuleNodeException getInactiveException(); }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\shared\ComponentMsgProcessor.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventSubscriptionEntity other = (EventSubscriptionEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); if (executionId != null) {
referenceIdAndClass.put(executionId, ExecutionEntity.class); } return referenceIdAndClass; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventType=" + eventType + ", eventName=" + eventName + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", activityId=" + activityId + ", tenantId=" + tenantId + ", configuration=" + configuration + ", revision=" + revision + ", created=" + created + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EventSubscriptionEntity.java
1
请完成以下Java代码
public String getDisplayName() { return displayName; } /** * @return true if this action is currently running */ public final boolean isRunning() { return running; } @Override public void execute() { running = true; try { execute0(); } finally { running = false; } } private void execute0() { final IQuery<I_C_Invoice_Candidate> query = retrieveInvoiceCandidatesToApproveQuery() .create(); // // Fail if there is nothing to update final int countToUpdate = query.count(); if (countToUpdate <= 0) { throw new AdempiereException("@NoSelection@"); } // // Ask user if we shall updated final boolean doUpdate = clientUI.ask() .setParentWindowNo(windowNo)
.setAdditionalMessage(msgBL.getMsg(Env.getCtx(), MSG_DoYouWantToUpdate_1P, new Object[] { countToUpdate })) .setDefaultAnswer(false) .getAnswer(); if (!doUpdate) { return; } // // Update selected invoice candidates and mark them as approved for invoicing final int countUpdated = query.update(new IQueryUpdater<I_C_Invoice_Candidate>() { @Override public boolean update(final I_C_Invoice_Candidate ic) { ic.setApprovalForInvoicing(true); return MODEL_UPDATED; } }); // // Refresh rows, because they were updated if (countUpdated > 0) { gridTab.dataRefreshAll(); } // // Inform the user clientUI.info(windowNo, "Updated", // AD_Message/title "#" + countUpdated // message ); } private final IQueryBuilder<I_C_Invoice_Candidate> retrieveInvoiceCandidatesToApproveQuery() { return gridTab.createQueryBuilder(I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, true) // not processed .addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_ApprovalForInvoicing, true) // not already approved ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\IC_ApproveForInvoicing_Action.java
1
请完成以下Java代码
public class JsonType implements VariableType { private static final Logger logger = LoggerFactory.getLogger(JsonType.class); public static final String JSON = "json"; private final int maxLength; private ObjectMapper objectMapper; private boolean serializePOJOsInVariablesToJson; private JsonTypeConverter jsonTypeConverter; public JsonType( int maxLength, ObjectMapper objectMapper, boolean serializePOJOsInVariablesToJson, JsonTypeConverter jsonTypeConverter ) { this.maxLength = maxLength; this.objectMapper = objectMapper; this.serializePOJOsInVariablesToJson = serializePOJOsInVariablesToJson; this.jsonTypeConverter = jsonTypeConverter; } public String getTypeName() { return JSON; } public boolean isCachable() { return true; } public Object getValue(ValueFields valueFields) { Object loadedValue = null; if (valueFields.getTextValue() != null && valueFields.getTextValue().length() > 0) { try { loadedValue = jsonTypeConverter.convertToValue( objectMapper.readTree(valueFields.getTextValue()), valueFields );
} catch (Exception e) { logger.error("Error reading json variable " + valueFields.getName(), e); } } return loadedValue; } public void setValue(Object value, ValueFields valueFields) { try { valueFields.setTextValue(objectMapper.writeValueAsString(value)); if (value != null) { valueFields.setTextValue2(value.getClass().getName()); } } catch (JsonProcessingException e) { logger.error("Error writing json variable " + valueFields.getName(), e); } } public boolean isAbleToStore(Object value) { if (value == null) { return true; } if ( JsonNode.class.isAssignableFrom(value.getClass()) || (objectMapper.canSerialize(value.getClass()) && serializePOJOsInVariablesToJson) ) { try { return objectMapper.writeValueAsString(value).length() <= maxLength; } catch (JsonProcessingException e) { logger.error("Error writing json variable of type " + value.getClass(), e); } } return false; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JsonType.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "string") public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isReadable() { return readable; } public void setReadable(boolean readable) { this.readable = readable; } public boolean isWritable() { return writable;
} public void setWritable(boolean writable) { this.writable = writable; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public String getDatePattern() { return datePattern; } public void setDatePattern(String datePattern) { this.datePattern = datePattern; } public List<RestEnumFormProperty> getEnumValues() { return enumValues; } public void setEnumValues(List<RestEnumFormProperty> enumValues) { this.enumValues = enumValues; } public void addEnumValue(RestEnumFormProperty enumValue) { enumValues.add(enumValue); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\form\RestFormProperty.java
2
请完成以下Java代码
public @Nullable Principal getUserPrincipal() { Authentication auth = getAuthentication(); if ((auth == null) || (auth.getPrincipal() == null)) { return null; } return auth; } private boolean isGranted(String role) { Authentication auth = getAuthentication(); if (this.rolePrefix != null && role != null && !role.startsWith(this.rolePrefix)) { role = this.rolePrefix + role; } if ((auth == null) || (auth.getPrincipal() == null)) { return false; } Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); if (authorities == null) { return false; } for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) { return true; } } return false; } /** * Simple searches for an exactly matching * {@link org.springframework.security.core.GrantedAuthority#getAuthority()}. * <p> * Will always return <code>false</code> if the <code>SecurityContextHolder</code> * contains an <code>Authentication</code> with <code>null</code> * <code>principal</code> and/or <code>GrantedAuthority[]</code> objects. * @param role the <code>GrantedAuthority</code><code>String</code> representation to * check for * @return <code>true</code> if an <b>exact</b> (case sensitive) matching granted * authority is located, <code>false</code> otherwise */
@Override public boolean isUserInRole(String role) { return isGranted(role); } @Override public String toString() { return "SecurityContextHolderAwareRequestWrapper[ " + getRequest() + "]"; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestWrapper.java
1
请完成以下Java代码
public String getF_MOBIL() { return F_MOBIL; } public void setF_MOBIL(String f_MOBIL) { F_MOBIL = f_MOBIL; } public String getF_EMAIL() { return F_EMAIL; } public void setF_EMAIL(String f_EMAIL) { F_EMAIL = f_EMAIL; } public String getF_BGOFFICEID() { return F_BGOFFICEID; } public void setF_BGOFFICEID(String f_BGOFFICEID) { F_BGOFFICEID = f_BGOFFICEID; } public String getF_INFOMOBIL() { return F_INFOMOBIL; } public void setF_INFOMOBIL(String f_INFOMOBIL) { F_INFOMOBIL = f_INFOMOBIL; } public String getF_INFOMAN() { return F_INFOMAN; } public void setF_INFOMAN(String f_INFOMAN) { F_INFOMAN = f_INFOMAN; } public String getF_LOGPASS() { return F_LOGPASS; } public void setF_LOGPASS(String f_LOGPASS) { F_LOGPASS = f_LOGPASS; } public String getF_STARTDATE() { return F_STARTDATE; } public void setF_STARTDATE(String f_STARTDATE) { F_STARTDATE = f_STARTDATE; } public String getF_STOPDATE() { return F_STOPDATE; } public void setF_STOPDATE(String f_STOPDATE) { F_STOPDATE = f_STOPDATE; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_MEMO() { return F_MEMO; } public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; }
public String getF_AUDITTIME() { return F_AUDITTIME; } public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; } public Integer getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISPRINTBILL() { return F_ISPRINTBILL; } public void setF_ISPRINTBILL(String f_ISPRINTBILL) { F_ISPRINTBILL = f_ISPRINTBILL; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
1
请在Spring Boot框架中完成以下Java代码
private void createUserTenant(String userId, Boolean isUpdate, Integer tenantId) { if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) { //判断当前用户是否已在该租户下面 Integer count = sysUserTenantMapper.userTenantIzExist(userId, tenantId); //count 为0 新增租户用户,否则不用新增 if (count == 0) { SysUserTenant userTenant = new SysUserTenant(); userTenant.setTenantId(tenantId); userTenant.setUserId(userId); userTenant.setStatus(isUpdate ? CommonConstant.USER_TENANT_UNDER_REVIEW : CommonConstant.USER_TENANT_NORMAL); sysUserTenantMapper.insert(userTenant); } } } /** * 新建或更新用户部门关系表 * @param idsMap 部门id集合 key为企业微信的id value 为系统部门的id * @param sysUserId 系统对应的用户id */ private void userDepartSaveOrUpdate(Map<String, String> idsMap, String sysUserId, String[] departIds) { LambdaQueryWrapper<SysUserDepart> query = new LambdaQueryWrapper<>(); query.eq(SysUserDepart::getUserId,sysUserId);
for (String departId:departIds) { departId = departId.trim(); if(idsMap.containsKey(departId)){ String value = idsMap.get(departId); //查询用户是否在部门里面 query.eq(SysUserDepart::getDepId,value); long count = sysUserDepartService.count(query); if(count == 0){ //不存在,则新增部门用户关系 SysUserDepart sysUserDepart = new SysUserDepart(null,sysUserId,value); sysUserDepartService.save(sysUserDepart); } } } } public List<JwUserDepartVo> getThirdUserBindByWechat(int tenantId) { return sysThirdAccountMapper.getThirdUserBindByWechat(tenantId,THIRD_TYPE); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\ThirdAppWechatEnterpriseServiceImpl.java
2
请完成以下Java代码
protected MilestoneInstanceEntityManager getMilestoneInstanceEntityManager() { return cmmnEngineConfiguration.getMilestoneInstanceEntityManager(); } protected HistoricCaseInstanceEntityManager getHistoricCaseInstanceEntityManager() { return cmmnEngineConfiguration.getHistoricCaseInstanceEntityManager(); } protected HistoricMilestoneInstanceEntityManager getHistoricMilestoneInstanceEntityManager() { return cmmnEngineConfiguration.getHistoricMilestoneInstanceEntityManager(); } protected HistoricPlanItemInstanceEntityManager getHistoricPlanItemInstanceEntityManager() { return cmmnEngineConfiguration.getHistoricPlanItemInstanceEntityManager(); } protected VariableInstanceEntityManager getVariableInstanceEntityManager() { return cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableInstanceEntityManager(); } protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() { return cmmnEngineConfiguration.getVariableServiceConfiguration().getHistoricVariableInstanceEntityManager(); } protected IdentityLinkEntityManager getIdentityLinkEntityManager() { return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager(); } protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkEntityManager(); } protected EntityLinkEntityManager getEntityLinkEntityManager() { return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getEntityLinkEntityManager(); }
protected HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() { return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getHistoricEntityLinkEntityManager(); } protected TaskEntityManager getTaskEntityManager() { return cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskEntityManager(); } protected HistoricTaskLogEntryEntityManager getHistoricTaskLogEntryEntityManager() { return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskLogEntryEntityManager(); } protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() { return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskInstanceEntityManager(); } protected CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\AbstractCmmnManager.java
1
请完成以下Java代码
private void updateData(final String element, final int id, final I_C_AcctSchema_Element elementRecord) { MAccount.updateValueDescription(Env.getCtx(), element + "=" + id, ITrx.TRXNAME_ThreadInherited); // { final int clientId = elementRecord.getAD_Client_ID(); final String sql = "UPDATE C_ValidCombination SET " + element + "=? WHERE " + element + " IS NULL AND AD_Client_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { id, clientId }, ITrx.TRXNAME_ThreadInherited); } // { final int acctSchemaId = elementRecord.getC_AcctSchema_ID(); final String sql = "UPDATE Fact_Acct SET " + element + "=? WHERE " + element + " IS NULL AND C_AcctSchema_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { id, acctSchemaId }, ITrx.TRXNAME_ThreadInherited); } }
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_C_AcctSchema_Element element) { final AcctSchemaElementType elementType = AcctSchemaElementType.ofCode(element.getElementType()); if (!elementType.isDeletable()) { throw new AdempiereException("@DeleteError@ @IsMandatory@"); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }) public void afterDelete(final I_C_AcctSchema_Element element) { MAccount.updateValueDescription(Env.getCtx(), "AD_Client_ID=" + element.getAD_Client_ID(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_AcctSchema_Element.java
1
请完成以下Java代码
public class DefinitionEntityManagerImpl extends AbstractEngineEntityManager<DmnEngineConfiguration, DecisionEntity, DecisionDataManager> implements DecisionEntityManager { public DefinitionEntityManagerImpl(DmnEngineConfiguration dmnEngineConfiguration, DecisionDataManager DefinitionDataManager) { super(dmnEngineConfiguration, DefinitionDataManager); } @Override public DecisionEntity findLatestDecisionByKey(String DefinitionKey) { return dataManager.findLatestDecisionByKey(DefinitionKey); } @Override public DecisionEntity findLatestDecisionByKeyAndTenantId(String DefinitionKey, String tenantId) { return dataManager.findLatestDecisionByKeyAndTenantId(DefinitionKey, tenantId); } @Override public void deleteDecisionsByDeploymentId(String deploymentId) { dataManager.deleteDecisionsByDeploymentId(deploymentId); } @Override public List<DmnDecision> findDecisionsByQueryCriteria(DecisionQueryImpl DefinitionQuery) { return dataManager.findDecisionsByQueryCriteria(DefinitionQuery); } @Override public long findDecisionCountByQueryCriteria(DecisionQueryImpl DefinitionQuery) { return dataManager.findDecisionCountByQueryCriteria(DefinitionQuery); } @Override public DecisionEntity findDecisionByDeploymentAndKey(String deploymentId, String DefinitionKey) { return dataManager.findDecisionByDeploymentAndKey(deploymentId, DefinitionKey); }
@Override public DecisionEntity findDecisionByDeploymentAndKeyAndTenantId(String deploymentId, String decisionKey, String tenantId) { return dataManager.findDecisionByDeploymentAndKeyAndTenantId(deploymentId, decisionKey, tenantId); } @Override public DecisionEntity findDecisionByKeyAndVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { if (tenantId == null || DmnEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findDecisionByKeyAndVersion(definitionKey, definitionVersion); } else { return dataManager.findDecisionByKeyAndVersionAndTenantId(definitionKey, definitionVersion, tenantId); } } @Override public List<DmnDecision> findDecisionsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDecisionsByNativeQuery(parameterMap); } @Override public long findDecisionCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDecisionCountByNativeQuery(parameterMap); } @Override public void updateDecisionTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateDecisionTenantIdForDeployment(deploymentId, newTenantId); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DefinitionEntityManagerImpl.java
1
请完成以下Java代码
public class VEditorUI { static final String KEY_VEditor_Height = "VEditor.Height"; static final int DEFAULT_VEditor_Height = 23; public static Object[] getUIDefaults() { return new Object[] { // // Label (and also editor's labels) border // NOTE: we add a small space on top in order to have the label text aligned on same same base line as the text from the right text field. AdempiereLabelUI.KEY_Border, new BorderUIResource(BorderFactory.createEmptyBorder(3, 0, 0, 0)) // // Editor button align (i.e. that small button of an editor field which is opening the Info Window) , VEditorDialogButtonAlign.DEFAULT_EditorUI, VEditorDialogButtonAlign.Right // , VEditorDialogButtonAlign.createUIKey("VNumber"), VEditorDialogButtonAlign.Hide // , VEditorDialogButtonAlign.createUIKey("VDate"), VEditorDialogButtonAlign.Hide // , VEditorDialogButtonAlign.createUIKey("VURL"), VEditorDialogButtonAlign.Right // i.e. the online button // // Editor height , KEY_VEditor_Height, DEFAULT_VEditor_Height // // VButton editor , "VButton.Action.textColor", AdempierePLAF.createActiveValueProxy("black", Color.BLACK) , "VButton.Posted.textColor", new ColorUIResource(Color.MAGENTA)
}; } public static final int getVEditorHeight() { return AdempierePLAF.getInt(KEY_VEditor_Height, DEFAULT_VEditor_Height); } public static final void installMinMaxSizes(final JComponent comp) { final int height = VEditorUI.getVEditorHeight(); comp.setMinimumSize(new Dimension(30, height)); comp.setMaximumSize(new Dimension(Integer.MAX_VALUE, height)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\VEditorUI.java
1
请完成以下Java代码
protected void initialized(Supplier<C> context) { } /** * Decides whether the rule implemented by the strategy matches the supplied request. * @param request the source request * @param context a supplier for the initialized context (may throw an exception) * @return if the request matches */ protected abstract boolean matches(HttpServletRequest request, Supplier<C> context); /** * Returns {@code true} if the specified context is a * {@link WebServerApplicationContext} with a matching server namespace. * @param context the context to check * @param serverNamespace the server namespace to match against * @return {@code true} if the server namespace of the context matches * @since 4.0.1 */ protected final boolean hasServerNamespace(@Nullable ApplicationContext context, String serverNamespace) { if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) { return false; }
return WebServerApplicationContext.hasServerNamespace(context, serverNamespace); } /** * Returns the server namespace if the specified context is a * {@link WebServerApplicationContext}. * @param context the context * @return the server namespace or {@code null} if the context is not a * {@link WebServerApplicationContext} * @since 4.0.1 */ protected final @Nullable String getServerNamespace(@Nullable ApplicationContext context) { if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) { return null; } return WebServerApplicationContext.getServerNamespace(context); } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\web\servlet\ApplicationContextRequestMatcher.java
1
请完成以下Java代码
public void setFreeFreightPoint(BigDecimal freeFreightPoint) { this.freeFreightPoint = freeFreightPoint; } public Integer getCommentGrowthPoint() { return commentGrowthPoint; } public void setCommentGrowthPoint(Integer commentGrowthPoint) { this.commentGrowthPoint = commentGrowthPoint; } public Integer getPriviledgeFreeFreight() { return priviledgeFreeFreight; } public void setPriviledgeFreeFreight(Integer priviledgeFreeFreight) { this.priviledgeFreeFreight = priviledgeFreeFreight; } public Integer getPriviledgeSignIn() { return priviledgeSignIn; } public void setPriviledgeSignIn(Integer priviledgeSignIn) { this.priviledgeSignIn = priviledgeSignIn; } public Integer getPriviledgeComment() { return priviledgeComment; } public void setPriviledgeComment(Integer priviledgeComment) { this.priviledgeComment = priviledgeComment; } public Integer getPriviledgePromotion() { return priviledgePromotion; } public void setPriviledgePromotion(Integer priviledgePromotion) { this.priviledgePromotion = priviledgePromotion; } public Integer getPriviledgeMemberPrice() { return priviledgeMemberPrice; } public void setPriviledgeMemberPrice(Integer priviledgeMemberPrice) { this.priviledgeMemberPrice = priviledgeMemberPrice; } public Integer getPriviledgeBirthday() { return priviledgeBirthday; } public void setPriviledgeBirthday(Integer priviledgeBirthday) { this.priviledgeBirthday = priviledgeBirthday; } public String getNote() { return note; }
public void setNote(String note) { this.note = note; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", growthPoint=").append(growthPoint); sb.append(", defaultStatus=").append(defaultStatus); sb.append(", freeFreightPoint=").append(freeFreightPoint); sb.append(", commentGrowthPoint=").append(commentGrowthPoint); sb.append(", priviledgeFreeFreight=").append(priviledgeFreeFreight); sb.append(", priviledgeSignIn=").append(priviledgeSignIn); sb.append(", priviledgeComment=").append(priviledgeComment); sb.append(", priviledgePromotion=").append(priviledgePromotion); sb.append(", priviledgeMemberPrice=").append(priviledgeMemberPrice); sb.append(", priviledgeBirthday=").append(priviledgeBirthday); sb.append(", note=").append(note); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLevel.java
1
请完成以下Java代码
public Response getTextResponseTypeDefined() { String message = "This is a plain text response"; return Response .status(Response.Status.OK) .entity(message) .type(MediaType.TEXT_PLAIN) .build(); } @GET @Path("/text_plain_annotation") @Produces({ MediaType.TEXT_PLAIN }) public Response getTextResponseTypeAnnotated() { String message = "This is a plain text response via annotation"; return Response .status(Response.Status.OK) .entity(message) .build(); } @GET @Path("/pojo") public Response getPojoResponse() { Person person = new Person("Abh", "Nepal"); return Response .status(Response.Status.OK) .entity(person) .build(); }
@GET @Path("/json") public Response getJsonResponse() { String message = "{\"hello\": \"This is a JSON response\"}"; return Response .status(Response.Status.OK) .entity(message) .type(MediaType.APPLICATION_JSON) .build(); } @GET @Path("/xml") @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> This is a xml response </hello>"; } @GET @Path("/html") @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + " This is a html title </title>" + "<body><h1>" + " This is a html response body " + "</body></h1>" + "</html> "; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\Responder.java
1
请完成以下Java代码
public ChangeTenantIdResult execute(CommandContext commandContext) { String sourceTenantId = builder.getSourceTenantId(); String targetTenantId = builder.getTargetTenantId(); Map<String, Object> parameters = new HashMap<>(); parameters.put("sourceTenantId", sourceTenantId); parameters.put("targetTenantId", targetTenantId); parameters.put("definitionTenantId", builder.getDefinitionTenantId()); DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class); Map<String, Long> results = executeOperation(dbSqlSession, parameters); DefaultChangeTenantIdResult result = new DefaultChangeTenantIdResult(results); beforeReturn(commandContext, result); return result; } protected void beforeReturn(CommandContext commandContext, ChangeTenantIdResult result) {
// Nothing to do } protected abstract Map<String, Long> executeOperation(DbSqlSession dbSqlSession, Map<String, Object> parameters); protected AbstractEngineConfiguration getEngineConfiguration(CommandContext commandContext) { AbstractEngineConfiguration configuration = commandContext.getEngineConfigurations().get(engineScopeType); if (configuration != null) { return configuration; } throw new FlowableException("There is no engine registered for the scope type " + engineScopeType); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\tenant\BaseChangeTenantIdCmd.java
1
请完成以下Java代码
public long getTail() { return tail.get(); } public long getCursor() { return cursor.get(); } public int getBufferSize() { return bufferSize; } /** * Setters */ public void setBufferPaddingExecutor(BufferPaddingExecutor bufferPaddingExecutor) { this.bufferPaddingExecutor = bufferPaddingExecutor; } public void setRejectedPutHandler(RejectedPutBufferHandler rejectedPutHandler) {
this.rejectedPutHandler = rejectedPutHandler; } public void setRejectedTakeHandler(RejectedTakeBufferHandler rejectedTakeHandler) { this.rejectedTakeHandler = rejectedTakeHandler; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("RingBuffer [bufferSize=").append(bufferSize) .append(", tail=").append(tail) .append(", cursor=").append(cursor) .append(", paddingThreshold=").append(paddingThreshold).append("]"); return builder.toString(); } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\buffer\RingBuffer.java
1
请在Spring Boot框架中完成以下Java代码
public QuoteDTO save(QuoteDTO quoteDTO) { log.debug("Request to save Quote : {}", quoteDTO); Quote quote = quoteMapper.toEntity(quoteDTO); quote = quoteRepository.save(quote); return quoteMapper.toDto(quote); } /** * Get all the quotes. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<QuoteDTO> findAll(Pageable pageable) { log.debug("Request to get all Quotes"); return quoteRepository.findAll(pageable) .map(quoteMapper::toDto); } /** * Get one quote by id. * * @param id the id of the entity
* @return the entity */ @Override @Transactional(readOnly = true) public Optional<QuoteDTO> findOne(Long id) { log.debug("Request to get Quote : {}", id); return quoteRepository.findById(id) .map(quoteMapper::toDto); } /** * Delete the quote by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete Quote : {}", id); quoteRepository.deleteById(id); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\impl\QuoteServiceImpl.java
2
请完成以下Java代码
private HuIdsFilterList computeFixedHUIds() { return convert(new CaseConverter<HuIdsFilterList>() { @Override public HuIdsFilterList acceptAll() { return HuIdsFilterList.ALL; } @Override public HuIdsFilterList acceptAllBut(@NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds) { if (excludeHUIds.isEmpty()) { return HuIdsFilterList.ALL; } else { return null; // cannot compute } } @Override public HuIdsFilterList acceptNone() { return HuIdsFilterList.NONE; } @Override public HuIdsFilterList acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds) { return fixedHUIds; } @Override public HuIdsFilterList huQuery(@NonNull final IHUQueryBuilder initialHUQueryCopy, @NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds) { return null; // cannot compute } }); } public boolean isPossibleHighVolume(final int highVolumeThreshold) { final Integer estimatedSize = estimateSize(); return estimatedSize == null || estimatedSize > highVolumeThreshold; } @Nullable private Integer estimateSize() { return getFixedHUIds().map(HuIdsFilterList::estimateSize).orElse(null); } interface CaseConverter<T> { T acceptAll(); T acceptAllBut(@NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds);
T acceptNone(); T acceptOnly(@NonNull HuIdsFilterList fixedHUIds, @NonNull Set<HuId> alwaysIncludeHUIds); T huQuery(@NonNull IHUQueryBuilder initialHUQueryCopy, @NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds); } public synchronized <T> T convert(@NonNull final CaseConverter<T> converter) { if (initialHUQuery == null) { if (initialHUIds == null) { throw new IllegalStateException("initialHUIds shall not be null for " + this); } else if (initialHUIds.isAll()) { if (mustHUIds.isEmpty() && shallNotHUIds.isEmpty()) { return converter.acceptAll(); } else { return converter.acceptAllBut(ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } else { final ImmutableSet<HuId> fixedHUIds = Stream.concat( initialHUIds.stream(), mustHUIds.stream()) .distinct() .filter(huId -> !shallNotHUIds.contains(huId)) // not excluded .collect(ImmutableSet.toImmutableSet()); if (fixedHUIds.isEmpty()) { return converter.acceptNone(); } else { return converter.acceptOnly(HuIdsFilterList.of(fixedHUIds), ImmutableSet.copyOf(mustHUIds)); } } } else { return converter.huQuery(initialHUQuery.copy(), ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterData.java
1
请在Spring Boot框架中完成以下Java代码
public void setTerminatePlanItemDefinitionIds(List<String> terminatePlanItemDefinitionIds) { this.terminatePlanItemDefinitionIds = terminatePlanItemDefinitionIds; } public List<String> getAddWaitingForRepetitionPlanItemDefinitionIds() { return addWaitingForRepetitionPlanItemDefinitionIds; } @ApiModelProperty(value = "add waiting for repetition to provided plan item definition ids") public void setAddWaitingForRepetitionPlanItemDefinitionIds(List<String> addWaitingForRepetitionPlanItemDefinitionIds) { this.addWaitingForRepetitionPlanItemDefinitionIds = addWaitingForRepetitionPlanItemDefinitionIds; } public List<String> getRemoveWaitingForRepetitionPlanItemDefinitionIds() { return removeWaitingForRepetitionPlanItemDefinitionIds; } @ApiModelProperty(value = "remove waiting for repetition to provided plan item definition ids") public void setRemoveWaitingForRepetitionPlanItemDefinitionIds(List<String> removeWaitingForRepetitionPlanItemDefinitionIds) { this.removeWaitingForRepetitionPlanItemDefinitionIds = removeWaitingForRepetitionPlanItemDefinitionIds; } public Map<String, String> getChangePlanItemIds() { return changePlanItemIds; } @ApiModelProperty(value = "map an existing plan item id to new plan item id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.")
public void setChangePlanItemIds(Map<String, String> changePlanItemIds) { this.changePlanItemIds = changePlanItemIds; } public Map<String, String> getChangePlanItemIdsWithDefinitionId() { return changePlanItemIdsWithDefinitionId; } @ApiModelProperty(value = "map an existing plan item id to new plan item id with the plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemIdsWithDefinitionId(Map<String, String> changePlanItemIdsWithDefinitionId) { this.changePlanItemIdsWithDefinitionId = changePlanItemIdsWithDefinitionId; } public List<PlanItemDefinitionWithTargetIdsRequest> getChangePlanItemDefinitionsWithNewTargetIds() { return changePlanItemDefinitionsWithNewTargetIds; } @ApiModelProperty(value = "map an existing plan item id to a new plan item id and plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemDefinitionsWithNewTargetIds(List<PlanItemDefinitionWithTargetIdsRequest> changePlanItemDefinitionsWithNewTargetIds) { this.changePlanItemDefinitionsWithNewTargetIds = changePlanItemDefinitionsWithNewTargetIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\ChangePlanItemStateRequest.java
2
请在Spring Boot框架中完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; }
public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public void setProperties(List<RestFormProperty> properties) { this.properties = properties; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestFormProperty.class) public List<RestFormProperty> getProperties() { return properties; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\form\SubmitFormRequest.java
2
请完成以下Java代码
private final class RfqResponseLineQtyByNetAmtComparator implements Comparator<I_C_RfQResponseLineQty> { public RfqResponseLineQtyByNetAmtComparator() { super(); } @Override public int compare(final I_C_RfQResponseLineQty q1, final I_C_RfQResponseLineQty q2) { if (q1 == null) { throw new IllegalArgumentException("o1 = null"); } if (q2 == null) { throw new IllegalArgumentException("o2 = null"); } // if (!rfqBL.isValidAmt(q1)) { return -99; } if (!rfqBL.isValidAmt(q2)) { return +99; } final BigDecimal net1 = rfqBL.calculatePriceWithoutDiscount(q1); if (net1 == null)
{ return -9; } final BigDecimal net2 = rfqBL.calculatePriceWithoutDiscount(q2); if (net2 == null) { return +9; } return net1.compareTo(net2); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\DefaultRfQResponseRankingStrategy.java
1
请完成以下Java代码
public class WebAuthnAuthenticationProvider implements AuthenticationProvider { private static final String AUTHORITY = FactorGrantedAuthority.WEBAUTHN_AUTHORITY; private final WebAuthnRelyingPartyOperations relyingPartyOperations; private final UserDetailsService userDetailsService; /** * Creates a new instance. * @param relyingPartyOperations the {@link WebAuthnRelyingPartyOperations} to use. * Cannot be null. * @param userDetailsService the {@link UserDetailsService} to use. Cannot be null. */ public WebAuthnAuthenticationProvider(WebAuthnRelyingPartyOperations relyingPartyOperations, UserDetailsService userDetailsService) { Assert.notNull(relyingPartyOperations, "relyingPartyOperations cannot be null"); Assert.notNull(userDetailsService, "userDetailsService cannot be null"); this.relyingPartyOperations = relyingPartyOperations; this.userDetailsService = userDetailsService; } @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { WebAuthnAuthenticationRequestToken webAuthnRequest = (WebAuthnAuthenticationRequestToken) authentication; try { PublicKeyCredentialUserEntity userEntity = this.relyingPartyOperations .authenticate(webAuthnRequest.getWebAuthnRequest()); String username = userEntity.getName(); UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); Collection<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities()); authorities.add(FactorGrantedAuthority.fromAuthority(AUTHORITY)); return new WebAuthnAuthentication(userEntity, authorities); } catch (RuntimeException ex) { throw new BadCredentialsException(ex.getMessage(), ex); } } @Override public boolean supports(Class<?> authentication) { return WebAuthnAuthenticationRequestToken.class.isAssignableFrom(authentication); } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthenticationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Void> deleteUser(String id) { return this.userDao.findById(id) .flatMap(user -> this.userDao.delete(user)); } public Mono<User> updateUser(String id, User user) { return this.userDao.findById(id) .flatMap(u -> { u.setName(user.getName()); u.setAge(user.getAge()); u.setDescription(user.getDescription()); return this.userDao.save(u); }); } public Flux<User> getUserByAge(Integer from, Integer to) { return this.userDao.findByAgeBetween(from, to); } public Flux<User> getUserByName(String name) { return this.userDao.findByNameEquals(name); } public Flux<User> getUserByDescription(String description) { return this.userDao.findByDescriptionIsLike(description); } /** * 分页查询,只返回分页后的数据,count值需要通过 getUserByConditionCount * 方法获取 */ public Flux<User> getUserByCondition(int size, int page, User user) { Query query = getQuery(user); Sort sort = new Sort(Sort.Direction.DESC, "age"); Pageable pageable = PageRequest.of(page, size, sort); return template.find(query.with(pageable), User.class); }
/** * 返回 count,配合 getUserByCondition使用 */ public Mono<Long> getUserByConditionCount(User user) { Query query = getQuery(user); return template.count(query, User.class); } private Query getQuery(User user) { Query query = new Query(); Criteria criteria = new Criteria(); if (!StringUtils.isEmpty(user.getName())) { criteria.and("name").is(user.getName()); } if (!StringUtils.isEmpty(user.getDescription())) { criteria.and("description").regex(user.getDescription()); } query.addCriteria(criteria); return query; } }
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\service\UserService.java
2
请完成以下Java代码
public HitPolicy getHitPolicy() { return hitPolicy; } public void setHitPolicy(HitPolicy hitPolicy) { this.hitPolicy = hitPolicy; } public BuiltinAggregator getAggregation() { return aggregation; } public void setAggregation(BuiltinAggregator aggregation) { this.aggregation = aggregation; } public DecisionTableOrientation getPreferredOrientation() {
return preferredOrientation; } public void setPreferredOrientation(DecisionTableOrientation preferredOrientation) { this.preferredOrientation = preferredOrientation; } public String getOutputLabel() { return outputLabel; } public void setOutputLabel(String outputLabel) { this.outputLabel = outputLabel; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionTable.java
1
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * IsDirectPrint AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISDIRECTPRINT_AD_Reference_ID=319; /** Yes = Y */ public static final String ISDIRECTPRINT_Yes = "Y"; /** No = N */ public static final String ISDIRECTPRINT_No = "N"; /** Set Direct print. @param IsDirectPrint Print without dialog */ @Override public void setIsDirectPrint (java.lang.String IsDirectPrint) { set_Value (COLUMNNAME_IsDirectPrint, IsDirectPrint); } /** Get Direct print. @return Print without dialog */ @Override public java.lang.String getIsDirectPrint () { return (java.lang.String)get_Value(COLUMNNAME_IsDirectPrint); } /** Set Letzte Seiten. @param LastPages Letzte Seiten */ @Override public void setLastPages (int LastPages) { set_Value (COLUMNNAME_LastPages, Integer.valueOf(LastPages)); } /** Get Letzte Seiten. @return Letzte Seiten */ @Override public int getLastPages () { Integer ii = (Integer)get_Value(COLUMNNAME_LastPages); if (ii == null)
return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_PrinterRouting.java
1
请在Spring Boot框架中完成以下Java代码
public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public Boolean getIncludeEnded() { return includeEnded; } public void setIncludeEnded(Boolean includeEnded) { this.includeEnded = includeEnded; } public Boolean getIncludeLocalVariables() { return includeLocalVariables; } public void setIncludeLocalVariables(boolean includeLocalVariables) { this.includeLocalVariables = includeLocalVariables; } public String getTenantId() { return tenantId;
} public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public void setCaseInstanceIds(Set<String> caseInstanceIds) { this.caseInstanceIds = caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceQueryRequest.java
2
请完成以下Java代码
public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant(); } public LocalDate toLocalDate() { return localDate; } public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) { return Timestamp.from(toInstant(orgMapper)); } @Override public int compareTo(final @Nullable LocalDateAndOrgId o) { return compareToByLocalDate(o); }
/** * In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes. * A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?" * That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s. * * @see #compareTo(LocalDateAndOrgId) */ private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o) { if (o == null) { return 1; } return this.localDate.compareTo(o.localDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
1
请完成以下Java代码
public class ServerEventHandler extends SimpleChannelInboundHandler<String> { private static final Map<String, Channel> clients = new HashMap<>(); private static final int MAX_HISTORY = 5; private static final Queue<String> history = new LinkedList<>(); private void handleBroadcast(Message message, ChannelHandlerContext context) { final String channelId = id(context.channel()); System.out.printf("[clients: %d] message: %s\n", clients.size(), message); clients.forEach((id, channel) -> { if (!id.equals(channelId)) { ChannelFuture relay = channel.writeAndFlush(message.toString()); relay.addListener(new ChannelInfoListener("message relayed to " + id)); } }); history.add(message.toString() + "\n"); if (history.size() > MAX_HISTORY) history.poll(); } @Override public void channelRead0(ChannelHandlerContext context, String msg) { handleBroadcast(Message.parse(msg), context); } @Override public void channelActive(final ChannelHandlerContext context) { Channel channel = context.channel();
clients.put(id(channel), channel); history.forEach(channel::writeAndFlush); handleBroadcast(new OnlineMessage(id(channel)), context); } @Override public void channelInactive(ChannelHandlerContext context) { Channel channel = context.channel(); clients.remove(id(channel)); handleBroadcast(new OfflineMessage(id(channel)), context); } private static String id(Channel channel) { return channel.id() .asShortText(); } }
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\netty\customhandlersandlisteners\handler\ServerEventHandler.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Customs Tariff. @param M_CustomsTariff_ID Customs Tariff */ @Override public void setM_CustomsTariff_ID (int M_CustomsTariff_ID) { if (M_CustomsTariff_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, Integer.valueOf(M_CustomsTariff_ID)); } /** Get Customs Tariff. @return Customs Tariff */ @Override public int getM_CustomsTariff_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CustomsTariff_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CustomsTariff.java
1
请完成以下Java代码
public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public boolean isWithJobException() { return withJobException; } public String getLocale() { return locale; } public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(ProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); }
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; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public void vetoableChange (PropertyChangeEvent e) { final String propertyName = e.getPropertyName(); if (I_M_Transaction.COLUMNNAME_M_Product_ID.equals(propertyName)) { productField.setValue(e.getNewValue()); } else if (I_M_Transaction.COLUMNNAME_C_BPartner_ID.equals(propertyName)) { bpartnerField.setValue(e.getNewValue()); } } // vetoableChange public void setProductFieldValue(final Object value) { productField.setValue(value); refresh(); } public void setDate(final Timestamp date) { dateFField.setValue(date); dateTField.setValue(date); refresh(); } /************************************************************************** * Refresh - Create Query and refresh grid */ private void refresh() { final Object organization = orgField.getValue(); final Object locator = locatorField.getValue(); final Object product = productField.getValue();
final Object movementType = mtypeField.getValue(); final Timestamp movementDateFrom = dateFField.getValue(); final Timestamp movementDateTo = dateTField.getValue(); final Object bpartnerId = bpartnerField.getValue(); Services.get(IClientUI.class).executeLongOperation(panel, () -> refresh(organization, locator, product, movementType, movementDateFrom, movementDateTo, bpartnerId, statusBar)); } // refresh /** * Zoom */ @Override public void zoom() { super.zoom(); // Zoom panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); AWindow frame = new AWindow(); if (!frame.initWindow(adWindowId, query)) { panel.setCursor(Cursor.getDefaultCursor()); return; } AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; panel.setCursor(Cursor.getDefaultCursor()); } // zoom } // VTrxMaterial
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTrxMaterial.java
1
请完成以下Java代码
public void setAD_Process_ID (int AD_Process_ID) { if (AD_Process_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Process_ID, Integer.valueOf(AD_Process_ID)); } /** Get Prozess. @return Process or Report */ @Override public int getAD_Process_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class); } @Override public void setAD_Role(org.compiere.model.I_AD_Role AD_Role) { set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role); } /** Set Rolle. @param AD_Role_ID Responsibility Role */ @Override public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); }
/** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); } /** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Access.java
1
请完成以下Java代码
public class EventSubscriptionQueryValue implements Serializable { private static final long serialVersionUID = 1L; protected String eventType; protected String eventName; public EventSubscriptionQueryValue(String eventName, String eventType) { this.eventName = eventName; this.eventType = eventType; } public String getEventType() { return eventType; }
public void setEventType(String eventType) { this.eventType = eventType; } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\EventSubscriptionQueryValue.java
1
请完成以下Java代码
protected void setValue(final Object value) { setValue(IValidationContext.DISABLED, value); } private void setValue(final IValidationContext validationCtx, final Object value) { String retValue = null; try { // Checkbox if (m_displayType == DisplayType.YesNo) { if (value instanceof Boolean) m_check.setSelected(((Boolean)value).booleanValue()); else m_check.setSelected("Y".equals(value)); return; } // metas-2009_0021_AP1_CR053: begin else if (m_displayType == DisplayType.Button && m_button != null) { m_button.setValue(value); } // metas-2009_0021_AP1_CR053: end else if (value == null) { retValue = null; } // Number else if (DisplayType.isNumeric(m_displayType)) { retValue = m_numberFormat.format(value); } // Date else if (DisplayType.isDate(m_displayType)) { retValue = m_dateFormat.format(value); } // Row ID else if (m_displayType == DisplayType.RowID) { retValue = ""; } // Lookup else if (m_lookup != null && DisplayType.isAnyLookup(m_displayType)) { retValue = m_lookup.getDisplay(validationCtx, value); } // Button else if (m_displayType == DisplayType.Button) { if (IColumnBL.isRecordIdColumnName(m_columnName)) retValue = "#" + value + "#"; else retValue = null; } // Password (fixed string) else if (m_password) { retValue = "**********"; } // other (String ...) else
{ super.setValue(value); return; } } catch (Exception e) { log.error("(" + value + ") " + value.getClass().getName(), e); retValue = value.toString(); } super.setValue(retValue); } // setValue @Override public String toString() { return "VCellRenderer[" + m_columnName + ",DisplayType=" + m_displayType + " - " + m_lookup + "]"; } // toString /** * Sets precision to be used in case we are dealing with a number. * * If not set, default displayType's precision will be used. * * @param precision */ public void setPrecision(final int precision) { if (m_numberFormat != null) { m_numberFormat.setMinimumFractionDigits(precision); m_numberFormat.setMaximumFractionDigits(precision); } } } // VCellRenderer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCellRenderer.java
1
请完成以下Java代码
public void setLabelWidth (int LabelWidth) { set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth)); } /** Get Label Width. @return Width of the Label */ public int getLabelWidth () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth); 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); } /** Get Record ID/ColumnName
@return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Printer Name. @param PrinterName Name of the Printer */ public void setPrinterName (String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } /** Get Printer Name. @return Name of the Printer */ public String getPrinterName () { return (String)get_Value(COLUMNNAME_PrinterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentLocationAdaptersRegistry { private static final Logger logger = LogManager.getLogger(DocumentLocationAdaptersRegistry.class); private final CompositeDocumentLocationAdapterFactory factories; public DocumentLocationAdaptersRegistry(final List<DocumentLocationAdapterFactory> factories) { this.factories = new CompositeDocumentLocationAdapterFactory(factories); logger.info("Factories: {}", this.factories); } public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(@NonNull final Object record) { return factories.getDocumentLocationAdapterIfHandled(record); }
public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(@NonNull final Object record) { return factories.getDocumentBillLocationAdapterIfHandled(record); } public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(@NonNull final Object record) { return factories.getDocumentDeliveryLocationAdapter(record); } public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(@NonNull final Object record) { return factories.getDocumentHandOverLocationAdapter(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\adapter\DocumentLocationAdaptersRegistry.java
2
请在Spring Boot框架中完成以下Java代码
public ScheduledPackageableLocks getLocks(@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { if (scheduleIds.isEmpty()) {return ScheduledPackageableLocks.EMPTY;} final ImmutableMap<TableRecordReference, ShipmentScheduleAndJobScheduleId> scheduleIdsByRecordRef = scheduleIds.stream() .collect(ImmutableMap.toImmutableMap( ShipmentScheduleAndJobScheduleId::toTableRecordReference, scheduleId -> scheduleId )); final TableRecordReferenceSet recordRefs = TableRecordReferenceSet.of(scheduleIdsByRecordRef.keySet()); return ScheduledPackageableLocks.of( CollectionUtils.mapKeys( lockManager.getLockInfosByRecordIds(recordRefs), scheduleIdsByRecordRef::get ) ); } public void lockSchedules( final @NonNull ShipmentScheduleAndJobScheduleIdSet scheduleIds, final @NonNull UserId lockedBy) { shipmentScheduleLockRepository.lock( ShipmentScheduleLockRequest.builder() // TODO: consider locking/unlocking per schedule too? .shipmentScheduleIds(scheduleIds.getShipmentScheduleIds()) .lockType(ShipmentScheduleLockType.PICKING) .lockedBy(lockedBy) .build()); } public void unlockSchedules(@NonNull final PickingJob pickingJob) { if (pickingJob.getLockedBy() == null) { return;
} this.unlockSchedules(pickingJob.getScheduleIds(), pickingJob.getLockedBy()); } public void unlockSchedules( final @NonNull ShipmentScheduleAndJobScheduleIdSet scheduleIds, final @NonNull UserId lockedBy) { shipmentScheduleLockRepository.unlock( ShipmentScheduleUnLockRequest.builder() // TODO: consider locking/unlocking per schedule too? .shipmentScheduleIds(scheduleIds.getShipmentScheduleIds()) .lockType(ShipmentScheduleLockType.PICKING) .lockedBy(lockedBy) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobLockService.java
2
请完成以下Java代码
/* package */class MaterialTrackingQuery implements IMaterialTrackingQuery { private int productId = -1; private int bpartnerId = -1; private String lot = null; private Boolean processed = null; private Boolean completeFlatrateTerm = null; private List<?> withLinkedDocuments = null; private OnMoreThanOneFound onMoreThanOneFound = OnMoreThanOneFound.ThrowException; private boolean returnReadOnlyRecords; @Override public String toString() { return "MaterialTrackingQuery [" + "productId=" + productId + ", bpartnerId=" + bpartnerId + ", processed=" + processed + ", completeFlatrateTerm" + completeFlatrateTerm + ", withLinkedDocuments=" + withLinkedDocuments + ", returnReadOnlyRecords=" + returnReadOnlyRecords + ", onMoreThanOneFound=" + onMoreThanOneFound + "]"; } @Override public int getC_BPartner_ID() { return bpartnerId; } @Override public IMaterialTrackingQuery setC_BPartner_ID(final int bpartnerId) { this.bpartnerId = bpartnerId; return this; } @Override public int getM_Product_ID() { return productId; } @Override public IMaterialTrackingQuery setM_Product_ID(final int productId) { this.productId = productId; return this; } @Override public Boolean getProcessed() { return processed; } @Override public IMaterialTrackingQuery setProcessed(final Boolean processed) { this.processed = processed; return this; } @Override public IMaterialTrackingQuery setWithLinkedDocuments(final List<?> linkedModels) { if (linkedModels == null || linkedModels.isEmpty()) { withLinkedDocuments = Collections.emptyList(); } else { withLinkedDocuments = new ArrayList<>(linkedModels); } return this; } @Override public List<?> getWithLinkedDocuments() {
return withLinkedDocuments; } @Override public IMaterialTrackingQuery setOnMoreThanOneFound(final OnMoreThanOneFound onMoreThanOneFound) { Check.assumeNotNull(onMoreThanOneFound, "onMoreThanOneFound not null"); this.onMoreThanOneFound = onMoreThanOneFound; return this; } @Override public OnMoreThanOneFound getOnMoreThanOneFound() { return onMoreThanOneFound; } @Override public IMaterialTrackingQuery setCompleteFlatrateTerm(final Boolean completeFlatrateTerm) { this.completeFlatrateTerm = completeFlatrateTerm; return this; } @Override public Boolean getCompleteFlatrateTerm() { return completeFlatrateTerm; } @Override public IMaterialTrackingQuery setLot(final String lot) { this.lot = lot; return this; } @Override public String getLot() { return lot; } @Override public IMaterialTrackingQuery setReturnReadOnlyRecords(boolean returnReadOnlyRecords) { this.returnReadOnlyRecords = returnReadOnlyRecords; return this; } @Override public boolean isReturnReadOnlyRecords() { return returnReadOnlyRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingQuery.java
1
请完成以下Java代码
protected void setupCaching(final IModelCacheService cachingService) { cachingService.addTableCacheConfigIfAbsent(I_C_AcctSchema.class); final CacheMgt cacheMgt = CacheMgt.get(); cacheMgt.enableRemoteCacheInvalidationForTableName(I_C_Period.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_C_PeriodControl.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(MAccount.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_M_Product_Acct.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_M_Product_Category_Acct.Table_Name); // GL Distribution: changes performed by Admin (on client) shall be visible to accounting engine (on server). cacheMgt.enableRemoteCacheInvalidationForTableName(I_GL_Distribution.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_GL_DistributionLine.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_C_VAT_Code.Table_Name); } @Override public void onUserLogin(final int adOrgRepoId, final int AD_Role_ID, final int AD_User_ID) { final Properties ctx = Env.getCtx(); final ClientId adClientId = Env.getClientId(ctx); // // Set default conversion type to context if (adClientId.isRegular()) { try { final OrgId adOrgId = OrgId.ofRepoId(adOrgRepoId); final Instant date = Env.getDate(ctx).toInstant(); final CurrencyConversionTypeId conversionTypeId = currenciesRepo.getDefaultConversionTypeId(adClientId, adOrgId, date); Env.setContext(ctx, CTXNAME_C_ConversionType_ID, conversionTypeId.getRepoId()); } catch (final Exception e) { logger.warn("Failed finding the default conversion type. Skip", e); } } }
private void setupAccountingService() { runInThread(AccountingDocsToRepostDBTableWatcher.builder() .sysConfigBL(sysConfigBL) .postingService(postingService) .build()); runInThread(FactAcctLogDBTableWatcher.builder() .sysConfigBL(sysConfigBL) .factAcctLogService(factAcctLogService) .build()); runInThread(FactAcctOpenItemsToUpdateDBTableWatcher.builder() .sysConfigBL(sysConfigBL) .faOpenItemsService(faOpenItemsService) .build()); } private void runInThread(@NonNull final Runnable watcher) { final Thread thread = new Thread(watcher); thread.setDaemon(true); thread.setName("accounting-" + watcher.getClass().getSimpleName()); thread.start(); logger.info("Started {}", thread); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\AcctModuleInterceptor.java
1
请完成以下Java代码
public class ExtensionElementsImpl extends BpmnModelElementInstanceImpl implements ExtensionElements { public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ExtensionElements.class, BPMN_ELEMENT_EXTENSION_ELEMENTS) .namespaceUri(BPMN20_NS) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<ExtensionElements>() { public ExtensionElements newInstance(ModelTypeInstanceContext instanceContext) { return new ExtensionElementsImpl(instanceContext); } }); typeBuilder.build(); } public ExtensionElementsImpl(ModelTypeInstanceContext context) { super(context); } public Collection<ModelElementInstance> getElements() { return ModelUtil.getModelElementCollection(getDomElement().getChildElements(), modelInstance); } public Query<ModelElementInstance> getElementsQuery() { return new QueryImpl<ModelElementInstance>(getElements()); } public ModelElementInstance addExtensionElement(String namespaceUri, String localName) {
ModelElementType extensionElementType = modelInstance.registerGenericType(namespaceUri, localName); ModelElementInstance extensionElement = extensionElementType.newInstance(modelInstance); addChildElement(extensionElement); return extensionElement; } public <T extends ModelElementInstance> T addExtensionElement(Class<T> extensionElementClass) { ModelElementInstance extensionElement = modelInstance.newInstance(extensionElementClass); addChildElement(extensionElement); return extensionElementClass.cast(extensionElement); } @Override public void addChildElement(ModelElementInstance extensionElement) { getDomElement().appendChild(extensionElement.getDomElement()); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ExtensionElementsImpl.java
1
请完成以下Java代码
public abstract class AbstractSqlTimeseriesDao extends BaseAbstractSqlTimeseriesDao implements AggregationTimeseriesDao { protected static final long SECONDS_IN_DAY = TimeUnit.DAYS.toSeconds(1); @Autowired protected ScheduledLogExecutorComponent logExecutor; @Value("${sql.ts.batch_size:1000}") protected int tsBatchSize; @Value("${sql.ts.batch_max_delay:100}") protected long tsMaxDelay; @Value("${sql.ts.stats_print_interval_ms:1000}") protected long tsStatsPrintIntervalMs; @Value("${sql.ts.batch_threads:4}") protected int tsBatchThreads; @Value("${sql.timescale.batch_threads:4}") protected int timescaleBatchThreads; @Value("${sql.batch_sort:true}") protected boolean batchSortEnabled; @Value("${sql.ttl.ts.ts_key_value_ttl:0}") private long systemTtl; public void cleanup(long systemTtl) { log.info("Going to cleanup old timeseries data using ttl: {}s", systemTtl); try (Connection connection = dataSource.getConnection(); PreparedStatement stmt = connection.prepareStatement("call cleanup_timeseries_by_ttl(?,?,?)")) { stmt.setObject(1, ModelConstants.NULL_UUID); stmt.setLong(2, systemTtl); stmt.setLong(3, 0); stmt.setQueryTimeout((int) TimeUnit.HOURS.toSeconds(1)); stmt.execute(); printWarnings(stmt); try (ResultSet resultSet = stmt.getResultSet()) { resultSet.next(); log.info("Total telemetry removed stats by TTL for entities: [{}]", resultSet.getLong(1)); } } catch (SQLException e) { log.error("SQLException occurred during timeseries TTL task execution ", e); } } protected ListenableFuture<List<ReadTsKvQueryResult>> processFindAllAsync(TenantId tenantId, EntityId entityId, List<ReadTsKvQuery> queries) { List<ListenableFuture<ReadTsKvQueryResult>> futures = queries .stream() .map(query -> findAllAsync(tenantId, entityId, query))
.collect(Collectors.toList()); return Futures.transform(Futures.allAsList(futures), new Function<>() { @Nullable @Override public List<ReadTsKvQueryResult> apply(@Nullable List<ReadTsKvQueryResult> results) { if (results == null || results.isEmpty()) { return null; } return results.stream().filter(Objects::nonNull).collect(Collectors.toList()); } }, service); } protected long computeTtl(long ttl) { if (systemTtl > 0) { if (ttl == 0) { ttl = systemTtl; } else { ttl = Math.min(systemTtl, ttl); } } return ttl; } protected int getDataPointDays(TsKvEntry tsKvEntry, long ttl) { return tsKvEntry.getDataPoints() * Math.max(1, (int) (ttl / SECONDS_IN_DAY)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\AbstractSqlTimeseriesDao.java
1
请完成以下Java代码
public boolean isDirectProcessQueueItem() { return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem); } @Override public void setIsFileSystem (final boolean IsFileSystem) { set_Value (COLUMNNAME_IsFileSystem, IsFileSystem); } @Override public boolean isFileSystem() { return get_ValueAsBoolean(COLUMNNAME_IsFileSystem); } @Override public void setIsReport (final boolean IsReport) { set_Value (COLUMNNAME_IsReport, IsReport); } @Override public boolean isReport() { return get_ValueAsBoolean(COLUMNNAME_IsReport); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPOReference (final @Nullable java.lang.String POReference) {
set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java
1
请完成以下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 Payroll List Type. @param HR_ListType_ID Payroll List Type */ public void setHR_ListType_ID (int HR_ListType_ID) { if (HR_ListType_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID)); } /** Get Payroll List Type. @return Payroll List Type */ public int getHR_ListType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID); 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); } /** 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\eevolution\model\X_HR_ListType.java
1
请完成以下Java代码
public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); } @Override public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate_RebookedFrom() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_RebookedFrom_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override public void setMD_Candidate_RebookedFrom(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate_RebookedFrom) { set_ValueFromPO(COLUMNNAME_MD_Candidate_RebookedFrom_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate_RebookedFrom); } @Override public void setMD_Candidate_RebookedFrom_ID (final int MD_Candidate_RebookedFrom_ID) { if (MD_Candidate_RebookedFrom_ID < 1) set_Value (COLUMNNAME_MD_Candidate_RebookedFrom_ID, null); else set_Value (COLUMNNAME_MD_Candidate_RebookedFrom_ID, MD_Candidate_RebookedFrom_ID); } @Override public int getMD_Candidate_RebookedFrom_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_RebookedFrom_ID); } @Override public void setMD_Candidate_Transaction_Detail_ID (final int MD_Candidate_Transaction_Detail_ID) { if (MD_Candidate_Transaction_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_Transaction_Detail_ID, null); else
set_ValueNoCheck (COLUMNNAME_MD_Candidate_Transaction_Detail_ID, MD_Candidate_Transaction_Detail_ID); } @Override public int getMD_Candidate_Transaction_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_Transaction_Detail_ID); } @Override public void setMD_Stock_ID (final int MD_Stock_ID) { if (MD_Stock_ID < 1) set_Value (COLUMNNAME_MD_Stock_ID, null); else set_Value (COLUMNNAME_MD_Stock_ID, MD_Stock_ID); } @Override public int getMD_Stock_ID() { return get_ValueAsInt(COLUMNNAME_MD_Stock_ID); } @Override public void setMovementQty (final BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } @Override public BigDecimal getMovementQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTransactionDate (final @Nullable java.sql.Timestamp TransactionDate) { set_Value (COLUMNNAME_TransactionDate, TransactionDate); } @Override public java.sql.Timestamp getTransactionDate() { return get_ValueAsTimestamp(COLUMNNAME_TransactionDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Transaction_Detail.java
1
请完成以下Java代码
public static RemoteToLocalSyncResult obtainedNewDataRecord(@NonNull final DataRecord datarecord) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(datarecord) .remoteToLocalStatus(RemoteToLocalStatus.OBTAINED_NEW_CONTACT_PERSON) .build(); } public static RemoteToLocalSyncResult noChanges(@NonNull final DataRecord dataRecord) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(dataRecord) .remoteToLocalStatus(RemoteToLocalStatus.NO_CHANGES) .build(); } public static RemoteToLocalSyncResult error(@NonNull final DataRecord datarecord, String errorMessage) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(datarecord) .remoteToLocalStatus(RemoteToLocalStatus.ERROR) .errorMessage(errorMessage) .build(); } public enum RemoteToLocalStatus { /** See {@link RemoteToLocalSyncResult#deletedOnRemotePlatform(DataRecord)}. */ DELETED_ON_REMOTE_PLATFORM, /** See {@link RemoteToLocalSyncResult#notYetAddedToRemotePlatform(DataRecord)}. */ NOT_YET_ADDED_TO_REMOTE_PLATFORM, /** See {@link RemoteToLocalSyncResult#obtainedRemoteId(DataRecord)}. */ OBTAINED_REMOTE_ID, /** See {@link RemoteToLocalSyncResult#obtainedRemoteEmail(DataRecord)}. */ OBTAINED_REMOTE_EMAIL, /** See {@link RemoteToLocalSyncResult#obtainedEmailBounceInfo(DataRecord)}. */ OBTAINED_EMAIL_BOUNCE_INFO,
OBTAINED_NEW_CONTACT_PERSON, NO_CHANGES, OBTAINED_OTHER_REMOTE_DATA, ERROR; } RemoteToLocalStatus remoteToLocalStatus; String errorMessage; DataRecord synchedDataRecord; @Builder private RemoteToLocalSyncResult( @NonNull final DataRecord synchedDataRecord, @Nullable final RemoteToLocalStatus remoteToLocalStatus, @Nullable final String errorMessage) { this.synchedDataRecord = synchedDataRecord; this.remoteToLocalStatus = remoteToLocalStatus; this.errorMessage = errorMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\RemoteToLocalSyncResult.java
1
请完成以下Java代码
public ColorUIResource getFocusColor() { return getPrimary2(); } @Override public ColorUIResource getPrimaryControlShadow() { return getPrimary3(); } @Override public ColorUIResource getMenuSelectedBackground() { return getPrimary1(); } @Override public ColorUIResource getMenuSelectedForeground() { return WHITE; } @Override public ColorUIResource getMenuItemBackground() { return WHITE; } @Override public ColorUIResource getToggleButtonCheckColor() { return new ColorUIResource(220, 241, 203);
} @Override public void addCustomEntriesToTable(final UIDefaults table) { super.addCustomEntriesToTable(table); final Object[] uiDefaults = { "ScrollBar.thumbHighlight", getPrimaryControlHighlight(), PlasticScrollBarUI.MAX_BUMPS_WIDTH_KEY, new Integer(22), PlasticScrollBarUI.MAX_BUMPS_WIDTH_KEY, new Integer(30), // TabbedPane // "TabbedPane.selected", getWhite(), "TabbedPane.selectHighlight", new ColorUIResource(231, 218, 188), "TabbedPane.unselectedBackground", null, // let AdempiereTabbedPaneUI calculate it AdempiereLookAndFeel.ERROR_BG_KEY, error, AdempiereLookAndFeel.ERROR_FG_KEY, txt_error, AdempiereLookAndFeel.INACTIVE_BG_KEY, inactive, AdempiereLookAndFeel.INFO_BG_KEY, info, AdempiereLookAndFeel.MANDATORY_BG_KEY, mandatory }; table.putDefaults(uiDefaults); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempiereTheme.java
1
请完成以下Java代码
public boolean isRunnable() { final VEditor editor = getEditor(); return editor.isReadWrite(); } @Override public void run() { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); final Lookup lookup = gridField.getLookup(); final int windowNo = gridField.getWindowNo(); final VBPartner vbp = new VBPartner(Env.getWindow(windowNo), windowNo); int BPartner_ID = 0; // if update, get current value if (!createNew) { final Object value = editor.getValue(); if (value instanceof Integer) BPartner_ID = ((Integer)value).intValue(); else if (value != null) BPartner_ID = Integer.parseInt(value.toString()); }
vbp.loadBPartner(BPartner_ID); vbp.setVisible(true); // get result int result = vbp.getC_BPartner_ID(); if (result == 0 // 0 = not saved && result == BPartner_ID) // the same return; // Maybe new BPartner - put in cache lookup.getDirect(IValidationContext.NULL, new Integer(result), false, true); // actionCombo (new Integer(result)); // data binding gridField.getGridTab().setValue(gridField, result); } // actionBPartner }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\BPartnerNewUpdateContextEditorAction.java
1
请完成以下Java代码
public void setMD_Cockpit_ID (final int MD_Cockpit_ID) { if (MD_Cockpit_ID < 1) set_Value (COLUMNNAME_MD_Cockpit_ID, null); else set_Value (COLUMNNAME_MD_Cockpit_ID, MD_Cockpit_ID); } @Override public int getMD_Cockpit_ID() { return get_ValueAsInt(COLUMNNAME_MD_Cockpit_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
} @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQtyPending (final BigDecimal QtyPending) { set_Value (COLUMNNAME_QtyPending, QtyPending); } @Override public BigDecimal getQtyPending() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPending); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit_DDOrder_Detail.java
1
请完成以下Java代码
public void setSelectClause (String SelectClause) { set_Value (COLUMNNAME_SelectClause, SelectClause); } /** Get Sql SELECT. @return SQL SELECT clause */ public String getSelectClause () { return (String)get_Value(COLUMNNAME_SelectClause); } /** TokenType AD_Reference_ID=397 */ public static final int TOKENTYPE_AD_Reference_ID=397; /** SQL Command = Q */ public static final String TOKENTYPE_SQLCommand = "Q"; /** Internal Link = I */ public static final String TOKENTYPE_InternalLink = "I"; /** External Link = E */ public static final String TOKENTYPE_ExternalLink = "E"; /** Style = S */ public static final String TOKENTYPE_Style = "S"; /** Set TokenType. @param TokenType Wiki Token Type */ public void setTokenType (String TokenType) { set_Value (COLUMNNAME_TokenType, TokenType); } /** Get TokenType.
@return Wiki Token Type */ public String getTokenType () { return (String)get_Value(COLUMNNAME_TokenType); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WikiToken.java
1
请在Spring Boot框架中完成以下Java代码
public void onTimeout(TbMsgProfilerInfo profilerInfo) { Map.Entry<UUID, Long> ruleNodeInfo = profilerInfo.onTimeout(); if (ruleNodeInfo != null) { ruleNodeProfilerMap.computeIfAbsent(ruleNodeInfo.getKey(), TbRuleNodeProfilerInfo::new).record(ruleNodeInfo.getValue()); } } public RuleNodeInfo getLastVisitedRuleNode(UUID id) { return lastRuleNodeMap.get(id); } public void printProfilerStats() { if (profilerEnabled) { log.debug("Top Rule Nodes by max execution time:"); ruleNodeProfilerMap.values().stream() .sorted(Comparator.comparingLong(TbRuleNodeProfilerInfo::getMaxExecutionTime).reversed()).limit(5) .forEach(info -> log.debug("[{}][{}] max execution time: {}. {}", queueName, info.getRuleNodeId(), info.getMaxExecutionTime(), info.getLabel())); log.info("Top Rule Nodes by avg execution time:"); ruleNodeProfilerMap.values().stream() .sorted(Comparator.comparingDouble(TbRuleNodeProfilerInfo::getAvgExecutionTime).reversed()).limit(5)
.forEach(info -> log.info("[{}][{}] avg execution time: {}. {}", queueName, info.getRuleNodeId(), info.getAvgExecutionTime(), info.getLabel())); log.info("Top Rule Nodes by execution count:"); ruleNodeProfilerMap.values().stream() .sorted(Comparator.comparingInt(TbRuleNodeProfilerInfo::getExecutionCount).reversed()).limit(5) .forEach(info -> log.info("[{}][{}] execution count: {}. {}", queueName, info.getRuleNodeId(), info.getExecutionCount(), info.getLabel())); } } public void cleanup() { canceled = true; pendingMap.clear(); successMap.clear(); failedMap.clear(); } public boolean isCanceled() { return skipTimeoutMsgsPossible && canceled; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbMsgPackProcessingContext.java
2
请在Spring Boot框架中完成以下Java代码
void addDefaultAuthorizationServerMetadataCustomizer( Consumer<OAuth2AuthorizationServerMetadata.Builder> defaultAuthorizationServerMetadataCustomizer) { this.defaultAuthorizationServerMetadataCustomizer = (this.defaultAuthorizationServerMetadataCustomizer == null) ? defaultAuthorizationServerMetadataCustomizer : this.defaultAuthorizationServerMetadataCustomizer .andThen(defaultAuthorizationServerMetadataCustomizer); } @Override void init(HttpSecurity httpSecurity) { AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils .getAuthorizationServerSettings(httpSecurity); String authorizationServerMetadataEndpointUri = authorizationServerSettings.isMultipleIssuersAllowed() ? "/.well-known/oauth-authorization-server/**" : "/.well-known/oauth-authorization-server"; this.requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, authorizationServerMetadataEndpointUri); } @Override void configure(HttpSecurity httpSecurity) { OAuth2AuthorizationServerMetadataEndpointFilter authorizationServerMetadataEndpointFilter = new OAuth2AuthorizationServerMetadataEndpointFilter(); Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = getAuthorizationServerMetadataCustomizer(); if (authorizationServerMetadataCustomizer != null) { authorizationServerMetadataEndpointFilter .setAuthorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer); } httpSecurity.addFilterBefore(postProcess(authorizationServerMetadataEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class); } private Consumer<OAuth2AuthorizationServerMetadata.Builder> getAuthorizationServerMetadataCustomizer() {
Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = null; if (this.defaultAuthorizationServerMetadataCustomizer != null || this.authorizationServerMetadataCustomizer != null) { if (this.defaultAuthorizationServerMetadataCustomizer != null) { authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer; } if (this.authorizationServerMetadataCustomizer != null) { authorizationServerMetadataCustomizer = (authorizationServerMetadataCustomizer != null) ? authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer) : this.authorizationServerMetadataCustomizer; } } return authorizationServerMetadataCustomizer; } @Override RequestMatcher getRequestMatcher() { return this.requestMatcher; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2AuthorizationServerMetadataEndpointConfigurer.java
2
请完成以下Java代码
protected int calculateRepeatValue() { int times = -1; List<String> expression = Arrays.asList(repeat.split("/")); if (expression.size() > 1 && expression.get(0).startsWith("R") && expression.get(0).length() > 1) { times = Integer.parseInt(expression.get(0).substring(1)); if (times > 0) { times--; } } return times; } protected void setNewRepeat(int newRepeatValue) { List<String> expression = Arrays.asList(repeat.split("/")); expression = expression.subList(1, expression.size()); StringBuilder repeatBuilder = new StringBuilder("R"); repeatBuilder.append(newRepeatValue); for (String value : expression) { repeatBuilder.append("/"); repeatBuilder.append(value); } repeat = repeatBuilder.toString(); } protected Date calculateNextTimer() { BusinessCalendar businessCalendar = Context .getProcessEngineConfiguration() .getBusinessCalendarManager() .getBusinessCalendar(getBusinessCalendarName(TimerEventHandler.geCalendarNameFromConfiguration(jobHandlerConfiguration))); return businessCalendar.resolveDuedate(repeat, maxIterations); } protected String getBusinessCalendarName(String calendarName) { String businessCalendarName = CycleBusinessCalendar.NAME; if (StringUtils.isNotEmpty(calendarName)) { VariableScope execution = NoExecutionVariableScope.getSharedInstance(); if (StringUtils.isNotEmpty(this.executionId)) { execution = Context.getCommandContext().getExecutionEntityManager().findExecutionById(this.executionId); } businessCalendarName = (String) Context.getProcessEngineConfiguration().getExpressionManager().createExpression(calendarName).getValue(execution); }
return businessCalendarName; } public String getLockOwner() { return null; } public void setLockOwner(String lockOwner) { // Nothing to do } public Date getLockExpirationTime() { return null; } public void setLockExpirationTime(Date lockExpirationTime) { // Nothing to do } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntity.java
1
请完成以下Java代码
public Mono<Instance> find(InstanceId id) { return Mono.defer(() -> { if (!this.outdatedSnapshots.contains(id)) { return Mono.justOrEmpty(this.snapshots.get(id)); } else { return rehydrateSnapshot(id).doOnSuccess((v) -> this.outdatedSnapshots.remove(v.getId())); } }); } @Override public Mono<Instance> save(Instance instance) { return super.save(instance).doOnError(OptimisticLockingException.class, (e) -> this.outdatedSnapshots.add(instance.getId())); } public void start() { this.subscription = this.eventStore.findAll().concatWith(this.eventStore).subscribe(this::updateSnapshot); } public void stop() { if (this.subscription != null) { this.subscription.dispose(); this.subscription = null; } } protected Mono<Instance> rehydrateSnapshot(InstanceId id) { return super.find(id).map((instance) -> this.snapshots.compute(id, (key, snapshot) -> { // check if the loaded version hasn't been already outdated by a snapshot if (snapshot == null || instance.getVersion() >= snapshot.getVersion()) { return instance; } else { return snapshot;
} })); } protected void updateSnapshot(InstanceEvent event) { try { this.snapshots.compute(event.getInstance(), (key, old) -> { Instance instance = (old != null) ? old : Instance.create(key); if (event.getVersion() > instance.getVersion()) { return instance.apply(event); } return instance; }); } catch (Exception ex) { log.warn("Error while updating the snapshot with event {}", event, ex); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\SnapshottingInstanceRepository.java
1
请完成以下Java代码
private Integer getAttributeIdOrNull() { return AttributeKeyPartPatternType.AttributeIdAndValue == type ? attributeId.getRepoId() : null; } private static int compareNullsLast(final Integer i1, final Integer i2) { if (i1 == null) { return +1; } else if (i2 == null) { return -1; } else { return i1 - i2; } } public boolean matches(@NonNull final AttributesKeyPart part) { if (type == AttributeKeyPartPatternType.All) { return true; } else if (type == AttributeKeyPartPatternType.Other) { throw new AdempiereException("Invalid pattern " + this); } else if (type == AttributeKeyPartPatternType.None) { return AttributesKeyPart.NONE.equals(part); } else if (type == AttributeKeyPartPatternType.AttributeValueId) { return AttributeKeyPartType.AttributeValueId.equals(part.getType()) && Objects.equals(this.attributeValueId, part.getAttributeValueId()); } else if (type == AttributeKeyPartPatternType.AttributeIdAndValue) { return AttributeKeyPartType.AttributeIdAndValue.equals(part.getType()) && Objects.equals(this.attributeId, part.getAttributeId()) && (Check.isEmpty(this.value) //no value means all values allowed || Objects.equals(this.value, part.getValue())); } else if (type == AttributeKeyPartPatternType.AttributeId) { return AttributeKeyPartType.AttributeIdAndValue.equals(part.getType()) && Objects.equals(this.attributeId, part.getAttributeId()); } else { throw new AdempiereException("Unknown type: " + type); } } boolean isWildcardMatching() { return type == AttributeKeyPartPatternType.AttributeId; }
AttributesKeyPart toAttributeKeyPart(@Nullable final AttributesKey context) { if (type == AttributeKeyPartPatternType.All) { return AttributesKeyPart.ALL; } else if (type == AttributeKeyPartPatternType.Other) { return AttributesKeyPart.OTHER; } else if (type == AttributeKeyPartPatternType.None) { return AttributesKeyPart.NONE; } else if (type == AttributeKeyPartPatternType.AttributeValueId) { return AttributesKeyPart.ofAttributeValueId(attributeValueId); } else if (type == AttributeKeyPartPatternType.AttributeIdAndValue) { return AttributesKeyPart.ofAttributeIdAndValue(attributeId, value); } else if (type == AttributeKeyPartPatternType.AttributeId) { if (context == null) { throw new AdempiereException("Context is required to convert `" + this + "` to " + AttributesKeyPart.class); } final String valueEffective = context.getValueByAttributeId(attributeId); return AttributesKeyPart.ofAttributeIdAndValue(attributeId, valueEffective); } else { throw new AdempiereException("Unknown type: " + type); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPartPattern.java
1
请完成以下Java代码
private void execute(final RegisterListenerRequest listener) { if (!listener.isActive()) { return; // nothing to do } if (!TrxEventTiming.BEFORE_COMMIT.equals(listener.getTiming()) && !TrxEventTiming.AFTER_COMMIT.equals(listener.getTiming()) && !TrxEventTiming.AFTER_CLOSE.equals(listener.getTiming())) { return; // nothing to do } try { listener.getHandlingMethod().onTransactionEvent(ITrx.TRX_None); } catch (Exception e) { throw AdempiereException.wrapIfNeeded(e) .setParameter("listener", listener) .appendParametersToMessage(); } } @Override public void fireBeforeCommit(final ITrx trx) { throw new UnsupportedOperationException(); }
@Override public void fireAfterCommit(final ITrx trx) { throw new UnsupportedOperationException(); } @Override public void fireAfterRollback(final ITrx trx) { throw new UnsupportedOperationException(); } @Override public void fireAfterClose(ITrx trx) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AutoCommitTrxListenerManager.java
1
请完成以下Java代码
protected boolean isDmnEnabled() { return Context .getProcessEngineConfiguration() .isDmnEnabled(); } protected Integer getTaskMetricsTimeToLive() { return Context .getProcessEngineConfiguration() .getParsedTaskMetricsTimeToLive(); } protected boolean shouldRescheduleNow() { int batchSize = getBatchSize(); for (DbOperation deleteOperation : deleteOperations.values()) {
if (deleteOperation.getRowsAffected() == batchSize) { return true; } } return false; } public int getBatchSize() { return Context .getProcessEngineConfiguration() .getHistoryCleanupBatchSize(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupRemovalTime.java
1
请完成以下Java代码
public static DocumentFilterDescriptorsProvider createFilterDescriptorsProvider() { return ImmutableDocumentFilterDescriptorsProvider.of(createPickingSlotBarcodeFilters()); } public static DocumentFilterDescriptor createPickingSlotBarcodeFilters() { return DocumentFilterDescriptor.builder() .setFilterId(PickingSlotBarcodeFilter_FilterId) .setFrequentUsed(true) .setParametersLayoutType(PanelLayoutType.SingleOverlayField) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(PARAM_Barcode) .displayName(TranslatableStrings.adMessage(MSG_BarcodeFilter)) .mandatory(true) .widgetType(DocumentFieldWidgetType.Text) .barcodeScannerType(BarcodeScannerType.QRCode)) .build(); } @Nullable public static PickingSlotQRCode getPickingSlotQRCode(final DocumentFilterList filters) { final String barcodeString = StringUtils.trimBlankToNull(filters.getParamValueAsString(PickingSlotBarcodeFilter_FilterId, PARAM_Barcode)); if (barcodeString == null) { return null; } // // Try parsing the Global QR Code, if possible final GlobalQRCode globalQRCode = GlobalQRCode.parse(barcodeString).orNullIfError(); //
// Case: valid Global QR Code if (globalQRCode != null) { return PickingSlotQRCode.ofGlobalQRCode(globalQRCode); } // // Case: Legacy barcode support else { final IPickingSlotDAO pickingSlotDAO = Services.get(IPickingSlotDAO.class); return pickingSlotDAO.getPickingSlotIdAndCaptionByCode(barcodeString) .map(PickingSlotQRCode::ofPickingSlotIdAndCaption) .orElseThrow(() -> new AdempiereException("Invalid barcode: " + barcodeString)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewFilters.java
1
请完成以下Java代码
public void setImplementation(String implementation) { this.implementation = implementation; } public List<FieldExtension> getFieldExtensions() { return fieldExtensions; } public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance;
} @Override public abstract AbstractFlowableHttpHandler clone(); public void setValues(AbstractFlowableHttpHandler otherHandler) { super.setValues(otherHandler); setImplementation(otherHandler.getImplementation()); setImplementationType(otherHandler.getImplementationType()); fieldExtensions = new ArrayList<>(); if (otherHandler.getFieldExtensions() != null && !otherHandler.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherHandler.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\AbstractFlowableHttpHandler.java
1
请完成以下Java代码
public static String whileRtrim(String s) { int i = s.length() - 1; while (i >= 0 && Character.isWhitespace(s.charAt(i))) { i--; } return s.substring(0, i + 1); } private static boolean checkStrings(String ltrim, String rtrim) { boolean result = false; if (ltrimResult.equalsIgnoreCase(ltrim) && rtrimResult.equalsIgnoreCase(rtrim)) result = true; return result; } // Going through the String detecting Whitespaces @Benchmark public boolean whileCharacters() { String ltrim = whileLtrim(src); String rtrim = whileRtrim(src); return checkStrings(ltrim, rtrim); } // replaceAll() and Regular Expressions @Benchmark public boolean replaceAllRegularExpression() { String ltrim = src.replaceAll("^\\s+", ""); String rtrim = src.replaceAll("\\s+$", ""); return checkStrings(ltrim, rtrim); } public static String patternLtrim(String s) { return LTRIM.matcher(s) .replaceAll(""); } public static String patternRtrim(String s) { return RTRIM.matcher(s) .replaceAll(""); } // Pattern matches() with replaceAll @Benchmark
public boolean patternMatchesLTtrimRTrim() { String ltrim = patternLtrim(src); String rtrim = patternRtrim(src); return checkStrings(ltrim, rtrim); } // Guava CharMatcher trimLeadingFrom / trimTrailingFrom @Benchmark public boolean guavaCharMatcher() { String ltrim = CharMatcher.whitespace().trimLeadingFrom(src); String rtrim = CharMatcher.whitespace().trimTrailingFrom(src); return checkStrings(ltrim, rtrim); } // Apache Commons StringUtils containsIgnoreCase @Benchmark public boolean apacheCommonsStringUtils() { String ltrim = StringUtils.stripStart(src, null); String rtrim = StringUtils.stripEnd(src, null); return checkStrings(ltrim, rtrim); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\trim\LTrimRTrim.java
1
请完成以下Java代码
private ImmutableList<I_M_InOut> getSelectedInOuts() { final IInOutDAO inOutDAO = Services.get(IInOutDAO.class); return getSelectedRowIds() .stream() .map(rowId -> inOutDAO.getById(InOutId.ofRepoId(rowId.toInt()), I_M_InOut.class)) .collect(GuavaCollectors.toImmutableList()); } @Override protected String doIt() throws Exception { final DocStatus docStatus = DocStatus.ofCode(transportationOrder.getDocStatus()); if (docStatus.isCompleted()) {
// this error should not be thrown since we have AD_Val_Rule for the parameter throw new AdempiereException("Transportation Order should not be closed"); } final ImmutableList<InOutId> inOutIds = getSelectedInOuts() .stream() .map(it -> InOutId.ofRepoId(it.getM_InOut_ID())) .collect(GuavaCollectors.toImmutableList()); final InOutToTransportationOrderService service = SpringContextHolder.instance.getBean(InOutToTransportationOrderService.class); service.addShipmentsToTransportationOrder(ShipperTransportationId.ofRepoId(transportationOrder.getM_ShipperTransportation_ID()), inOutIds); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\inout\process\M_InOut_AddToTransportationOrderProcess_GridView.java
1
请完成以下Java代码
public void refresh() { } /** {@inheritDoc} */ @Override public Object getProperty(String name) { ConfigurationProperty configurationProperty = findConfigurationProperty(name); return (configurationProperty != null) ? configurationProperty.getValue() : null; } /** {@inheritDoc} */ @Override public Origin getOrigin(String name) { return Origin.from(findConfigurationProperty(name)); } private ConfigurationProperty findConfigurationProperty(String name) { try { return findConfigurationProperty(ConfigurationPropertyName.of(name)); } catch (InvalidConfigurationPropertyNameException ex) {
// simulate non-exposed version of ConfigurationPropertyName.of(name, nullIfInvalid) if(ex.getInvalidCharacters().size() == 1 && ex.getInvalidCharacters().get(0).equals('.')) { return null; } throw ex; } } private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) { if (name == null) { return null; } for (ConfigurationPropertySource configurationPropertySource : getSource()) { if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) { ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name); if (configurationProperty != null) { return configurationProperty; } } } return null; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableConfigurationPropertySourcesPropertySource.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<TwoFaProviderConfig> getTwoFaProviderConfig(TenantId tenantId, TwoFaProviderType providerType) { return getPlatformTwoFaSettings(tenantId, true) .flatMap(twoFaSettings -> twoFaSettings.getProviderConfig(providerType)); } @Override public Optional<PlatformTwoFaSettings> getPlatformTwoFaSettings(TenantId tenantId, boolean sysadminSettingsAsDefault) { return Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, TWO_FACTOR_AUTH_SETTINGS_KEY)) .map(adminSettings -> JacksonUtil.treeToValue(adminSettings.getJsonValue(), PlatformTwoFaSettings.class)); } @Override public PlatformTwoFaSettings savePlatformTwoFaSettings(TenantId tenantId, PlatformTwoFaSettings twoFactorAuthSettings) throws ThingsboardException { ConstraintValidator.validateFields(twoFactorAuthSettings); for (TwoFaProviderConfig providerConfig : twoFactorAuthSettings.getProviders()) { twoFactorAuthService.checkProvider(tenantId, providerConfig.getProviderType()); } if (tenantId.isSysTenantId()) { if (twoFactorAuthSettings.isEnforceTwoFa()) { if (twoFactorAuthSettings.getProviders().isEmpty()) { throw new DataValidationException("At least one 2FA provider is required if enforcing is enabled"); } if (twoFactorAuthSettings.getEnforcedUsersFilter() == null) { throw new DataValidationException("Users filter to enforce 2FA for is required"); } } } else { twoFactorAuthSettings.setEnforceTwoFa(false); twoFactorAuthSettings.setEnforcedUsersFilter(null); } AdminSettings settings = Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY)) .orElseGet(() -> { AdminSettings newSettings = new AdminSettings(); newSettings.setKey(TWO_FACTOR_AUTH_SETTINGS_KEY); return newSettings; }); settings.setJsonValue(JacksonUtil.valueToTree(twoFactorAuthSettings)); adminSettingsService.saveAdminSettings(tenantId, settings);
return twoFactorAuthSettings; } @Override public void deletePlatformTwoFaSettings(TenantId tenantId) { Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY)) .ifPresent(adminSettings -> adminSettingsDao.removeById(tenantId, adminSettings.getId().getId())); } private void checkAccountTwoFaSettings(TenantId tenantId, User user, AccountTwoFaSettings settings) { if (settings.getConfigs().isEmpty()) { if (twoFactorAuthService.isEnforceTwoFaEnabled(tenantId, user)) { throw new DataValidationException("At least one 2FA provider is required"); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\config\DefaultTwoFaConfigManager.java
2
请完成以下Java代码
public static class Builder { private final String name; private String image; private String imageTag = "latest"; private String imageWebsite; private final Map<String, String> environment = new TreeMap<>(); private final Set<Integer> ports = new TreeSet<>(); private String command; private final Map<String, String> labels = new TreeMap<>(); protected Builder(String name) { this.name = name; } public Builder imageAndTag(String imageAndTag) { String[] split = imageAndTag.split(":", 2); String tag = (split.length == 1) ? "latest" : split[1]; return image(split[0]).imageTag(tag); } public Builder image(String image) { this.image = image; return this; } public Builder imageTag(String imageTag) { this.imageTag = imageTag; return this; } public Builder imageWebsite(String imageWebsite) { this.imageWebsite = imageWebsite; return this; } public Builder environment(String key, String value) { this.environment.put(key, value); return this; } public Builder environment(Map<String, String> environment) { this.environment.putAll(environment); return this; }
public Builder ports(Collection<Integer> ports) { this.ports.addAll(ports); return this; } public Builder ports(int... ports) { return ports(Arrays.stream(ports).boxed().toList()); } public Builder command(String command) { this.command = command; return this; } public Builder label(String key, String value) { this.labels.put(key, value); return this; } public Builder labels(Map<String, String> label) { this.labels.putAll(label); return this; } /** * Builds the {@link ComposeService} instance. * @return the built instance */ public ComposeService build() { return new ComposeService(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeService.java
1
请完成以下Java代码
protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage) { throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } /** * Method not supported. * * @throws UnsupportedOperationException */ @Override protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage) { throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } @Override public void saveChangesIfNeeded() { throw new UnsupportedOperationException();
} @Override public void setSaveOnChange(boolean saveOnChange) { throw new UnsupportedOperationException(); } @Override public UOMType getQtyUOMTypeOrNull() { // ASI attribute storages does not support Qty Storage return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\ASIAttributeStorage.java
1
请完成以下Java代码
private String getAggregateHuPiName(final I_M_HU hu) { // note: if HU is an aggregate HU, then there won't be an NPE here. final I_M_HU_Item parentItem = hu.getM_HU_Item_Parent(); final I_M_HU_PI_Item parentPIItem = handlingUnitsBL.getPIItem(parentItem); if (parentPIItem == null) { // new HUException("Aggregate HU's parent item has no M_HU_PI_Item; parent-item=" + parentItem) // .setParameter("parent M_HU_PI_Item_ID", parentItem != null ? parentItem.getM_HU_PI_Item_ID() : null) // .throwIfDeveloperModeOrLogWarningElse(logger); return "?"; } HuPackingInstructionsId includedPIId = HuPackingInstructionsId.ofRepoIdOrNull(parentPIItem.getIncluded_HU_PI_ID()); if (includedPIId == null) { //noinspection ThrowableNotThrown new HUException("Aggregate HU's parent item has M_HU_PI_Item without an Included_HU_PI; parent-item=" + parentItem).throwIfDeveloperModeOrLogWarningElse(logger); return "?"; } final I_M_HU_PI included_HU_PI = handlingUnitsBL.getPI(includedPIId); return included_HU_PI.getName(); } // NOTE: this method can be overridden by extending classes in order to optimize how the HUs are counted. @Override public int getIncludedHUsCount() { // NOTE: we need to iterate the HUs and count them (instead of doing a COUNT directly on database), // because we rely on HU&Items caching // and also because in case of aggregated HUs, we need special handling final IncludedHUsCounter includedHUsCounter = new IncludedHUsCounter(getM_HU()); final HUIterator huIterator = new HUIterator();
huIterator.setListener(includedHUsCounter.toHUIteratorListener()); huIterator.setEnableStorageIteration(false); huIterator.iterate(getM_HU()); return includedHUsCounter.getHUsCount(); } protected String escape(final String string) { return StringUtils.maskHTML(string); } @Override public IHUDisplayNameBuilder setShowIfDestroyed(final boolean showIfDestroyed) { this.showIfDestroyed = showIfDestroyed; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUDisplayNameBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public void reactivateIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } private static void addDescription(final I_C_BankStatement bankStatement, final String description) { final String desc = bankStatement.getDescription(); if (desc == null) { bankStatement.setDescription(description); } else { bankStatement.setDescription(desc + " | " + description); }
} private static void addDescription(final I_C_BankStatementLine line, final String description) { final String desc = line.getDescription(); if (desc == null) { line.setDescription(description); } else { line.setDescription(desc + " | " + description); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\BankStatementDocumentHandler.java
2
请完成以下Java代码
private static BigDecimal toBigDecimal(@Nullable final Object value) { if (value == null) { return null; } else if (value instanceof BigDecimal) { return (BigDecimal)value; } else { final String valueStr = value.toString().trim(); if (valueStr.isEmpty()) { return null; } return new BigDecimal(valueStr); } } public ZonedDateTime getValueAsZonedDateTime() { return DateTimeConverters.fromObjectToZonedDateTime(value); } public LocalDate getValueAsLocalDate() { return DateTimeConverters.fromObjectToLocalDate(value); } public IntegerLookupValue getValueAsIntegerLookupValue() { return DataTypes.convertToIntegerLookupValue(value); } public LookupValue getValueAsStringLookupValue() { if (value == null) { return null; } else if (value instanceof Map) { @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>)value; return JSONLookupValue.stringLookupValueFromJsonMap(map); } else if (value instanceof JSONLookupValue) { final JSONLookupValue json = (JSONLookupValue)value; return json.toIntegerLookupValue(); } else { throw new AdempiereException("Cannot convert value '" + value + "' (" + value.getClass() + ") to " + IntegerLookupValue.class);
} } @Nullable public <T extends ReferenceListAwareEnum> T getValueAsEnum(@NonNull final Class<T> enumType) { if (value == null) { return null; } else if (enumType.isInstance(value)) { //noinspection unchecked return (T)value; } final String valueStr; if (value instanceof Map) { @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>)value; final LookupValue.StringLookupValue lookupValue = JSONLookupValue.stringLookupValueFromJsonMap(map); valueStr = lookupValue.getIdAsString(); } else if (value instanceof JSONLookupValue) { final JSONLookupValue json = (JSONLookupValue)value; valueStr = json.getKey(); } else { valueStr = value.toString(); } try { return ReferenceListAwareEnums.ofNullableCode(valueStr, enumType); } catch (Exception ex) { throw new AdempiereException("Failed converting `" + value + "` (" + value.getClass().getSimpleName() + ") to " + enumType.getSimpleName(), ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentChangedEvent.java
1
请完成以下Java代码
public Object getCellEditorValue() { return checkbox.isSelected(); } /** * Get visual Component * * @param table * @param value * @param isSelected * @param row * @param column * @return Component */ @Override public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
final boolean selected = DisplayType.toBooleanNonNull(value, false); checkbox.setSelected(selected); return checkbox; } @Override public boolean isCellEditable(final EventObject anEvent) { return true; } @Override public boolean shouldSelectCell(final EventObject anEvent) { return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\SelectionColumnCellEditor.java
1