instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class PreAuthenticatedAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = 620L; private final Object principal; private final @Nullable Object credentials; /** * Constructor used for an authentication request. The * {@link org.springframework.security.core.Authentication#isAuthenticated()} will * return <code>false</code>. * @param aPrincipal The pre-authenticated principal * @param aCredentials The pre-authenticated credentials */ public PreAuthenticatedAuthenticationToken(Object aPrincipal, @Nullable Object aCredentials) { super((Collection<? extends GrantedAuthority>) null); this.principal = aPrincipal; this.credentials = aCredentials; } /** * Constructor used for an authentication response. The * {@link org.springframework.security.core.Authentication#isAuthenticated()} will * return <code>true</code>. * @param aPrincipal The authenticated principal * @param anAuthorities The granted authorities */ public PreAuthenticatedAuthenticationToken(Object aPrincipal, @Nullable Object aCredentials, Collection<? extends GrantedAuthority> anAuthorities) { super(anAuthorities); this.principal = aPrincipal; this.credentials = aCredentials; setAuthenticated(true); } protected PreAuthenticatedAuthenticationToken(Builder<?> builder) { super(builder); this.principal = builder.principal; this.credentials = builder.credentials; } /** * Get the credentials */ @Override public @Nullable Object getCredentials() { return this.credentials; } /** * Get the principal */ @Override
public Object getPrincipal() { return this.principal; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link PreAuthenticatedAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private Object principal; private @Nullable Object credentials; protected Builder(PreAuthenticatedAuthenticationToken token) { super(token); this.principal = token.principal; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } @Override public B credentials(@Nullable Object credentials) { this.credentials = credentials; return (B) this; } @Override public PreAuthenticatedAuthenticationToken build() { return new PreAuthenticatedAuthenticationToken(this); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\PreAuthenticatedAuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> handleSQLException(Exception e){ String msg = e.getMessage(); String extractvalue = "extractvalue"; String updatexml = "updatexml"; if(msg!=null && (msg.toLowerCase().indexOf(extractvalue)>=0 || msg.toLowerCase().indexOf(updatexml)>=0)){ return Result.error("校验失败,sql解析异常!"); } return Result.error("校验失败,sql解析异常!" + msg); } /** * 根据应用id获取字典列表和详情 * @param request */ @GetMapping("/getDictListByLowAppId") public Result<List<SysDictVo>> getDictListByLowAppId(HttpServletRequest request){ String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request)); List<SysDictVo> list = sysDictService.getDictListByLowAppId(lowAppId); return Result.ok(list); } /** * 添加字典 * @param sysDictVo * @param request * @return
*/ @PostMapping("/addDictByLowAppId") public Result<String> addDictByLowAppId(@RequestBody SysDictVo sysDictVo,HttpServletRequest request){ String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request)); String tenantId = oConvertUtils.getString(TokenUtils.getTenantIdByRequest(request)); sysDictVo.setLowAppId(lowAppId); sysDictVo.setTenantId(oConvertUtils.getInteger(tenantId, null)); sysDictService.addDictByLowAppId(sysDictVo); return Result.ok("添加成功"); } @PutMapping("/editDictByLowAppId") public Result<String> editDictByLowAppId(@RequestBody SysDictVo sysDictVo,HttpServletRequest request){ String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request)); sysDictVo.setLowAppId(lowAppId); sysDictService.editDictByLowAppId(sysDictVo); return Result.ok("编辑成功"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDictController.java
2
请完成以下Java代码
void contextPrepared(ConfigurableApplicationContext context) { doWithListeners("spring.boot.application.context-prepared", (listener) -> listener.contextPrepared(context)); } void contextLoaded(ConfigurableApplicationContext context) { doWithListeners("spring.boot.application.context-loaded", (listener) -> listener.contextLoaded(context)); } void started(ConfigurableApplicationContext context, Duration timeTaken) { doWithListeners("spring.boot.application.started", (listener) -> listener.started(context, timeTaken)); } void ready(ConfigurableApplicationContext context, Duration timeTaken) { doWithListeners("spring.boot.application.ready", (listener) -> listener.ready(context, timeTaken)); } void failed(@Nullable ConfigurableApplicationContext context, Throwable exception) { doWithListeners("spring.boot.application.failed", (listener) -> callFailedListener(listener, context, exception), (step) -> { step.tag("exception", exception.getClass().toString()); String message = exception.getMessage(); if (message != null) { step.tag("message", message); } }); } private void callFailedListener(SpringApplicationRunListener listener, @Nullable ConfigurableApplicationContext context, Throwable exception) { try { listener.failed(context, exception); } catch (Throwable ex) { if (exception == null) { ReflectionUtils.rethrowRuntimeException(ex); } if (this.log.isDebugEnabled()) { this.log.error("Error handling failed", ex); } else { String message = ex.getMessage(); message = (message != null) ? message : "no error message";
this.log.warn("Error handling failed (" + message + ")"); } } } private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction) { doWithListeners(stepName, listenerAction, null); } private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction, @Nullable Consumer<StartupStep> stepAction) { StartupStep step = this.applicationStartup.start(stepName); this.listeners.forEach(listenerAction); if (stepAction != null) { stepAction.accept(step); } step.end(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationRunListeners.java
1
请完成以下Java代码
protected class MetricsQueryIntervalCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectInterval(metricsQuery); } }
protected class MetricsQuerySumCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectSum(metricsQuery); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public EventSubscriptionBuilder processInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; return this; } @Override public EventSubscriptionBuilder processDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } @Override public EventSubscriptionBuilder activityId(String activityId) { this.activityId = activityId; return this; } @Override public EventSubscriptionBuilder subScopeId(String subScopeId) { this.subScopeId = subScopeId; return this; } @Override public EventSubscriptionBuilder scopeId(String scopeId) { this.scopeId = scopeId; return this; } @Override public EventSubscriptionBuilder scopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; return this; } @Override public EventSubscriptionBuilder scopeDefinitionKey(String scopeDefinitionKey) { this.scopeDefinitionKey = scopeDefinitionKey; return this; } @Override public EventSubscriptionBuilder scopeType(String scopeType) { this.scopeType = scopeType; return this; } @Override public EventSubscriptionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public EventSubscriptionBuilder configuration(String configuration) { this.configuration = configuration; return this; } @Override public EventSubscription create() { return eventSubscriptionService.createEventSubscription(this); } @Override public String getEventType() { return eventType; } @Override public String getEventName() { return eventName; } @Override public Signal getSignal() { return signal; } @Override public String getExecutionId() { return executionId;
} @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getActivityId() { return activityId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getScopeDefinitionKey() { return scopeDefinitionKey; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String getConfiguration() { return configuration; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java
2
请完成以下Java代码
public class ImageCode implements Serializable { private static final long serialVersionUID = -7831615057416168810L; private BufferedImage image; private String code; private LocalDateTime expireTime; public ImageCode(BufferedImage image, String code, int expireIn) { this.image = image; this.code = code; this.expireTime = LocalDateTime.now().plusSeconds(expireIn); } public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) { this.image = image; this.code = code; this.expireTime = expireTime; } boolean isExpire() { return LocalDateTime.now().isAfter(expireTime); } public BufferedImage getImage() { return image; } public void setImage(BufferedImage image) {
this.image = image; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public LocalDateTime getExpireTime() { return expireTime; } public void setExpireTime(LocalDateTime expireTime) { this.expireTime = expireTime; } }
repos\SpringAll-master\59.Spring-Security-SessionManager\src\main\java\cc\mrbird\validate\code\ImageCode.java
1
请完成以下Java代码
public static String buildRequestUrl(HttpServletRequest r) { return buildRequestUrl(r.getServletPath(), r.getRequestURI(), r.getContextPath(), r.getPathInfo(), r.getQueryString()); } /** * Obtains the web application-specific fragment of the URL. */ private static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo, String queryString) { StringBuilder url = new StringBuilder(); if (servletPath != null) { url.append(servletPath); if (pathInfo != null) { url.append(pathInfo); } } else { url.append(requestURI.substring(contextPath.length())); } if (queryString != null) { url.append("?").append(queryString); } return url.toString(); } /**
* Returns true if the supplied URL starts with a "/" or is absolute. */ public static boolean isValidRedirectUrl(String url) { return url != null && (url.startsWith("/") || isAbsoluteUrl(url)); } /** * Decides if a URL is absolute based on whether it contains a valid scheme name, as * defined in RFC 1738. */ public static boolean isAbsoluteUrl(String url) { return (url != null) ? ABSOLUTE_URL.matcher(url).matches() : false; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\UrlUtils.java
1
请完成以下Java代码
public String getInputDataItem() { return inputDataItem; } public void setInputDataItem(String inputDataItem) { this.inputDataItem = inputDataItem; } public String getLoopCardinality() { return loopCardinality; } public void setLoopCardinality(String loopCardinality) { this.loopCardinality = loopCardinality; } public String getCompletionCondition() { return completionCondition; } public void setCompletionCondition(String completionCondition) { this.completionCondition = completionCondition; } public String getElementVariable() { return elementVariable; } public void setElementVariable(String elementVariable) { this.elementVariable = elementVariable; } public String getElementIndexVariable() { return elementIndexVariable; } public void setElementIndexVariable(String elementIndexVariable) { this.elementIndexVariable = elementIndexVariable; } public boolean isSequential() { return sequential; }
public void setSequential(boolean sequential) { this.sequential = sequential; } public String getLoopDataOutputRef() { return loopDataOutputRef; } public void setLoopDataOutputRef(String loopDataOutputRef) { this.loopDataOutputRef = loopDataOutputRef; } public String getOutputDataItem() { return outputDataItem; } public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; } public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; } public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setLoopDataOutputRef(otherLoopCharacteristics.getLoopDataOutputRef()); setOutputDataItem(otherLoopCharacteristics.getOutputDataItem()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请完成以下Java代码
public class AD_User_SortPref_Line_RecalculateSeqNo extends JavaProcess { @Override protected void prepare() { // nothing to do } /** * Recalculates SeqNo in AD_User_SortPref_Line_Product in 10-steps for the current AD_User_SortPref_Line, keeping the order they already had */ @Override protected String doIt() throws Exception { // // Services final ITrxManager trxManager = Services.get(ITrxManager.class); final IUserSortPrefDAO userSortPrefDAO = Services.get(IUserSortPrefDAO.class); final Properties ctx = getCtx(); trxManager.runInNewTrx(new TrxRunnable() {
@Override public void run(final String localTrxName) throws Exception { int seqNumber = 10; final ProcessInfo processInfo = getProcessInfo(); final int recordId = processInfo.getRecord_ID(); final I_AD_User_SortPref_Line sortPreferenceLine = InterfaceWrapperHelper.create(ctx, recordId, I_AD_User_SortPref_Line.class, localTrxName); final Iterator<I_AD_User_SortPref_Line_Product> sortPreferenceLineProducts = userSortPrefDAO.retrieveSortPreferenceLineProducts(sortPreferenceLine).iterator(); while (sortPreferenceLineProducts.hasNext()) { final I_AD_User_SortPref_Line_Product sortPreferenceLineProduct = sortPreferenceLineProducts.next(); sortPreferenceLineProduct.setSeqNo(seqNumber); InterfaceWrapperHelper.save(sortPreferenceLineProduct); seqNumber = seqNumber + 10; } } }); return "@SeqNoRecalculated@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_SortPref_Line_RecalculateSeqNo.java
1
请完成以下Java代码
public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeys.values(); } @Override public KeyName[] getHighCardinalityKeyNames() { return HighCardinalityKeys.values(); } }; @NonNullApi enum LowCardinalityKeys implements KeyName { /** * Route ID. */ ROUTE_ID { @Override public String asString() { return "spring.cloud.gateway.route.id"; } }, /** * HTTP Method. */ METHOD { @Override public String asString() { return "http.method"; } }, /** * HTTP Status.
*/ STATUS { @Override public String asString() { return "http.status_code"; } }, /** * HTTP URI taken from the Route. */ ROUTE_URI { @Override public String asString() { return "spring.cloud.gateway.route.uri"; } } } @NonNullApi enum HighCardinalityKeys implements KeyName { /** * Full HTTP URI. */ URI { @Override public String asString() { return "http.uri"; } } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\observation\GatewayDocumentedObservation.java
1
请在Spring Boot框架中完成以下Java代码
public class CorsConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractHttpConfigurer<CorsConfigurer<H>, H> { private static final String CORS_CONFIGURATION_SOURCE_BEAN_NAME = "corsConfigurationSource"; private static final String CORS_FILTER_BEAN_NAME = "corsFilter"; private CorsConfigurationSource configurationSource; /** * Creates a new instance * * @see HttpSecurity#cors(Customizer) */ public CorsConfigurer() { } public CorsConfigurer<H> configurationSource(CorsConfigurationSource configurationSource) { this.configurationSource = configurationSource; return this; } @Override public void configure(H http) { ApplicationContext context = http.getSharedObject(ApplicationContext.class); CorsFilter corsFilter = getCorsFilter(context); Assert.state(corsFilter != null, () -> "Please configure either a " + CORS_FILTER_BEAN_NAME + " bean or a " + CORS_CONFIGURATION_SOURCE_BEAN_NAME + "bean."); http.addFilter(corsFilter); } private CorsFilter getCorsFilter(ApplicationContext context) { if (this.configurationSource != null) { return new CorsFilter(this.configurationSource); } boolean containsCorsFilter = context.containsBeanDefinition(CORS_FILTER_BEAN_NAME); if (containsCorsFilter) { return context.getBean(CORS_FILTER_BEAN_NAME, CorsFilter.class);
} boolean containsCorsSource = context.containsBean(CORS_CONFIGURATION_SOURCE_BEAN_NAME); if (containsCorsSource) { CorsConfigurationSource configurationSource = context.getBean(CORS_CONFIGURATION_SOURCE_BEAN_NAME, CorsConfigurationSource.class); return new CorsFilter(configurationSource); } return MvcCorsFilter.getMvcCorsFilter(context); } static class MvcCorsFilter { private static final String HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector"; /** * This needs to be isolated into a separate class as Spring MVC is an optional * dependency and will potentially cause ClassLoading issues * @param context * @return */ private static CorsFilter getMvcCorsFilter(ApplicationContext context) { if (context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) { CorsConfigurationSource corsConfigurationSource = context .getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, CorsConfigurationSource.class); return new CorsFilter(corsConfigurationSource); } throw new NoSuchBeanDefinitionException(CorsConfigurationSource.class, "Failed to find a bean that implements `CorsConfigurationSource`. Please ensure that you are using " + "`@EnableWebMvc`, are publishing a `WebMvcConfigurer`, or are publishing a `CorsConfigurationSource` bean."); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\CorsConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
private JsonRequestLocationUpsert getDeliveryAddressUpsertRequest( @NonNull final OrderDeliveryAddress orderDeliveryAddress, @NonNull final String patientId) { final BPartnerLocationCandidate bPartnerLocationCandidate = BPartnerLocationCandidate.fromDeliveryAddress(orderDeliveryAddress); final String locationHash = computeHashKey(bPartnerLocationCandidate); final String bPartnerLocationIdentifier = ExternalIdentifierFormat.formatDeliveryAddressExternalIdHash(patientId, locationHash); final JsonRequestLocation deliveryAddressRequest = bPartnerLocationCandidate.toJsonRequestLocation(); return JsonRequestLocationUpsert.builder() .requestItem(JsonRequestLocationUpsertItem.builder() .locationIdentifier(bPartnerLocationIdentifier) .location(deliveryAddressRequest) .build()) .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .build(); } @VisibleForTesting @NonNull
public static String computeHashKey(@NonNull final BPartnerLocationCandidate bPartnerLocationCandidate) { try { final String bpartnerLocationString = JsonObjectMapperHolder .sharedJsonObjectMapper() .writeValueAsString(bPartnerLocationCandidate); final String hashedValue = StringUtils.createHash(StringUtils.removeWhitespaces(bpartnerLocationString).toLowerCase(), null); Check.assumeNotNull(hashedValue, "hashedValue cannot be null! bPartnerLocationCandidate: {}", bPartnerLocationCandidate); return hashedValue; } catch (final Exception e) { throw new RuntimeException("Fail to process hashed value for " + bPartnerLocationCandidate + "; error: " + e); } } }
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\ordercandidate\processor\DeliveryAddressUpsertProcessor.java
2
请完成以下Java代码
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); this.credentials = null; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link UsernamePasswordAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private @Nullable Object principal; private @Nullable Object credentials;
protected Builder(UsernamePasswordAuthenticationToken token) { super(token); this.principal = token.principal; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } @Override public B credentials(@Nullable Object credentials) { this.credentials = credentials; return (B) this; } @Override public UsernamePasswordAuthenticationToken build() { return new UsernamePasswordAuthenticationToken(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\UsernamePasswordAuthenticationToken.java
1
请完成以下Java代码
private I_M_ReceiptSchedule getReceiptScheduleOrNull(final Object model) { if (!InterfaceWrapperHelper.isInstanceOf(model, I_M_ReceiptSchedule.class)) { // does not apply return null; } return InterfaceWrapperHelper.create(model, I_M_ReceiptSchedule.class); } /** * Makes sure that only HUs which have <code>HUStatus=Planning</code> are allowed to be assigned to an Receipt Schedule. * If the given <code>model</code> is <code>null</code> or not an {@link I_M_ReceiptSchedule}, the method just returns. */ @Override public void assertAssignable(final I_M_HU hu, final Object model, final String trxName) throws HUNotAssignableException { final I_M_ReceiptSchedule receiptSchedule = getReceiptScheduleOrNull(model); if (receiptSchedule == null) { // does not apply return; } // // Only HUs which have HUStatus=Planning are allowed to be assigned to an Receipt Schedule final String huStatus = hu.getHUStatus(); if (!X_M_HU.HUSTATUS_Planning.equals(huStatus)) { throw new HUNotAssignableException("@HUStatus@ <> Planning", model, hu); }
} /** * Updates the given assigned {@code hu}'s {@code M_Locator_ID} from the I_M_ReceiptSchedule that is given {@code model}. * */ @Override public void onHUAssigned(final I_M_HU hu, final Object model, final String trxName) { final I_M_ReceiptSchedule receiptSchedule = getReceiptScheduleOrNull(model); if (receiptSchedule == null) { // does not apply return; } // // Update HU's locator (if needed) final WarehouseId warehouseId = Services.get(IReceiptScheduleBL.class).getWarehouseEffectiveId(receiptSchedule); final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId); hu.setM_Locator_ID(locatorId.getRepoId()); InterfaceWrapperHelper.save(hu, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUAssignmentListener.java
1
请在Spring Boot框架中完成以下Java代码
public class CategoryQueryReq extends QueryReq { /** 类别id */ private String id; /** 类别名称(模糊匹配) */ private String categoryName; /** 父分类id (一级分类的parentId为空) */ private String parentId; public String getId() { return id; } public void setId(String id) { this.id = id; }
public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\CategoryQueryReq.java
2
请完成以下Java代码
public Optional<PriceLimitRestrictions> get() { return cache.getOrLoad(0, this::retrievePriceLimitRestrictions); } private Optional<PriceLimitRestrictions> retrievePriceLimitRestrictions() { final I_C_PriceLimit_Restriction priceLimitRestrictionsRecord = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_PriceLimit_Restriction.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .create() .firstOnly(I_C_PriceLimit_Restriction.class); if (priceLimitRestrictionsRecord == null) { return Optional.empty(); } final PriceLimitRestrictions priceLimitRestrictions = PriceLimitRestrictions.builder() .basePricingSystemId(PricingSystemId.ofRepoId(priceLimitRestrictionsRecord.getBase_PricingSystem_ID())) .priceAddAmt(priceLimitRestrictionsRecord.getStd_AddAmt()) .discountPercent(priceLimitRestrictionsRecord.getDiscount())
.build(); return Optional.of(priceLimitRestrictions); } @Override public Set<CountryId> getPriceCountryIds() { return get() .map(this::getPriceCountryIds) .orElseGet(ImmutableSet::of); } private final Set<CountryId> getPriceCountryIds(final PriceLimitRestrictions priceLimitRestrictions) { final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class); return priceListsRepo.retrieveCountryIdsByPricingSystem(priceLimitRestrictions.getBasePricingSystemId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\limit\impl\PriceLimitRestrictionsRepository.java
1
请完成以下Java代码
public final Optional<ILock> getElementsLock() { final String elementsLockOwnerName = getParameters().getParameterAsString(PARAMETERNAME_ElementsLockOwner); if (Check.isBlank(elementsLockOwnerName)) { return Optional.empty(); // no lock was created for this workpackage } final LockOwner elementsLockOwner = LockOwner.forOwnerName(elementsLockOwnerName); try { final ILock existingLockForOwner = Services.get(ILockManager.class).getExistingLockForOwner(elementsLockOwner); return Optional.of(existingLockForOwner); } catch (final LockFailedException e) { // this can happen, if e.g. there was a restart, or if the WP was flagged as error once Loggables.addLog("Missing lock for ownerName={}; was probably cleaned up meanwhile", elementsLockOwnerName); return Optional.empty(); } } /** * Returns the {@link NullLatchStrategy}. */ @Override public ILatchStragegy getLatchStrategy() { return NullLatchStrategy.INSTANCE; } public final <T> List<T> retrieveItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(getC_Queue_WorkPackage(), modelType); } /**
* Retrieves all active POs, even the ones that are caught in other packages */ public final <T> List<T> retrieveAllItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItems(getC_Queue_WorkPackage(), modelType); } public final List<I_C_Queue_Element> retrieveQueueElements(final boolean skipAlreadyScheduledItems) { return Services.get(IQueueDAO.class).retrieveQueueElements(getC_Queue_WorkPackage(), skipAlreadyScheduledItems); } /** * retrieves all active PO's IDs, even the ones that are caught in other packages */ public final Set<Integer> retrieveAllItemIds() { return Services.get(IQueueDAO.class).retrieveAllItemIds(getC_Queue_WorkPackage()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackageProcessorAdapter.java
1
请完成以下Java代码
public UserNotificationsGroup getGroupByName(@NonNull final NotificationGroupName groupName) { return userNotificationGroupsByInternalName.getOrDefault(groupName, defaults); } public String getUserADLanguageOrGet(@NonNull final Supplier<String> defaultLanguageSupplier) { final String adLanguage = getUserADLanguage(); return adLanguage != null ? adLanguage : defaultLanguageSupplier.get(); } public boolean isUserInChargeSet() { return userInChargeId != null; }
public UserNotificationsConfig deriveWithNotificationGroups(final List<UserNotificationsGroup> notificationGroups) { if (notificationGroups.isEmpty()) { return this; } final Map<NotificationGroupName, UserNotificationsGroup> newUserNotificationGroupsByInternalName = new HashMap<>(userNotificationGroupsByInternalName); notificationGroups.forEach(notificationGroup -> newUserNotificationGroupsByInternalName.put(notificationGroup.getGroupInternalName(), notificationGroup)); return toBuilder() .clearUserNotificationGroups() .userNotificationGroups(newUserNotificationGroupsByInternalName.values()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationsConfig.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Dosage Form. @param M_DosageForm_ID Dosage Form */ @Override public void setM_DosageForm_ID (int M_DosageForm_ID) { if (M_DosageForm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DosageForm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DosageForm_ID, Integer.valueOf(M_DosageForm_ID)); } /** Get Dosage Form. @return Dosage Form */ @Override public int getM_DosageForm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DosageForm_ID); if (ii == null) return 0; return ii.intValue(); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_DosageForm.java
1
请在Spring Boot框架中完成以下Java代码
public void setManagerPassword(String managerPassword) { this.managerPassword = managerPassword; } @Override public DefaultSpringSecurityContextSource getObject() throws Exception { if (!unboundIdPresent) { throw new IllegalStateException("Embedded LDAP server is not provided"); } this.container = getContainer(); this.port = this.container.getPort(); DefaultSpringSecurityContextSource contextSourceFromProviderUrl = new DefaultSpringSecurityContextSource( "ldap://127.0.0.1:" + this.port + "/" + this.root); if (this.managerDn != null) { contextSourceFromProviderUrl.setUserDn(this.managerDn); if (this.managerPassword == null) { throw new IllegalStateException("managerPassword is required if managerDn is supplied"); } contextSourceFromProviderUrl.setPassword(this.managerPassword); } contextSourceFromProviderUrl.afterPropertiesSet(); return contextSourceFromProviderUrl; } @Override public Class<?> getObjectType() { return DefaultSpringSecurityContextSource.class; } @Override public void destroy() { if (this.container instanceof Lifecycle) { ((Lifecycle) this.container).stop(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } private EmbeddedLdapServerContainer getContainer() { if (!unboundIdPresent) { throw new IllegalStateException("Embedded LDAP server is not provided"); } UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif); unboundIdContainer.setApplicationContext(this.context); unboundIdContainer.setPort(getEmbeddedServerPort());
unboundIdContainer.afterPropertiesSet(); return unboundIdContainer; } private int getEmbeddedServerPort() { if (this.port == null) { this.port = getDefaultEmbeddedServerPort(); } return this.port; } private int getDefaultEmbeddedServerPort() { try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) { return serverSocket.getLocalPort(); } catch (IOException ex) { return RANDOM_PORT; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\EmbeddedLdapServerContextSourceFactoryBean.java
2
请完成以下Java代码
public final class CalloutMethodPointcut implements ICalloutMethodPointcut { @Getter private final Method method; @Getter private final Set<String> columnNames; @Getter private final Class<?> modelClass; @Getter private final boolean paramCalloutFieldRequired; @Getter private final boolean skipIfCopying; @Getter private final boolean skipIfIndirectlyCalled; public CalloutMethodPointcut( @NonNull final Class<?> modelClass, @NonNull final Method method, @NonNull final String[] columnNames, final boolean paramCalloutFieldRequired, final boolean skipIfCopying, final boolean skipIfIndirectlyCalled) { this.modelClass = modelClass; this.method = method;
Check.assume(columnNames.length > 0, "columnNames not empty"); this.columnNames = new HashSet<>(columnNames.length); for (final String columnName : columnNames) { Check.assumeNotNull(columnName, "columnName not null"); this.columnNames.add(columnName); } this.paramCalloutFieldRequired = paramCalloutFieldRequired; this.skipIfCopying = skipIfCopying; this.skipIfIndirectlyCalled = skipIfIndirectlyCalled; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\CalloutMethodPointcut.java
1
请完成以下Java代码
public void dispose() { dataPublisher.complete(); this.server.dispose(); } /** * RSocket implementation */ private class RSocketImpl extends AbstractRSocket { /** * Handle Request/Response messages * * @param payload Message payload * @return payload response */ @Override public Mono<Payload> requestResponse(Payload payload) { try { return Mono.just(payload); // reflect the payload back to the sender } catch (Exception x) { return Mono.error(x); } } /** * Handle Fire-and-Forget messages * * @param payload Message payload * @return nothing */ @Override public Mono<Void> fireAndForget(Payload payload) { try { dataPublisher.publish(payload); // forward the payload return Mono.empty(); } catch (Exception x) { return Mono.error(x); } } /** * Handle Request/Stream messages. Each request returns a new stream. * * @param payload Payload that can be used to determine which stream to return * @return Flux stream containing simulated measurement data */ @Override
public Flux<Payload> requestStream(Payload payload) { String streamName = payload.getDataUtf8(); if (DATA_STREAM_NAME.equals(streamName)) { return Flux.from(dataPublisher); } return Flux.error(new IllegalArgumentException(streamName)); } /** * Handle request for bidirectional channel * * @param payloads Stream of payloads delivered from the client * @return */ @Override public Flux<Payload> requestChannel(Publisher<Payload> payloads) { Flux.from(payloads) .subscribe(gameController::processPayload); Flux<Payload> channel = Flux.from(gameController); return channel; } } }
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\Server.java
1
请完成以下Java代码
protected String provideTenantId(DecisionDefinition decisionDefinition, HistoricDecisionInstanceEntity event) { TenantIdProvider tenantIdProvider = Context.getProcessEngineConfiguration().getTenantIdProvider(); String tenantId = null; if(tenantIdProvider != null) { TenantIdProviderHistoricDecisionInstanceContext ctx = null; if(event.getExecutionId() != null) { ctx = new TenantIdProviderHistoricDecisionInstanceContext(decisionDefinition, getExecution(event)); } else if(event.getCaseExecutionId() != null) { ctx = new TenantIdProviderHistoricDecisionInstanceContext(decisionDefinition, getCaseExecution(event)); } else { ctx = new TenantIdProviderHistoricDecisionInstanceContext(decisionDefinition); } tenantId = tenantIdProvider.provideTenantIdForHistoricDecisionInstance(ctx); } return tenantId; } protected DelegateExecution getExecution(HistoricDecisionInstanceEntity event) { return Context.getCommandContext().getExecutionManager().findExecutionById(event.getExecutionId()); } protected DelegateCaseExecution getCaseExecution(HistoricDecisionInstanceEntity event) { return Context.getCommandContext().getCaseExecutionManager().findCaseExecutionById(event.getCaseExecutionId()); } protected Date calculateRemovalTime(HistoricDecisionInstanceEntity historicDecisionInstance, DecisionDefinition decisionDefinition) { return Context.getProcessEngineConfiguration() .getHistoryRemovalTimeProvider() .calculateRemovalTime(historicDecisionInstance, decisionDefinition); } protected void provideRemovalTime(HistoryEvent historyEvent) { String rootProcessInstanceId = historyEvent.getRootProcessInstanceId(); if (rootProcessInstanceId != null) { HistoricProcessInstanceEventEntity historicRootProcessInstance =
getHistoricRootProcessInstance(rootProcessInstanceId); if (historicRootProcessInstance != null) { Date removalTime = historicRootProcessInstance.getRemovalTime(); historyEvent.setRemovalTime(removalTime); } } } protected boolean isHistoryRemovalTimeStrategyStart() { return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy()); } protected String getHistoryRemovalTimeStrategy() { return Context.getProcessEngineConfiguration() .getHistoryRemovalTimeStrategy(); } protected HistoricProcessInstanceEventEntity getHistoricRootProcessInstance(String rootProcessInstanceId) { return Context.getCommandContext().getDbEntityManager() .selectById(HistoricProcessInstanceEventEntity.class, rootProcessInstanceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultDmnHistoryEventProducer.java
1
请完成以下Java代码
public boolean isBorderOpaque() { return true; } @Override public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) { // if the collapsible is collapsed, we do not want its border to be painted. if (c instanceof JXCollapsiblePane) { if (((JXCollapsiblePane)c).isCollapsed()) { return; } } g.setColor(getSeparatorColor()); if (isFirst(c)) { g.drawLine(x, y + 2, x + width, y + 2); } g.drawLine(x, y + height - 1, x + width, y + height - 1); } }
@Override public final Component add(final Component comp) { return collapsible.add(comp); } public final void setCollapsed(final boolean collapsed) { collapsible.setCollapsed(collapsed); } public final void setCollapsible(final boolean collapsible) { this.toggleAction.setEnabled(collapsible); if (!collapsible) { this.collapsible.setCollapsed(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CollapsiblePanel.java
1
请在Spring Boot框架中完成以下Java代码
public class UserResponse { private Integer id; private String name; private Integer gender; public Integer getId() { return id; } public UserResponse setId(Integer id) { this.id = id; return this; } public String getName() { return name;
} public UserResponse setName(String name) { this.name = name; return this; } public Integer getGender() { return gender; } public UserResponse setGender(Integer gender) { this.gender = gender; return this; } }
repos\SpringBoot-Labs-master\lab-58\lab-58-user-service\src\main\java\cn\iocoder\springboot\lab58\userservice\response\UserResponse.java
2
请完成以下Java代码
public BigDecimal getQualityAdjustmentForMonthOrNull(final int month) { if (!qualityAdjustmentsActive) { return null; } return month2qualityAdjustment.get(month); } @Override public final BigDecimal getQualityAdjustmentForDateOrNull(final Date date) { final int month = TimeUtil.asCalendar(date).get(Calendar.MONTH); return getQualityAdjustmentForMonthOrNull(month); } /** * @return zero if the given percentage is below 10, <code>0.06</code> otherwise */ @Override public BigDecimal getScrapProcessingFeeForPercentage(final BigDecimal percentage) { if (percentage.compareTo(new BigDecimal("10.00")) < 0) { return BigDecimal.ZERO; } else { return new BigDecimal("0.06"); } } @Override public BigDecimal getScrapPercentageTreshold() { return new BigDecimal("10.00"); } @Override public boolean isFeeForProducedMaterial(final I_M_Product product) { return M_PRODUCT_SORTING_OUT_FEE_VALUE.equals(product.getValue()); } @Override public BigDecimal getFeeForProducedMaterial(final I_M_Product m_Product, final BigDecimal percentage) { final List<BigDecimal> percentages = new ArrayList<>(feeProductPercentage2fee.keySet()); // iterating from first to 2nd-last for (int i = 0; i < percentages.size() - 1; i++) { final BigDecimal currentPercentage = percentages.get(i); final BigDecimal nextPercentage = percentages.get(i + 1); if (currentPercentage.compareTo(percentage) <= 0 && nextPercentage.compareTo(percentage) > 0) { // found it: 'percentage' is in the interval that starts with 'currentPercentage' return feeProductPercentage2fee.get(currentPercentage); } } final BigDecimal lastInterval = percentages.get(percentages.size() - 1); return feeProductPercentage2fee.get(lastInterval);
} @Override public Currency getCurrency() { return currencyDAO.getByCurrencyCode(CURRENCY_ISO); } public static void setOverallNumberOfInvoicings(final int overallNumberOfInvoicings) { HardCodedQualityBasedConfig.overallNumberOfInvoicings = overallNumberOfInvoicings; } @Override public int getOverallNumberOfInvoicings() { return overallNumberOfInvoicings; } public static void setQualityAdjustmentActive(final boolean qualityAdjustmentOn) { HardCodedQualityBasedConfig.qualityAdjustmentsActive = qualityAdjustmentOn; } @Override public I_M_Product getRegularPPOrderProduct() { final IContextAware ctxAware = getContext(); return productPA.retrieveProduct(ctxAware.getCtx(), M_PRODUCT_REGULAR_PP_ORDER_VALUE, true, // throwExIfProductNotFound ctxAware.getTrxName()); } /** * @return the date that was set with {@link #setValidToDate(Timestamp)}, or falls back to "now plus 2 months". Never returns <code>null</code>. */ @Override public Timestamp getValidToDate() { if (validToDate == null) { return TimeUtil.addMonths(SystemTime.asDate(), 2); } return validToDate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\HardCodedQualityBasedConfig.java
1
请完成以下Java代码
public static <T> void withCallbackAndTimeout(ListenableFuture<T> future, Consumer<T> onSuccess, Consumer<Throwable> onFailure, long timeoutInMs, ScheduledExecutorService timeoutExecutor, Executor callbackExecutor) { future = Futures.withTimeout(future, timeoutInMs, TimeUnit.MILLISECONDS, timeoutExecutor); withCallback(future, onSuccess, onFailure, callbackExecutor); } public static <T> void withCallback(ListenableFuture<T> future, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor) { FutureCallback<T> callback = new FutureCallback<T>() { @Override public void onSuccess(T result) { try { onSuccess.accept(result); } catch (Throwable th) {
onFailure(th); } } @Override public void onFailure(Throwable t) { onFailure.accept(t); } }; if (executor != null) { Futures.addCallback(future, callback, executor); } else { Futures.addCallback(future, callback, MoreExecutors.directExecutor()); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\AsyncCallbackTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public ConcurrentKafkaListenerContainerFactory<String, Greeting> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Greeting> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(greetingConsumerFactory()); return factory; } @Bean public RecordMessageConverter multiTypeConverter() { StringJsonMessageConverter converter = new StringJsonMessageConverter(); DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper(); typeMapper.setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence.TYPE_ID); typeMapper.addTrustedPackages("com.baeldung.spring.kafka"); Map<String, Class<?>> mappings = new HashMap<>(); mappings.put("greeting", Greeting.class); mappings.put("farewell", Farewell.class); typeMapper.setIdClassMapping(mappings); converter.setTypeMapper(typeMapper); return converter; } @Bean public ConsumerFactory<String, Object> multiTypeConsumerFactory() { HashMap<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); props.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id_test"); return new DefaultKafkaConsumerFactory<>(props); } @Bean @Primary public ConcurrentKafkaListenerContainerFactory<String, Object> greetingKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(multiTypeConsumerFactory()); factory.setCommonErrorHandler(errorHandler());
factory.getContainerProperties() .setAckMode(ContainerProperties.AckMode.RECORD); return factory; } @Bean public DefaultErrorHandler errorHandler() { BackOff fixedBackOff = new FixedBackOff(interval, maxAttempts); DefaultErrorHandler errorHandler = new DefaultErrorHandler((consumerRecord, e) -> { System.out.println(String.format("consumed record %s because this exception was thrown",consumerRecord.toString(),e.getClass().getName())); }, fixedBackOff); //Commented because of the test //errorHandler.addRetryableExceptions(SocketTimeoutException.class,RuntimeException.class); errorHandler.addNotRetryableExceptions(NullPointerException.class); return errorHandler; } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\kafka\retryable\KafkaConsumerConfig.java
2
请完成以下Java代码
public static LU of(@NonNull final I_M_HU lu, @NonNull final List<TU> tus) { return builder().hu(lu).tus(TUsList.of(tus)).build(); } public static LU of(@NonNull final I_M_HU lu, @NonNull final TUsList tus) { return builder().hu(lu).tus(tus).build(); } public LU markedAsPreExistingLU() { return this.isPreExistingLU ? this : toBuilder().isPreExistingLU(true).build(); } public HuId getId() {return HuId.ofRepoId(hu.getM_HU_ID());} public I_M_HU toHU() {return hu;} public Stream<I_M_HU> streamAllLUAndTURecords() { return Stream.concat(Stream.of(hu), tus.streamHURecords()); } public Stream<TU> streamTUs() {return tus.stream();} public QtyTU getQtyTU() {return tus.getQtyTU();} public LU mergeWith(@NonNull final LU other) { if (this.hu.getM_HU_ID() != other.hu.getM_HU_ID()) { throw new AdempiereException("Cannot merge " + this + " with " + other + " because they don't have the same HU"); } return builder() .hu(this.hu) .isPreExistingLU(this.isPreExistingLU && other.isPreExistingLU) .tus(this.tus.mergeWith(other.tus)) .build(); } private static List<LU> mergeLists(final List<LU> list1, final List<LU> list2) { if (list2.isEmpty()) { return list1; } if (list1.isEmpty()) {
return list2; } else { final HashMap<HuId, LU> lusNew = new HashMap<>(); list1.forEach(lu -> lusNew.put(lu.getId(), lu)); list2.forEach(lu -> lusNew.compute(lu.getId(), (luId, existingLU) -> existingLU == null ? lu : existingLU.mergeWith(lu))); return ImmutableList.copyOf(lusNew.values()); } } public boolean containsAnyOfHUIds(final Collection<HuId> huIds) { if (huIds.isEmpty()) {return false;} return huIds.contains(getId()) // LU matches || tus.containsAnyOfHUIds(huIds); // any of the TU matches } public void forEachAffectedHU(@NonNull final LUTUCUConsumer consumer) { tus.forEachAffectedHU(this, consumer); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\LUTUResult.java
1
请完成以下Java代码
public static IAutoCloseable temporaryDisableIt() { final boolean disabledOld = disabled.getAndSet(true); return () -> disabled.set(disabledOld); } @Override public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40; } @Override public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return !disabled.get();
} @Override public String generateStringValue( final Properties ctx_IGNORED, @NonNull final IAttributeSet attributeSet, final I_M_Attribute attribute_IGNORED) { final I_M_HU hu = Services.get(IHUAttributesBL.class).getM_HU(attributeSet); // Just don't use the M_HU_ID as serial number. It introduced FUD as multiple packs can have the same HU and each pack needs an individual SSCC. final SSCC18 sscc18 = sscc18CodeBL.generate(OrgId.ofRepoIdOrAny(hu.getAD_Org_ID())); return sscc18.asString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attributes\sscc18\impl\SSCC18AttributeValueGenerator.java
1
请完成以下Java代码
public Properties getCtx() { return ctx; } public String getTrxName() { return trxName; } public Class<T> getModelClass() { return modelClass; } public String getModelTableName() { return modelTableName; } public ImmutableMap<String, Object> getQueryOptions() { return queryOptions; } public PInstanceId getQueryOnlySelectionId() { return queryOnlySelectionId; } public IQueryFilter<T> getMainFilter() { return mainFilter; } public ICompositeQueryFilter<T> getMainFilterAsComposite() { return (ICompositeQueryFilter<T>)mainFilter; } public ICompositeQueryFilter<T> getMainFilterAsCompositeOrNull() { return mainFilter instanceof ICompositeQueryFilter ? (ICompositeQueryFilter<T>)mainFilter : null;
} public IQueryOrderBy getQueryOrderBy() { return queryOrderBy; } public QueryLimit getQueryLimit() { return queryLimit; } public void setQueryLimit(@NonNull final QueryLimit queryLimit) { this.queryLimit = queryLimit; } public boolean isExplodeORJoinsToUnions() { return explodeORJoinsToUnions; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AbstractQueryBuilderDAO.java
1
请完成以下Java代码
public ExecutionResult apply(final String trxName) { final I_AD_MigrationStep step = getAD_MigrationStep(); // Already applied if (X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode())) { log("Already applied", "SKIP", false); return ExecutionResult.Ignored; } final IMigrationStepExecutor executor = createDelegatedMigrationStepExecutor(step); return executor.apply(trxName); } @Override public ExecutionResult rollback(final String trxName) { final I_AD_MigrationStep step = getAD_MigrationStep(); // Not Applied, no rollback is needed if (!X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode())) { log("Not applied. Nothing to rollback", "SKIP", false);
return ExecutionResult.Ignored; } final IMigrationStepExecutor executor = createDelegatedMigrationStepExecutor(step); return executor.rollback(trxName); } private IMigrationStepExecutor createDelegatedMigrationStepExecutor(final I_AD_MigrationStep step) { final IMigrationExecutorContext migrationCtx = getMigrationExecutorContext(); final IMigrationExecutorProvider factory = migrationCtx.getMigrationExecutorProvider(); final IMigrationStepExecutor executor = factory.newMigrationStepExecutor(migrationCtx, step); return executor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\CompositeMigrationStepExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class SimpleBookRepository implements BookRepository { private static final Logger logger = LoggerFactory.getLogger(SimpleBookRepository.class); /** * condition 在什么条件下 缓存结果 * unless 除非结果怎么怎么样的时候被缓存 !#result.auto.equals('vector') 当结果的auto不等于vector的时候被缓存 * unless Default is "", meaning that caching is never vetoed.(需要慢慢体会) 否的时候生效,真的时候失效 * https://docs.spring.io/spring/docs/5.0.7.RELEASE/javadoc-api/ * @param isbn * @return */ @Override @Cacheable(cacheNames = "books", key = "#isbn.hashCode()", condition = "#isbn.equals('isbn-4567')", unless = "!#result.auto.equals('vector')") public Book getByIsbn(String isbn) { simulateSlowService(); return new Book(isbn, "Some book", "vector"); } /** * 最好指定key,此时会根据key将cache中的内容更新为最新 * @param book * @return */ @Override @CachePut(cacheNames = "books", key = "#book.isbn.hashCode()") // 方法的返回值会被更新到缓存中 public Book update(Book book) { logger.info("更新book"); return book; } /** * beforeInvocation = true 意味着不管业务如何出错,缓存已清空 * beforeInvocation = false 等待方法处理完之后再清空缓存,缺点是如果逻辑出异常了,会导致缓存不会被清空 */ @Override @CacheEvict(cacheNames = "books", allEntries = true, beforeInvocation = true) public void clear() { logger.warn("清空books缓存数据");
throw new RuntimeException("测试 beforeInvocation = fasle"); } /** * 模拟慢查询 */ private void simulateSlowService() { try { long time = 3000L; Thread.sleep(time); } catch (InterruptedException e) { throw new IllegalStateException(e); } } }
repos\spring-boot-quick-master\quick-cache\src\main\java\com\quick\cache\repo\SimpleBookRepository.java
2
请完成以下Java代码
public void performExecution(final ActivityExecution execution) throws Exception { executeWithErrorPropagation(execution, new Callable<Void>() { @Override public Void call() throws Exception { ScriptInvocation invocation = new ScriptInvocation(script, execution); Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(invocation); Object result = invocation.getInvocationResult(); if (result != null && resultVariable != null) { execution.setVariable(resultVariable, result); } leave(execution); return null; } }); } /** * Searches recursively through the exception to see if the exception itself * or one of its causes is a {@link BpmnError}. *
* @param e * the exception to check * @return the BpmnError that was the cause of this exception or null if no * BpmnError was found */ protected BpmnError checkIfCauseOfExceptionIsBpmnError(Throwable e) { if (e instanceof BpmnError) { return (BpmnError) e; } else if (e.getCause() == null) { return null; } return checkIfCauseOfExceptionIsBpmnError(e.getCause()); } public ExecutableScript getScript() { return script; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ScriptTaskActivityBehavior.java
1
请完成以下Java代码
public void setAccessTokenResponseClient( ReactiveOAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; } /** * Sets the resolver used for resolving the {@link OAuth2Token subject token}. * @param subjectTokenResolver the resolver used for resolving the {@link OAuth2Token * subject token} */ public void setSubjectTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> subjectTokenResolver) { Assert.notNull(subjectTokenResolver, "subjectTokenResolver cannot be null"); this.subjectTokenResolver = subjectTokenResolver; } /** * Sets the resolver used for resolving the {@link OAuth2Token actor token}. * @param actorTokenResolver the resolver used for resolving the {@link OAuth2Token * actor token} */ public void setActorTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver) { Assert.notNull(actorTokenResolver, "actorTokenResolver cannot be null"); this.actorTokenResolver = actorTokenResolver; } /** * 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\TokenExchangeReactiveOAuth2AuthorizedClientProvider.java
1
请完成以下Java代码
public void setLockedBy (int LockedBy) { set_Value (COLUMNNAME_LockedBy, Integer.valueOf(LockedBy)); } /** Get Locked By. @return User who locked this record */ public int getLockedBy () { Integer ii = (Integer)get_Value(COLUMNNAME_LockedBy); if (ii == null) return 0; return ii.intValue(); } /** Set Locked Date. @param LockedDate Date when this record was locked */ public void setLockedDate (Timestamp LockedDate) { set_Value (COLUMNNAME_LockedDate, LockedDate); } /** Get Locked Date. @return Date when this record was locked */ public Timestamp getLockedDate () { return (Timestamp)get_Value(COLUMNNAME_LockedDate); } /** Set Phone. @param Phone Identifies a telephone number */ public void setPhone (String Phone) { throw new IllegalArgumentException ("Phone is virtual column"); } /** Get Phone. @return Identifies a telephone number */ public String getPhone () { return (String)get_Value(COLUMNNAME_Phone); } public I_R_Group getR_Group() throws RuntimeException { return (I_R_Group)MTable.get(getCtx(), I_R_Group.Table_Name) .getPO(getR_Group_ID(), get_TrxName()); } /** Set Group. @param R_Group_ID Request Group */ public void setR_Group_ID (int R_Group_ID) { if (R_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_R_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID)); } /** Get Group. @return Request Group */ public int getR_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID);
if (ii == null) return 0; return ii.intValue(); } public I_R_Request getR_Request() throws RuntimeException { return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name) .getPO(getR_Request_ID(), get_TrxName()); } /** Set Request. @param R_Request_ID Request from a Business Partner or Prospect */ public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Request. @return Request from a Business Partner or Prospect */ public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_Status getR_Status() throws RuntimeException { return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name) .getPO(getR_Status_ID(), get_TrxName()); } /** Set Status. @param R_Status_ID Request Status */ public void setR_Status_ID (int R_Status_ID) { throw new IllegalArgumentException ("R_Status_ID is virtual column"); } /** Get Status. @return Request Status */ public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_R_Group_Prospect.java
1
请完成以下Java代码
public int getAD_SysConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_SysConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** ConfigurationLevel AD_Reference_ID=53222 */ public static final int CONFIGURATIONLEVEL_AD_Reference_ID=53222; /** System = S */ public static final String CONFIGURATIONLEVEL_System = "S"; /** Client = C */ public static final String CONFIGURATIONLEVEL_Client = "C"; /** Organization = O */ public static final String CONFIGURATIONLEVEL_Organization = "O"; /** Set Configuration Level. @param ConfigurationLevel Configuration Level for this parameter */ public void setConfigurationLevel (String ConfigurationLevel) { set_Value (COLUMNNAME_ConfigurationLevel, ConfigurationLevel); } /** Get Configuration Level. @return Configuration Level for this parameter */ public String getConfigurationLevel () { return (String)get_Value(COLUMNNAME_ConfigurationLevel); } /** 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); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SysConfig.java
1
请在Spring Boot框架中完成以下Java代码
public void regenerateTaxLines(final SAPGLJournalId glJournalId) { updateById(glJournalId, glJournal -> glJournal.regenerateTaxLines(taxProvider, currencyConverter)); } public DocStatus getDocStatus(final SAPGLJournalId glJournalId) { return glJournalRepository.getDocStatus(glJournalId); } @NonNull public SAPGLJournal reverse(@NonNull final SAPGLJournalReverseRequest reverseJournalRequest) { final SAPGLJournal journalToBeReversed = glJournalRepository.getById(reverseJournalRequest.getSourceJournalId()); final SAPGLJournal reversal = glJournalRepository.create(journalToBeReversed.getReversal(reverseJournalRequest.getDateDoc()), currencyConverter); glJournalRepository.save(journalToBeReversed.withDocStatus(DocStatus.Reversed)); return reversal; } @NonNull public SAPGLJournal copy(@NonNull final SAPGLJournalCopyRequest copyRequest) { final SAPGLJournal journalToBeCopied = glJournalRepository.getById(copyRequest.getSourceJournalId()); final SAPGLJournalCreateRequest createRequest = SAPGLJournalCreateRequest.of(journalToBeCopied, copyRequest.getDateDoc(), copyRequest.getNegateAmounts()); return glJournalRepository.create(createRequest, currencyConverter); } public void updateTrxInfo(final I_SAP_GLJournalLine glJournalLine) { final FAOpenItemTrxInfo openItemTrxInfo; final AccountId accountId = AccountId.ofRepoIdOrNull(glJournalLine.getC_ValidCombination_ID()); if (accountId != null) { final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(glJournalLine.getSAP_GLJournal_ID()); final SAPGLJournalLineId lineId; if (glJournalLine.getSAP_GLJournalLine_ID() <= 0) { lineId = glJournalRepository.acquireLineId(glJournalId); glJournalLine.setSAP_GLJournalLine_ID(lineId.getRepoId()); } else { lineId = SAPGLJournalLineId.ofRepoId(glJournalId, glJournalLine.getSAP_GLJournalLine_ID()); } openItemTrxInfo = computeTrxInfo(accountId, lineId).orElse(null); }
else { openItemTrxInfo = null; } SAPGLJournalLoaderAndSaver.updateRecordFromOpenItemTrxInfo(glJournalLine, openItemTrxInfo); } private Optional<FAOpenItemTrxInfo> computeTrxInfo( @NonNull final AccountId accountId, @NonNull final SAPGLJournalLineId sapGLJournalLineId) { return Optional.empty(); } public void fireAfterComplete(final I_SAP_GLJournal record) { final SAPGLJournal glJournal = glJournalRepository.getByRecord(record); faOpenItemsService.fireGLJournalCompleted(glJournal); } public void fireAfterReactivate(final I_SAP_GLJournal record) { final SAPGLJournal glJournal = glJournalRepository.getByRecord(record); faOpenItemsService.fireGLJournalReactivated(glJournal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalService.java
2
请在Spring Boot框架中完成以下Java代码
public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static SettModeTypeEnum getEnum(String enumName) { SettModeTypeEnum resultEnum = null; SettModeTypeEnum[] enumAry = SettModeTypeEnum.values(); for (int i = 0; i < enumAry.length; i++) { if (enumAry[i].name().equals(enumName)) { resultEnum = enumAry[i]; break; } } return resultEnum; } public static Map<String, Map<String, Object>> toMap() { SettModeTypeEnum[] ary = SettModeTypeEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); enumMap.put(key, map); }
return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { SettModeTypeEnum[] ary = SettModeTypeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); list.add(map); } return list; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\SettModeTypeEnum.java
2
请完成以下Java代码
public static ProcessPreconditionsResolution checkEligibleForHUsSelection(final I_M_InOut shipment) { // shipment must be completed or closed closed final String docStatus = shipment.getDocStatus(); if (!(docStatus.equals(X_M_InOut.DOCSTATUS_Completed) || docStatus.equals(X_M_InOut.DOCSTATUS_Closed))) { return ProcessPreconditionsResolution.reject("shipment not completed"); } final List<I_M_HU> shipmentHandlingUnits = Services.get(IHUInOutDAO.class).retrieveShippedHandlingUnits(shipment); if (shipmentHandlingUnits.isEmpty()) { return ProcessPreconditionsResolution.reject("shipment has no handling units assigned"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception
{ final I_M_InOut shipment = getRecord(I_M_InOut.class); final List<I_M_HU> shipmentHandlingUnits = Services.get(IHUInOutDAO.class).retrieveShippedHandlingUnits(shipment); getResult().setRecordToOpen(RecordsToOpen.builder() .records(TableRecordReference.ofCollection(shipmentHandlingUnits)) .adWindowId(null) .target(RecordsToOpen.OpenTarget.GridView) .targetTab(RecordsToOpen.TargetTab.SAME_TAB_OVERLAY) .automaticallySetReferencingDocumentPaths(true) .useAutoFilters(false) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_InOut_Shipment_SelectHUs.java
1
请在Spring Boot框架中完成以下Java代码
public class ItemType { @Id private Long id; @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "ITEM_TYPE_ID") private List<Item> items = new ArrayList<>(); private String name; public Long getId() { return id; } public List<Item> getItems() { return items; }
public String getName() { return name; } public void setId(Long id) { this.id = id; } public void setItems(List<Item> items) { this.items = items; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\boot\domain\ItemType.java
2
请完成以下Java代码
public boolean isMandatory() { return get_ValueAsBoolean(COLUMNNAME_IsMandatory); } @Override public void setIsPartUniqueIndex (final boolean IsPartUniqueIndex) { set_Value (COLUMNNAME_IsPartUniqueIndex, IsPartUniqueIndex); } @Override public boolean isPartUniqueIndex() { return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPosition (final int Position) { set_Value (COLUMNNAME_Position, Position); } @Override public int getPosition() { return get_ValueAsInt(COLUMNNAME_Position); } /** * Type AD_Reference_ID=53241 * Reference name: EXP_Line_Type */
public static final int TYPE_AD_Reference_ID=53241; /** XML Element = E */ public static final String TYPE_XMLElement = "E"; /** XML Attribute = A */ public static final String TYPE_XMLAttribute = "A"; /** Embedded EXP Format = M */ public static final String TYPE_EmbeddedEXPFormat = "M"; /** Referenced EXP Format = R */ public static final String TYPE_ReferencedEXPFormat = "R"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
1
请完成以下Java代码
public void reviewPicking() { reviewPicking(qtyPicked.toBigDecimal()); } private static PickingCandidateApprovalStatus computeApprovalStatus(final Quantity qtyPicked, final BigDecimal qtyReview, final PickingCandidatePickStatus pickStatus) { if (qtyReview == null) { return PickingCandidateApprovalStatus.TO_BE_APPROVED; } // final BigDecimal qtyReviewToMatch; if (pickStatus.isPickRejected()) { qtyReviewToMatch = BigDecimal.ZERO; } else { qtyReviewToMatch = qtyPicked.toBigDecimal(); } // if (qtyReview.compareTo(qtyReviewToMatch) == 0) { return PickingCandidateApprovalStatus.APPROVED; } else { return PickingCandidateApprovalStatus.REJECTED; } } private static PickingCandidatePickStatus computePickOrPackStatus(@Nullable final PackToSpec packToSpec) { return packToSpec != null ? PickingCandidatePickStatus.PACKED : PickingCandidatePickStatus.PICKED; } public boolean isPickFromPickingOrder() { return getPickFrom().isPickFromPickingOrder();
} public void issueToPickingOrder(@Nullable final List<PickingCandidateIssueToBOMLine> issuesToPickingOrder) { this.issuesToPickingOrder = issuesToPickingOrder != null ? ImmutableList.copyOf(issuesToPickingOrder) : ImmutableList.of(); } public PickingCandidateSnapshot snapshot() { return PickingCandidateSnapshot.builder() .id(getId()) .qtyReview(getQtyReview()) .pickStatus(getPickStatus()) .approvalStatus(getApprovalStatus()) .processingStatus(getProcessingStatus()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidate.java
1
请完成以下Java代码
public void setVariableType(VariableType variableType) { this.variableType = variableType; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public Date getLastUpdatedTime() { return lastUpdatedTime; } public void setLastUpdatedTime(Date lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; } @Override public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public Date getTime() { return getCreateTime(); } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue);
} if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } // non-supported (v6) @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
1
请完成以下Java代码
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers() .getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { logger.error("HttpResponseHandler unexpected message received: " + msg); return; } MapValues value = streamidMap.get(streamId); if (value == null) { logger.error("Message received for unknown stream id " + streamId); ctx.close(); } else { ByteBuf content = msg.content(); if (content.isReadable()) { int contentLength = content.readableBytes(); byte[] arr = new byte[contentLength]; content.readBytes(arr); String response = new String(arr, 0, contentLength, CharsetUtil.UTF_8); logger.info("Response from Server: "+ (response)); value.setResponse(response); } value.getPromise() .setSuccess(); } } public static class MapValues { ChannelFuture writeFuture; ChannelPromise promise; String response; public String getResponse() { return response;
} public void setResponse(String response) { this.response = response; } public MapValues(ChannelFuture writeFuture2, ChannelPromise promise2) { this.writeFuture = writeFuture2; this.promise = promise2; } public ChannelFuture getWriteFuture() { return writeFuture; } public ChannelPromise getPromise() { return promise; } } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\netty\http2\client\Http2ClientResponseHandler.java
1
请完成以下Java代码
public ActiveOrHistoricCurrencyAndAmount getCdtNoteAmt() { return cdtNoteAmt; } /** * Sets the value of the cdtNoteAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setCdtNoteAmt(ActiveOrHistoricCurrencyAndAmount value) { this.cdtNoteAmt = value; } /** * Gets the value of the taxAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getTaxAmt() { return taxAmt; } /** * Sets the value of the taxAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTaxAmt(ActiveOrHistoricCurrencyAndAmount value) { this.taxAmt = value; } /** * Gets the value of the adjstmntAmtAndRsn property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the adjstmntAmtAndRsn property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdjstmntAmtAndRsn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentAdjustment1 } *
* */ public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() { if (adjstmntAmtAndRsn == null) { adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>(); } return this.adjstmntAmtAndRsn; } /** * Gets the value of the rmtdAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() { return rmtdAmt; } /** * Sets the value of the rmtdAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) { this.rmtdAmt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceAmount1.java
1
请完成以下Java代码
private static final ImmutableMap<String, Object> convertMailHeadersToJson(final MultiValueMap<String, Object> mailRawHeaders) { return mailRawHeaders.entrySet() .stream() .map(entry -> GuavaCollectors.entry(entry.getKey(), convertListToJson(entry.getValue()))) .filter(entry -> entry.getValue() != null) .collect(GuavaCollectors.toImmutableMap()); } private static final Object convertListToJson(final List<Object> values) { if (values == null || values.isEmpty()) { return ImmutableList.of(); } else if (values.size() == 1) { return convertValueToJson(values.get(0)); }
else { return values.stream() .map(v -> convertValueToJson(v)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } } private static final Object convertValueToJson(final Object value) { if (value == null) { return null; } return value.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailMessageHandler.java
1
请在Spring Boot框架中完成以下Java代码
public LogoutResponseConfigurer logoutResponseResolver(Saml2LogoutResponseResolver logoutResponseResolver) { this.logoutResponseResolver = logoutResponseResolver; return this; } private Saml2LogoutResponseValidator logoutResponseValidator() { if (this.logoutResponseValidator != null) { return this.logoutResponseValidator; } if (USE_OPENSAML_5) { return new OpenSaml5LogoutResponseValidator(); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } private Saml2LogoutResponseResolver logoutResponseResolver(RelyingPartyRegistrationRepository registrations) { if (this.logoutResponseResolver != null) { return this.logoutResponseResolver; } if (USE_OPENSAML_5) { return new OpenSaml5LogoutResponseResolver(registrations); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } } private static class Saml2RequestMatcher implements RequestMatcher { private final SecurityContextHolderStrategy securityContextHolderStrategy; Saml2RequestMatcher(SecurityContextHolderStrategy securityContextHolderStrategy) { this.securityContextHolderStrategy = securityContextHolderStrategy; } @Override public boolean matches(HttpServletRequest request) { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); if (authentication == null) { return false; } if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal) {
return true; } if (authentication.getCredentials() instanceof Saml2ResponseAssertionAccessor) { return true; } return authentication instanceof Saml2Authentication; } } private static class Saml2RelyingPartyInitiatedLogoutFilter extends LogoutFilter { Saml2RelyingPartyInitiatedLogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) { super(logoutSuccessHandler, handlers); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2LogoutConfigurer.java
2
请完成以下Spring Boot application配置
logging.level.org.springframework=info management.endpoints.web.exposure.include=* spring.datasource.url=jdbc:h2:mem:testdb spring.h2.console.enabled=true spring.jpa.defer-datasource-initialization=true spring.jpa.show-sql=true #spring.datasource.url=jdbc:mysql://localhost:3306/social-media-database #spring.datasource.username=social-media-user #spring.datasource.password=dummypassword # #spring.jpa.hibernate.ddl-auto=update #spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect #spring.security.user.name=username #spring.security.user.password=password # \connect social-med
ia-user@localhost:3306 #docker run --detach #--env MYSQL_ROOT_PASSWORD=dummypassword #--env MYSQL_USER=social-media-user #--env MYSQL_PASSWORD=dummypassword #--env MYSQL_DATABASE=social-media-database #--name mysql #--publish 3306:3306 #mysql:8-oracle #
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\resources\application.properties
2
请完成以下Java代码
private IntVar[] getRowCells(IntVar[][] sudokuCells, int rowNum) { return sudokuCells[rowNum]; } private IntVar[] getColumnCells(IntVar[][] sudokuCells, int columnNum) { IntVar[] columnCells = new IntVar[9]; for (int i = 0; i < 9; i++) { columnCells[i] = sudokuCells[i][columnNum]; } return columnCells; } private IntVar[] getCellsInRange(int columnLb, int columnUb, int rowLb, int rowUb, IntVar[][] sudokuCells) { int size = (columnUb - columnLb + 1) * (rowUb - rowLb + 1); IntVar[] cellsInRange = new IntVar[size]; int index = 0; for (int i = rowLb; i <= rowUb; i++) { for (int j = columnLb; j <= columnUb; j++) { cellsInRange[index++] = sudokuCells[i][j]; } } return cellsInRange; } private Integer[][] getNineByNineMatrix(IntVar[] sudokuCells) { Integer[][] sudokuCellsMatrix = new Integer[9][9]; int index = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { sudokuCellsMatrix[i][j] = sudokuCells[index++].getValue(); }
} return sudokuCellsMatrix; } public void printSolution(Integer[][] solvedSudokuBoards) { StringBuilder stringBuilder = new StringBuilder("\n"); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { stringBuilder.append(solvedSudokuBoards[i][j]).append(" "); if ((j + 1) % 3 == 0 && (j + 1) % 9 != 0) { stringBuilder.append("| "); } } stringBuilder.append("\n"); if ((i + 1) % 3 == 0 && (i + 1) % 9 != 0) { stringBuilder.append("---------------------\n"); } } stringBuilder.append("\n"); logger.info(stringBuilder.toString()); } }
repos\tutorials-master\choco-solver\src\main\java\com\baeldung\cp\SudokuSolver.java
1
请完成以下Java代码
public final class BPartnerClassifier { public static BPartnerClassifier any() { return ANY; } public static BPartnerClassifier none() { return NONE; } public static BPartnerClassifier specific(@NonNull final BPartnerId bpartnerId) { return new BPartnerClassifier(BPartnerClassifierType.SPECIFIC, bpartnerId); } public static BPartnerClassifier specificOrNone(@Nullable final BPartnerId bpartnerId) { return bpartnerId != null ? specific(bpartnerId) : none(); } public static BPartnerClassifier specificOrAny(@Nullable final BPartnerId bpartnerId) { return bpartnerId != null ? specific(bpartnerId) : any(); } private static final BPartnerClassifier ANY = new BPartnerClassifier(BPartnerClassifierType.ANY, null); private static final BPartnerClassifier NONE = new BPartnerClassifier(BPartnerClassifierType.NONE, null); private enum BPartnerClassifierType { ANY, NONE, SPECIFIC } private final BPartnerClassifierType type; private final BPartnerId bpartnerId; private BPartnerClassifier(@NonNull final BPartnerClassifierType type, final BPartnerId bpartnerId) { this.type = type; this.bpartnerId = bpartnerId; } public boolean isAny() { return type == BPartnerClassifierType.ANY; } public boolean isNone() { return type == BPartnerClassifierType.NONE; } public boolean isSpecificBPartner() { return type == BPartnerClassifierType.SPECIFIC; } public BPartnerId getBpartnerId() {
if (type != BPartnerClassifierType.SPECIFIC) { throw new AdempiereException("Only specific types have bpartner ID but not " + this); } return bpartnerId; } public boolean isMatching(@NonNull final BPartnerClassifier other) { if (isAny()) { return true; } else if (isNone()) { return other.isAny() || other.isNone(); } else if (isSpecificBPartner()) { return other.isAny() || this.equals(other); } else { throw new IllegalStateException("Case not handled: this=" + this + ", other=" + other); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\commons\src\main\java\de\metas\material\commons\attributes\clasifiers\BPartnerClassifier.java
1
请在Spring Boot框架中完成以下Java代码
public class HttpTransportHealthChecker extends TransportHealthChecker<HttpTransportMonitoringConfig> { private RestTemplate restTemplate; protected HttpTransportHealthChecker(HttpTransportMonitoringConfig config, TransportMonitoringTarget target) { super(config, target); } @Override protected void initClient() throws Exception { if (restTemplate == null) { restTemplate = new RestTemplateBuilder() .setConnectTimeout(Duration.ofMillis(config.getRequestTimeoutMs())) .setReadTimeout(Duration.ofMillis(config.getRequestTimeoutMs())) .build(); log.debug("Initialized HTTP client"); } }
@Override protected void sendTestPayload(String payload) throws Exception { String accessToken = target.getDevice().getCredentials().getCredentialsId(); restTemplate.postForObject(target.getBaseUrl() + "/api/v1/" + accessToken + "/telemetry", payload, String.class); } @Override protected void destroyClient() throws Exception {} @Override protected TransportType getTransportType() { return TransportType.HTTP; } }
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\transport\impl\HttpTransportHealthChecker.java
2
请完成以下Java代码
public void run() { log.info(m_cmd); try { m_child = Runtime.getRuntime().exec(m_cmd); // m_outStream = m_child.getInputStream(); m_errStream = m_child.getErrorStream(); m_inStream = m_child.getOutputStream(); // if (checkInterrupted()) return; m_outReader.start(); m_errReader.start(); // try { if (checkInterrupted()) return; m_errReader.join(); if (checkInterrupted()) return; m_outReader.join(); if (checkInterrupted()) return; m_exitValue = m_child.waitFor(); //metas: c.ghita@metas.ro } catch (InterruptedException ie) { m_errorLog = m_errorLog+""+ie.getMessage(); //metas: c.ghita@metas.ro m_exitValue = -1;//metas: c.ghita@metas.ro log.info("(ie) - " + ie); } // ExitValue try { if (m_child != null) { log.debug("run - ExitValue=" + m_exitValue); //metas: c.ghita@metas.ro : start } } catch (Exception e) { m_exitValue = -1; //metas: c.ghita@metas.ro } log.info("done"); } catch (IOException ioe) { m_errorLog = m_errorLog+""+ioe.getMessage(); //metas: c.ghita@metas.ro m_exitValue = -1; //metas: c.ghita@metas.ro log.error("(ioe)", ioe); } } // run /** * Check if interrupted * @return true if interrupted */ private boolean checkInterrupted() { if (isInterrupted()) { log.info("interrupted"); // interrupt child processes if (m_child != null) m_child.destroy(); m_child = null; if (m_outReader != null && m_outReader.isAlive()) m_outReader.interrupt(); m_outReader = null; if (m_errReader != null && m_errReader.isAlive()) m_errReader.interrupt(); m_errReader = null; // close Streams if (m_inStream != null) try { m_inStream.close(); } catch (Exception e) {} m_inStream = null; if (m_outStream != null)
try { m_outStream.close(); } catch (Exception e) {} m_outStream = null; if (m_errStream != null) try { m_errStream.close(); } catch (Exception e) {} m_errStream = null; // return true; } return false; } // checkInterrupted /** * Get Out Info * @return StringBuffer */ public StringBuffer getOut() { return m_out; } // getOut /** * Get Err Info * @return StringBuffer */ public StringBuffer getErr() { return m_err; } // getErr /** * Get The process input stream - i.e. we output to it * @return OutputStream */ public OutputStream getInStream() { return m_inStream; } // getInStream /* * metas: c.ghita@metas.ro * if the value is 0, means that was a normal termination * get exit value */ public Integer getExitValue() { return m_exitValue; } /* * metas: c.ghita@metas.ro * get error log */ public String getErrorLog() { return m_errorLog; } } // Task
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Task.java
1
请完成以下Java代码
public final class UpperCaseQueryFilterModifier implements IQueryFilterModifier { public static final transient UpperCaseQueryFilterModifier instance = new UpperCaseQueryFilterModifier(); private UpperCaseQueryFilterModifier() { } @Override public @NonNull String getColumnSql(@NonNull String columnName) { final String columnSqlNew = "UPPER(" + columnName + ")"; return columnSqlNew; } @Override public String getValueSql(Object value, List<Object> params) { final String valueSql; if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; valueSql = modelValue.getColumnName(); } else
{ valueSql = "?"; params.add(value); } return "UPPER(" + valueSql + ")"; } @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return null; } final String str = (String)value; return str.toUpperCase(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\UpperCaseQueryFilterModifier.java
1
请在Spring Boot框架中完成以下Java代码
public void setS_Issue(de.metas.serviceprovider.model.I_S_Issue S_Issue) { set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue); } /** Set Issue. @param S_Issue_ID Issue */ @Override public void setS_Issue_ID (int S_Issue_ID) { if (S_Issue_ID < 1) set_Value (COLUMNNAME_S_Issue_ID, null); else set_Value (COLUMNNAME_S_Issue_ID, Integer.valueOf(S_Issue_ID)); } /** Get Issue. @return Issue */ @Override public int getS_Issue_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_S_Issue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalIssueDetail.java
2
请完成以下Java代码
public java.lang.String getMappingRuleValue() { return get_ValueAsString(COLUMNNAME_MappingRuleValue); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_Shipper_Mapping_Config_ID (final int M_Shipper_Mapping_Config_ID) {
if (M_Shipper_Mapping_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, M_Shipper_Mapping_Config_ID); } @Override public int getM_Shipper_Mapping_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_Mapping_Config_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_Mapping_Config.java
1
请完成以下Java代码
private I_M_PricingSystem getM_PricingSystem() { Check.assumeNotNull(_pricingSystem, "_pricingSystem not null"); return _pricingSystem; } public Builder setM_Material_Tracking(final I_M_Material_Tracking materialTracking) { _materialTracking = materialTracking; return this; } private int getM_Material_Tracking_ID() { Check.assumeNotNull(_materialTracking, "_materialTracking not null"); return _materialTracking.getM_Material_Tracking_ID(); } public Builder setAllProductionOrders(final List<IQualityInspectionOrder> qualityInspectionOrders) { _allProductionOrders = qualityInspectionOrders; return this; }
private List<IQualityInspectionOrder> getProductionOrders() { Check.assumeNotNull(_allProductionOrders, "_qualityInspectionOrders not null"); return _allProductionOrders; } public Builder setNotYetInvoicedProductionOrders(final List<IQualityInspectionOrder> qualityInspectionOrders) { _notYetInvoicedPPOrderIDs = new HashSet<>(); for (final IQualityInspectionOrder order : qualityInspectionOrders) { _notYetInvoicedPPOrderIDs.add(order.getPP_Order().getPP_Order_ID()); } return this; } private Set<Integer> getNotYetInvoicedPPOrderIDs() { Check.assumeNotNull(_notYetInvoicedPPOrderIDs, "_notYetInvoicedProductionOrders not null"); return _notYetInvoicedPPOrderIDs; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingDocumentsPricingInfo.java
1
请完成以下Java代码
public int getM_CostType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel
*/ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostQueue.java
1
请完成以下Java代码
public int getLine_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Line_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Line Stroke. @param LineStroke Width of the Line Stroke */ public void setLineStroke (BigDecimal LineStroke) { set_Value (COLUMNNAME_LineStroke, LineStroke); } /** Get Line Stroke. @return Width of the Line Stroke */ public BigDecimal getLineStroke () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineStroke); if (bd == null) return Env.ZERO; return bd; } /** LineStrokeType AD_Reference_ID=312 */ public static final int LINESTROKETYPE_AD_Reference_ID=312; /** Solid Line = S */ public static final String LINESTROKETYPE_SolidLine = "S"; /** Dashed Line = D */ public static final String LINESTROKETYPE_DashedLine = "D"; /** Dotted Line = d */ public static final String LINESTROKETYPE_DottedLine = "d"; /** Dash-Dotted Line = 2 */ public static final String LINESTROKETYPE_Dash_DottedLine = "2"; /** Set Line Stroke Type. @param LineStrokeType Type of the Line Stroke
*/ public void setLineStrokeType (String LineStrokeType) { set_Value (COLUMNNAME_LineStrokeType, LineStrokeType); } /** Get Line Stroke Type. @return Type of the Line Stroke */ public String getLineStrokeType () { return (String)get_Value(COLUMNNAME_LineStrokeType); } /** 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_PrintTableFormat.java
1
请在Spring Boot框架中完成以下Java代码
public String getBPartnerName(@NonNull final BPartnerId bpartnerId) { return bpartnerNamesCache.computeIfAbsent(bpartnerId, bpartnerService::getBPartnerName); } @Override public ZonedDateTime toZonedDateTime(@NonNull final java.sql.Timestamp timestamp, @NonNull final OrgId orgId) { final ZoneId zoneId = orgDAO.getTimeZone(orgId); return TimeUtil.asZonedDateTime(timestamp, zoneId); } @Override public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotIdAndCaptionsCache.computeIfAbsent(pickingSlotId, pickingSlotService::getPickingSlotIdAndCaption); } @Override public String getProductNo(@NonNull final ProductId productId) { return getProductInfo(productId).getProductNo(); } @Override public Optional<GS1ProductCodes> getGS1ProductCodes(@NonNull final ProductId productId, @Nullable final BPartnerId customerId) { return getProductInfo(productId).getGs1ProductCodes().getEffectiveCodes(customerId); } @Override public ProductCategoryId getProductCategoryId(@NonNull final ProductId productId) { return getProductInfo(productId).getProductCategoryId(); } @Override public ITranslatableString getProductName(@NonNull final ProductId productId) { return getProductInfo(productId).getName(); } private ProductInfo getProductInfo(@NonNull final ProductId productId) { return productInfoCache.computeIfAbsent(productId, productService::getById); } @Override public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId) { return huService.getPackingInfo(huPIItemProductId);
} @Override public String getPICaption(@NonNull final HuPackingInstructionsId piId) { return huService.getPI(piId).getName(); } @Override public String getLocatorName(@NonNull final LocatorId locatorId) { return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById); } @Override public HUQRCode getQRCodeByHUId(final HuId huId) { return huService.getQRCodeByHuId(huId); } @Override public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return pickingJobLockService.getLocks(scheduleIds); } @Override public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId) { return orderService.getSalesOrderLineSeqNo(orderAndLineId); } // // // }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java
2
请完成以下Java代码
public class AtomicOperationTransitionNotifyListenerStart extends AbstractEventAtomicOperation { @Override protected ScopeImpl getScope(InterpretableExecution execution) { return (ScopeImpl) execution.getActivity(); } @Override protected String getEventName() { return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_START; } @Override protected void eventNotificationsCompleted(InterpretableExecution execution) { TransitionImpl transition = execution.getTransition(); ActivityImpl destination = null;
if (transition == null) { // this is null after async cont. -> transition is not stored in execution destination = (ActivityImpl) execution.getActivity(); } else { destination = transition.getDestination(); } ActivityImpl activity = (ActivityImpl) execution.getActivity(); if (activity != destination) { ActivityImpl nextScope = AtomicOperationTransitionNotifyListenerTake.findNextScope(activity, destination); execution.setActivity(nextScope); execution.performOperation(TRANSITION_CREATE_SCOPE); } else { execution.setTransition(null); execution.setActivity(destination); execution.performOperation(ACTIVITY_EXECUTE); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationTransitionNotifyListenerStart.java
1
请完成以下Java代码
public class FormField implements Serializable { private static final long serialVersionUID = 1L; protected String id; protected String name; protected String type; protected Object value; protected boolean required; protected boolean readOnly; protected boolean overrideId; protected String placeholder; protected Map<String, Object> params; protected LayoutDefinition layout; public String getId() { return id; } public void setId(String id) { this.id = id; } 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 Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public boolean isReadOnly() { return readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } public boolean isOverrideId() { return overrideId; } public void setOverrideId(boolean overrideId) {
this.overrideId = overrideId; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public LayoutDefinition getLayout() { return layout; } public void setLayout(LayoutDefinition layout) { this.layout = layout; } @JsonInclude(Include.NON_EMPTY) public Map<String, Object> getParams() { return params; } public void setParams(Map<String, Object> params) { this.params = params; } @JsonIgnore public Object getParam(String name) { if (params != null) { return params.get(name); } return null; } }
repos\flowable-engine-main\modules\flowable-form-model\src\main\java\org\flowable\form\model\FormField.java
1
请完成以下Java代码
public static boolean verify(String ldapPassword, String inputPassword) throws NoSuchAlgorithmException { // MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1 MessageDigest md = MessageDigest.getInstance("SHA-1"); // 取出加密字符 if (ldapPassword.startsWith("{SSHA}")) { ldapPassword = ldapPassword.substring(6); } else if (ldapPassword.startsWith("{SHA}")) { ldapPassword = ldapPassword.substring(5); } // 解码BASE64 byte[] ldapPasswordByte = Base64.decode(ldapPassword); byte[] shaCode; byte[] salt; // 前20位是SHA-1加密段,20位后是最初加密时的随机明文 if (ldapPasswordByte.length <= 20) { shaCode = ldapPasswordByte; salt = new byte[0]; } else { shaCode = new byte[20]; salt = new byte[ldapPasswordByte.length - 20]; System.arraycopy(ldapPasswordByte, 0, shaCode, 0, 20); System.arraycopy(ldapPasswordByte, 20, salt, 0, salt.length); } // 把用户输入的密码添加到摘要计算信息
md.update(inputPassword.getBytes()); // 把随机明文添加到摘要计算信息 md.update(salt); // 按SSHA把当前用户密码进行计算 byte[] inputPasswordByte = md.digest(); // 返回校验结果 return MessageDigest.isEqual(shaCode, inputPasswordByte); } /** * Ascii转换为字符串 * * @param value Ascii串 * @return 字符串 */ public static String asciiToString(String value) { StringBuilder sbu = new StringBuilder(); String[] chars = value.split(","); for (String aChar : chars) { sbu.append((char) Integer.parseInt(aChar)); } return sbu.toString(); } }
repos\spring-boot-demo-master\demo-ldap\src\main\java\com\xkcoding\ldap\util\LdapUtils.java
1
请完成以下Java代码
public void notify(DelegateTask delegateTask) { // Note: we can't cache the result of the expression, because the // execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}' VariableScope variableScope = delegateTask.getExecution(); if (variableScope == null) { variableScope = delegateTask.getCaseExecution(); } Object delegate = expression.getValue(variableScope); applyFieldDeclaration(fieldDeclarations, delegate); if (delegate instanceof TaskListener) { try { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new TaskListenerInvocation((TaskListener)delegate, delegateTask)); }catch (Exception e) { throw new ProcessEngineException("Exception while invoking TaskListener: "+e.getMessage(), e); } } else { throw new ProcessEngineException("Delegate expression " + expression + " did not resolve to an implementation of " + TaskListener.class ); }
} /** * returns the expression text for this task listener. Comes in handy if you want to * check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); } public List<FieldDeclaration> getFieldDeclarations() { return fieldDeclarations; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\listener\DelegateExpressionTaskListener.java
1
请在Spring Boot框架中完成以下Java代码
public String delete(String id) { try { client.deleteById(db_core,id); client.commit(db_core); return id; } catch (Exception e) { e.printStackTrace(); } return "error"; } /** * 删除所有的索引 * @return */ @RequestMapping("deleteAll") public String deleteAll(){ try { solrService.deleteAll(db_core); return "success"; } catch (Exception e) { e.printStackTrace(); } return "error"; } /** * 根据id查询索引 * @return * @throws Exception */ @RequestMapping("getById/{id}") public String getById(@PathVariable String id) throws Exception { SolrDocument document = solrService.getById(db_core,id); System.out.println(document); return document.toString(); } /** * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息 * @return */ @RequestMapping("search/{q}") public SolrDocumentList search(@PathVariable String q){ SolrDocumentList results = null; try { results = solrService.querySolr(db_core,q,"keyword"); } catch (IOException e) { e.printStackTrace(); } catch (SolrServerException e) {
e.printStackTrace(); } return results; } /** * 文件创建索引 */ @RequestMapping("doc/dataimport") public String dataimport(){ // 1、清空索引,生产环境不建议这样使用,可以保存文件新建及更新时间,增量创建索引 try { solrService.deleteAll(file_core); } catch (Exception e) { e.printStackTrace(); } // 2、创建索引 Mono<String> result = WebClient.create(solrHost) .get() .uri(fileDataImport) .retrieve() .bodyToMono(String.class); System.out.println(result.block()); return "success"; } /** * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息 * @return */ @RequestMapping("doc/search/{q}") public SolrDocumentList docSearch(@PathVariable String q){ SolrDocumentList results = null; try { results = solrService.querySolr(file_core,q,"keyword"); } catch (IOException e) { e.printStackTrace(); } catch (SolrServerException e) { e.printStackTrace(); } return results; } }
repos\springboot-demo-master\solr\src\main\java\demo\et59\solr\controller\SolrController.java
2
请完成以下Java代码
public static VersionProperty of(String property) { return of(property, true); } /** * Specify if the property is internally defined and can be tuned according to the * build system. * @return {@code true} if the property is defined within the scope of this project */ public boolean isInternal() { return this.internal; } /** * Return a camel cased representation of this instance. * @return the property in camel case format */ public String toCamelCaseFormat() { String[] tokens = this.property.split("[-.]"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { String part = tokens[i]; if (i > 0) { part = StringUtils.capitalize(part); } sb.append(part); } return sb.toString(); } public String toStandardFormat() { return this.property; } private static String validateFormat(String property) { for (char c : property.toCharArray()) { if (Character.isUpperCase(c)) { throw new IllegalArgumentException("Invalid property '" + property + "', must not contain upper case"); } if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) { throw new IllegalArgumentException("Unsupported character '" + c + "' for '" + property + "'"); } } return property; }
@Override public int compareTo(VersionProperty o) { return this.property.compareTo(o.property); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VersionProperty that = (VersionProperty) o; return this.internal == that.internal && this.property.equals(that.property); } @Override public int hashCode() { return Objects.hash(this.property, this.internal); } @Override public String toString() { return this.property; } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionProperty.java
1
请完成以下Java代码
public void setTransfertTime (final @Nullable BigDecimal TransfertTime) { set_Value (COLUMNNAME_TransfertTime, TransfertTime); } @Override public BigDecimal getTransfertTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWorkingTime (final @Nullable BigDecimal WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public BigDecimal getWorkingTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WorkingTime); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield);
} @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } @Override public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID) { if (C_Manufacturing_Aggregation_ID < 1) set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null); else set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID); } @Override public int getC_Manufacturing_Aggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_Planning.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Gross Amount. @param GrossRAmt Gross Remuneration Amount */ public void setGrossRAmt (BigDecimal GrossRAmt) { set_Value (COLUMNNAME_GrossRAmt, GrossRAmt); } /** Get Gross Amount. @return Gross Remuneration Amount */ public BigDecimal getGrossRAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrossRAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Gross Cost. @param GrossRCost Gross Remuneration Costs */ public void setGrossRCost (BigDecimal GrossRCost) { set_Value (COLUMNNAME_GrossRCost, GrossRCost); } /** Get Gross Cost. @return Gross Remuneration Costs */ public BigDecimal getGrossRCost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrossRCost); if (bd == null) return Env.ZERO; return bd; } /** Set Overtime Amount. @param OvertimeAmt Hourly Overtime Rate */ public void setOvertimeAmt (BigDecimal OvertimeAmt) { set_Value (COLUMNNAME_OvertimeAmt, OvertimeAmt); } /** Get Overtime Amount. @return Hourly Overtime Rate */ public BigDecimal getOvertimeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Overtime Cost. @param OvertimeCost Hourly Overtime Cost */ public void setOvertimeCost (BigDecimal OvertimeCost) { set_Value (COLUMNNAME_OvertimeCost, OvertimeCost); } /** Get Overtime Cost.
@return Hourly Overtime Cost */ public BigDecimal getOvertimeCost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost); if (bd == null) return Env.ZERO; return bd; } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UserRemuneration.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductBOMRestController { private final BOMRestService bomRestService; public ProductBOMRestController(final BOMRestService bomRestService) { this.bomRestService = bomRestService; } @ApiOperation("Create a new bill of material version.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully created bill of material"), @ApiResponse(code = 401, message = "You are not authorized to perform this action"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(code = 422, message = "The request entity could not be processed") }) @PutMapping("{orgCode}") public ResponseEntity<?> createBOMs( @ApiParam(required = true, value = "Organisation within to create the bom formula.")
@PathVariable("orgCode") @Nullable final String orgCode, @RequestBody @NonNull final JsonBOMCreateRequest request) { try { final JsonBOMCreateResponse bomId = bomRestService.createBOMs(orgCode, request); return ResponseEntity.ok().body(bomId); } catch (final Exception ex) { final JsonError error = JsonError.ofSingleItem(JsonErrors.ofThrowable(ex, Env.getADLanguageOrBaseLanguage())); return ResponseEntity.unprocessableEntity().body(error); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bom\ProductBOMRestController.java
2
请完成以下Java代码
public boolean isLandscape () { Object oo = get_Value(COLUMNNAME_IsLandscape); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Label Height. @param LabelHeight Height of the label */ public void setLabelHeight (int LabelHeight) { set_Value (COLUMNNAME_LabelHeight, Integer.valueOf(LabelHeight)); } /** Get Label Height. @return Height of the label */ public int getLabelHeight () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelHeight); if (ii == null) return 0; return ii.intValue(); } /** Set Label Width. @param LabelWidth Width of the Label */ public void setLabelWidth (int LabelWidth) { set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth)); } /** Get Label Width. @return Width of the Label */ public int getLabelWidth () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Printer Name. @param PrinterName Name of the Printer */ public void setPrinterName (String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } /** Get Printer Name. @return Name of the Printer */ public String getPrinterName () { return (String)get_Value(COLUMNNAME_PrinterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java
1
请完成以下Java代码
public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return Dies ist ein manueller Vorgang */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenznummer. @param ReferenceNo Ihre Kunden- oder Lieferantennummer beim Geschäftspartner
*/ @Override public void setReferenceNo (java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } /** Get Referenznummer. @return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public java.lang.String getReferenceNo () { return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo.java
1
请在Spring Boot框架中完成以下Java代码
protected Logger getLogger() { return this.logger; } private boolean isGemFireDotPrefixedProperty(@NonNull String propertyName) { return StringUtils.hasText(propertyName) && propertyName.startsWith(GEMFIRE_PROPERTY_PREFIX); } private boolean isNotSet(Properties gemfireProperties, String propertyName) { return !gemfireProperties.containsKey(normalizeGemFirePropertyName(propertyName)); } private boolean isValidGemFireProperty(String propertyName) { try { GemFireProperties.from(normalizeGemFirePropertyName(propertyName)); return true;
} catch (IllegalArgumentException cause) { getLogger().warn(String.format("[%s] is not a valid Apache Geode property", propertyName)); // TODO: uncomment line below and replace line above when SBDG is rebased on SDG 2.3.0.RC2 or later. //getLogger().warn(cause.getMessage()); return false; } } private String normalizeGemFirePropertyName(@NonNull String propertyName) { int index = propertyName.lastIndexOf("."); return index > -1 ? propertyName.substring(index + 1) : propertyName; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\EnvironmentSourcedGemFirePropertiesAutoConfiguration.java
2
请完成以下Java代码
public java.lang.String getEventName() { return get_ValueAsString(COLUMNNAME_EventName); } @Override public void setEventTime (final @Nullable java.sql.Timestamp EventTime) { set_ValueNoCheck (COLUMNNAME_EventTime, EventTime); } @Override public java.sql.Timestamp getEventTime() { return get_ValueAsTimestamp(COLUMNNAME_EventTime); } @Override public void setEventTopicName (final @Nullable java.lang.String EventTopicName) { set_Value (COLUMNNAME_EventTopicName, EventTopicName); } @Override public java.lang.String getEventTopicName() { return get_ValueAsString(COLUMNNAME_EventTopicName); } /** * EventTypeName AD_Reference_ID=540802 * Reference name: EventTypeName */ public static final int EVENTTYPENAME_AD_Reference_ID=540802; /** LOCAL = LOCAL */ public static final String EVENTTYPENAME_LOCAL = "LOCAL"; /** DISTRIBUTED = DISTRIBUTED */ public static final String EVENTTYPENAME_DISTRIBUTED = "DISTRIBUTED"; @Override public void setEventTypeName (final @Nullable java.lang.String EventTypeName) { set_Value (COLUMNNAME_EventTypeName, EventTypeName); } @Override public java.lang.String getEventTypeName() { return get_ValueAsString(COLUMNNAME_EventTypeName); } @Override public void setEvent_UUID (final java.lang.String Event_UUID) { set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID); }
@Override public java.lang.String getEvent_UUID() { return get_ValueAsString(COLUMNNAME_Event_UUID); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setIsErrorAcknowledged (final boolean IsErrorAcknowledged) { set_Value (COLUMNNAME_IsErrorAcknowledged, IsErrorAcknowledged); } @Override public boolean isErrorAcknowledged() { return get_ValueAsBoolean(COLUMNNAME_IsErrorAcknowledged); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog.java
1
请完成以下Java代码
public TimeRange getRange() { return range; } public Builder datasetsComputeDuration(@Nullable final Duration datasetsComputeDuration) { this.datasetsComputeDuration = datasetsComputeDuration; return this; } public void putValue( @NonNull final String dataSetName, @NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSet(dataSetName).putValue(dataSetValueKey, fieldName, value); } public void putValueIfAbsent( @NonNull final String dataSetName, @NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value)
{ dataSet(dataSetName).putValueIfAbsent(dataSetValueKey, fieldName, value); } public Builder error(@NonNull final Exception exception) { final ITranslatableString errorMessage = AdempiereException.isUserValidationError(exception) ? AdempiereException.extractMessageTrl(exception) : TranslatableStrings.adMessage(MSG_FailedLoadingKPI); this.error = WebuiError.of(exception, errorMessage); return this; } public Builder error(@NonNull final ITranslatableString errorMessage) { this.error = WebuiError.of(errorMessage); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataResult.java
1
请完成以下Java代码
public void setRelativeToCurrent(boolean relativeToCurrent) { this.relativeToCurrent = relativeToCurrent; } public @Nullable SeekPosition getPosition() { return this.position; } public @Nullable Function<Long, Long> getOffsetComputeFunction() { return this.offsetComputeFunction; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TopicPartitionOffset that = (TopicPartitionOffset) o; return Objects.equals(this.topicPartition, that.topicPartition) && Objects.equals(this.position, that.position); } @Override
public int hashCode() { return Objects.hash(this.topicPartition, this.position); } @Override public String toString() { return "TopicPartitionOffset{" + "topicPartition=" + this.topicPartition + ", offset=" + this.offset + ", relativeToCurrent=" + this.relativeToCurrent + (this.position == null ? "" : (", position=" + this.position.name())) + '}'; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\TopicPartitionOffset.java
1
请完成以下Java代码
public void onSuccess() { } @Override public void onFailure(Throwable t) { } }; default UUID getId() { return EntityId.NULL_UUID; } void onSuccess();
void onFailure(Throwable t); static <V> TbCallback wrap(SettableFuture<V> future) { return new TbCallback() { @Override public void onSuccess() { future.set(null); } @Override public void onFailure(Throwable t) { future.setException(t); } }; } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\queue\TbCallback.java
1
请完成以下Java代码
public I_C_UOM getUomById(final UomId uomId) { return uomsCache.computeIfAbsent(uomId, uomDAO::getById); } public I_C_UOM getUomByProductId(final ProductId productId) { final UomId uomId = getProductById(productId).getUomId(); return getUomById(uomId); } private void warmUpUOMs(final Collection<UomId> uomIds) { if (uomIds.isEmpty()) { return; }
CollectionUtils.getAllOrLoad(uomsCache, uomIds, this::retrieveUOMsByIds); } private Map<UomId, I_C_UOM> retrieveUOMsByIds(final Collection<UomId> uomIds) { final List<I_C_UOM> uoms = uomDAO.getByIds(uomIds); return Maps.uniqueIndex(uoms, uom -> UomId.ofRepoId(uom.getC_UOM_ID())); } public ImmutableSet<WarehouseId> getAllActiveWarehouseIds() { return warehouseRepository.getAllActiveIds(); } public Warehouse getWarehouseById(@NonNull final WarehouseId warehouseId) { return warehouseRepository.getById(warehouseId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowCache.java
1
请完成以下Java代码
private static PrivateKeyHolder loadPrivateKey(PemSslStoreDetails details, ResourceLoader resourceLoader) throws IOException { PemContent pemContent = PemContent.load(details.privateKey(), resourceLoader); return new PrivateKeyHolder( (pemContent != null) ? pemContent.getPrivateKey(details.privateKeyPassword()) : null); } @Override public @Nullable String type() { return this.details.type(); } @Override public @Nullable String alias() { return this.details.alias(); } @Override public @Nullable String password() { return this.details.password(); } @Override public @Nullable List<X509Certificate> certificates() { return this.certificatesSupplier.get().certificates(); } @Override public @Nullable PrivateKey privateKey() {
return this.privateKeySupplier.get().privateKey(); } @Override public PemSslStore withAlias(@Nullable String alias) { return new LoadedPemSslStore(this.details.withAlias(alias), this.resourceLoader); } @Override public PemSslStore withPassword(@Nullable String password) { return new LoadedPemSslStore(this.details.withPassword(password), this.resourceLoader); } private record PrivateKeyHolder(@Nullable PrivateKey privateKey) { } private record CertificatesHolder(@Nullable List<X509Certificate> certificates) { } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\LoadedPemSslStore.java
1
请在Spring Boot框架中完成以下Java代码
public String productInfo(Integer id) { return "商品编号:" + id; } // 手动使用 Sentinel 客户端 API @GetMapping("/entry_demo") public String entryDemo() { Entry entry = null; try { // 访问资源 entry = SphU.entry("entry_demo"); // ... 执行业务逻辑 return "执行成功"; } catch (BlockException ex) { return "被拒绝"; } finally { // 释放资源 if (entry != null) { entry.exit(); } } }
// 测试 @SentinelResource 注解 @GetMapping("/annotations_demo") @SentinelResource(value = "annotations_demo_resource", blockHandler = "blockHandler", fallback = "fallback") public String annotationsDemo(@RequestParam(required = false) Integer id) throws InterruptedException { if (id == null) { throw new IllegalArgumentException("id 参数不允许为空"); } return "success..."; } // BlockHandler 处理函数,参数最后多一个 BlockException,其余与原函数一致. public String blockHandler(Integer id, BlockException ex) { return "block:" + ex.getClass().getSimpleName(); } // Fallback 处理函数,函数签名与原函数一致或加一个 Throwable 类型的参数. public String fallback(Integer id, Throwable throwable) { return "fallback:" + throwable.getMessage(); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\controller\DemoController.java
2
请在Spring Boot框架中完成以下Java代码
public class AlipayCore { /** 私有构造函数 **/ private AlipayCore(){} /** * 除去数组中的空值和签名参数 * @param sArray 签名参数组 * @return 去掉空值与签名参数后的新签名参数组 */ public static Map<String, String> paraFilter(Map<String, String> sArray) { Map<String, String> result = new HashMap<String, String>(); if (sArray == null || sArray.isEmpty()) { return result; } for (String key : sArray.keySet()) { String value = sArray.get(key); if (value == null || "".equals(value) || "sign".equalsIgnoreCase(key) || "sign_type".equalsIgnoreCase(key)) { continue; } result.put(key, value); } return result; } /** * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串 * @param params 需要排序并参与字符拼接的参数组 * @return 拼接后字符串 */ public static String createLinkString(Map<String, String> params) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); String prestr = ""; for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = params.get(key); if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value; } else { prestr = prestr + key + "=" + value + "&"; } } return prestr; } /** * 生成文件摘要 * @param strFilePath 文件路径 * @param file_digest_type 摘要算法 * @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if("MD5".equals(file_digest_type)){ return DigestUtils.md5Hex(file.createInputStream()); } else if("SHA".equals(file_digest_type)) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\alipay\util\AlipayCore.java
2
请在Spring Boot框架中完成以下Java代码
public class GetBPartnerFromFileRouteBuilder extends IdAwareRouteBuilder { @VisibleForTesting public static final String UPSERT_BPARTNER_ENDPOINT_ID = "GetBPartnerFromFileRouteBuilder.UPSERT_BPARTNER_ENDPOINT_ID"; @VisibleForTesting public static final String UPSERT_BPARTNER_PROCESSOR_ID = "GetBPartnerFromFileRouteBuilder.UPSERT_BPARTNER_PROCESSOR_ID"; @NonNull private final BPartnerFileEndpointConfig fileEndpointConfig; @Getter @NonNull private final String routeId; @NonNull private final JsonExternalSystemRequest enabledByExternalSystemRequest; @NonNull private final PInstanceLogger pInstanceLogger; @Builder private GetBPartnerFromFileRouteBuilder( @NonNull final BPartnerFileEndpointConfig fileEndpointConfig, @NonNull final CamelContext camelContext, @NonNull final String routeId, @NonNull final JsonExternalSystemRequest enabledByExternalSystemRequest, @NonNull final ProcessLogger processLogger) { super(camelContext); this.fileEndpointConfig = fileEndpointConfig; this.routeId = routeId; this.enabledByExternalSystemRequest = enabledByExternalSystemRequest; this.pInstanceLogger = PInstanceLogger.builder() .pInstanceId(enabledByExternalSystemRequest.getAdPInstanceId()) .processLogger(processLogger) .build(); } @Override public void configure() { //@formatter:off from(fileEndpointConfig.getBPartnerFileEndpoint()) .id(routeId) .streamCache("true") .log("Business Partner Sync Route Started with Id=" + routeId)
.process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest)) .split(body().tokenize("\n")) .streaming() .process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest)) .filter(new SkipFirstLinePredicate()) .doTry() .unmarshal(new BindyCsvDataFormat(BPartnerRow.class)) .process(getBPartnerUpsertProcessor()).id(UPSERT_BPARTNER_PROCESSOR_ID) .choice() .when(bodyAs(BPUpsertCamelRequest.class).isNull()) .log(LoggingLevel.INFO, "Nothing to do! No bpartner to upsert!") .otherwise() .log(LoggingLevel.DEBUG, "Calling metasfresh-api to upsert Business Partners: ${body}") .to("{{" + MF_UPSERT_BPARTNER_V2_CAMEL_URI + "}}").id(UPSERT_BPARTNER_ENDPOINT_ID) .endChoice() .end() .endDoTry() .doCatch(Throwable.class) .to(direct(ERROR_WRITE_TO_ADISSUE)) .end() .end(); //@formatter:on } @NonNull private BPartnerUpsertProcessor getBPartnerUpsertProcessor() { return BPartnerUpsertProcessor.builder() .externalSystemRequest(enabledByExternalSystemRequest) .pInstanceLogger(pInstanceLogger) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\bpartner\GetBPartnerFromFileRouteBuilder.java
2
请完成以下Java代码
class CostRevaluationDocumentHandler implements DocumentHandler { private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); private final CostRevaluationService costRevaluationService; CostRevaluationDocumentHandler( @NonNull final CostRevaluationService costRevaluationService) { this.costRevaluationService = costRevaluationService; } private static I_M_CostRevaluation extractRecord(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_M_CostRevaluation.class); } @Override public String getSummary(final DocumentTableFields docFields) { return extractRecord(docFields).getDocumentNo(); } @Override public String getDocumentInfo(final DocumentTableFields docFields) { return getSummary(docFields); } @Override public int getDoc_User_ID(final DocumentTableFields docFields) { return extractRecord(docFields).getCreatedBy(); } @Override public LocalDate getDocumentDate(final DocumentTableFields docFields) { final I_M_CostRevaluation record = extractRecord(docFields); return TimeUtil.asLocalDate(record.getDateAcct(), orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID()))); }
@Override public String completeIt(final DocumentTableFields docFields) { final I_M_CostRevaluation costRevaluation = extractRecord(docFields); final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(costRevaluation.getDocStatus()); if (!docStatus.isDraftedOrInProgress()) { throw new AdempiereException("Invalid document status"); } final CostRevaluationId costRevaluationId = CostRevaluationId.ofRepoId(costRevaluation.getM_CostRevaluation_ID()); if (!costRevaluationService.hasActiveLines(costRevaluationId)) { throw new AdempiereException("@NoLines@"); } // Make sure all lines are evaluated costRevaluationService.createDetails(costRevaluationId); costRevaluation.setDocAction(IDocument.ACTION_None); return DocStatus.Completed.getCode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\CostRevaluationDocumentHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void setPrice(Double price) { this.price = price; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BookDTO bookDTO = (BookDTO) o; if (bookDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), bookDTO.getId()); } @Override
public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "BookDTO{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", author='" + getAuthor() + "'" + ", published='" + getPublished() + "'" + ", quantity=" + getQuantity() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\BookDTO.java
2
请完成以下Java代码
public void setDDOrderDetailType (final java.lang.String DDOrderDetailType) { set_Value (COLUMNNAME_DDOrderDetailType, DDOrderDetailType); } @Override public java.lang.String getDDOrderDetailType() { return get_ValueAsString(COLUMNNAME_DDOrderDetailType); } @Override public org.eevolution.model.I_DD_OrderLine getDD_OrderLine() { return get_ValueAsPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class); } @Override public void setDD_OrderLine(final org.eevolution.model.I_DD_OrderLine DD_OrderLine) { set_ValueFromPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class, DD_OrderLine); } @Override public void setDD_OrderLine_ID (final int DD_OrderLine_ID) { if (DD_OrderLine_ID < 1) set_Value (COLUMNNAME_DD_OrderLine_ID, null); else set_Value (COLUMNNAME_DD_OrderLine_ID, DD_OrderLine_ID); } @Override public int getDD_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID); } @Override public void setMD_Cockpit_DDOrder_Detail_ID (final int MD_Cockpit_DDOrder_Detail_ID) { if (MD_Cockpit_DDOrder_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Cockpit_DDOrder_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Cockpit_DDOrder_Detail_ID, MD_Cockpit_DDOrder_Detail_ID); } @Override public int getMD_Cockpit_DDOrder_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Cockpit_DDOrder_Detail_ID); } @Override public de.metas.material.cockpit.model.I_MD_Cockpit getMD_Cockpit() {
return get_ValueAsPO(COLUMNNAME_MD_Cockpit_ID, de.metas.material.cockpit.model.I_MD_Cockpit.class); } @Override public void setMD_Cockpit(final de.metas.material.cockpit.model.I_MD_Cockpit MD_Cockpit) { set_ValueFromPO(COLUMNNAME_MD_Cockpit_ID, de.metas.material.cockpit.model.I_MD_Cockpit.class, MD_Cockpit); } @Override public void setMD_Cockpit_ID (final int MD_Cockpit_ID) { if (MD_Cockpit_ID < 1) set_Value (COLUMNNAME_MD_Cockpit_ID, null); else set_Value (COLUMNNAME_MD_Cockpit_ID, MD_Cockpit_ID); } @Override public int getMD_Cockpit_ID() { return get_ValueAsInt(COLUMNNAME_MD_Cockpit_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQtyPending (final BigDecimal QtyPending) { set_Value (COLUMNNAME_QtyPending, QtyPending); } @Override public BigDecimal getQtyPending() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPending); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit_DDOrder_Detail.java
1
请完成以下Java代码
public void setDescription (final @Nullable String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setEndpointName (final String EndpointName) { set_Value (COLUMNNAME_EndpointName, EndpointName); } @Override public String getEndpointName() { return get_ValueAsString(COLUMNNAME_EndpointName); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Config_ScriptedImportConversion_ID (final int ExternalSystem_Config_ScriptedImportConversion_ID) { if (ExternalSystem_Config_ScriptedImportConversion_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID, ExternalSystem_Config_ScriptedImportConversion_ID); } @Override public int getExternalSystem_Config_ScriptedImportConversion_ID() {
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setScriptIdentifier (final String ScriptIdentifier) { set_Value (COLUMNNAME_ScriptIdentifier, ScriptIdentifier); } @Override public String getScriptIdentifier() { return get_ValueAsString(COLUMNNAME_ScriptIdentifier); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ScriptedImportConversion.java
1
请完成以下Java代码
private static void updateContextFromADClientValue(final Properties ctx, final String AD_Client_Value) { if (Check.isEmpty(AD_Client_Value, true)) { throw new ReplicationException(MSG_XMLClientValueMandatory); } final int adClientId; try { adClientId = getADClientIdByValue(ctx, AD_Client_Value, ITrx.TRXNAME_None); } catch (final Exception e) { throw new ReplicationException(MSG_XMLClientNotFound, e) .setParameter(I_AD_Client.COLUMNNAME_Value, AD_Client_Value); } if (adClientId < 0) { throw new ReplicationException(MSG_XMLClientNotFound) .setParameter(I_AD_Client.COLUMNNAME_Value, AD_Client_Value); } setReplicationCtx(ctx, Env.CTXNAME_AD_Client_ID, adClientId, false); } private static void updateContextFromSession(final Properties ctx, final int adSessionId) { if (adSessionId <= 0) { s_log.debug("Skip because there is not AD_Session_ID"); return; } final MFSession session = Services.get(ISessionBL.class).getSessionById(ctx, adSessionId); if (session == null) { s_log.debug("Skip because no session found for ID: {}", adSessionId); return; } if (session.isDestroyed()) { s_log.debug("Skip because session is already processed: {}", session); return; }
// Update context from session session.updateContext(ctx); setReplicationCtx(ctx, Env.CTXNAME_AD_Client_ID, session.getAD_Client_ID(), false); setReplicationCtx(ctx, Env.CTXNAME_AD_Session_ID, adSessionId, false); setReplicationCtx(ctx, Env.CTXNAME_AD_Role_ID, session.getAD_Role_ID(), true); setReplicationCtx(ctx, Env.CTXNAME_Date, session.getLoginDate(), true); setReplicationCtx(ctx, Env.CTXNAME_AD_Org_ID, session.getAD_Org_ID(), true); setReplicationCtx(ctx, Env.CTXNAME_AD_User_ID, session.getAD_User_ID(), true); } private Object getXMLValue(final String xPathExpression, final Node rootNode, final I_EXP_FormatLine formatLine) throws XPathExpressionException { final String value = XMLHelper.getString(xPathExpression, rootNode); if (!Check.isEmpty(value)) { return value; } // Default value String defaultValue = null; final String defaultValueExpr = formatLine.getDefaultValue(); if (!Check.isEmpty(defaultValueExpr, true)) { defaultValue = Env.parseContext(ctx, 0, defaultValueExpr, false, true); // onlyWindow=false, ignoreUnparsable=true } return defaultValue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\server\rpl\api\impl\ImportHelper.java
1
请完成以下Java代码
public void setC_LicenseFeeSettingsLine_ID (final int C_LicenseFeeSettingsLine_ID) { if (C_LicenseFeeSettingsLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, C_LicenseFeeSettingsLine_ID); } @Override public int getC_LicenseFeeSettingsLine_ID() { return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettingsLine_ID); } @Override public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints) { set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); }
@Override public BigDecimal getPercentOfBasePoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettingsLine.java
1
请完成以下Java代码
private void softRefresh(String cacheKeyStr) { // 加一个分布式锁,只放一个请求去刷新缓存 RedisLock redisLock = new RedisLock((RedisTemplate<String, Object>) redisOperations, cacheKeyStr + "_lock"); try { if (redisLock.tryLock()) { redisOperations.expire(cacheKeyStr, this.expirationSecondTime, TimeUnit.SECONDS); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { redisLock.unlock(); } } /** * 硬刷新(走数据库) * * @param cacheKeyStr */ @SuppressWarnings("unchecked") private void forceRefresh(String cacheKeyStr) { // 尽量少的去开启线程,因为线程池是有限的 ThreadTaskUtils.run(new Runnable() { @Override public void run() { // 加一个分布式锁,只放一个请求去刷新缓存 RedisLock redisLock = new RedisLock((RedisTemplate<String, Object>) redisOperations, cacheKeyStr + "_lock"); try { if (redisLock.lock()) { // 获取锁之后再判断一下过期时间,看是否需要加载数据 Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr); if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) { // 通过获取代理方法信息重新加载缓存数据 CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), cacheKeyStr); } } } catch (Exception e) { logger.info(e.getMessage(), e); } finally { redisLock.unlock(); } } }); } /** * 获取缓存的有效时间 * * @return */ public long getExpirationSecondTime() {
return expirationSecondTime; } /** * 获取RedisCacheKey * * @param key * @return */ public RedisCacheKey getRedisCacheKey(Object key) { return new RedisCacheKey(key).usePrefix(this.prefix) .withKeySerializer(redisOperations.getKeySerializer()); } /** * 获取RedisCacheKey * * @param key * @return */ public String getCacheKey(Object key) { return new String(getRedisCacheKey(key).getKeyBytes()); } /** * 是否强制刷新(走数据库),默认是false * * @return */ public boolean getForceRefresh() { return forceRefresh; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\redis\cache\CustomizedRedisCache.java
1
请完成以下Java代码
public LU mergeWith(@NonNull final LU other) { if (this.hu.getM_HU_ID() != other.hu.getM_HU_ID()) { throw new AdempiereException("Cannot merge " + this + " with " + other + " because they don't have the same HU"); } return builder() .hu(this.hu) .isPreExistingLU(this.isPreExistingLU && other.isPreExistingLU) .tus(this.tus.mergeWith(other.tus)) .build(); } private static List<LU> mergeLists(final List<LU> list1, final List<LU> list2) { if (list2.isEmpty()) { return list1; } if (list1.isEmpty()) { return list2; } else {
final HashMap<HuId, LU> lusNew = new HashMap<>(); list1.forEach(lu -> lusNew.put(lu.getId(), lu)); list2.forEach(lu -> lusNew.compute(lu.getId(), (luId, existingLU) -> existingLU == null ? lu : existingLU.mergeWith(lu))); return ImmutableList.copyOf(lusNew.values()); } } public boolean containsAnyOfHUIds(final Collection<HuId> huIds) { if (huIds.isEmpty()) {return false;} return huIds.contains(getId()) // LU matches || tus.containsAnyOfHUIds(huIds); // any of the TU matches } public void forEachAffectedHU(@NonNull final LUTUCUConsumer consumer) { tus.forEachAffectedHU(this, consumer); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\LUTUResult.java
1
请完成以下Java代码
public String getCaseExecutionId() { return caseExecutionId; } public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public long getSequenceCounter() { return sequenceCounter; } public void setSequenceCounter(long sequenceCounter) { this.sequenceCounter = sequenceCounter; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } // persistent object implementation ///////////////
public Object getPersistentState() { // events are immutable return HistoryEvent.class; } // state inspection public boolean isEventOfType(HistoryEventType type) { return type.getEventName().equals(eventType); } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEvent.java
1
请在Spring Boot框架中完成以下Java代码
public EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() { return this.embeddedDatabaseConnection; } public void setEmbeddedDatabaseConnection(EmbeddedDatabaseConnection embeddedDatabaseConnection) { this.embeddedDatabaseConnection = embeddedDatabaseConnection; } public ClassLoader getClassLoader() { return this.classLoader; } public Xa getXa() { return this.xa; } public void setXa(Xa xa) { this.xa = xa; } /** * XA Specific datasource settings. */ public static class Xa { /** * XA datasource fully qualified name. */ private @Nullable String dataSourceClassName; /** * Properties to pass to the XA data source. */ private Map<String, String> properties = new LinkedHashMap<>(); public @Nullable String getDataSourceClassName() { return this.dataSourceClassName; } public void setDataSourceClassName(@Nullable String dataSourceClassName) { this.dataSourceClassName = dataSourceClassName; } public Map<String, String> getProperties() { return this.properties; }
public void setProperties(Map<String, String> properties) { this.properties = properties; } } static class DataSourceBeanCreationException extends BeanCreationException { private final DataSourceProperties properties; private final EmbeddedDatabaseConnection connection; DataSourceBeanCreationException(String message, DataSourceProperties properties, EmbeddedDatabaseConnection connection) { super(message); this.properties = properties; this.connection = connection; } DataSourceProperties getProperties() { return this.properties; } EmbeddedDatabaseConnection getConnection() { return this.connection; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java
2
请完成以下Java代码
public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) { this.permissionEvaluator = permissionEvaluator; } private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) { if (role == null) { return role; } if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) { return role; } if (role.startsWith(defaultRolePrefix)) { return role; } return defaultRolePrefix + role; } @Override public Object getFilterObject() { return this.filterObject; }
@Override public Object getReturnObject() { return this.returnObject; } @Override public Object getThis() { return this; } @Override public void setFilterObject(Object obj) { this.filterObject = obj; } @Override public void setReturnObject(Object obj) { this.returnObject = obj; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java
1
请完成以下Java代码
public class ShipmentScheduleSegmentFromHU implements IShipmentScheduleSegment { // services private final transient IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class); private final Set<Integer> bpartnerIds = new HashSet<>(); private final Set<Integer> bpartnersIdsRO = Collections.unmodifiableSet(bpartnerIds); // private final Set<Integer> locatorIds = new HashSet<>(); private final Set<Integer> locatorsIdsRO = Collections.unmodifiableSet(locatorIds); // private Set<Integer> productIdsRO = null; // lazy init // private final int huId; private final boolean hasQtyOnHandChanges; public ShipmentScheduleSegmentFromHU(@NonNull final I_M_HU hu) { huId = hu.getM_HU_ID(); final I_M_HU huOld = InterfaceWrapperHelper.createOld(hu, I_M_HU.class); boolean hasQtyOnHandChanges = false; final boolean isQtyOnHandOld = huStatusBL.isQtyOnHand(huOld.getHUStatus()); final boolean isQtyOnHand = huStatusBL.isQtyOnHand(hu.getHUStatus()); if (isQtyOnHandOld) { bpartnerIds.add(huOld.getC_BPartner_ID()); locatorIds.add(huOld.getM_Locator_ID()); hasQtyOnHandChanges = true; } if (isQtyOnHand) { bpartnerIds.add(hu.getC_BPartner_ID()); locatorIds.add(hu.getM_Locator_ID()); hasQtyOnHandChanges = true; } this.hasQtyOnHandChanges = hasQtyOnHandChanges; // If there are no QtyOnHand changes, set no products // => prevent triggering any change... because there is not if (!hasQtyOnHandChanges) { productIdsRO = Collections.emptySet(); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("bpartnerIds", bpartnerIds) .add("locatorIds", locatorIds) .add("productIdsRO", productIdsRO) .add("huId", huId) .add("hasQtyOnHandChanges", hasQtyOnHandChanges) .toString(); } @Override public Set<Integer> getProductIds() { if (productIdsRO != null) { return productIdsRO;
} // // Extract affected products final List<Integer> productIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Storage.class, Env.getCtx(), ITrx.TRXNAME_None) .addEqualsFilter(I_M_HU_Storage.COLUMNNAME_M_HU_ID, huId) .andCollect(I_M_HU_Storage.COLUMNNAME_M_Product_ID, I_M_Product.class) .create() .listIds(); productIdsRO = Collections.unmodifiableSet(new HashSet<>(productIdsList)); return productIdsRO; } @Override public Set<Integer> getBpartnerIds() { return bpartnersIdsRO; } @Override public Set<Integer> getLocatorIds() { return locatorsIdsRO; } public boolean hasQtyOnHandChanges() { return hasQtyOnHandChanges; } @Override public Set<Integer> getBillBPartnerIds() { return ImmutableSet.of(); } @Override public Set<ShipmentScheduleAttributeSegment> getAttributes() { return ImmutableSet.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\segments\ShipmentScheduleSegmentFromHU.java
1
请在Spring Boot框架中完成以下Java代码
public StringFilter getSymbol() { return symbol; } public void setSymbol(StringFilter symbol) { this.symbol = symbol; } public BigDecimalFilter getPrice() { return price; } public void setPrice(BigDecimalFilter price) { this.price = price; } public ZonedDateTimeFilter getLastTrade() { return lastTrade; } public void setLastTrade(ZonedDateTimeFilter lastTrade) { this.lastTrade = lastTrade; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final QuoteCriteria that = (QuoteCriteria) o;
return Objects.equals(id, that.id) && Objects.equals(symbol, that.symbol) && Objects.equals(price, that.price) && Objects.equals(lastTrade, that.lastTrade); } @Override public int hashCode() { return Objects.hash( id, symbol, price, lastTrade ); } @Override public String toString() { return "QuoteCriteria{" + (id != null ? "id=" + id + ", " : "") + (symbol != null ? "symbol=" + symbol + ", " : "") + (price != null ? "price=" + price + ", " : "") + (lastTrade != null ? "lastTrade=" + lastTrade + ", " : "") + "}"; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteCriteria.java
2
请完成以下Java代码
private void configureProcessingContext(final IMutableHUContext huContext) { if (!HUConstants.isUseCacheWhenCreatingHUs()) { return; } final boolean configured = huContext.isPropertyTrue(IHUContext.PROPERTY_Configured); if (configured) { return; } final IHUStorageDAO storageDAO = new SaveOnCommitHUStorageDAO(); final DefaultHUStorageFactory huStorageFactory = new DefaultHUStorageFactory(storageDAO); huContext.setHUStorageFactory(huStorageFactory); final SaveOnCommitHUAttributesDAO huAttributesDAO = new SaveOnCommitHUAttributesDAO(); final IAttributeStorageFactoryService attributeStorageFactoryService = Services.get(IAttributeStorageFactoryService.class); final IAttributeStorageFactory attributesStorageFactory = attributeStorageFactoryService .prepareHUAttributeStorageFactory(huAttributesDAO); huContext.setHUAttributeStorageFactory(attributesStorageFactory); } @Override public IMutableHUContext createMutableHUContext( @NonNull final Properties ctx, @NonNull final ClientAndOrgId clientAndOrgId) { final Properties ctxEffective = Env.copyCtx(ctx); Env.setClientId(ctxEffective, clientAndOrgId.getClientId()); Env.setOrgId(ctxEffective, clientAndOrgId.getOrgId()); return new MutableHUContext(ctxEffective, ITrx.TRXNAME_None); } // TODO: probably will have to add ClientAndOrgId here as well. I don't have time for this now @Override public IMutableHUContext createMutableHUContext(final Properties ctx, @NonNull final String trxName) { final PlainContextAware contextProvider = PlainContextAware.newWithTrxName(ctx, trxName); return new MutableHUContext(contextProvider); } @Override public IMutableHUContext createMutableHUContext(final IContextAware contextProvider) { return new MutableHUContext(contextProvider); } @Override public final IHUContext deriveWithTrxName(final IHUContext huContext, final String trxNameNew) { // FIXME: handle the case of SaveOnCommit Storage and Attributes when changing transaction name
// // Check: if transaction name was not changed, do nothing, return the old context final String contextTrxName = huContext.getTrxName();// // TODO tbp: here the context has wrong org. WHYYYYY final ITrxManager trxManager = Services.get(ITrxManager.class); if (trxManager.isSameTrxName(contextTrxName, trxNameNew)) { return huContext; } final IMutableHUContext huContextNew = huContext.copyAsMutable(); huContextNew.setTrxName(trxNameNew); configureProcessingContext(huContextNew); return huContextNew; } @Override public String toString() { return "HUContextFactory []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUContextFactory.java
1
请完成以下Java代码
public void setPhone(final String phone) { this.phone = phone; this.phoneSet = true; } public void setLanguage(final String language) { this.language = language; this.languageSet = true; } public void setInvoiceRule(final JsonInvoiceRule invoiceRule) { this.invoiceRule = invoiceRule; this.invoiceRuleSet = true; } public void setPOInvoiceRule(final JsonInvoiceRule invoiceRule) { this.poInvoiceRule = invoiceRule; this.poInvoiceRuleSet = true; } public void setUrl(final String url) { this.url = url; this.urlSet = true; } public void setUrl2(final String url2) { this.url2 = url2; this.url2Set = true; } public void setUrl3(final String url3) { this.url3 = url3; this.url3Set = true; } public void setGroup(final String group) { this.group = group; this.groupSet = true; }
public void setGlobalId(final String globalId) { this.globalId = globalId; this.globalIdset = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setVatId(final String vatId) { this.vatId = vatId; this.vatIdSet = true; } public void setMemo(final String memo) { this.memo = memo; this.memoIsSet = true; } public void setPriceListId(@Nullable final JsonMetasfreshId priceListId) { if (JsonMetasfreshId.toValue(priceListId) != null) { this.priceListId = priceListId; this.priceListIdSet = true; } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestBPartner.java
1
请完成以下Java代码
public List<MigrationInstructionDto> getInstructions() { return instructions; } public void setInstructions(List<MigrationInstructionDto> instructions) { this.instructions = instructions; } public Map<String, VariableValueDto> getVariables() { return variables; } public void setVariables(Map<String, VariableValueDto> variables) { this.variables = variables; } public static MigrationPlanDto from(MigrationPlan migrationPlan) { MigrationPlanDto dto = new MigrationPlanDto(); VariableMap variables = migrationPlan.getVariables(); if (variables != null) { dto.setVariables(VariableValueDto.fromMap(variables)); } dto.setSourceProcessDefinitionId(migrationPlan.getSourceProcessDefinitionId()); dto.setTargetProcessDefinitionId(migrationPlan.getTargetProcessDefinitionId()); ArrayList<MigrationInstructionDto> instructionDtos = new ArrayList<MigrationInstructionDto>(); if (migrationPlan.getInstructions() != null) { for (MigrationInstruction migrationInstruction : migrationPlan.getInstructions()) { MigrationInstructionDto migrationInstructionDto = MigrationInstructionDto.from(migrationInstruction); instructionDtos.add(migrationInstructionDto); } } dto.setInstructions(instructionDtos);
return dto; } public static MigrationPlan toMigrationPlan(ProcessEngine processEngine, ObjectMapper objectMapper, MigrationPlanDto migrationPlanDto) { MigrationPlanBuilder migrationPlanBuilder = processEngine.getRuntimeService().createMigrationPlan(migrationPlanDto.getSourceProcessDefinitionId(), migrationPlanDto.getTargetProcessDefinitionId()); Map<String, VariableValueDto> variableDtos = migrationPlanDto.getVariables(); if (variableDtos != null) { Map<String, Object> variables = VariableValueDto.toMap(variableDtos, processEngine, objectMapper); migrationPlanBuilder.setVariables(variables); } if (migrationPlanDto.getInstructions() != null) { for (MigrationInstructionDto migrationInstructionDto : migrationPlanDto.getInstructions()) { MigrationInstructionBuilder migrationInstructionBuilder = migrationPlanBuilder.mapActivities(migrationInstructionDto.getSourceActivityIds().get(0), migrationInstructionDto.getTargetActivityIds().get(0)); if (Boolean.TRUE.equals(migrationInstructionDto.isUpdateEventTrigger())) { migrationInstructionBuilder = migrationInstructionBuilder.updateEventTrigger(); } migrationPlanBuilder = migrationInstructionBuilder; } } return migrationPlanBuilder.build(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationPlanDto.java
1
请完成以下Java代码
public HistoricTaskInstanceQuery createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(commandExecutor, processEngineConfiguration.getDatabaseType()); } public HistoricDetailQuery createHistoricDetailQuery() { return new HistoricDetailQueryImpl(commandExecutor); } @Override public NativeHistoricDetailQuery createNativeHistoricDetailQuery() { return new NativeHistoricDetailQueryImpl(commandExecutor); } public HistoricVariableInstanceQuery createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(commandExecutor); } @Override public NativeHistoricVariableInstanceQuery createNativeHistoricVariableInstanceQuery() { return new NativeHistoricVariableInstanceQueryImpl(commandExecutor); } public void deleteHistoricTaskInstance(String taskId) { commandExecutor.execute(new DeleteHistoricTaskInstanceCmd(taskId)); } public void deleteHistoricProcessInstance(String processInstanceId) { commandExecutor.execute(new DeleteHistoricProcessInstanceCmd(processInstanceId)); }
public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() { return new NativeHistoricProcessInstanceQueryImpl(commandExecutor); } public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() { return new NativeHistoricTaskInstanceQueryImpl(commandExecutor); } public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() { return new NativeHistoricActivityInstanceQueryImpl(commandExecutor); } @Override public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId)); } @Override public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null)); } @Override public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) { return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoryServiceImpl.java
1
请完成以下Java代码
public static PPOrderId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PPOrderId(repoId) : null; } public static Optional<PPOrderId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final PPOrderId PPOrderId) { return PPOrderId != null ? PPOrderId.getRepoId() : -1; } int repoId; private PPOrderId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final PPOrderId id1, @Nullable final PPOrderId id2) {return Objects.equals(id1, id2);} public TableRecordReference toRecordRef() {return TableRecordReference.of(I_PP_Order.Table_Name, this);} public static PPOrderId ofRecordRef(@NonNull final TableRecordReference recordRef) {return recordRef.getIdAssumingTableName(I_PP_Order.Table_Name, PPOrderId::ofRepoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\eevolution\api\PPOrderId.java
1
请在Spring Boot框架中完成以下Java代码
public class AvailableForSalesResult { @NonNull AvailableForSalesQuery availableForSalesQuery; @NonNull ProductId productId; @NonNull AttributesKey storageAttributesKey; @NonNull OrgId orgId; @NonNull
Quantities quantities; @NonNull WarehouseId warehouseId; @Value @Builder public static class Quantities { @NonNull BigDecimal qtyOnHandStock; @NonNull BigDecimal qtyToBeShipped; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesResult.java
2