instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setIsbn(String isbn) { this.isbn = isbn; } public String getBookRating() { return bookRating; } public void setBookRating(String bookRating) { this.bookRating = bookRating; } @Override public String toString() { return "BookReview{" + "reviewsId=" + reviewsId + ", userId='" + userId + '\'' + ", isbn='" + isbn + '\'' + ", bookRating='" + bookRating + '\'' + '}'; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BookReview that = (BookReview) o; return Objects.equals(reviewsId, that.reviewsId) && Objects.equals(userId, that.userId) && Objects.equals(isbn, that.isbn) && Objects.equals(bookRating, that.bookRating); } @Override public int hashCode() { return Objects.hash(reviewsId, userId, isbn, bookRating); } }
repos\tutorials-master\spring-boot-modules\spring-caching-3\src\main\java\com\baeldung\caching\disable\BookReview.java
1
请完成以下Java代码
protected void setInternalValueDateInitial(Date value) { throw new UnsupportedOperationException("Setting initial value not supported"); } @Override protected Date getInternalValueDateInitial() { return null; } /** * @return {@code PROPAGATIONTYPE_NoPropagation}. */ @Override public String getPropagationType() { return X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation; } /** * @return {@link NullAggregationStrategy#instance}. */ @Override public IAttributeAggregationStrategy retrieveAggregationStrategy() { return NullAggregationStrategy.instance; } /** * @return {@link NullSplitterStrategy#instance}. */ @Override public IAttributeSplitterStrategy retrieveSplitterStrategy() { return NullSplitterStrategy.instance; } /** * @return {@link CopyHUAttributeTransferStrategy#instance}. */ @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return CopyHUAttributeTransferStrategy.instance; } /** * @return {@code true}. */ @Override public boolean isReadonlyUI() { return true; } /** * @return {@code true}. */ @Override
public boolean isDisplayedUI() { return true; } @Override public boolean isMandatory() { return false; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } /** * @return our attribute instance's {@code M_Attribute_ID}. */ @Override public int getDisplaySeqNo() { return attributeInstance.getM_Attribute_ID(); } /** * @return {@code true} */ @Override public boolean isUseInASI() { return true; } /** * @return {@code false}, since no HU-PI attribute is involved. */ @Override public boolean isDefinedByTemplate() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java
1
请在Spring Boot框架中完成以下Java代码
public R save(@RequestBody Notice notice) { return R.status(noticeService.save(notice)); } /** * 修改 */ @PostMapping("/update") @ApiOperationSupport(order = 4) @Operation(summary = "修改", description = "传入notice") public R update(@RequestBody Notice notice) { return R.status(noticeService.updateById(notice)); } /** * 新增或修改 */ @PostMapping("/submit") @ApiOperationSupport(order = 5) @Operation(summary = "新增或修改", description = "传入notice")
public R submit(@RequestBody Notice notice) { return R.status(noticeService.saveOrUpdate(notice)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 6) @Operation(summary = "逻辑删除", description = "传入notice") public R remove(@Parameter(description = "主键集合") @RequestParam String ids) { boolean temp = noticeService.deleteLogic(Func.toLongList(ids)); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-demo\src\main\java\com\example\demo\controller\NoticeController.java
2
请完成以下Java代码
public static GlobalQRCodeParseResult ok(@NonNull final GlobalQRCode globalQRCode) { return new GlobalQRCodeParseResult(globalQRCode, null); } public GlobalQRCodeParseResult(@Nullable final GlobalQRCode globalQRCode, @Nullable final String error) { if (CoalesceUtil.countNotNulls(globalQRCode, error) != 1) { throw Check.mkEx("One and only one shall be specified: " + globalQRCode + ", " + error); } this.globalQRCode = globalQRCode; this.error = error; } public GlobalQRCode orThrow() {
if (globalQRCode == null) { throw Check.mkEx(error); } else { return globalQRCode; } } public GlobalQRCode orNullIfError() { return globalQRCode; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCodeParseResult.java
1
请完成以下Java代码
private static OAuth2AccessToken.TokenType getAccessTokenType(Map<String, Object> tokenResponseParameters) { if (OAuth2AccessToken.TokenType.BEARER.getValue() .equalsIgnoreCase(getParameterValue(tokenResponseParameters, OAuth2ParameterNames.TOKEN_TYPE))) { return OAuth2AccessToken.TokenType.BEARER; } else if (OAuth2AccessToken.TokenType.DPOP.getValue() .equalsIgnoreCase(getParameterValue(tokenResponseParameters, OAuth2ParameterNames.TOKEN_TYPE))) { return OAuth2AccessToken.TokenType.DPOP; } return null; } private static long getExpiresIn(Map<String, Object> tokenResponseParameters) { return getParameterValue(tokenResponseParameters, OAuth2ParameterNames.EXPIRES_IN, 0L); } private static Set<String> getScopes(Map<String, Object> tokenResponseParameters) { if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) { String scope = getParameterValue(tokenResponseParameters, OAuth2ParameterNames.SCOPE); return new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))); } return Collections.emptySet(); } private static String getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName) { Object obj = tokenResponseParameters.get(parameterName); return (obj != null) ? obj.toString() : null; } private static long getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName, long defaultValue) {
long parameterValue = defaultValue; Object obj = tokenResponseParameters.get(parameterName); if (obj != null) { // Final classes Long and Integer do not need to be coerced if (obj.getClass() == Long.class) { parameterValue = (Long) obj; } else if (obj.getClass() == Integer.class) { parameterValue = (Integer) obj; } else { // Attempt to coerce to a long (typically from a String) try { parameterValue = Long.parseLong(obj.toString()); } catch (NumberFormatException ignored) { } } } return parameterValue; } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\DefaultMapOAuth2AccessTokenResponseConverter.java
1
请完成以下Java代码
public String getBusinessKey() { return businessKey; } public CaseExecutionState getState() { return state; } public boolean isCaseInstancesOnly() { return false; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; }
public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public String getDeploymentId() { return deploymentId; } public Boolean isRequired() { return required; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionQueryImpl.java
1
请完成以下Java代码
public ImmutableCredentialRecordBuilder backupState(boolean backupState) { this.backupState = backupState; return this; } public ImmutableCredentialRecordBuilder attestationObject(@Nullable Bytes attestationObject) { this.attestationObject = attestationObject; return this; } public ImmutableCredentialRecordBuilder attestationClientDataJSON(@Nullable Bytes attestationClientDataJSON) { this.attestationClientDataJSON = attestationClientDataJSON; return this; } public ImmutableCredentialRecordBuilder created(Instant created) { this.created = created; return this; } public ImmutableCredentialRecordBuilder lastUsed(Instant lastUsed) { this.lastUsed = lastUsed; return this;
} public ImmutableCredentialRecordBuilder label(String label) { this.label = label; return this; } public ImmutableCredentialRecord build() { return new ImmutableCredentialRecord(this.credentialType, this.credentialId, this.userEntityUserId, this.publicKey, this.signatureCount, this.uvInitialized, this.transports, this.backupEligible, this.backupState, this.attestationObject, this.attestationClientDataJSON, this.created, this.lastUsed, this.label); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutableCredentialRecord.java
1
请完成以下Java代码
public class DmnDecisionRequirementsGraphImpl implements DmnDecisionRequirementsGraph { protected String key; protected String name; protected Map<String, DmnDecision> decisions = new HashMap<String, DmnDecision>(); public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<DmnDecision> getDecisions() { return decisions.values(); } public void setDecisions(Map<String, DmnDecision> decisions) { this.decisions = decisions; } public void addDecision(DmnDecision decision) {
decisions.put(decision.getKey(), decision); } public DmnDecision getDecision(String key) { return decisions.get(key); } public Set<String> getDecisionKeys() { return decisions.keySet(); } @Override public String toString() { return "DmnDecisionRequirementsGraphImpl [key=" + key + ", name=" + name + ", decisions=" + decisions + "]"; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionRequirementsGraphImpl.java
1
请完成以下Java代码
public void setHelp (java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Kommentar/Hilfe. @return Comment or Hint */ @Override public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Order By Value. @param IsOrderByValue Order list using the value column instead of the name column */ @Override public void setIsOrderByValue (boolean IsOrderByValue) { set_Value (COLUMNNAME_IsOrderByValue, Boolean.valueOf(IsOrderByValue)); } /** Get Order By Value. @return Order list using the value column instead of the name column */ @Override public boolean isOrderByValue () { Object oo = get_Value(COLUMNNAME_IsOrderByValue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name);
} /** * ValidationType AD_Reference_ID=2 * Reference name: AD_Reference Validation Types */ public static final int VALIDATIONTYPE_AD_Reference_ID=2; /** ListValidation = L */ public static final String VALIDATIONTYPE_ListValidation = "L"; /** DataType = D */ public static final String VALIDATIONTYPE_DataType = "D"; /** TableValidation = T */ public static final String VALIDATIONTYPE_TableValidation = "T"; /** Set Validation type. @param ValidationType Different method of validating data */ @Override public void setValidationType (java.lang.String ValidationType) { set_Value (COLUMNNAME_ValidationType, ValidationType); } /** Get Validation type. @return Different method of validating data */ @Override public java.lang.String getValidationType () { return (java.lang.String)get_Value(COLUMNNAME_ValidationType); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public void setVFormat (java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public java.lang.String getVFormat () { return (java.lang.String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Reference.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisConfig { /** * 重写Redis序列化方式,使用Json方式: * 当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。 * Spring Data JPA为我们提供了下面的Serializer: * GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。 * 在此我们将自己配置RedisTemplate并定义Serializer。 * * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); // 全局开启AutoType,不建议使用 // ParserConfig.getGlobalInstance().setAutoTypeSupport(true); // 建议使用这种方式,小范围指定白名单 ParserConfig.getGlobalInstance().addAccept("com.xiaolyuh."); KryoRedisSerializer<Object> kryoRedisSerializer = new KryoRedisSerializer<>(Object.class); // 设置值(value)的序列化采用KryoRedisSerializer。 redisTemplate.setValueSerializer(kryoRedisSerializer); redisTemplate.setHashValueSerializer(kryoRedisSerializer); // 设置键(key)的序列化采用StringRedisSerializer。 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListener) { final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener(messageListener, ChannelTopicEnum.REDIS_CACHE_DELETE_TOPIC.getChannelTopic()); container.addMessageListener(messageListener, ChannelTopicEnum.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic()); return container; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\config\RedisConfig.java
2
请完成以下Java代码
public void setFieldValueFormat (String FieldValueFormat) { set_Value (COLUMNNAME_FieldValueFormat, FieldValueFormat); } /** Get Value Format. @return Value Format */ public String getFieldValueFormat () { return (String)get_Value(COLUMNNAME_FieldValueFormat); } /** Set Null Value. @param IsNullFieldValue Null Value */ public void setIsNullFieldValue (boolean IsNullFieldValue) { set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue)); } /** Get Null Value. @return Null Value */ public boolean isNullFieldValue () { Object oo = get_Value(COLUMNNAME_IsNullFieldValue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public void setSeqNo (int SeqNo) {
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Type AD_Reference_ID=540203 */ public static final int TYPE_AD_Reference_ID=540203; /** Set Field Value = SV */ public static final String TYPE_SetFieldValue = "SV"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Action.java
1
请完成以下Java代码
public class Employee { private int id; private String name; private String address; public Employee(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\entities\Employee.java
1
请完成以下Java代码
default String getProductValueAndName(final int productId) { return getProductValueAndName(ProductId.ofRepoIdOrNull(productId)); } String getProductValue(ProductId productId); GS1ProductCodesCollection getGS1ProductCodesCollection(@NonNull ProductId productId); GS1ProductCodesCollection getGS1ProductCodesCollection(@NonNull I_M_Product product); /** * @return GTIN/EAN13 */ Optional<GTIN> getGTIN(@NonNull ProductId productId); ImmutableMap<ProductId, String> getProductValues(Set<ProductId> productIds); String getProductName(ProductId productId); ProductType getProductType(ProductId productId); ProductCategoryId getDefaultProductCategoryId(); ITranslatableString getProductNameTrl(@NonNull ProductId productId); @Nullable ProductId retrieveMappedProductIdOrNull(ProductId productId, OrgId orgId); boolean isHaddexProduct(ProductId productId); /** * @return {@code M_Product.M_AttributeSet_ID} */ AttributeSetDescriptor getProductMasterDataSchemaOrNull(ProductId productId); /** * @return {@code M_Product.M_AttributeSet_ID} */ @NonNull AttributeSetId getMasterDataSchemaAttributeSetId(@NonNull ProductId productId);
ImmutableList<String> retrieveSupplierApprovalNorms(ProductId productId); boolean isDiscontinuedAt(I_M_Product productRecord, LocalDate targetDate); Optional<IssuingToleranceSpec> getIssuingToleranceSpec(@NonNull ProductId productId); @NonNull ImmutableList<I_M_Product> getByIdsInTrx(@NonNull Set<ProductId> productIds); Optional<ProductId> getProductIdByBarcode(@NonNull String barcode, @NonNull ClientId clientId); Optional<ProductId> getProductIdByGTIN(@NonNull GTIN gtin); Optional<ProductId> getProductIdByGTIN(@NonNull GTIN gtin, @Nullable BPartnerId bpartnerId, @NonNull ClientId clientId); Optional<ProductId> getProductIdByGTINStrictly(@NonNull GTIN gtin, @NonNull ClientId clientId); ProductId getProductIdByGTINStrictlyNotNull(@NonNull GTIN gtin, @NonNull ClientId clientId); Optional<ProductId> getProductIdByEAN13(@NonNull EAN13 ean13); Optional<ProductId> getProductIdByEAN13(@NonNull EAN13 ean13, @Nullable BPartnerId bpartnerId, @NonNull ClientId clientId); boolean isValidEAN13Product(@NonNull EAN13 ean13, @NonNull ProductId expectedProductId); boolean isValidEAN13Product(@NonNull EAN13 ean13, @NonNull ProductId expectedProductId, @Nullable BPartnerId bpartnerId); Set<ProductId> getProductIdsMatchingQueryString( @NonNull String queryString, @NonNull ClientId clientId, @NonNull QueryLimit limit); @NonNull List<I_M_Product> getByIds(@NonNull Set<ProductId> productIds); boolean isExistingValue(@NonNull String value, @NonNull ClientId clientId); void setProductCodeFieldsFromGTIN(@NonNull I_M_Product record, @Nullable GTIN gtin); void setProductCodeFieldsFromEAN13ProductCode(@NonNull I_M_Product record, @Nullable EAN13ProductCode ean13ProductCode); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IProductBL.java
1
请完成以下Java代码
public File createPDF() { return null; } /** * Get Process Message * * @return clear text error message */ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * * @return AD_User_ID (Created) */ @Override public int getDoc_User_ID() { return getCreatedBy(); } // getDoc_User_ID /** * Get Document Approval Amount * * @return DR amount */ @Override public BigDecimal getApprovalAmt() { return getTotalDr(); } // getApprovalAmt /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */
@Deprecated public boolean isComplete() { return Services.get(IGLJournalBL.class).isComplete(this); } // isComplete // metas: cg: 02476 private static void setAmtPrecision(final I_GL_Journal journal) { final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoIdOrNull(journal.getC_AcctSchema_ID()); if (acctSchemaId == null) { return; } final AcctSchema as = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId); final CurrencyPrecision precision = as.getStandardPrecision(); final BigDecimal controlAmt = precision.roundIfNeeded(journal.getControlAmt()); journal.setControlAmt(controlAmt); } } // MJournal
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournal.java
1
请完成以下Java代码
public class DelegatingReactiveAuthenticationManager implements ReactiveAuthenticationManager { private final List<ReactiveAuthenticationManager> delegates; private boolean continueOnError = false; private final Log logger = LogFactory.getLog(getClass()); public DelegatingReactiveAuthenticationManager(ReactiveAuthenticationManager... entryPoints) { this(Arrays.asList(entryPoints)); } public DelegatingReactiveAuthenticationManager(List<ReactiveAuthenticationManager> entryPoints) { Assert.notEmpty(entryPoints, "entryPoints cannot be null"); this.delegates = entryPoints; } @Override public Mono<Authentication> authenticate(Authentication authentication) {
Flux<ReactiveAuthenticationManager> result = Flux.fromIterable(this.delegates); Function<ReactiveAuthenticationManager, Mono<Authentication>> logging = (m) -> m.authenticate(authentication) .doOnError(AuthenticationException.class, (ex) -> ex.setAuthenticationRequest(authentication)) .doOnError(this.logger::debug); return ((this.continueOnError) ? result.concatMapDelayError(logging) : result.concatMap(logging)).next(); } /** * Continue iterating when a delegate errors, defaults to {@code false} * @param continueOnError whether to continue when a delegate errors * @since 6.3 */ public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManager.java
1
请完成以下Java代码
public ResponseEntity<Object> resetPwd(@RequestBody Set<Long> ids) { String pwd = passwordEncoder.encode("123456"); userService.resetPwd(ids, pwd); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改头像") @PostMapping(value = "/updateAvatar") public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){ return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); } @Log("修改邮箱") @ApiOperation("修改邮箱") @PostMapping(value = "/updateEmail/{code}") public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword()); UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername()); if(!passwordEncoder.matches(password, userDto.getPassword())){ throw new BadRequestException("密码错误");
} verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code); userService.updateEmail(userDto.getUsername(),user.getEmail()); return new ResponseEntity<>(HttpStatus.OK); } /** * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误 * @param resources / */ private void checkLevel(User resources) { Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); Integer optLevel = roleService.findByRoles(resources.getRoles()); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足"); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\UserController.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig { // @formatter:off @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception { auth .userDetailsService(userDetailsService) .passwordEncoder(new BCryptPasswordEncoder()); } // @formatter:on // @formatter:off @Bean WebSecurityCustomizer ignoringCustomizer() { return (web) -> web .ignoring().requestMatchers(PathRequest.toH2Console()); }
// @formatter:on // @formatter:off @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests((authorize) -> authorize .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() .anyRequest().authenticated() ) .formLogin((formLogin) -> formLogin .permitAll() ) .build(); } // @formatter:on }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\config\WebSecurityConfig.java
2
请完成以下Java代码
public EventSubscriptionQueryImpl activityId(String activityId) { ensureNotNull("activity id", activityId); this.activityId = activityId; return this; } public EventSubscriptionQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public EventSubscriptionQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public EventSubscriptionQuery includeEventSubscriptionsWithoutTenantId() { this.includeEventSubscriptionsWithoutTenantId = true; return this; } public EventSubscriptionQueryImpl eventType(String eventType) { ensureNotNull("event type", eventType); this.eventType = eventType; return this; } public EventSubscriptionQuery orderByCreated() { return orderBy(EventSubscriptionQueryProperty.CREATED); } public EventSubscriptionQuery orderByTenantId() { return orderBy(EventSubscriptionQueryProperty.TENANT_ID); } //results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getEventSubscriptionManager() .findEventSubscriptionCountByQueryCriteria(this); } @Override
public List<EventSubscription> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getEventSubscriptionManager() .findEventSubscriptionsByQueryCriteria(this,page); } //getters ////////////////////////////////////////// public String getEventSubscriptionId() { return eventSubscriptionId; } public String getEventName() { return eventName; } public String getEventType() { return eventType; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getActivityId() { return activityId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\EventSubscriptionQueryImpl.java
1
请完成以下Java代码
public Builder setDescription(@NonNull final ITranslatableString description) { this.description = description; return this; } public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder setUIStyle(@Nullable final String uiStyle) { this.uiStyle = uiStyle; return this; } public Builder addColumn(final DocumentLayoutColumnDescriptor.Builder columnBuilder) { Check.assumeNotNull(columnBuilder, "Parameter columnBuilder is not null"); columnsBuilders.add(columnBuilder); return this; } public Builder addColumn(final List<DocumentLayoutElementDescriptor.Builder> elementsBuilders) { if (elementsBuilders == null || elementsBuilders.isEmpty()) { return this; } final DocumentLayoutElementGroupDescriptor.Builder elementsGroupBuilder = DocumentLayoutElementGroupDescriptor.builder(); elementsBuilders.stream() .map(elementBuilder -> DocumentLayoutElementLineDescriptor.builder().addElement(elementBuilder)) .forEach(elementLineBuilder -> elementsGroupBuilder.addElementLine(elementLineBuilder)); final DocumentLayoutColumnDescriptor.Builder column = DocumentLayoutColumnDescriptor.builder().addElementGroup(elementsGroupBuilder); addColumn(column); return this; } public Builder setInvalid(final String invalidReason) { Check.assumeNotEmpty(invalidReason, "invalidReason is not empty"); this.invalidReason = invalidReason; logger.trace("Layout section was marked as invalid: {}", this); return this; }
public Builder setClosableMode(@NonNull final ClosableMode closableMode) { this.closableMode = closableMode; return this; } public Builder setCaptionMode(@NonNull final CaptionMode captionMode) { this.captionMode = captionMode; return this; } public boolean isValid() { return invalidReason == null; } public boolean isInvalid() { return invalidReason != null; } public boolean isNotEmpty() { return streamElementBuilders().findAny().isPresent(); } private Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return columnsBuilders.stream().flatMap(DocumentLayoutColumnDescriptor.Builder::streamElementBuilders); } public Builder setExcludeSpecialFields() { streamElementBuilders().forEach(elementBuilder -> elementBuilder.setExcludeSpecialFields()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSectionDescriptor.java
1
请完成以下Java代码
public class MissingAuthorization { private String permissionName; private String resourceType; protected String resourceId; public MissingAuthorization(String permissionName, String resourceType, String resourceId) { this.permissionName = permissionName; this.resourceType = resourceType; this.resourceId = resourceId; } public String getViolatedPermissionName() { return permissionName; } public String getResourceType() { return resourceType;
} public String getResourceId() { return resourceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[permissionName=" + permissionName + ", resourceType=" + resourceType + ", resourceId=" + resourceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\authorization\MissingAuthorization.java
1
请完成以下Java代码
public List<ExecutionInfo> getExecutionInfos() { return executionInfos; } @Override public boolean isFullyFetched() { return iterator.isFullyFetched(); } @Override public int getAvailableWithoutFetching() { return iterator.remaining(); } @NonNull @Override public Iterator<Row> iterator() { return iterator; } @Override public boolean wasApplied() { return iterator.wasApplied(); } private class RowIterator extends CountingIterator<Row> { private GuavaSession session; private Statement statement; private AsyncResultSet currentPage; private Iterator<Row> currentRows; private RowIterator(GuavaSession session, Statement statement, AsyncResultSet firstPage) { super(firstPage.remaining()); this.session = session; this.statement = statement; this.currentPage = firstPage; this.currentRows = firstPage.currentPage().iterator(); } @Override protected Row computeNext() { maybeMoveToNextPage(); return currentRows.hasNext() ? currentRows.next() : endOfData(); } private void maybeMoveToNextPage() { if (!currentRows.hasNext() && currentPage.hasMorePages()) { BlockingOperation.checkNotDriverThread(); ByteBuffer nextPagingState = currentPage.getExecutionInfo().getPagingState();
this.statement = this.statement.setPagingState(nextPagingState); AsyncResultSet nextPage = GuavaSession.getSafe(this.session.executeAsync(this.statement)); currentPage = nextPage; remaining += nextPage.remaining(); currentRows = nextPage.currentPage().iterator(); executionInfos.add(nextPage.getExecutionInfo()); // The definitions can change from page to page if this result set was built from a bound // 'SELECT *', and the schema was altered. columnDefinitions = nextPage.getColumnDefinitions(); } } private boolean isFullyFetched() { return !currentPage.hasMorePages(); } private boolean wasApplied() { return currentPage.wasApplied(); } } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\guava\GuavaMultiPageResultSet.java
1
请完成以下Java代码
public class WEBUI_PP_Order_M_Source_HU_Delete extends WEBUI_PP_Order_Template implements IProcessPrecondition { @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PPOrderLineRow pickingSlotRow = getSingleSelectedRow(); if (!pickingSlotRow.isSourceHU()) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_SOURCE_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception
{ final PPOrderLineRow rowToProcess = getSingleSelectedRow(); final HuId huId = rowToProcess.getHuId(); // unselect the row we just deleted the record of, to avoid an 'EntityNotFoundException' final boolean sourceWasDeleted = SourceHUsService.get().deleteSourceHuMarker(huId); if (sourceWasDeleted) { getView().invalidateAll(); } invalidateView(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_M_Source_HU_Delete.java
1
请完成以下Java代码
public class PaymentResponse { @JacksonXmlProperty(localName = "status") private String status; @JacksonXmlProperty(localName = "message") private String message; @JacksonXmlProperty(localName = "referenceNumber") private String referenceNumber; public PaymentResponse() { } public PaymentResponse(String status, String message, String referenceNumber) { this.status = status; this.message = message; this.referenceNumber = referenceNumber; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; }
public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getReferenceNumber() { return referenceNumber; } public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-3\src\main\java\com\baeldung\xmlpost\model\PaymentResponse.java
1
请完成以下Java代码
public void onParameterChanged(@NonNull final String parameterName) { if (PARAM_M_Product_ID.equals(parameterName)) { if (productId != null) { qtyCUsPerTU = getHUStorageQty(productId).toBigDecimal(); } } } @Override protected String doIt() { if (productId == null) { throw new FillMandatoryException(PARAM_M_Product_ID); } if (qtyCUsPerTU == null || qtyCUsPerTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } final HuId huId = getSelectedHUId(); final Quantity qtyToRemove = Quantity.of(qtyCUsPerTU, getHUStorageQty(productId).getUOM()); pickingCandidateService.removeQtyFromHU(RemoveQtyFromHURequest.builder() .qtyToRemove(qtyToRemove) .huId(huId) .productId(productId) .build()); return MSG_OK; } @Override protected void postProcess(final boolean success) { invalidateView(); invalidateParentView(); } private HuId getSelectedHUId() { return getSingleSelectedRow().getHuId(); } private boolean checkSourceHuPreconditionIncludingEmptyHUs() { final HuId huId = getSelectedHUId(); final Collection<HuId> sourceHUs = sourceHUsRepository.retrieveMatchingSourceHUIds(huId); return !sourceHUs.isEmpty(); } private List<ProductId> getProductIds() { return getHUProductStorages()
.stream() .filter(productStorage -> !productStorage.isEmpty()) .map(IProductStorage::getProductId) .distinct() .collect(ImmutableList.toImmutableList()); } private Quantity getHUStorageQty(@NonNull final ProductId productId) { return getHUProductStorages() .stream() .filter(productStorage -> ProductId.equals(productStorage.getProductId(), productId)) .map(IHUProductStorage::getQty) .findFirst() .orElseThrow(() -> new AdempiereException("No Qty found for " + productId)); } private ImmutableList<IHUProductStorage> getHUProductStorages() { ImmutableList<IHUProductStorage> huProductStorage = _huProductStorages; if (huProductStorage == null) { final HuId huId = getSelectedHUId(); final I_M_HU hu = handlingUnitsBL.getById(huId); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); huProductStorage = _huProductStorages = ImmutableList.copyOf(storageFactory .getStorage(hu) .getProductStorages()); } return huProductStorage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_ReturnQtyToSourceHU.java
1
请完成以下Java代码
public class GetCamundaFormDefinitionCmd implements Command<CamundaFormDefinition> { protected CamundaFormRef camundaFormRef; protected String deploymentId; public GetCamundaFormDefinitionCmd(CamundaFormRef camundaFormRef, String deploymentId) { this.camundaFormRef = camundaFormRef; this.deploymentId = deploymentId; } @Override public CamundaFormDefinition execute(CommandContext commandContext) { String binding = camundaFormRef.getBinding(); String key = camundaFormRef.getKey(); CamundaFormDefinitionEntity definition = null; CamundaFormDefinitionManager manager = commandContext.getCamundaFormDefinitionManager();
if (binding.equals(DefaultFormHandler.FORM_REF_BINDING_DEPLOYMENT)) { definition = manager.findDefinitionByDeploymentAndKey(deploymentId, key); } else if (binding.equals(DefaultFormHandler.FORM_REF_BINDING_LATEST)) { definition = manager.findLatestDefinitionByKey(key); } else if (binding.equals(DefaultFormHandler.FORM_REF_BINDING_VERSION)) { definition = manager.findDefinitionByKeyVersionAndTenantId(key, camundaFormRef.getVersion(), null); } else { throw new BadUserRequestException("Unsupported binding type for camundaFormRef. Expected to be one of " + DefaultFormHandler.ALLOWED_FORM_REF_BINDINGS + " but was:" + binding); } return definition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetCamundaFormDefinitionCmd.java
1
请完成以下Java代码
private HUEditorRow getParentHURowOrNull(final HUEditorRow cuRow) { if (cuRow == null) { return null; } return getView().getParentRowByChildIdOrNull(cuRow.getId()); } private boolean isAggregateHU(final HUEditorRow huRow) { final I_M_HU hu = huRow.getM_HU(); return handlingUnitsBL.isAggregateHU(hu); } private final void updateViewFromResult(final WebuiHUTransformCommandResult result) { final HUEditorView view = getView(); view.addHUIds(result.getHuIdsToAddToView()); view.removeHUIds(result.getHuIdsToRemoveFromView()); if (!result.getHuIdsChanged().isEmpty()) { removeHUsIfDestroyed(result.getHuIdsChanged()); } } /** @return true if view was changed and needs invalidation */ private final boolean removeSelectedRowsIfHUDestoyed() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return false; } else if (selectedRowIds.isAll()) { return false; } final HUEditorView view = getView(); final ImmutableSet<HuId> selectedHUIds = view.streamByIds(selectedRowIds) .map(HUEditorRow::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); return removeHUsIfDestroyed(selectedHUIds);
} /** * @return true if at least one HU was removed */ private boolean removeHUsIfDestroyed(final Collection<HuId> huIds) { final ImmutableSet<HuId> destroyedHUIds = huIds.stream() .distinct() .map(huId -> load(huId, I_M_HU.class)) .filter(Services.get(IHandlingUnitsBL.class)::isDestroyed) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (destroyedHUIds.isEmpty()) { return false; } final HUEditorView view = getView(); final boolean changes = view.removeHUIds(destroyedHUIds); return changes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_Add_Batch_SerialNo_To_CUs.java
1
请完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; }
public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Name: " + this.name + "\nEmail: " + this.email; } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\User.java
1
请完成以下Java代码
public class InvokeGRSSignumAction extends AlterExternalSystemServiceStatusAction { public final ExternalSystemConfigRepo externalSystemConfigDAO = SpringContextHolder.instance.getBean(ExternalSystemConfigRepo.class); @Override protected IExternalSystemChildConfigId getExternalChildConfigId() { final int id; if (this.childConfigId > 0) { id = this.childConfigId; } else { final IExternalSystemChildConfig childConfig = externalSystemConfigDAO.getChildByParentIdAndType(ExternalSystemParentConfigId.ofRepoId(getRecord_ID()), getExternalSystemType()) .orElseThrow(() -> new AdempiereException("No childConfig found for type GRSSignum and parent config") .appendParametersToMessage() .setParameter("externalSystemParentConfigId:", ExternalSystemParentConfigId.ofRepoId(getRecord_ID()))); id = childConfig.getId().getRepoId(); } return ExternalSystemGRSSignumConfigId.ofRepoId(id); } @Override protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(externalSystemParentConfig.getChildConfig()); if (EmptyUtil.isEmpty(grsConfig.getCamelHttpResourceAuthKey())) { throw new AdempiereException("camelHttpResourceAuthKey for childConfig should not be empty at this point") .appendParametersToMessage() .setParameter("childConfigId", grsConfig.getId()); }
final Map<String, String> parameters = new HashMap<>(); parameters.put(ExternalSystemConstants.PARAM_CAMEL_HTTP_RESOURCE_AUTH_KEY, grsConfig.getCamelHttpResourceAuthKey()); parameters.put(ExternalSystemConstants.PARAM_BASE_PATH, grsConfig.getBaseUrl()); return parameters; } @Override protected String getTabName() { return ExternalSystemType.GRSSignum.getValue(); } @Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.GRSSignum; } @Override protected long getSelectedRecordCount(final IProcessPreconditionsContext context) { return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_ExternalSystem_Config_GRSSignum.Table_Name.equals(recordRef.getTableName())) .count(); } @Override protected String getOrgCode(@NonNull final ExternalSystemParentConfig config) { return orgDAO.getById(config.getOrgId()).getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeGRSSignumAction.java
1
请完成以下Java代码
public void executeAsync(final OutputStream out) { Check.assume(executorService == null, "No other execution started: {}", executorService); prepareDataSource(); // // Prepare & execute asynchronously executorService = Executors.newFixedThreadPool(2); final Runnable exportRunnable = new Runnable() { @Override public void run() { exporter.export(out); } }; final Runnable exportMonitor = new Runnable() { @Override public void run() { int prevRowCount = exporter.getExportedRowCount(); ExportStatus exportStatus = exporter.getExportStatus(); while (exportStatus != ExportStatus.Finished) { try { Thread.sleep(1000 * 10); // wait 10sec } catch (InterruptedException e) { // interruption required, just stop it break; } exportStatus = exporter.getExportStatus(); final int rowCount = exporter.getExportedRowCount(); if (exportStatus == ExportStatus.Finished) { break; } if (prevRowCount >= rowCount) { // the export thread is stagnating... we will need to stop everything break; } prevRowCount = rowCount; }
executorService.shutdownNow(); } }; futureExportResult = executorService.submit(exportRunnable); executorService.submit(exportMonitor); } public void waitToFinish() { try { futureExportResult.get(); } catch (InterruptedException e) { throw new AdempiereException(e.getLocalizedMessage(), e); } catch (ExecutionException e) { Throwable ex = e.getCause(); if (ex == null) { ex = e; } throw ex instanceof AdempiereException ? (AdempiereException)ex : new AdempiereException(ex.getLocalizedMessage(), ex); // NOPMD by tsa on 3/15/13 7:44 PM } finally { executorService.shutdownNow(); executorService = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\ASyncExporterWrapper.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; }
public List<Double> getData() { return data; } public void setData(List<Double> data) { this.data = data; } public Label getLabel() { return label; } public void setLabel(Label label) { this.label = label; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\api\model\jmh\Serie.java
1
请完成以下Java代码
private boolean hasTokenExpired(OAuth2Token token) { return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew)); } /** * Sets the client used when requesting an access token credential at the Token * Endpoint for the {@code client_credentials} grant. * @param accessTokenResponseClient the client used when requesting an access token * credential at the Token Endpoint for the {@code client_credentials} grant */ public void setAccessTokenResponseClient( ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; } /** * Sets the maximum acceptable clock skew, which is used when checking the * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is * 60 seconds. * * <p> * An access token is considered expired if * {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew
*/ public void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access * token expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\ClientCredentialsReactiveOAuth2AuthorizedClientProvider.java
1
请在Spring Boot框架中完成以下Java代码
class PurchaseCandidateImmutableFields { @Nullable ExternalSystemId externalSystemId; @Nullable ExternalId externalHeaderId; @Nullable ExternalId externalLineId; @Nullable String poReference; @Nullable OrderAndLineId salesOrderAndLineIdOrNull; @NonNull DemandGroupReference groupReference; @NonNull BPartnerId vendorId; @NonNull OrgId orgId;
@NonNull WarehouseId warehouseId; @NonNull ProductId productId; @NonNull AttributeSetInstanceId attributeSetInstanceId; String vendorProductNo; boolean aggregatePOs; @Nullable ForecastLineId forecastLineId; @Nullable Dimension dimension; @Nullable PurchaseCandidateSource source; @Nullable String externalPurchaseOrderUrl; }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidateImmutableFields.java
2
请完成以下Java代码
public BigDecimal getQtyInvoicedInOrderedUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInOrderedUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSupplier_GTIN_CU (final @Nullable java.lang.String Supplier_GTIN_CU) { set_ValueNoCheck (COLUMNNAME_Supplier_GTIN_CU, Supplier_GTIN_CU); } @Override public java.lang.String getSupplier_GTIN_CU() { return get_ValueAsString(COLUMNNAME_Supplier_GTIN_CU); } @Override public void setTaxAmtInfo (final @Nullable BigDecimal TaxAmtInfo) { set_Value (COLUMNNAME_TaxAmtInfo, TaxAmtInfo); } @Override public BigDecimal getTaxAmtInfo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtInfo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void settaxfree (final boolean taxfree) { set_Value (COLUMNNAME_taxfree, taxfree); } @Override public boolean istaxfree() { return get_ValueAsBoolean(COLUMNNAME_taxfree); } @Override public void setUPC_CU (final @Nullable java.lang.String UPC_CU) { set_ValueNoCheck (COLUMNNAME_UPC_CU, UPC_CU); } @Override public java.lang.String getUPC_CU()
{ return get_ValueAsString(COLUMNNAME_UPC_CU); } @Override public void setUPC_TU (final @Nullable java.lang.String UPC_TU) { set_ValueNoCheck (COLUMNNAME_UPC_TU, UPC_TU); } @Override public java.lang.String getUPC_TU() { return get_ValueAsString(COLUMNNAME_UPC_TU); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_500_v.java
1
请完成以下Java代码
public void setAD_LabelPrinter_ID (int AD_LabelPrinter_ID) { if (AD_LabelPrinter_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, Integer.valueOf(AD_LabelPrinter_ID)); } /** Get Label printer. @return Label Printer Definition */ public int getAD_LabelPrinter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_LabelPrinter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description);
} /** Set 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinter.java
1
请完成以下Java代码
public Optional<I_M_HU_PI_Item_Product> retrieveDefaultForProduct( @NonNull final ProductId productId, @Nullable final BPartnerId bpartnerId, @NonNull final ZonedDateTime date) { final IHUPIItemProductQuery query = createHUPIItemProductQuery(); query.setBPartnerId(bpartnerId); query.setProductId(productId); query.setDate(date); query.setDefaultForProduct(true); final I_M_HU_PI_Item_Product huPIItemProduct = retrieveFirst(Env.getCtx(), query, ITrx.TRXNAME_None); return Optional.ofNullable(huPIItemProduct); } @Override public Optional<HUPIItemProductId> retrieveDefaultIdForProduct( @NonNull final ProductId productId, @Nullable final BPartnerId bpartnerId, @NonNull final ZonedDateTime date) { return retrieveDefaultForProduct(productId, bpartnerId, date) .map(huPiItemProduct -> HUPIItemProductId.ofRepoIdOrNull(huPiItemProduct.getM_HU_PI_Item_Product_ID())); }
@Override @Nullable public I_M_HU_PI_Item_Product retrieveDefaultForProduct( @NonNull final ProductId productId, @NonNull final ZonedDateTime date) { final IHUPIItemProductQuery query = createHUPIItemProductQuery(); query.setProductId(productId); query.setDate(date); query.setDefaultForProduct(true); return retrieveFirst(Env.getCtx(), query, ITrx.TRXNAME_None); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductDAO.java
1
请完成以下Java代码
public void setAD_Process_CustomQuery(final org.compiere.model.I_AD_Process AD_Process_CustomQuery) { set_ValueFromPO(COLUMNNAME_AD_Process_CustomQuery_ID, org.compiere.model.I_AD_Process.class, AD_Process_CustomQuery); } @Override public void setAD_Process_CustomQuery_ID (final int AD_Process_CustomQuery_ID) { if (AD_Process_CustomQuery_ID < 1) set_Value (COLUMNNAME_AD_Process_CustomQuery_ID, null); else set_Value (COLUMNNAME_AD_Process_CustomQuery_ID, AD_Process_CustomQuery_ID); } @Override public int getAD_Process_CustomQuery_ID() { return get_ValueAsInt(COLUMNNAME_AD_Process_CustomQuery_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsAdditionalCustomQuery (final boolean IsAdditionalCustomQuery) { set_Value (COLUMNNAME_IsAdditionalCustomQuery, IsAdditionalCustomQuery); } @Override public boolean isAdditionalCustomQuery() { return get_ValueAsBoolean(COLUMNNAME_IsAdditionalCustomQuery);
} @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); } @Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_ConfigGroup.java
1
请完成以下Java代码
public class MChatEntry extends X_CM_ChatEntry { /** * */ private static final long serialVersionUID = -158924400098841023L; /** * Standard Constructor * @param ctx cintext * @param CM_ChatEntry_ID id * @param trxName transaction */ public MChatEntry (Properties ctx, int CM_ChatEntry_ID, String trxName) { super (ctx, CM_ChatEntry_ID, trxName); if (CM_ChatEntry_ID == 0) { setChatEntryType (CHATENTRYTYPE_NoteFlat); // N setConfidentialType (CONFIDENTIALTYPE_PublicInformation); } } // MChatEntry /** * Parent Constructor * @param chat parent * @param data text */ public MChatEntry (MChat chat, String data) { this (chat.getCtx(), 0, chat.get_TrxName()); setCM_Chat_ID(chat.getCM_Chat_ID()); setConfidentialType(chat.getConfidentialType()); setCharacterData(data); setChatEntryType (CHATENTRYTYPE_NoteFlat); // N } // MChatEntry /** * Thread Constructor * @param entry peer * @param data text */ public MChatEntry (MChatEntry peer, String data) { this (peer.getCtx(), 0, peer.get_TrxName()); setCM_Chat_ID(peer.getCM_Chat_ID()); setCM_ChatEntryParent_ID (peer.getCM_ChatEntryParent_ID()); // Set GrandParent int id = peer.getCM_ChatEntryGrandParent_ID(); if (id == 0) id = peer.getCM_ChatEntryParent_ID(); setCM_ChatEntryGrandParent_ID (id); setConfidentialType(peer.getConfidentialType()); setCharacterData(data); setChatEntryType (CHATENTRYTYPE_ForumThreaded); } // MChatEntry /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MChatEntry (Properties ctx, ResultSet rs, String trxName)
{ super (ctx, rs, trxName); } // MChatEntry /** * Can be published * @param ConfidentialType minimum confidential type * @return true if withing confidentiality */ public boolean isConfidentialType(String ConfidentialType) { String ct = getConfidentialType(); if (ConfidentialType == null || CONFIDENTIALTYPE_PublicInformation.equals(ct)) return true; if (CONFIDENTIALTYPE_PartnerConfidential.equals(ct)) { return CONFIDENTIALTYPE_PartnerConfidential.equals(ConfidentialType); } else if (CONFIDENTIALTYPE_PrivateInformation.equals(ct)) { return CONFIDENTIALTYPE_Internal.equals(ConfidentialType) || CONFIDENTIALTYPE_PrivateInformation.equals(ConfidentialType); } else if (CONFIDENTIALTYPE_Internal.equals(ct)) { return CONFIDENTIALTYPE_Internal.equals(ConfidentialType); } return false; } // } // MChatEntry
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MChatEntry.java
1
请在Spring Boot框架中完成以下Java代码
public class ServerVerticle extends AbstractVerticle { @Autowired private Integer defaultPort; private void getAllArticlesHandler(RoutingContext routingContext) { vertx.eventBus() .<String>send(ArticleRecipientVerticle.GET_ALL_ARTICLES, "", result -> { if (result.succeeded()) { routingContext.response() .putHeader("content-type", "application/json") .setStatusCode(200) .end(result.result() .body()); } else { routingContext.response() .setStatusCode(500) .end(); } });
} @Override public void start() throws Exception { super.start(); Router router = Router.router(vertx); router.get("/api/baeldung/articles") .handler(this::getAllArticlesHandler); vertx.createHttpServer() .requestHandler(router::accept) .listen(config().getInteger("http.port", defaultPort)); } }
repos\tutorials-master\vertx-modules\spring-vertx\src\main\java\com\baeldung\vertxspring\verticles\ServerVerticle.java
2
请完成以下Java代码
public GridField getField() { return m_mField; } /** * Feature Request [1707462] * Set VFormat * @param strMask mask * @author fer_luck */ public void setVFormat (String strMask) { m_VFormat = strMask; //Get the actual caret from the field, if there's no //caret then just catch the exception and continue //creating the new caret. try{ CaretListener [] cl = this.getCaretListeners(); this.removeCaretListener(cl[0]); } catch(ClassCastException ex ){ log.debug("VString.setVFormat - No caret Listeners"); } //hengsin: [ adempiere-Bugs-1891037 ], preserve current data before change of format String s = getText(); setDocument(new MDocString(m_VFormat, m_fieldLength, this)); setText(s); } // setVFormat /** * Set Text (optionally obscured) * @param text text */ @Override public void setText (String text) { if (m_obscure != null && !m_infocus) { super.setFont(m_obscureFont); super.setText (m_obscure.getObscuredValue(text)); super.setForeground(Color.gray); } else { if (m_stdFont != null) { super.setFont(m_stdFont); super.setForeground(AdempierePLAF.getTextColor_Normal()); } super.setText (text); } } // setText /** * Get Text (clear) * @return text */ @Override public String getText () { String text = super.getText(); if (m_obscure != null && text != null && text.length() > 0) { if (text.equals(m_obscure.getObscuredValue())) text = m_obscure.getClearValue(); } return text; } // getText /**
* Feature Request [1707462] * Get VFormat * @return strMask mask * @author fer_luck */ public String getVFormat () { return this.m_VFormat; } // getVFormat /** * Focus Gained. * Enabled with Obscure * @param e event */ @Override public void focusGained (FocusEvent e) { m_infocus = true; setText(getText()); // clear } // focusGained /** * Focus Lost * Enabled with Obscure * @param e event */ @Override public void focusLost (FocusEvent e) { m_infocus = false; setText(getText()); // obscure } // focus Lost @Override public void setFont(Font f) { super.setFont(f); m_stdFont = f; m_obscureFont = new Font("SansSerif", Font.ITALIC, m_stdFont.getSize()); } // metas @Override public boolean isAutoCommit() { return true; } } // VString
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VString.java
1
请在Spring Boot框架中完成以下Java代码
public static Optional<BPUpsertCamelRequest> usersToBPartnerUpsert( @NonNull final String orgCode, @NonNull final JsonMetasfreshId bPartnerId, @Nullable final Users... users) { if (users == null) { return Optional.empty(); } final JsonRequestContactUpsert.JsonRequestContactUpsertBuilder usersUpsertBuilder = JsonRequestContactUpsert.builder(); final HashSet<String> seenUserIds = new HashSet<>(); for (final Users user : users) { DataMapper.userToBPartnerContact(user) .filter(contactUpsertItem -> !seenUserIds.contains(contactUpsertItem.getContactIdentifier())) .ifPresent(contactUpsertItem -> { seenUserIds.add(contactUpsertItem.getContactIdentifier()); usersUpsertBuilder.requestItem(contactUpsertItem); }); } final JsonRequestContactUpsert usersUpsert = usersUpsertBuilder.build();
if (Check.isEmpty(usersUpsert.getRequestItems())) { return Optional.empty(); } return contactToBPartnerUpsert(usersUpsert, bPartnerId, orgCode); } @NonNull public static Optional<JsonRequestBPartnerLocationAndContact> pharmacyToDropShipBPartner(@Nullable final String pharmacyId) { if(Check.isBlank(pharmacyId)) { return Optional.empty(); } return Optional.of(JsonRequestBPartnerLocationAndContact.builder() .bPartnerIdentifier(formatExternalId(pharmacyId)) .bPartnerLocationIdentifier(formatExternalId(pharmacyId)) .build()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\common\DataMapper.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { // ------------------------ // PUBLIC METHODS // ------------------------ /** * Create a new user with an auto-generated id and email and name as passed * values. */ @RequestMapping(value="/create") @ResponseBody public String create(String email, String name) { try { User user = new User(email, name); userDao.create(user); } catch (Exception ex) { return "Error creating the user: " + ex.toString(); } return "User succesfully created!"; } /** * Delete the user with the passed id. */ @RequestMapping(value="/delete") @ResponseBody public String delete(long id) { try { User user = new User(id); userDao.delete(user); } catch (Exception ex) { return "Error deleting the user: " + ex.toString(); } return "User succesfully deleted!"; } /** * Retrieve the id for the user with the passed email address. */ @RequestMapping(value="/get-by-email") @ResponseBody
public String getByEmail(String email) { String userId; try { User user = userDao.getByEmail(email); userId = String.valueOf(user.getId()); } catch (Exception ex) { return "User not found: " + ex.toString(); } return "The user id is: " + userId; } /** * Update the email and the name for the user indentified by the passed id. */ @RequestMapping(value="/update") @ResponseBody public String updateName(long id, String email, String name) { try { User user = userDao.getById(id); user.setEmail(email); user.setName(name); userDao.update(user); } catch (Exception ex) { return "Error updating the user: " + ex.toString(); } return "User succesfully updated!"; } // ------------------------ // PRIVATE FIELDS // ------------------------ // Wire the UserDao used inside this controller. @Autowired private UserDao userDao; } // class UserController
repos\spring-boot-samples-master\spring-boot-mysql-jpa-hibernate\src\main\java\netgloo\controllers\UserController.java
2
请完成以下Java代码
private void generalOwnership () { String set = "SET AD_Org_ID=0 WHERE AD_Client_ID=" + getAD_Client_ID() + " AND AD_Org_ID<>0"; // R_ContactInterest String sql = "UPDATE R_ContactInterest " + set; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 0) log.debug("generalOwnership - R_ContactInterest=" + no); // AD_User_Roles sql = "UPDATE AD_User_Roles " + set; no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 0) log.debug("generalOwnership - AD_User_Roles=" + no); // C_BPartner_Product sql = "UPDATE C_BPartner_Product " + set; no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 0) log.debug("generalOwnership - C_BPartner_Product=" + no);
// Withholding sql = "UPDATE C_BP_Withholding x " + set; no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 0) log.debug("generalOwnership - C_BP_Withholding=" + no); // Replenish sql = "UPDATE M_Replenish " + set; no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 0) log.debug("generalOwnership - M_Replenish=" + no); } // generalOwnership } // OrgOwnership
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\OrgOwnership.java
1
请完成以下Java代码
public Builder setFrequentUsed(final boolean frequentUsed) { this.frequentUsed = frequentUsed; return this; } public Builder setInlineRenderMode(final DocumentFilterInlineRenderMode inlineRenderMode) { this.inlineRenderMode = inlineRenderMode; return this; } private DocumentFilterInlineRenderMode getInlineRenderMode() { return inlineRenderMode != null ? inlineRenderMode : DocumentFilterInlineRenderMode.BUTTON; } public Builder setParametersLayoutType(final PanelLayoutType parametersLayoutType) { this.parametersLayoutType = parametersLayoutType; return this; } private PanelLayoutType getParametersLayoutType() { return parametersLayoutType != null ? parametersLayoutType : PanelLayoutType.Panel; } public Builder setFacetFilter(final boolean facetFilter) { this.facetFilter = facetFilter; return this; } public boolean hasParameters() { return !parameters.isEmpty();
} public Builder addParameter(final DocumentFilterParamDescriptor.Builder parameter) { parameters.add(parameter); return this; } public Builder addInternalParameter(final String parameterName, final Object constantValue) { return addInternalParameter(DocumentFilterParam.ofNameEqualsValue(parameterName, constantValue)); } public Builder addInternalParameter(final DocumentFilterParam parameter) { internalParameters.add(parameter); return this; } public Builder putDebugProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); if (debugProperties == null) { debugProperties = new LinkedHashMap<>(); } debugProperties.put("debug-" + name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterDescriptor.java
1
请完成以下Java代码
private Collection<ApplicationListener<?>> getListeners() { List<ApplicationListener<?>> listeners = new ArrayList<>(); listeners.add(new AnsiOutputApplicationListener()); listeners.add(EnvironmentPostProcessorApplicationListener .with(EnvironmentPostProcessorsFactory.of(ConfigDataEnvironmentPostProcessor.class))); listeners.add(new LoggingApplicationListener()); listeners.add(new RemoteUrlPropertyExtractor()); return listeners; } private Banner getBanner() { ClassPathResource banner = new ClassPathResource("remote-banner.txt", RemoteSpringApplication.class); return new ResourceBanner(banner); } private void waitIndefinitely() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) {
Thread.currentThread().interrupt(); } } } /** * Run the {@link RemoteSpringApplication}. * @param args the program arguments (including the remote URL as a non-option * argument) */ public static void main(String[] args) { new RemoteSpringApplication().run(args); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\RemoteSpringApplication.java
1
请在Spring Boot框架中完成以下Java代码
public void write(T t, @Nullable Type type, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { this.smartConverter.write(t, ResolvableType.forType(type), contentType, outputMessage, null); } @Override public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) { return this.smartConverter.canRead(ResolvableType.forClass(clazz), mediaType); } @Override public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) { return this.smartConverter.canWrite(clazz, mediaType); } @Override public List<MediaType> getSupportedMediaTypes() { return this.smartConverter.getSupportedMediaTypes();
} @Override public T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return this.smartConverter.read(clazz, inputMessage); } @Override public void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { this.smartConverter.write(t, contentType, outputMessage); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\web\server\GenericHttpMessageConverterAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public void getCorsFile(String urlPath, HttpServletResponse response,FileAttribute fileAttribute) throws IOException { URL url; try { urlPath = WebUtils.decodeUrl(urlPath); url = WebUtils.normalizedURL(urlPath); } catch (Exception ex) { logger.error(String.format(BASE64_DECODE_ERROR_MSG, urlPath),ex); return; } assert urlPath != null; if (!urlPath.toLowerCase().startsWith("http") && !urlPath.toLowerCase().startsWith("https") && !urlPath.toLowerCase().startsWith("ftp")) { logger.info("读取跨域文件异常,可能存在非法访问,urlPath:{}", urlPath); return; } InputStream inputStream = null; logger.info("读取跨域pdf文件url:{}", urlPath); if (!urlPath.toLowerCase().startsWith("ftp:")) { factory.setConnectionRequestTimeout(2000); factory.setConnectTimeout(10000); factory.setReadTimeout(72000); HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy()).build(); factory.setHttpClient(httpClient); restTemplate.setRequestFactory(factory); RequestCallback requestCallback = request -> { request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL)); String proxyAuthorization = fileAttribute.getKkProxyAuthorization(); if(StringUtils.hasText(proxyAuthorization)){ Map<String,String> proxyAuthorizationMap = mapper.readValue(proxyAuthorization, Map.class); proxyAuthorizationMap.forEach((key, value) -> request.getHeaders().set(key, value)); } }; try { restTemplate.execute(url.toURI(), HttpMethod.GET, requestCallback, fileResponse -> {
IOUtils.copy(fileResponse.getBody(), response.getOutputStream()); return null; }); } catch (Exception e) { System.out.println(e); } }else{ try { if(urlPath.contains(".svg")) { response.setContentType("image/svg+xml"); } inputStream = (url).openStream(); IOUtils.copy(inputStream, response.getOutputStream()); } catch (IOException e) { logger.error("读取跨域文件异常,url:{}", urlPath); } finally { IOUtils.closeQuietly(inputStream); } } } /** * 通过api接口入队 * * @param url 请编码后在入队 */ @GetMapping("/addTask") @ResponseBody public String addQueueTask(String url) { logger.info("添加转码队列url:{}", url); cacheService.addQueueTask(url); return "success"; } }
repos\kkFileView-master\server\src\main\java\cn\keking\web\controller\OnlinePreviewController.java
2
请完成以下Java代码
public static ProductAndAttributes toProductAndAttributes(@NonNull final LookupValue lookupValue) { final ProductId productId = lookupValue.getIdAs(ProductId::ofRepoId); final Map<Object, Object> valuesByAttributeIdMap = lookupValue.getAttribute(ATTRIBUTE_ASI); final ImmutableAttributeSet attributes = ImmutableAttributeSet.ofValuesByAttributeIdMap(valuesByAttributeIdMap); return ProductAndAttributes.builder() .productId(productId) .attributes(attributes) .build(); } private boolean isFullTextSearchEnabled() { final boolean disabled = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DisableFullTextSearch, false); return !disabled; } @Value @Builder(toBuilder = true) public static class ProductAndAttributes { @NonNull ProductId productId;
@Default @NonNull ImmutableAttributeSet attributes = ImmutableAttributeSet.EMPTY; } private interface I_M_Product_Lookup_V { String Table_Name = "M_Product_Lookup_V"; String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; String COLUMNNAME_IsActive = "IsActive"; String COLUMNNAME_M_Product_ID = "M_Product_ID"; String COLUMNNAME_Value = "Value"; String COLUMNNAME_Name = "Name"; String COLUMNNAME_UPC = "UPC"; String COLUMNNAME_BPartnerProductNo = "BPartnerProductNo"; String COLUMNNAME_BPartnerProductName = "BPartnerProductName"; String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID"; String COLUMNNAME_Discontinued = "Discontinued"; String COLUMNNAME_DiscontinuedFrom = "DiscontinuedFrom"; String COLUMNNAME_IsBOM = "IsBOM"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\ProductLookupDescriptor.java
1
请完成以下Java代码
public List<SessionDescriptor> getSessions() { return this.sessions; } /** * A description of user's {@link Session session} exposed by {@code sessions} * endpoint. Primarily intended for serialization to JSON. */ public static final class SessionDescriptor { private final String id; private final Set<String> attributeNames; private final Instant creationTime; private final Instant lastAccessedTime; private final long maxInactiveInterval; private final boolean expired; SessionDescriptor(Session session) { this.id = session.getId(); this.attributeNames = session.getAttributeNames(); this.creationTime = session.getCreationTime(); this.lastAccessedTime = session.getLastAccessedTime(); this.maxInactiveInterval = session.getMaxInactiveInterval().getSeconds(); this.expired = session.isExpired(); } public String getId() { return this.id; }
public Set<String> getAttributeNames() { return this.attributeNames; } public Instant getCreationTime() { return this.creationTime; } public Instant getLastAccessedTime() { return this.lastAccessedTime; } public long getMaxInactiveInterval() { return this.maxInactiveInterval; } public boolean isExpired() { return this.expired; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\actuate\endpoint\SessionsDescriptor.java
1
请完成以下Java代码
public class ScriptServiceTask extends ServiceTask implements HasInParameters { public static final String SCRIPT_TASK = "script"; protected boolean autoStoreVariables; protected boolean doNotIncludeVariables = false; protected List<IOParameter> inParameters; public ScriptServiceTask() { this.type = SCRIPT_TASK; } public String getScriptFormat() { return implementationType; } public void setScriptFormat(String scriptFormat) { this.implementationType = scriptFormat; } public String getScript() { for (FieldExtension fieldExtension : fieldExtensions) { if ("script".equalsIgnoreCase(fieldExtension.getFieldName())) { String script = fieldExtension.getStringValue(); if (StringUtils.isNotEmpty(script)) { return script; } return fieldExtension.getExpression(); } } return null; } public boolean isAutoStoreVariables() { return autoStoreVariables; } public void setAutoStoreVariables(boolean autoStoreVariables) { this.autoStoreVariables = autoStoreVariables; } public boolean isDoNotIncludeVariables() { return doNotIncludeVariables; } public void setDoNotIncludeVariables(boolean doNotIncludeVariables) { this.doNotIncludeVariables = doNotIncludeVariables; } @Override public List<IOParameter> getInParameters() {
return inParameters; } @Override public void addInParameter(IOParameter inParameter) { if (inParameters == null) { inParameters = new ArrayList<>(); } inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public ScriptServiceTask clone() { ScriptServiceTask clone = new ScriptServiceTask(); clone.setValues(this); return clone; } public void setValues(ScriptServiceTask otherElement) { super.setValues(otherElement); setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables()); inParameters = null; if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { inParameters = new ArrayList<>(); for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ScriptServiceTask.java
1
请在Spring Boot框架中完成以下Java代码
default Profile profile(ArticleAssemblyJdbcEntity source) { return new Profile(source.authorUsername(), source.authorBio(), source.authorImage(), source.authorFollowing()); } default List<String> tagList(String source) { if (source == null) { return null; } return Arrays.stream(source.split(",")).toList(); } default String tagList(List<Tag> source) { if (source == null || source.isEmpty()) { return null; } return source.stream().map(Tag::name).collect(Collectors.joining(",")); } default List<ArticleTagJdbcEntity> tagIds(List<Tag> source) { return source.stream().map(t -> new ArticleTagJdbcEntity(t.id())).toList(); } default List<Tag> tags(ArticleJdbcEntity source) { var tagIds = source.tagIds(); if (tagIds != null) { var tagList = source.tagList(); if (tagList != null) {
var tagNames = tagList.split(","); if (tagNames.length == tagIds.size()) { List<Tag> tags = new ArrayList<>(); for (var i = 0; i < tagIds.size(); i++) { var tag = new Tag(tagIds.get(i).tagId(), tagNames[i]); tags.add(tag); } return tags; } } } return List.of(); } } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\ArticleJdbcRepositoryAdapter.java
2
请完成以下Java代码
protected void localUsage() { paramDesc("-input <file>", "Use text data from <file> to train the model"); System.err.printf("\nExamples:\n"); System.err.printf("java %s -input corpus.txt -output vectors.txt -size 200 -window 5 -sample 0.0001 -negative 5 -hs 0 -binary -cbow 1 -iter 3\n\n", Train.class.getName()); } void execute(String[] args) throws IOException { if (args.length <= 1) usage(); Config config = new Config(); setConfig(args, config);
int i; if ((i = argPos("-input", args)) >= 0) config.setInputFile(args[i + 1]); Word2VecTraining w2v = new Word2VecTraining(config); System.err.printf("Starting training using text file %s\nthreads = %d, iter = %d\n", config.getInputFile(), config.getNumThreads(), config.getIter()); w2v.trainModel(); } public static void main(String[] args) throws IOException { new Train().execute(args); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Train.java
1
请完成以下Java代码
public Optional<String> getByPathAsString(final String... path) { return getByPath(path).map(Object::toString); } public Optional<Object> getByPath(final String... path) { Object currentValue = properties; for (final String pathElement : path) { if (!(currentValue instanceof Map)) { //throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties); return Optional.empty(); } //noinspection unchecked final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null); if (value == null) { return Optional.empty(); } else { currentValue = value;
} } return Optional.of(currentValue); } private static Optional<Object> getByKey(final Map<String, Object> map, final String key) { return map.entrySet() .stream() .filter(e -> e.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getValue) .filter(Objects::nonNull) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaApplicationLongMessage { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(KafkaApplicationLongMessage.class, args); LongMessageProducer producer = context.getBean(LongMessageProducer.class); String fileData = readLongMessage(); producer.sendMessage(fileData); //Deliberate delay to let listener consume produced message before main thread stops Thread.sleep(5000); context.close(); } private static String readLongMessage() throws IOException { String data = ""; //update complete location of large message here data = new String(Files.readAllBytes(Paths.get("RandomTextFile.txt"))); return data; } @Bean public LongMessageProducer longMessageProducer() { return new LongMessageProducer(); } @Bean public LongMessageListener longMessageListener() { return new LongMessageListener(); } public static class LongMessageProducer {
@Autowired private KafkaTemplate<String, String> kafkaTemplate; @Value(value = "${long.message.topic.name}") private String topicName; public void sendMessage(String message) { kafkaTemplate.send(topicName, message); System.out.println("Long message Sent"); } } public static class LongMessageListener { @KafkaListener(topics = "${long.message.topic.name}", groupId = "longMessage", containerFactory = "longMessageKafkaListenerContainerFactory") public void listenGroupLongMessage(String message) { System.out.println("Received Message in group 'longMessage'"); } } }
repos\tutorials-master\spring-kafka-4\src\main\java\com\baeldung\spring\kafka\KafkaApplicationLongMessage.java
2
请在Spring Boot框架中完成以下Java代码
public class DDOrderRef { int ddOrderCandidateId; int ddOrderId; int ddOrderLineId; @Builder(toBuilder = true) @Jacksonized private DDOrderRef( final int ddOrderCandidateId, final int ddOrderId, final int ddOrderLineId) { if (ddOrderCandidateId <= 0 && ddOrderId <= 0) { throw new AdempiereException("At least one of ddOrderCandidateId or ddOrderId shall be set"); } this.ddOrderCandidateId = normalizeId(ddOrderCandidateId); this.ddOrderId = normalizeId(ddOrderId); this.ddOrderLineId = normalizeId(this.ddOrderId > 0 ? ddOrderLineId : -1); } private static int normalizeId(final int id) {return id > 0 ? id : -1;} public static class DDOrderRefBuilder { @Nullable public DDOrderRef buildOrNull() { if (ddOrderCandidateId <= 0 && ddOrderId <= 0) { return null; } return build(); } } @Nullable public static DDOrderRef ofNullableDDOrderAndLineId(final int ddOrderId, final int ddOrderLineId) { return builder().ddOrderId(ddOrderId).ddOrderLineId(ddOrderLineId).buildOrNull(); }
public static DDOrderRef ofNullableDDOrderCandidateId(final int ddOrderCandidateId) { return ddOrderCandidateId > 0 ? builder().ddOrderCandidateId(ddOrderCandidateId).build() : null; } public DDOrderRef withDdOrderCandidateId(final int ddOrderCandidateIdNew) { final int ddOrderCandidateIdNewNorm = normalizeId(ddOrderCandidateIdNew); return this.ddOrderCandidateId != ddOrderCandidateIdNewNorm ? toBuilder().ddOrderCandidateId(ddOrderCandidateIdNewNorm).build() : this; } public static DDOrderRef withDdOrderCandidateId(@Nullable final DDOrderRef ddOrderRef, final int ddOrderCandidateIdNew) { return ddOrderRef != null ? ddOrderRef.withDdOrderCandidateId(ddOrderCandidateIdNew) : ofNullableDDOrderCandidateId(ddOrderCandidateIdNew); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddorder\DDOrderRef.java
2
请在Spring Boot框架中完成以下Java代码
private void addNonceParameters(Map<String, Object> attributes, Map<String, Object> additionalParameters) { try { String nonce = this.secureKeyGenerator.generateKey(); String nonceHash = createHash(nonce); attributes.put(OidcParameterNames.NONCE, nonce); additionalParameters.put(OidcParameterNames.NONCE, nonceHash); } catch (NoSuchAlgorithmException e) { } } /** * Creates and adds additional PKCE parameters for use in the OAuth 2.0 Authorization and Access Token Requests * * @param attributes where {@link PkceParameterNames#CODE_VERIFIER} is stored for the token request * @param additionalParameters where {@link PkceParameterNames#CODE_CHALLENGE} and, usually, * {@link PkceParameterNames#CODE_CHALLENGE_METHOD} are added to be used in the authorization request. * * @since 5.2 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc7636#section-1.1">1.1. Protocol Flow</a> * @see <a target="_blank" href="https://tools.ietf.org/html/rfc7636#section-4.1">4.1. Client Creates a Code Verifier</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7636#section-4.2">4.2. Client Creates the Code Challenge</a> */ private void addPkceParameters(Map<String, Object> attributes, Map<String, Object> additionalParameters) { String codeVerifier = this.secureKeyGenerator.generateKey(); attributes.put(PkceParameterNames.CODE_VERIFIER, codeVerifier); try { String codeChallenge = createHash(codeVerifier); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, codeChallenge); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); } catch (NoSuchAlgorithmException e) { additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, codeVerifier); } } private static String createHash(String value) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\config\CustomOAuth2AuthorizationRequestResolver.java
2
请在Spring Boot框架中完成以下Java代码
public void updateAuthor() { Author author = authorRepository.findByName("Mark Janel"); author.setAge(45); } @Transactional public void updateBooks() { Author author = authorRepository.findByName("Quartis Young"); List<Book> books = author.getBooks(); for (Book book : books) { book.setIsbn("not available"); } }
@Transactional(readOnly = true) public void queryEntityHistory() { AuditReader reader = AuditReaderFactory.get(em); AuditQuery queryAtRev = reader.createQuery().forEntitiesAtRevision(Book.class, 3); System.out.println("Get all Book instances modified at revision #3:"); System.out.println(queryAtRev.getResultList()); AuditQuery queryOfRevs = reader.createQuery().forRevisionsOfEntity(Book.class, true, true); System.out.println("\nGet all Book instances in all their states that were audited:"); System.out.println(queryOfRevs.getResultList()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootEnvers\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public class UserEvent implements Comparable<UserEvent> { private String userEventId; private long eventNanoTime; private long globalSequenceNumber; @SuppressWarnings("unused") public UserEvent() { // Required for Jackson Serialization and Deserialization } public UserEvent(String userEventId) { this.userEventId = userEventId; } public String getUserEventId() { return userEventId; } public long getEventNanoTime() { return eventNanoTime; } public void setEventNanoTime(long eventNanoTime) { this.eventNanoTime = eventNanoTime; } public long getGlobalSequenceNumber() { return globalSequenceNumber; } public void setGlobalSequenceNumber(long globalSequenceNumber) { this.globalSequenceNumber = globalSequenceNumber;
} @Override public int compareTo(UserEvent other) { return Long.compare(this.globalSequenceNumber, other.globalSequenceNumber); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof UserEvent)) { return false; } UserEvent userEvent = (UserEvent) obj; return this.globalSequenceNumber == userEvent.globalSequenceNumber; } @Override public int hashCode() { return Objects.hash(globalSequenceNumber); } }
repos\tutorials-master\apache-kafka\src\main\java\com\baeldung\kafka\message\ordering\payload\UserEvent.java
1
请完成以下Java代码
public HUMoveToDirectWarehouseService setFailIfNoHUs(final boolean failIfNoHUs) { _failIfNoHUs = failIfNoHUs; return this; } private boolean isFailIfNoHUs() { return _failIfNoHUs; } public HUMoveToDirectWarehouseService setDocumentsCollection(final DocumentCollection documentsCollection) { this.documentsCollection = documentsCollection; return this; } public HUMoveToDirectWarehouseService setHUView(final HUEditorView huView) { this.huView = huView; return this; } private void notifyHUMoved(final I_M_HU hu) { final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); // // Invalidate all documents which are about this HU. if (documentsCollection != null) { try
{ documentsCollection.invalidateDocumentByRecordId(I_M_HU.Table_Name, huId.getRepoId()); } catch (final Exception ex) { logger.warn("Failed invalidating documents for M_HU_ID={}. Ignored", huId, ex); } } // // Remove this HU from the view // Don't invalidate. We will do it at the end of all processing. // // NOTE/Later edit: we decided to not remove it anymore // because in some views it might make sense to keep it there. // The right way would be to check if after moving it, the HU is still elgible for view's filters. // // if (huView != null) { huView.removeHUIds(ImmutableSet.of(huId)); } } /** * @return target warehouse where the HUs will be moved to. */ @NonNull private LocatorId getTargetLocatorId() { if (_targetLocatorId == null) { _targetLocatorId = huMovementBL.getDirectMoveLocatorId(); } return _targetLocatorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\HUMoveToDirectWarehouseService.java
1
请在Spring Boot框架中完成以下Java代码
public HttpClient configureSsl(HttpClient client) { final HttpClientProperties.Ssl ssl = getSslProperties(); if (getBundle() != null || (ssl.getKeyStore() != null && ssl.getKeyStore().length() > 0) || getTrustedX509CertificatesForTrustManager().length > 0 || ssl.isUseInsecureTrustManager()) { client = client.secure(sslContextSpec -> { // configure ssl configureSslContext(ssl, sslContextSpec); }); } return client; } protected void configureSslContext(HttpClientProperties.Ssl ssl, SslProvider.SslContextSpec sslContextSpec) { SslProvider.ProtocolSslContextSpec clientSslContext = (serverProperties.getHttp2().isEnabled()) ? Http2SslContextSpec.forClient() : Http11SslContextSpec.forClient(); clientSslContext.configure(sslContextBuilder -> { X509Certificate[] trustedX509Certificates = getTrustedX509CertificatesForTrustManager(); SslBundle bundle = getBundle(); if (trustedX509Certificates.length > 0) { setTrustManager(sslContextBuilder, trustedX509Certificates); } else if (ssl.isUseInsecureTrustManager()) { setTrustManager(sslContextBuilder, InsecureTrustManagerFactory.INSTANCE); } else if (bundle != null) { setTrustManager(sslContextBuilder, bundle.getManagers().getTrustManagerFactory()); } try { if (bundle != null) { sslContextBuilder.keyManager(bundle.getManagers().getKeyManagerFactory()); }
else { sslContextBuilder.keyManager(getKeyManagerFactory()); } } catch (Exception e) { logger.error(e); } }); sslContextSpec.sslContext(clientSslContext) .handshakeTimeout(ssl.getHandshakeTimeout()) .closeNotifyFlushTimeout(ssl.getCloseNotifyFlushTimeout()) .closeNotifyReadTimeout(ssl.getCloseNotifyReadTimeout()); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientSslConfigurer.java
2
请完成以下Java代码
protected void prepare() { } @Override protected String doIt() { final IArchiveAware archiveAware = getRecord(IArchiveAware.class); final I_AD_Archive archive = archiveAware.getAD_Archive(); Check.assumeNotNull(archive, "Parameter archive is not null"); final IArchiveBL archiveBL = Services.get(IArchiveBL.class); final byte[] data = archiveBL.getBinaryData(archive); final String contentType = archiveBL.getContentType(archive); final String filename = String.valueOf(archive.getRecord_ID()); openPdfFile(data, contentType, filename); return "OK";
} private void openPdfFile(@NonNull final byte[] data, @NonNull final String contentType, @NonNull final String filename) { final boolean backEndOrSwing = Ini.getRunMode() == RunMode.BACKEND || Ini.isSwingClient(); if (backEndOrSwing) { Services.get(IClientUI.class).download(data, contentType, filename); } else { getResult().setReportData(new ByteArrayResource(data), filename, contentType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\process\ExportArchivePDF.java
1
请完成以下Java代码
public static GTIN ofString(@NonNull final String value) { return new GTIN(value); } public static GTIN ofNullableString(@Nullable final String value) { final String valueNorm = StringUtils.trimBlankToNull(value); return valueNorm != null ? ofString(valueNorm) : null; } public static Optional<GTIN> optionalOfNullableString(@Nullable final String value) {return Optional.ofNullable(ofNullableString(value));} public static GTIN ofEAN13(@NonNull final EAN13 ean13) { return new GTIN(ean13); } public static Optional<GTIN> ofScannedCode(@NonNull final ScannedCode scannedCode) { return optionalOfNullableString(scannedCode.getAsString()); } @Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() {return value;} public ExplainedOptional<EAN13> toEAN13() { ExplainedOptional<EAN13> ean13Holder = this.ean13Holder; if (ean13Holder == null) { ean13Holder = this.ean13Holder = EAN13.ofString(value); } return ean13Holder; } public boolean isMatching(final @NonNull EAN13ProductCode expectedProductCode) { final EAN13 ean13 = toEAN13().orElse(null); return ean13 != null && ean13.isMatching(expectedProductCode); } public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode) { final EAN13 ean13 = toEAN13().orElse(null);
return ean13 != null && ean13.productCodeEndsWith(expectedProductCode); } /** * @return true if fixed code (e.g. not a variable weight EAN13 etc) */ public boolean isFixed() { final EAN13 ean13 = toEAN13().orElse(null); return ean13 == null || ean13.isFixed(); } /** * @return true if fixed code (e.g. not a variable weight EAN13 etc) */ public boolean isVariable() { final EAN13 ean13 = toEAN13().orElse(null); return ean13 == null || ean13.isVariableWeight(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GTIN.java
1
请完成以下Java代码
private void addCompleteListener(UserTask userTask) { addListenerToUserTask(userTask, TaskListener.EVENTNAME_COMPLETE, new CdiTaskListener(userTask.getId(), BusinessProcessEventType.COMPLETE_TASK)); } private void addAssignListener(UserTask userTask) { addListenerToUserTask(userTask, TaskListener.EVENTNAME_ASSIGNMENT, new CdiTaskListener(userTask.getId(), BusinessProcessEventType.ASSIGN_TASK)); } private void addCreateListener(UserTask userTask) { addListenerToUserTask(userTask, TaskListener.EVENTNAME_CREATE, new CdiTaskListener(userTask.getId(), BusinessProcessEventType.CREATE_TASK)); } protected void addDeleteListener(UserTask userTask) { addListenerToUserTask(userTask, TaskListener.EVENTNAME_DELETE, new CdiTaskListener(userTask.getId(), BusinessProcessEventType.DELETE_TASK)); } protected void addStartEventListener(FlowElement flowElement) { CdiExecutionListener listener = new CdiExecutionListener(flowElement.getId(), BusinessProcessEventType.START_ACTIVITY); addListenerToElement(flowElement, ExecutionListener.EVENTNAME_START, listener); } protected void addEndEventListener(FlowElement flowElement) { CdiExecutionListener listener = new CdiExecutionListener(flowElement.getId(), BusinessProcessEventType.END_ACTIVITY); addListenerToElement(flowElement, ExecutionListener.EVENTNAME_END, listener); } protected void addListenerToElement(FlowElement flowElement, String event, Object instance) {
FlowableListener listener = new FlowableListener(); listener.setEvent(event); listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_INSTANCE); listener.setInstance(instance); flowElement.getExecutionListeners().add(listener); } protected void addListenerToUserTask(UserTask userTask, String event, Object instance) { FlowableListener listener = new FlowableListener(); listener.setEvent(event); listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_INSTANCE); listener.setInstance(instance); userTask.getTaskListeners().add(listener); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\event\CdiEventSupportBpmnParseHandler.java
1
请完成以下Java代码
public void setBatchId(String batchId) { this.batchId = batchId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getSourceProcessDefinitionId() { return sourceProcessDefinitionId; } public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetProcessDefinitionId() { return targetProcessDefinitionId; } public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public List<ProcessInstanceBatchMigrationPartResult> getAllMigrationParts() { return allMigrationParts; } public void addMigrationPart(ProcessInstanceBatchMigrationPartResult migrationPart) { if (allMigrationParts == null) { allMigrationParts = new ArrayList<>(); } allMigrationParts.add(migrationPart); if (!STATUS_COMPLETED.equals(migrationPart.getStatus())) { if (waitingMigrationParts == null) { waitingMigrationParts = new ArrayList<>(); } waitingMigrationParts.add(migrationPart); } else { if (RESULT_SUCCESS.equals(migrationPart.getResult())) { if (succesfulMigrationParts == null) { succesfulMigrationParts = new ArrayList<>();
} succesfulMigrationParts.add(migrationPart); } else { if (failedMigrationParts == null) { failedMigrationParts = new ArrayList<>(); } failedMigrationParts.add(migrationPart); } } } public List<ProcessInstanceBatchMigrationPartResult> getSuccessfulMigrationParts() { return succesfulMigrationParts; } public List<ProcessInstanceBatchMigrationPartResult> getFailedMigrationParts() { return failedMigrationParts; } public List<ProcessInstanceBatchMigrationPartResult> getWaitingMigrationParts() { return waitingMigrationParts; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceBatchMigrationResult.java
1
请完成以下Java代码
public String getCamundaTaskPriority() { return camundaTaskPriorityAttribute.getValue(this); } @Override public void setCamundaTaskPriority(String taskPriority) { camundaTaskPriorityAttribute.setValue(this, taskPriority); } @Override public Integer getCamundaHistoryTimeToLive() { String ttl = getCamundaHistoryTimeToLiveString(); if (ttl != null) { return Integer.parseInt(ttl); } return null; } @Override public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) { var value = historyTimeToLive == null ? null : String.valueOf(historyTimeToLive); setCamundaHistoryTimeToLiveString(value); } @Override public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLiveAttribute.getValue(this); } @Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { if (historyTimeToLive == null) {
camundaHistoryTimeToLiveAttribute.removeAttribute(this); } else { camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive); } } @Override public Boolean isCamundaStartableInTasklist() { return camundaIsStartableInTasklistAttribute.getValue(this); } @Override public void setCamundaIsStartableInTasklist(Boolean isStartableInTasklist) { camundaIsStartableInTasklistAttribute.setValue(this, isStartableInTasklist); } @Override public String getCamundaVersionTag() { return camundaVersionTagAttribute.getValue(this); } @Override public void setCamundaVersionTag(String versionTag) { camundaVersionTagAttribute.setValue(this, versionTag); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ProcessImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; }
public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryResponse.java
2
请完成以下Java代码
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 org.compiere.model.I_M_InOutLine getRef_InOutLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getRef_InOutLine_ID(), get_TrxName()); } /** Set Referenced Shipment Line. @param Ref_InOutLine_ID Referenced Shipment Line */ public void setRef_InOutLine_ID (int Ref_InOutLine_ID) { if (Ref_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_Ref_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_Ref_InOutLine_ID, Integer.valueOf(Ref_InOutLine_ID)); } /** Get Referenced Shipment Line. @return Referenced Shipment Line */ public int getRef_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InOutLine getReversalLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getReversalLine_ID(), get_TrxName()); } /** Set Reversal Line. @param ReversalLine_ID Use to keep the reversal line ID for reversing costing purpose */ public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, null); else set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Reversal Line. @return Use to keep the reversal line ID for reversing costing purpose */ public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verworfene Menge. @param ScrappedQty Durch QA verworfene Menge */ public void setScrappedQty (BigDecimal ScrappedQty) { set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Verworfene Menge. @return Durch QA verworfene Menge */
public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Zielmenge. @param TargetQty Zielmenge der Warenbewegung */ public void setTargetQty (BigDecimal TargetQty) { set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Zielmenge der Warenbewegung */ public BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java
1
请在Spring Boot框架中完成以下Java代码
private static void updateHUAttributes( @NonNull final IAttributeStorage huAttributes, @NonNull final HUAttributesUpdateRequest from) { huAttributes.setValue(AttributeConstants.ATTR_SecurPharmScannedStatus, from.getStatus().getCode()); if (!from.isSkipUpdatingBestBeforeDate()) { final JsonExpirationDate bestBeforeDate = from.getBestBeforeDate(); huAttributes.setValue(AttributeConstants.ATTR_BestBeforeDate, bestBeforeDate != null ? bestBeforeDate.toLocalDate() : null); } if (!from.isSkipUpdatingLotNo()) { huAttributes.setValue(AttributeConstants.ATTR_LotNumber, from.getLotNo()); } if (!from.isSkipUpdatingSerialNo()) { huAttributes.setValue(AttributeConstants.ATTR_SerialNo, from.getSerialNo()); } } @Value @Builder
private static class HUAttributesUpdateRequest { public static final HUAttributesUpdateRequest ERROR = builder() .status(SecurPharmAttributesStatus.ERROR) // UPDATE just the status field, skip the others .skipUpdatingBestBeforeDate(true) .skipUpdatingLotNo(true) .skipUpdatingSerialNo(true) .build(); @NonNull SecurPharmAttributesStatus status; boolean skipUpdatingBestBeforeDate; @Nullable JsonExpirationDate bestBeforeDate; boolean skipUpdatingLotNo; @Nullable String lotNo; boolean skipUpdatingSerialNo; String serialNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\service\SecurPharmHUAttributesScanner.java
2
请完成以下Java代码
public int lastIndexOf(String m) { String text = this.value; if (text == null || m == null || text.length() < m.length()) { return -1; } return text.toLowerCase().lastIndexOf(m.toLowerCase()); } /** * 是否包含, 大小写不敏感 * <pre * "abcxyz" 包含 "abc" => true * "abcxyz" 包含 "ABC" => true * "abcxyz" 包含 "aBC" => true * </pre> * * @param m 被包含字符串 */ public boolean contains(String m) { String text = this.value; if (text.length() < m.length()) { return false; } return text.toLowerCase().contains(m.toLowerCase()); } /** * 任意一个包含返回true * <pre> * containsAny("abcdef", "a", "b) * 等价 * "abcdef".contains("a") || "abcdef".contains("b") * </pre> * * @param matchers 多个要判断的被包含项 */ public boolean containsAny(String... matchers) { for (String matcher : matchers) { if (contains(matcher)) { return true; } } return false; } /** * 所有都包含才返回true * * @param matchers 多个要判断的被包含项 */ public boolean containsAllIgnoreCase(String... matchers) { for (String matcher : matchers) { if (contains(matcher) == false) { return false; } } return true; } public NonCaseString trim() { return NonCaseString.of(this.value.trim()); } public NonCaseString replace(char oldChar, char newChar) { return NonCaseString.of(this.value.replace(oldChar, newChar)); } public NonCaseString replaceAll(String regex, String replacement) { return NonCaseString.of(this.value.replaceAll(regex, replacement)); } public NonCaseString substring(int beginIndex) { return NonCaseString.of(this.value.substring(beginIndex)); } public NonCaseString substring(int beginIndex, int endIndex) {
return NonCaseString.of(this.value.substring(beginIndex, endIndex)); } public boolean isNotEmpty() { return !this.value.isEmpty(); } @Override public int length() { return this.value.length(); } @Override public char charAt(int index) { return this.value.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.value.subSequence(start, end); } public String[] split(String regex) { return this.value.split(regex); } /** * @return 原始字符串 */ public String get() { return this.value; } @Override public String toString() { return this.value; } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java
1
请完成以下Java代码
public BatchQuery active() { this.suspensionState = SuspensionState.ACTIVE; return this; } public BatchQuery suspended() { this.suspensionState = SuspensionState.SUSPENDED; return this; } public SuspensionState getSuspensionState() { return suspensionState; } public BatchQuery orderById() { return orderBy(BatchQueryProperty.ID); }
@Override public BatchQuery orderByTenantId() { return orderBy(BatchQueryProperty.TENANT_ID); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getBatchManager() .findBatchCountByQueryCriteria(this); } public List<Batch> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getBatchManager() .findBatchesByQueryCriteria(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeliveryOrTransportTermsCode() { return deliveryOrTransportTermsCode; } /** * Sets the value of the deliveryOrTransportTermsCode property. * * @param value * allowed object is * {@link String } * */ public void setDeliveryOrTransportTermsCode(String value) { this.deliveryOrTransportTermsCode = value; } /** * Gets the value of the incotermCode property. * * @return * possible object is * {@link String } * */ public String getIncotermCode() { return incotermCode; } /** * Sets the value of the incotermCode property. * * @param value * allowed object is * {@link String } * */ public void setIncotermCode(String value) { this.incotermCode = value; } /** * Gets the value of the incotermText property. * * @return * possible object is * {@link String } * */ public String getIncotermText() { return incotermText; } /** * Sets the value of the incotermText property. * * @param value * allowed object is * {@link String } * */ public void setIncotermText(String value) {
this.incotermText = value; } /** * Gets the value of the incotermLocation property. * * @return * possible object is * {@link String } * */ public String getIncotermLocation() { return incotermLocation; } /** * Sets the value of the incotermLocation property. * * @param value * allowed object is * {@link String } * */ public void setIncotermLocation(String value) { this.incotermLocation = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\IncotermType.java
2
请完成以下Java代码
private List<Fact> createFacts_Variance( final AcctSchema as, final ProductAcctType varianceAcctType) { final DocLine_CostCollector docLine = getLine(); final AggregatedCostAmount costResult = docLine.getCreateCosts(as).orElse(null); if(costResult == null) { // NOTE: there is no need to fail if no cost details were created // because it might be that there are no cost elements defined for resource, which is acceptable return ImmutableList.of(); } final Account debit = docLine.getAccount(varianceAcctType, as); final Account credit = docLine.getAccount(ProductAcctType.P_WIP_Acct, as); final Quantity qty = getMovementQty(); final ArrayList<Fact> facts = new ArrayList<>(); for (final CostElement element : costResult.getCostElements()) { if (!element.isAccountable(as.getCosting()))
{ continue; } final CostAmount costs = costResult.getCostAmountForCostElement(element).getMainAmt(); final Fact fact = createFactLines(as, element, debit, credit, costs.negate(), qty.negate()); if (fact != null) { facts.add(fact); } } return facts; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\acct\Doc_PPCostCollector.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult<UserVO> get4(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return CommonResult.success(user); } /** * 测试抛出 NullPointerException 异常 */ @GetMapping("/exception-01") public UserVO exception01() { throw new NullPointerException("没有粗面鱼丸"); } /** * 测试抛出 ServiceException 异常 */ @GetMapping("/exception-02") public UserVO exception02() { throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND); }
// @PostMapping(value = "/add", // // ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头 // consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, // // ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头 // produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} // ) @PostMapping(value = "/add", // ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头 consumes = {MediaType.APPLICATION_XML_VALUE}, // ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头 produces = {MediaType.APPLICATION_XML_VALUE} ) // @PostMapping(value = "/add") public Mono<UserVO> add(@RequestBody Mono<UserVO> user) { return user; } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请完成以下Java代码
public Expression getCategoryExpression() { return categoryExpression; } public void setCategoryExpression(Expression categoryExpression) { this.categoryExpression = categoryExpression; } public Map<String, List<TaskListener>> getTaskListeners() { return taskListeners; } public void setTaskListeners(Map<String, List<TaskListener>> taskListeners) { this.taskListeners = taskListeners; } public List<TaskListener> getTaskListener(String eventName) { return taskListeners.get(eventName); } public void addTaskListener(String eventName, TaskListener taskListener) { if (TaskListener.EVENTNAME_ALL_EVENTS.equals(eventName)) { // In order to prevent having to merge the "all" tasklisteners with the ones for a specific eventName, // every time "getTaskListener()" is called, we add the listener explicitly to the individual lists
this.addTaskListener(TaskListener.EVENTNAME_CREATE, taskListener); this.addTaskListener(TaskListener.EVENTNAME_ASSIGNMENT, taskListener); this.addTaskListener(TaskListener.EVENTNAME_COMPLETE, taskListener); this.addTaskListener(TaskListener.EVENTNAME_DELETE, taskListener); } else { List<TaskListener> taskEventListeners = taskListeners.get(eventName); if (taskEventListeners == null) { taskEventListeners = new ArrayList<>(); taskListeners.put(eventName, taskEventListeners); } taskEventListeners.add(taskListener); } } public Expression getSkipExpression() { return skipExpression; } public void setSkipExpression(Expression skipExpression) { this.skipExpression = skipExpression; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\task\TaskDefinition.java
1
请完成以下Java代码
protected void executeExecutionListenersBeforeAll(CommandContext commandContext) { if (agendaOperationExecutionListeners != null && !agendaOperationExecutionListeners.isEmpty()) { for (AgendaOperationExecutionListener listener : agendaOperationExecutionListeners) { listener.beforeAll(commandContext); } } } protected void executeExecutionListenersAfterAll(CommandContext commandContext) { if (agendaOperationExecutionListeners != null && !agendaOperationExecutionListeners.isEmpty()) { for (AgendaOperationExecutionListener listener : agendaOperationExecutionListeners) { listener.afterAll(commandContext); } } } protected void executeExecutionListenersBeforeExecute(CommandContext commandContext, Runnable runnable) { if (agendaOperationExecutionListeners != null && !agendaOperationExecutionListeners.isEmpty()) { for (AgendaOperationExecutionListener listener : agendaOperationExecutionListeners) { listener.beforeExecute(commandContext, runnable); } } } protected void executeExecutionListenersAfterExecute(CommandContext commandContext, Runnable runnable) { if (agendaOperationExecutionListeners != null && !agendaOperationExecutionListeners.isEmpty()) {
for (AgendaOperationExecutionListener listener : agendaOperationExecutionListeners) { listener.afterExecute(commandContext, runnable); } } } protected void executeExecutionListenersAfterException(CommandContext commandContext, Runnable runnable, Throwable throwable) { if (agendaOperationExecutionListeners != null && !agendaOperationExecutionListeners.isEmpty()) { for (AgendaOperationExecutionListener listener : agendaOperationExecutionListeners) { listener.afterExecuteException(commandContext, runnable, throwable); } } } protected void executeOperation(CommandContext commandContext, Runnable runnable) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Executing agenda operation {}", runnable); } runnable.run(); } @Override public void setNext(CommandInterceptor next) { throw new UnsupportedOperationException("CommandInvoker must be the last interceptor in the chain"); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\interceptor\DmnCommandInvoker.java
1
请完成以下Java代码
protected void prepare() { // nothing } @Override protected String doIt() { final I_M_Forecast forecast = getM_Forecast(); ddOrderLowLevelService.completeBackwardDDOrders(forecast); return MSG_OK; } private I_M_Forecast getM_Forecast() { if (p_forecast != null) { return p_forecast;
} if (I_M_Forecast.Table_Name.equals(getTableName()) && getRecord_ID() > 0) { p_forecast = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_Forecast.class, get_TrxName()); } if (p_forecast == null || p_forecast.getM_Forecast_ID() <= 0) { throw new FillMandatoryException(I_M_Forecast.COLUMNNAME_M_Forecast_ID); } return p_forecast; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\M_Forecast_CompleteBackwardDDOrders.java
1
请完成以下Java代码
public String getJsonField() { return jsonField; } public void setJsonField(String jsonField) { this.jsonField = jsonField; } public String getJsonPointerExpression() { return jsonPointerExpression; } public void setJsonPointerExpression(String jsonPointerExpression) { this.jsonPointerExpression = jsonPointerExpression; } public String getXmlXPathExpression() {
return xmlXPathExpression; } public void setXmlXPathExpression(String xmlXPathExpression) { this.xmlXPathExpression = xmlXPathExpression; } public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\ChannelEventKeyDetection.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaCrossJoins\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public int getRed_1 () { Integer ii = (Integer)get_Value(COLUMNNAME_Red_1); if (ii == null) return 0; return ii.intValue(); } /** Set Repeat Distance. @param RepeatDistance Distance in points to repeat gradient color - or zero */ public void setRepeatDistance (int RepeatDistance) { set_Value (COLUMNNAME_RepeatDistance, Integer.valueOf(RepeatDistance)); } /** Get Repeat Distance. @return Distance in points to repeat gradient color - or zero */ public int getRepeatDistance () { Integer ii = (Integer)get_Value(COLUMNNAME_RepeatDistance); if (ii == null) return 0; return ii.intValue(); } /** StartPoint AD_Reference_ID=248 */ public static final int STARTPOINT_AD_Reference_ID=248; /** North = 1 */ public static final String STARTPOINT_North = "1"; /** North East = 2 */ public static final String STARTPOINT_NorthEast = "2"; /** East = 3 */ public static final String STARTPOINT_East = "3";
/** South East = 4 */ public static final String STARTPOINT_SouthEast = "4"; /** South = 5 */ public static final String STARTPOINT_South = "5"; /** South West = 6 */ public static final String STARTPOINT_SouthWest = "6"; /** West = 7 */ public static final String STARTPOINT_West = "7"; /** North West = 8 */ public static final String STARTPOINT_NorthWest = "8"; /** Set Start Point. @param StartPoint Start point of the gradient colors */ public void setStartPoint (String StartPoint) { set_Value (COLUMNNAME_StartPoint, StartPoint); } /** Get Start Point. @return Start point of the gradient colors */ public String getStartPoint () { return (String)get_Value(COLUMNNAME_StartPoint); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Color.java
1
请完成以下Java代码
public void setM_PackagingContainer_ID (int M_PackagingContainer_ID) { if (M_PackagingContainer_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PackagingContainer_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PackagingContainer_ID, Integer.valueOf(M_PackagingContainer_ID)); } /** Get Verpackung. @return Verpackung */ public int getM_PackagingContainer_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingContainer_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ 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 Suchschluessel. @param Value Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschluessel. @return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Breite. @param Width Breite */ public void setWidth (BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } /** Get Breite. @return Breite */ public BigDecimal getWidth () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Width); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_PackagingContainer.java
1
请完成以下Java代码
public void reportEdqsCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("edqsCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportStringCompressed() { getCounter("stringsCompressed").increment(); } @Override public void reportStringUncompressed() { getCounter("stringsUncompressed").increment(); } private void checkTiming(TenantId tenantId, EntityCountQuery query, long timingNanos) { double timingMs = timingNanos / 1000_000.0; String queryType = query instanceof EntityDataQuery ? "data" : "count"; if (timingMs < slowQueryThreshold) { log.debug("[{}] Executed " + queryType + " query in {} ms: {}", tenantId, timingMs, query); } else { log.warn("[{}] Executed slow " + queryType + " query in {} ms: {}", tenantId, timingMs, query); }
} private StatsTimer getTimer(String name) { return timers.computeIfAbsent(name, __ -> statsFactory.createStatsTimer("edqsTimers", name)); } private StatsCounter getCounter(String name) { return counters.computeIfAbsent(name, __ -> statsFactory.createStatsCounter("edqsCounters", name)); } private AtomicInteger getObjectGauge(ObjectType objectType) { return objectCounters.computeIfAbsent(objectType, type -> statsFactory.createGauge("edqsGauges", "objectsCount", new AtomicInteger(), "objectType", type.name())); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\stats\DefaultEdqsStatsService.java
1
请完成以下Java代码
public List<String> getBigramTempls_() { return bigramTempls_; } public void setBigramTempls_(List<String> bigramTempls_) { this.bigramTempls_ = bigramTempls_; } public List<String> getY_() { return y_; } public void setY_(List<String> y_) { this.y_ = y_; }
public List<List<Path>> getPathList_() { return pathList_; } public void setPathList_(List<List<Path>> pathList_) { this.pathList_ = pathList_; } public List<List<Node>> getNodeList_() { return nodeList_; } public void setNodeList_(List<List<Node>> nodeList_) { this.nodeList_ = nodeList_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
1
请完成以下Java代码
public class UmsMemberLoginLog implements Serializable { private Long id; private Long memberId; private Date createTime; private String ip; private String city; @ApiModelProperty(value = "登录类型:0->PC;1->android;2->ios;3->小程序") private Integer loginType; private String province; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Integer getLoginType() { return loginType; } public void setLoginType(Integer loginType) { this.loginType = loginType;
} public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } @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(", memberId=").append(memberId); sb.append(", createTime=").append(createTime); sb.append(", ip=").append(ip); sb.append(", city=").append(city); sb.append(", loginType=").append(loginType); sb.append(", province=").append(province); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLoginLog.java
1
请完成以下Java代码
public void setMessageConverter(MessageConverter messageConverter) { Assert.notNull(messageConverter, "'messageConverter' cannot be null"); this.messageConverter = messageConverter; } /** * Set a {@link KafkaHeaderMapper}. * @param headerMapper the header mapper to use for mapping headers of incoming {@link ConsumerRecord}. * @since 3.0 */ public void setKafkaHeaderMapper(KafkaHeaderMapper headerMapper) { Assert.notNull(headerMapper, "'headerMapper' cannot be null"); this.headerMapper = headerMapper; } @Override public MessageListener getDelegate() { return this.delegate; } @Override @SuppressWarnings("unchecked") public void onMessage(ConsumerRecord receivedRecord, @Nullable Acknowledgment acknowledgment, @Nullable Consumer consumer) { ConsumerRecord convertedConsumerRecord = convertConsumerRecord(receivedRecord); if (this.delegate instanceof AcknowledgingConsumerAwareMessageListener) { this.delegate.onMessage(convertedConsumerRecord, acknowledgment, consumer); } else if (this.delegate instanceof ConsumerAwareMessageListener) { this.delegate.onMessage(convertedConsumerRecord, consumer); } else if (this.delegate instanceof AcknowledgingMessageListener) { this.delegate.onMessage(convertedConsumerRecord, acknowledgment); } else { this.delegate.onMessage(convertedConsumerRecord); } }
private ConsumerRecord convertConsumerRecord(ConsumerRecord receivedRecord) { Map<String, Object> headerMap = new HashMap<>(); if (this.headerMapper != null) { this.headerMapper.toHeaders(receivedRecord.headers(), headerMap); } Message message = new GenericMessage<>(receivedRecord.value(), headerMap); Object convertedPayload = this.messageConverter.fromMessage(message, this.desiredValueType); if (convertedPayload == null) { throw new MessageConversionException(message, "Message cannot be converted by used MessageConverter"); } return rebuildConsumerRecord(receivedRecord, convertedPayload); } @SuppressWarnings("unchecked") private static ConsumerRecord rebuildConsumerRecord(ConsumerRecord receivedRecord, Object convertedPayload) { return new ConsumerRecord( receivedRecord.topic(), receivedRecord.partition(), receivedRecord.offset(), receivedRecord.timestamp(), receivedRecord.timestampType(), receivedRecord.serializedKeySize(), receivedRecord.serializedValueSize(), receivedRecord.key(), convertedPayload, receivedRecord.headers(), receivedRecord.leaderEpoch() ); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\ConvertingMessageListener.java
1
请完成以下Java代码
public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } /** * Return the value for the 'autoStartup' property. If "true", this * component will start upon a ContextRefreshedEvent. */ @Override public boolean isAutoStartup() { return this.autoStartup; } /** * Specify the phase in which this component should be started * and stopped. The startup order proceeds from lowest to highest, and * the shutdown order is the reverse of that. By default this value is * Integer.MAX_VALUE meaning that this component starts as late * as possible and stops as soon as possible. */ public void setPhase(int phase) { this.phase = phase; } /** * Return the phase in which this component will be started and stopped. */ @Override public int getPhase() { return this.phase; } @Override public void start() { synchronized (this.lifeCycleMonitor) { if (!this.running) { logger.info("Starting..."); doStart(); this.running = true; logger.info("Started.");
} } } @Override public void stop() { synchronized (this.lifeCycleMonitor) { if (this.running) { logger.info("Stopping..."); doStop(); this.running = false; logger.info("Stopped."); } } } @Override public void stop(Runnable callback) { synchronized (this.lifeCycleMonitor) { stop(); callback.run(); } } @Override public boolean isRunning() { return this.running; } @Override public void destroy() { stop(); } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\AbstractActivitiSmartLifeCycle.java
1
请在Spring Boot框架中完成以下Java代码
public class DeviceConfigException extends AdempiereException { public static DeviceConfigException permanentFailure(final String msg, final Throwable cause) { final boolean permanentFailure = true; return new DeviceConfigException(msg, cause, permanentFailure); } public static DeviceConfigException wrapIfNeeded(final Throwable throwable) { if (throwable == null) { return null; } final Throwable cause = extractCause(throwable); if (cause instanceof DeviceConfigException) { return (DeviceConfigException)cause; } else
{ final String msg = extractMessage(cause); final boolean permanentFailure = false; return new DeviceConfigException(msg, cause, permanentFailure); } } private final boolean permanentFailure; public DeviceConfigException(final String msg) { super(msg); permanentFailure = false; } private DeviceConfigException(final String msg, final Throwable cause, final boolean permanentFailure) { super(msg, cause); this.permanentFailure = permanentFailure; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfigException.java
2
请完成以下Java代码
public static void addAvailableBeamElements(ArrayList<BeamElement> elements, float prevScore, boolean canShift, boolean canReduce, boolean canRightArc, boolean canLeftArc, Object[] features, AveragedPerceptron classifier, boolean isDecode, int b, ArrayList<Integer> dependencyRelations) { if (canShift) { float score = classifier.shiftScore(features, isDecode); float addedScore = score + prevScore; elements.add(new BeamElement(addedScore, b, 0, -1)); } if (canReduce) { float score = classifier.reduceScore(features, isDecode); float addedScore = score + prevScore; elements.add(new BeamElement(addedScore, b, 1, -1)); } if (canRightArc) { float[] rightArcScores = classifier.rightArcScores(features, isDecode); for (int dependency : dependencyRelations) {
float score = rightArcScores[dependency]; float addedScore = score + prevScore; elements.add(new BeamElement(addedScore, b, 2, dependency)); } } if (canLeftArc) { float[] leftArcScores = classifier.leftArcScores(features, isDecode); for (int dependency : dependencyRelations) { float score = leftArcScores[dependency]; float addedScore = score + prevScore; elements.add(new BeamElement(addedScore, b, 3, dependency)); } } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\parser\PartialTreeBeamScorerThread.java
1
请完成以下Java代码
protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { final IWeightable weightable = getWeightableOrNull(attributeSet); if (weightable == null) { return false; } final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue()); if (!weightable.isWeightGrossAttribute(attributeCode)) { return false; } if (!weightable.hasWeightGross()) { return false; } if (!weightable.hasWeightTare()) { return false;
} if (!(attributeValueContext instanceof IHUAttributePropagationContext)) { return false; } final IHUAttributePropagationContext huAttributePropagationContext = (IHUAttributePropagationContext)attributeValueContext; final AttributeCode attr_WeightNet = weightable.getWeightNetAttribute(); if (huAttributePropagationContext.isExternalInput() && huAttributePropagationContext.isValueUpdatedBefore(attr_WeightNet)) { // // Net weight was set externally. Do not modify it. return false; } return true; } @Override public boolean isDisplayedUI(@NonNull final IAttributeSet attributeSet, @NonNull final I_M_Attribute attribute) { return isLUorTUorTopLevelVHU(attributeSet); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightGrossAttributeValueCallout.java
1
请完成以下Java代码
public void validateRemittanceAdviceLineInvoiceDocType(@NonNull final I_C_RemittanceAdvice_Line record) { final RemittanceAdviceLine remittanceAdviceLine = getLineOrFail(record); if (remittanceAdviceLine.getInvoiceId() != null) { final I_C_Invoice lineResolvedInvoice = invoiceDAO.getByIdInTrx(remittanceAdviceLine.getInvoiceId()); final I_C_DocType invoiceDocType = docTypeDAO.getById(lineResolvedInvoice.getC_DocTypeTarget_ID()); remittanceAdviceLine.validateInvoiceDocBaseType(InvoiceDocBaseType.ofCode(invoiceDocType.getDocBaseType())); remittanceAdviceRepo.updateRemittanceAdviceLine(remittanceAdviceLine); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_NEW }, ifColumnsChanged = { I_C_RemittanceAdvice_Line.COLUMNNAME_IsLineAcknowledged, I_C_RemittanceAdvice_Line.COLUMNNAME_IsInvoiceResolved, I_C_RemittanceAdvice_Line.COLUMNNAME_IsAmountValid}) public void recomputeIsDocumentAcknowledged(@NonNull final I_C_RemittanceAdvice_Line record) { final RemittanceAdviceId remittanceAdviceId = RemittanceAdviceId.ofRepoId(record.getC_RemittanceAdvice_ID()); final RemittanceAdvice remittanceAdvice = remittanceAdviceRepo.getRemittanceAdvice(remittanceAdviceId); final boolean hasAcknowledgedStatusChanged = remittanceAdvice.recomputeIsDocumentAcknowledged(); if (hasAcknowledgedStatusChanged) { remittanceAdviceRepo.updateRemittanceAdvice(remittanceAdvice); } }
@ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }) public void recomputeReadOnlyCurrenciesFlagOnDelete(@NonNull final I_C_RemittanceAdvice_Line record) { final RemittanceAdviceId remittanceAdviceId = RemittanceAdviceId.ofRepoId(record.getC_RemittanceAdvice_ID()); final RemittanceAdvice remittanceAdvice = remittanceAdviceRepo.getRemittanceAdvice(remittanceAdviceId); final boolean readOnlyCurrenciesFlagChanged = remittanceAdvice.recomputeCurrenciesReadOnlyFlag(); if (readOnlyCurrenciesFlagChanged) { remittanceAdviceRepo.updateRemittanceAdvice(remittanceAdvice); } } @NonNull private RemittanceAdviceLine getLineOrFail(@NonNull final I_C_RemittanceAdvice_Line record) { final RemittanceAdviceId remittanceAdviceId = RemittanceAdviceId.ofRepoId(record.getC_RemittanceAdvice_ID()); final RemittanceAdvice remittanceAdvice = remittanceAdviceRepo.getRemittanceAdvice(remittanceAdviceId); final RemittanceAdviceLineId remittanceAdviceLineId = RemittanceAdviceLineId.ofRepoId(record.getC_RemittanceAdvice_Line_ID()); return remittanceAdvice.getLine(remittanceAdviceLineId) .orElseThrow(() -> new AdempiereException("No line found under RemittanceAdviceId: {} with lineId: {}") .appendParametersToMessage() .setParameter("RemittanceAdviceId", remittanceAdviceId) .setParameter("RemittanceAdviceLineId", remittanceAdviceLineId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\interceptor\C_RemittanceAdvice_Line.java
1
请完成以下Java代码
public void setOrg(final OrgId orgId, final String orgName) { setProperty(Env.CTXNAME_AD_Org_ID, OrgId.toRepoId(orgId)); setProperty(Env.CTXNAME_AD_Org_Name, orgName); Ini.setProperty(Ini.P_ORG, orgName); } public void setUserOrgs(final String userOrgs) { setProperty(Env.CTXNAME_User_Org, userOrgs); } public OrgId getOrgId() { return OrgId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Org_ID)); } public void setWarehouse(final WarehouseId warehouseId, final String warehouseName) { setProperty(Env.CTXNAME_M_Warehouse_ID, WarehouseId.toRepoId(warehouseId)); Ini.setProperty(Ini.P_WAREHOUSE, warehouseName); } @Nullable public WarehouseId getWarehouseId() { return WarehouseId.ofRepoIdOrNull(getPropertyAsInt(Env.CTXNAME_M_Warehouse_ID)); } public void setPrinterName(final String printerName)
{ setProperty(Env.CTXNAME_Printer, printerName == null ? "" : printerName); Ini.setProperty(Ini.P_PRINTER, printerName); } public void setAcctSchema(final AcctSchema acctSchema) { setProperty("$C_AcctSchema_ID", acctSchema.getId().getRepoId()); setProperty("$C_Currency_ID", acctSchema.getCurrencyId().getRepoId()); setProperty("$HasAlias", acctSchema.getValidCombinationOptions().isUseAccountAlias()); } @Nullable public AcctSchemaId getAcctSchemaId() { return AcctSchemaId.ofRepoIdOrNull(getPropertyAsInt("$C_AcctSchema_ID")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\LoginContext.java
1
请在Spring Boot框架中完成以下Java代码
private UserEntity getUserEntity(String sessionID) { // SessionID为空 if (StringUtils.isEmpty(sessionID)) { return null; } // 获取UserEntity // TODO 暂时存储本地 // Object userEntity = redisService.get(sessionID); Object userEntity = RedisServiceTemp.userMap.get(sessionID); if (userEntity==null) { return null; } return (UserEntity) userEntity; }
/** * 获取用户ID * @param httpReq HTTP请求 * @return 用户ID */ private String getUserId(HttpServletRequest httpReq) { UserEntity userEntity = userUtil.getUser(httpReq); if (userEntity == null) { throw new CommonBizException(ExpCodeEnum.UNLOGIN); } return userEntity.getId(); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\user\UserControllerImpl.java
2
请完成以下Java代码
public class CaseInstanceMigrationBatchCmd implements Command<Batch> { protected CmmnEngineConfiguration cmmnEngineConfiguration; protected String caseDefinitionId; protected String caseDefinitionKey; protected int caseDefinitionVersion; protected String caseDefinitionTenantId; protected CaseInstanceMigrationDocument caseInstanceMigrationDocument; public CaseInstanceMigrationBatchCmd(CaseInstanceMigrationDocument caseInstanceMigrationDocument, String caseDefinitionId, CmmnEngineConfiguration cmmnEngineConfiguration) { if (caseDefinitionId == null) { throw new FlowableException("Must specify a case definition id to migrate"); } if (caseInstanceMigrationDocument == null) { throw new FlowableException("Must specify a case instance migration document to migrate"); } this.caseDefinitionId = caseDefinitionId; this.caseInstanceMigrationDocument = caseInstanceMigrationDocument; this.cmmnEngineConfiguration = cmmnEngineConfiguration; } public CaseInstanceMigrationBatchCmd(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId, CaseInstanceMigrationDocument caseInstanceMigrationDocument, CmmnEngineConfiguration cmmnEngineConfiguration) { if (caseDefinitionKey == null) { throw new FlowableException("Must specify a case definition id to migrate"); } if (caseDefinitionTenantId == null) { throw new FlowableException("Must specify a case definition tenant id to migrate"); } if (caseInstanceMigrationDocument == null) { throw new FlowableException("Must specify a case instance migration document to migrate"); } this.caseDefinitionKey = caseDefinitionKey; this.caseDefinitionVersion = caseDefinitionVersion;
this.caseDefinitionTenantId = caseDefinitionTenantId; this.caseInstanceMigrationDocument = caseInstanceMigrationDocument; this.cmmnEngineConfiguration = cmmnEngineConfiguration; } @Override public Batch execute(CommandContext commandContext) { CaseInstanceMigrationManager migrationManager = cmmnEngineConfiguration.getCaseInstanceMigrationManager(); if (caseDefinitionId != null) { return migrationManager.batchMigrateCaseInstancesOfCaseDefinition(caseDefinitionId, caseInstanceMigrationDocument, commandContext); } else if (caseDefinitionKey != null && caseDefinitionVersion >= 0) { return migrationManager.batchMigrateCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, caseInstanceMigrationDocument, commandContext); } else { throw new FlowableException("Cannot migrate case(es), not enough information"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\CaseInstanceMigrationBatchCmd.java
1
请完成以下Java代码
public String getProcessMsg() { return null; } @Override public String getSummary() { return getDocumentNo() + "/" + getDatePromised(); } @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateOrdered()); } @Override public File createPDF() { final DocumentReportService documentReportService = SpringContextHolder.instance.getBean(DocumentReportService.class); final ReportResultData report = documentReportService.createStandardDocumentReportData(getCtx(), StandardDocumentReportType.MANUFACTURING_ORDER, getPP_Order_ID()); return report.writeToTemporaryFile(get_TableName() + get_ID()); } @Override public String getDocumentInfo() { final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); final DocTypeId docTypeId = DocTypeId.ofRepoId(getC_DocType_ID()); final ITranslatableString docTypeName = docTypeBL.getNameById(docTypeId); return docTypeName.translate(Env.getADLanguageOrBaseLanguage()) + " " + getDocumentNo(); } private PPOrderRouting getOrderRouting() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return Services.get(IPPOrderRoutingRepository.class).getByOrderId(orderId); } @Override public String toString() { return "MPPOrder[ID=" + get_ID() + "-DocumentNo=" + getDocumentNo() + ",IsSOTrx=" + isSOTrx()
+ ",C_DocType_ID=" + getC_DocType_ID() + "]"; } /** * Auto report the first Activity and Sub contracting if are Milestone Activity */ private void autoReportActivities() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { if (activity.isMilestone() && (activity.isSubcontracting() || orderRouting.isFirstActivity(activity))) { ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder() .order(this) .orderActivity(activity) .qtyMoved(activity.getQtyToDeliver()) .durationSetup(Duration.ZERO) .duration(Duration.ZERO) .build()); } } } private void createVariances() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); // for (final I_PP_Order_BOMLine bomLine : getLines()) { ppCostCollectorBL.createMaterialUsageVariance(this, bomLine); } // final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { ppCostCollectorBL.createResourceUsageVariance(this, activity); } } } // MPPOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java
1
请完成以下Java代码
private void initUI() { MiniTable table = new MiniTable(); table.setRowSelectionAllowed(false); relatedTbl = table; } private void init() { ColumnInfo[] s_layoutRelated = new ColumnInfo[] { new ColumnInfo(Msg.translate(Env.getCtx(), "Warehouse"), "orgname", String.class), new ColumnInfo( Msg.translate(Env.getCtx(), "Value"), "(Select Value from M_Product p where p.M_Product_ID=M_PRODUCT_SUBSTITUTERELATED_V.Substitute_ID)", String.class), new ColumnInfo(Msg.translate(Env.getCtx(), "Name"), "Name", String.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyAvailable"), "QtyAvailable", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyOnHand"), "QtyOnHand", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyReserved"), "QtyReserved", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "PriceStd"), "PriceStd", Double.class) }; String s_sqlFrom = "M_PRODUCT_SUBSTITUTERELATED_V"; String s_sqlWhere = "M_Product_ID = ? AND M_PriceList_Version_ID = ? and RowType = 'R'"; m_sqlRelated = relatedTbl.prepareTable(s_layoutRelated, s_sqlFrom, s_sqlWhere, false, "M_PRODUCT_SUBSTITUTERELATED_V"); relatedTbl.setMultiSelection(false); // relatedTbl.addMouseListener(this); // relatedTbl.getSelectionModel().addListSelectionListener(this); relatedTbl.autoSize(); } private void refresh(int M_Product_ID, int M_PriceList_Version_ID) { String sql = m_sqlRelated; log.trace(sql); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, M_Product_ID);
pstmt.setInt(2, M_PriceList_Version_ID); rs = pstmt.executeQuery(); relatedTbl.loadTable(rs); rs.close(); } catch (Exception e) { log.warn(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } public java.awt.Component getComponent() { return (java.awt.Component)relatedTbl; } @Override public void refresh(int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID) { refresh( M_Product_ID, M_PriceList_Version_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductRelated.java
1
请完成以下Java代码
public void calculate(final IPricingContext pricingCtx, final IPricingResult result) { final ZonedDateTime date = extractPriceDate(pricingCtx); final HashSet<PriceListVersionId> seenPriceListVersionIds = new HashSet<>(); PriceListVersionId currentPriceListVersionId = getPriceListVersionIdEffective(pricingCtx, date); do { if (currentPriceListVersionId != null && !seenPriceListVersionIds.add(currentPriceListVersionId)) { // loop detected, we already tried to compute using that price list version break; } final IEditablePricingContext pricingCtxEffective = pricingCtx.copy(); pricingCtxEffective.setPriceListVersionId(currentPriceListVersionId); includedPricingRules.calculate(pricingCtxEffective, result); if (result.isCalculated()) { return; } currentPriceListVersionId = getBasePriceListVersionId(currentPriceListVersionId, date); } while (currentPriceListVersionId != null); } @Nullable private PriceListVersionId getPriceListVersionIdEffective(final IPricingContext pricingCtx, @NonNull final ZonedDateTime date) { final I_M_PriceList_Version contextPLV = pricingCtx.getM_PriceList_Version(); if (contextPLV != null) { return contextPLV.isActive() ? PriceListVersionId.ofRepoId(contextPLV.getM_PriceList_Version_ID()) : null; } final I_M_PriceList_Version plv = priceListDAO.retrievePriceListVersionOrNull( pricingCtx.getPriceListId(), date, null // processed ); return plv != null && plv.isActive() ? PriceListVersionId.ofRepoId(plv.getM_PriceList_Version_ID()) : null; }
@Nullable private PriceListVersionId getBasePriceListVersionId(@Nullable final PriceListVersionId priceListVersionId, @NonNull final ZonedDateTime date) { if (priceListVersionId == null) { return null; } return priceListDAO.getBasePriceListVersionIdForPricingCalculationOrNull(priceListVersionId, date); } @NonNull private static ZonedDateTime extractPriceDate(@NonNull final IPricingContext pricingCtx) { return pricingCtx.getPriceDate().atStartOfDay(SystemTime.zoneId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\PriceListVersionPricingRule.java
1
请完成以下Java代码
public int getM_ShippingPackage_ID() { return get_ValueAsInt(COLUMNNAME_M_ShippingPackage_ID); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } @Override public void setPackageNetTotal (final BigDecimal PackageNetTotal) { set_Value (COLUMNNAME_PackageNetTotal, PackageNetTotal); } @Override public BigDecimal getPackageNetTotal() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageNetTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageWeight (final @Nullable BigDecimal PackageWeight) { set_Value (COLUMNNAME_PackageWeight, PackageWeight); } @Override public BigDecimal getPackageWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { throw new IllegalArgumentException ("ProductValue is virtual column"); }
@Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyLU (final @Nullable BigDecimal QtyLU) { set_Value (COLUMNNAME_QtyLU, QtyLU); } @Override public BigDecimal getQtyLU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final @Nullable BigDecimal QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public BigDecimal getQtyTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShippingPackage.java
1
请在Spring Boot框架中完成以下Java代码
private boolean isSkipBecauseMatchingsAlreadyExist() { return _skipIfMatchingsAlreadyExist && matchInvoiceService.hasMatchInvs(getInvoiceLineId(), getInOutLineId(), getInoutCostId()); } /** * @return true if underlying invoice line is part of a credit memo invoice */ private boolean isCreditMemoInvoice() { if (_creditMemoInvoice == null) { _creditMemoInvoice = invoiceBL.isCreditMemo(getInvoice()); } return _creditMemoInvoice; } /** * @return true if underlying inout line is part of a material returns (customer or vendor). */ private boolean isMaterialReturns() { if (_materialReturns == null) { final I_M_InOut inout = getInOut(); _materialReturns = MovementType.isMaterialReturn(inout.getMovementType()); } return _materialReturns; } private ProductId getProductId() { final I_M_InOutLine inoutLine = getInOutLine(); final ProductId inoutLineProductId = ProductId.ofRepoId(inoutLine.getM_Product_ID()); // // Make sure M_Product_ID matches if (getType().isMaterial()) { final I_C_InvoiceLine invoiceLine = getInvoiceLine(); final ProductId invoiceLineProductId = ProductId.ofRepoId(invoiceLine.getM_Product_ID()); if (!ProductId.equals(invoiceLineProductId, inoutLineProductId)) { final String invoiceProductName = productBL.getProductValueAndName(invoiceLineProductId); final String inoutProductName = productBL.getProductValueAndName(inoutLineProductId); throw new AdempiereException("@Invalid@ @M_Product_ID@" + "\n @C_InvoiceLine_ID@: " + invoiceLine + ", @M_Product_ID@=" + invoiceProductName + "\n @M_InOutLine_ID@: " + inoutLine + ", @M_Product_ID@=" + inoutProductName); } }
return inoutLineProductId; } private boolean isSOTrx() { final I_C_Invoice invoice = getInvoice(); final I_M_InOut inout = getInOut(); final boolean invoiceIsSOTrx = invoice.isSOTrx(); final boolean inoutIsSOTrx = inout.isSOTrx(); // // Make sure IsSOTrx matches if (invoiceIsSOTrx != inoutIsSOTrx) { throw new AdempiereException("@Invalid @IsSOTrx@" + "\n @C_Invoice_ID@: " + invoice + ", @IsSOTrx@=" + invoiceIsSOTrx + "\n @M_InOut_ID@: " + inout + ", @IsSOTrx@=" + inoutIsSOTrx); } return inoutIsSOTrx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\service\MatchInvBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityUtil { @Autowired private UserDetailsService userDetailsService; public void logInAs(String username) { UserDetails user = userDetailsService.loadUserByUsername(username); if (user == null) { throw new IllegalStateException("User " + username + " doesn't exist, please provide a valid user"); } SecurityContextHolder.setContext( new SecurityContextImpl( new Authentication() { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return user.getAuthorities(); } @Override public Object getCredentials() { return user.getPassword(); } @Override public Object getDetails() { return user; } @Override public Object getPrincipal() { return user;
} @Override public boolean isAuthenticated() { return true; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {} @Override public String getName() { return user.getUsername(); } } ) ); org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username); } }
repos\Activiti-develop\activiti-examples\activiti-api-spring-integration-example\src\main\java\org\activiti\examples\SecurityUtil.java
2
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } /** * Returns task State of history tasks */ public String getTaskState() { return taskState; } public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) { HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto(); dto.id = taskInstance.getId(); dto.processDefinitionKey = taskInstance.getProcessDefinitionKey(); dto.processDefinitionId = taskInstance.getProcessDefinitionId(); dto.processInstanceId = taskInstance.getProcessInstanceId(); dto.executionId = taskInstance.getExecutionId(); dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey(); dto.caseDefinitionId = taskInstance.getCaseDefinitionId(); dto.caseInstanceId = taskInstance.getCaseInstanceId(); dto.caseExecutionId = taskInstance.getCaseExecutionId(); dto.activityInstanceId = taskInstance.getActivityInstanceId(); dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription(); dto.deleteReason = taskInstance.getDeleteReason(); dto.owner = taskInstance.getOwner(); dto.assignee = taskInstance.getAssignee(); dto.startTime = taskInstance.getStartTime(); dto.endTime = taskInstance.getEndTime(); dto.duration = taskInstance.getDurationInMillis(); dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey(); dto.priority = taskInstance.getPriority(); dto.due = taskInstance.getDueDate(); dto.parentTaskId = taskInstance.getParentTaskId(); dto.followUp = taskInstance.getFollowUpDate(); dto.tenantId = taskInstance.getTenantId(); dto.removalTime = taskInstance.getRemovalTime(); dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId(); dto.taskState = taskInstance.getTaskState(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java
1
请完成以下Java代码
public String charge(final ICalloutField calloutField) { if (isCalloutActive()) { return NO_ERROR; } final I_C_Payment payment = calloutField.getModel(I_C_Payment.class); final int C_Charge_ID = payment.getC_Charge_ID(); if (C_Charge_ID <= 0) // assuming it is resetting value { return NO_ERROR; } payment.setC_Invoice(null); payment.setC_Order(null); // 2008/07/18 Globalqss [ 2021745 ] // mTab.setValue ("C_Project_ID", null); payment.setIsPrepayment(false); // payment.setDiscountAmt(BigDecimal.ZERO); payment.setWriteOffAmt(BigDecimal.ZERO); payment.setIsOverUnderPayment(Boolean.FALSE); payment.setOverUnderAmt(BigDecimal.ZERO); return NO_ERROR; } // charge /** * Payment_Document Type. Verify that Document Type (AP/AR) and Invoice * (SO/PO) are in sync */ public String docType(final ICalloutField calloutField) { final I_C_Payment payment = calloutField.getModel(I_C_Payment.class); final I_C_DocType docType = InterfaceWrapperHelper.load(payment.getC_DocType_ID(), I_C_DocType.class); if (docType != null) { calloutField.putWindowContext("IsSOTrx", docType.isSOTrx());
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(docType) .setOldDocumentNo(payment.getDocumentNo()) .setDocumentModel(payment) .buildOrNull(); if (documentNoInfo != null && documentNoInfo.isDocNoControlled()) { payment.setDocumentNo(documentNoInfo.getDocumentNo()); } } paymentBL.validateDocTypeIsInSync(payment); return NO_ERROR; } // docType /** * Payment_Amounts. Change of: - IsOverUnderPayment -> set OverUnderAmt to 0 - * C_Currency_ID, C_ConvesionRate_ID -> convert all - PayAmt, DiscountAmt, * WriteOffAmt, OverUnderAmt -> PayAmt make sure that add up to * InvoiceOpenAmt */ public String amounts(final ICalloutField calloutField) { if (isCalloutActive()) // assuming it is resetting value { return NO_ERROR; } final I_C_Payment payment = calloutField.getModel(I_C_Payment.class); paymentBL.updateAmounts(payment, calloutField.getColumnName(), true); return NO_ERROR; } // amounts } // CalloutPayment
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\CalloutPayment.java
1