instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void stockCheckRetry(OrderCreatedEvent orderCreatedEvent) { logger.info("Message received: {}", orderCreatedEvent); orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSING); inventoryService.checkInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity()); orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSED); logger.info("Message processed successfully: {}", orderCreatedEvent); } @SqsListener(value = "${events.queues.order-processing-async-queue}", acknowledgementMode = SqsListenerAcknowledgementMode.MANUAL, id = "async-order-processing-container", messageVisibilitySeconds = "3") public void slowStockCheckAsynchronous(OrderCreatedEvent orderCreatedEvent, Acknowledgement acknowledgement) { logger.info("Message received: {}", orderCreatedEvent); orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSING); CompletableFuture.runAsync(() -> inventoryService.slowCheckInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity())) .thenRun(() -> orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSED))
.thenCompose(voidFuture -> acknowledgement.acknowledgeAsync()) .thenRun(() -> logger.info("Message for order {} acknowledged", orderCreatedEvent.id())); logger.info("Releasing processing thread."); } @SqsListener(value = "${events.queues.order-processing-no-retries-queue}", acknowledgementMode = "${events.acknowledgment.order-processing-no-retries-queue}", id = "no-retries-order-processing-container", messageVisibilitySeconds = "3") public void stockCheckNoRetries(OrderCreatedEvent orderCreatedEvent) { logger.info("Message received: {}", orderCreatedEvent); // Fire and forget scenario where we're not interested on the outcome, e.g. a sales event with limited inventory. orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.RECEIVED); inventoryService.checkInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity()); logger.info("Message processed: {}", orderCreatedEvent); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\acknowledgement\listener\OrderProcessingListeners.java
1
请完成以下Java代码
public Integer getControlBehavior() { return controlBehavior; } public void setControlBehavior(Integer controlBehavior) { this.controlBehavior = controlBehavior; } public Integer getWarmUpPeriodSec() { return warmUpPeriodSec; } public void setWarmUpPeriodSec(Integer warmUpPeriodSec) { this.warmUpPeriodSec = warmUpPeriodSec; } public Integer getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public void setMaxQueueingTimeMs(Integer maxQueueingTimeMs) { this.maxQueueingTimeMs = maxQueueingTimeMs; } public boolean isClusterMode() { return clusterMode; } public FlowRuleEntity setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; return this; } public ClusterFlowConfig getClusterConfig() { return clusterConfig; } public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) { this.clusterConfig = clusterConfig; return this; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; }
@Override public FlowRule toRule() { FlowRule flowRule = new FlowRule(); flowRule.setCount(this.count); flowRule.setGrade(this.grade); flowRule.setResource(this.resource); flowRule.setLimitApp(this.limitApp); flowRule.setRefResource(this.refResource); flowRule.setStrategy(this.strategy); if (this.controlBehavior != null) { flowRule.setControlBehavior(controlBehavior); } if (this.warmUpPeriodSec != null) { flowRule.setWarmUpPeriodSec(warmUpPeriodSec); } if (this.maxQueueingTimeMs != null) { flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); } flowRule.setClusterMode(clusterMode); flowRule.setClusterConfig(clusterConfig); return flowRule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java
1
请完成以下Java代码
public boolean isScriptEditor() { if (scriptEditor != null) { return scriptEditor; } final VEditor editor = getEditor(); if (editor == null) { return false; } final GridField gridField = editor.getField(); final String columnName = gridField.getColumnName(); if (columnName == null) { return false; } if (columnName.equals("Script") || columnName.endsWith("_Script")) { scriptEditor = true; } else { scriptEditor = false; } return scriptEditor; } @Override public String getName() { return isScriptEditor() ? "Script" : "Editor"; } @Override public String getIcon() { return isScriptEditor() ? "Script16" : "Editor16"; } @Override public boolean isAvailable() { final GridField gridField = getEditor().getField(); if (gridField == null) { return false; } final int displayType = gridField.getDisplayType(); if (displayType == DisplayType.Text || displayType == DisplayType.URL) { if (gridField.getFieldLength() > gridField.getDisplayLength()) { return true; } else { return false; } } else if (displayType == DisplayType.TextLong || displayType == DisplayType.Memo) { return true; } else { return false; } } @Override public boolean isRunnable() { return true; } @Override public void run() { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); final Object value = editor.getValue(); final String text = value == null ? null : value.toString();
final boolean editable = editor.isReadWrite(); final String textNew = startEditor(gridField, text, editable); if (editable) { gridField.getGridTab().setValue(gridField, textNew); } // TODO: i think is handled above // Data Binding // try // { // fireVetoableChange(m_columnName, m_oldText, getText()); // } // catch (PropertyVetoException pve) // { // } } protected String startEditor(final GridField gridField, final String text, final boolean editable) { final Properties ctx = Env.getCtx(); final String columnName = gridField.getColumnName(); final String title = Services.get(IMsgBL.class).translate(ctx, columnName); final int windowNo = gridField.getWindowNo(); final Frame frame = Env.getWindow(windowNo); final String textNew; if (gridField.getDisplayType() == DisplayType.TextLong) { // Start it HTMLEditor ed = new HTMLEditor (frame, title, text, editable); textNew = ed.getHtmlText(); } else { final Container comp = (Container)getEditor(); final int fieldLength = gridField.getFieldLength(); textNew = Editor.startEditor(comp, title, text, editable, fieldLength); } return textNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\TextEditorContextMenuAction.java
1
请完成以下Java代码
public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() { return parsedDeploymentBuilderFactory; } public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) { this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory; } public BpmnDeploymentHelper getBpmnDeploymentHelper() { return bpmnDeploymentHelper; } public void setBpmnDeploymentHelper(BpmnDeploymentHelper bpmnDeploymentHelper) { this.bpmnDeploymentHelper = bpmnDeploymentHelper; } public CachingAndArtifactsManager getCachingAndArtifcatsManager() {
return cachingAndArtifactsManager; } public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) { this.cachingAndArtifactsManager = manager; } public void setDisableExistingStartEventSubscriptions(boolean disableExistingStartEventSubscriptions) { this.disableExistingStartEventSubscriptions = disableExistingStartEventSubscriptions; } public boolean shouldDisableExistingStartEventSubscriptions() { return disableExistingStartEventSubscriptions; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请完成以下Java代码
public boolean isIncludeCaseVariables() { return includeCaseVariables; } public Collection<String> getVariableNamesToInclude() { return variableNamesToInclude; } public List<HistoricCaseInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public boolean isNeedsCaseDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(HistoricCaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName()); } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; }
public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) { this.safeCaseInstanceIds = safeCaseInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricCaseInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
ClientRSocketConnector clientRSocketConnector(IntegrationProperties integrationProperties, RSocketStrategies rSocketStrategies) { IntegrationProperties.RSocket.Client client = integrationProperties.getRsocket().getClient(); ClientRSocketConnector clientRSocketConnector; if (client.getUri() != null) { clientRSocketConnector = new ClientRSocketConnector(client.getUri()); } else if (client.getHost() != null && client.getPort() != null) { clientRSocketConnector = new ClientRSocketConnector(client.getHost(), client.getPort()); } else { throw new IllegalStateException("Neither uri nor host and port is set"); } clientRSocketConnector.setRSocketStrategies(rSocketStrategies); return clientRSocketConnector; } /** * Check if a remote address is configured for the RSocket Integration client. */ static class RemoteRSocketServerAddressConfigured extends AnyNestedCondition { RemoteRSocketServerAddressConfigured() { super(ConfigurationPhase.REGISTER_BEAN); }
@ConditionalOnProperty("spring.integration.rsocket.client.uri") static class WebSocketAddressConfigured { } @ConditionalOnProperty({ "spring.integration.rsocket.client.host", "spring.integration.rsocket.client.port" }) static class TcpAddressConfigured { } } } } }
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void setSMaxAge(@Nullable Duration sMaxAge) { this.customized = true; this.sMaxAge = sMaxAge; } public @Nullable CacheControl toHttpCacheControl() { PropertyMapper map = PropertyMapper.get(); CacheControl control = createCacheControl(); map.from(this::getMustRevalidate).whenTrue().toCall(control::mustRevalidate); map.from(this::getNoTransform).whenTrue().toCall(control::noTransform); map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic); map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate); map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate); map.from(this::getStaleWhileRevalidate) .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); map.from(this::getStaleIfError) .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); map.from(this::getSMaxAge) .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); // check if cacheControl remained untouched if (control.getHeaderValue() == null) { return null; } return control; } private CacheControl createCacheControl() { if (Boolean.TRUE.equals(this.noStore)) { return CacheControl.noStore(); } if (Boolean.TRUE.equals(this.noCache)) { return CacheControl.noCache(); }
if (this.maxAge != null) { return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS); } return CacheControl.empty(); } private boolean hasBeenCustomized() { return this.customized; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\WebProperties.java
2
请完成以下Java代码
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { log.info("[I68] <<< filter"); EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE); if (!"GET".equalsIgnoreCase(requestContext.getMethod())) { EntityTransaction t = em.getTransaction(); if (t.isActive()) { if (!t.getRollbackOnly()) { t.commit(); } } } em.close(); } }
@Path("/") public static class CarsRootLocator extends ODataRootLocator { private CarsODataJPAServiceFactory serviceFactory; public CarsRootLocator(CarsODataJPAServiceFactory serviceFactory) { this.serviceFactory = serviceFactory; } @Override public ODataServiceFactory getServiceFactory() { return this.serviceFactory; } } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\JerseyConfig.java
1
请完成以下Java代码
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 CachingMetadataManager metadata() throws MetadataProviderException, ResourceException { List<MetadataProvider> providers = new ArrayList<>(); providers.add(oktaExtendedMetadataProvider()); CachingMetadataManager metadataManager = new CachingMetadataManager(providers); metadataManager.setDefaultIDP(defaultIdp); return metadataManager; } @Bean @Qualifier("saml") public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() { SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successRedirectHandler.setDefaultTargetUrl("/home"); return successRedirectHandler; } @Bean @Qualifier("saml") public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() { SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler(); failureHandler.setUseForward(true); failureHandler.setDefaultFailureUrl("/error"); return failureHandler; } @Bean public SimpleUrlLogoutSuccessHandler successLogoutHandler() { SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler(); successLogoutHandler.setDefaultTargetUrl("/"); return successLogoutHandler; } @Bean public SecurityContextLogoutHandler logoutHandler() { SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler(); logoutHandler.setInvalidateHttpSession(true); logoutHandler.setClearAuthentication(true); return logoutHandler; } @Bean public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() { return new SAMLLogoutProcessingFilter(successLogoutHandler(), logoutHandler()); } @Bean
public SAMLLogoutFilter samlLogoutFilter() { return new SAMLLogoutFilter(successLogoutHandler(), new LogoutHandler[] { logoutHandler() }, new LogoutHandler[] { logoutHandler() }); } @Bean public HTTPPostBinding httpPostBinding() { return new HTTPPostBinding(parserPool(), VelocityFactory.getEngine()); } @Bean public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() { return new HTTPRedirectDeflateBinding(parserPool()); } @Bean public SAMLProcessorImpl processor() { ArrayList<SAMLBinding> bindings = new ArrayList<>(); bindings.add(httpRedirectDeflateBinding()); bindings.add(httpPostBinding()); return new SAMLProcessorImpl(bindings); } }
repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\SamlSecurityConfig.java
2
请完成以下Java代码
public void parseText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { if (trie != null) { BaseSearcher searcher = this.getSearcher(text); int offset; Map.Entry<String, CoreDictionary.Attribute> entry; while ((entry = searcher.next()) != null) { offset = searcher.getOffset(); processor.hit(offset, offset + entry.getKey().length(), entry.getValue()); } } DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = dat.getSearcher(text, 0); while (searcher.next()) { processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value); } } /** * 最长匹配 * * @param text 文本 * @param processor 处理器 */ public void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { if (trie != null) { final int[] lengthArray = new int[text.length()]; final CoreDictionary.Attribute[] attributeArray = new CoreDictionary.Attribute[text.length()]; char[] charArray = text.toCharArray(); DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = dat.getSearcher(charArray, 0); while (searcher.next()) { lengthArray[searcher.begin] = searcher.length; attributeArray[searcher.begin] = searcher.value; } trie.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute>() { @Override public void hit(int begin, int end, CoreDictionary.Attribute value) { int length = end - begin; if (length > lengthArray[begin]) { lengthArray[begin] = length; attributeArray[begin] = value; } }
}); for (int i = 0; i < charArray.length; ) { if (lengthArray[i] == 0) { ++i; } else { processor.hit(i, i + lengthArray[i], attributeArray[i]); i += lengthArray[i]; } } } else dat.parseLongestText(text, processor); } /** * 热更新(重新加载)<br> * 集群环境(或其他IOAdapter)需要自行删除缓存文件(路径 = HanLP.Config.CustomDictionaryPath[0] + Predefine.BIN_EXT) * * @return 是否加载成功 */ public boolean reload() { if (path == null || path.length == 0) return false; IOUtil.deleteFile(path[0] + Predefine.BIN_EXT); // 删掉缓存 return loadMainDictionary(path[0], normalization); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\DynamicCustomDictionary.java
1
请完成以下Java代码
public class ShipmentScheduleDeliveryDayBL implements IShipmentScheduleDeliveryDayBL { @Override public IDeliveryDayAllocable asDeliveryDayAllocable(final I_M_ShipmentSchedule sched) { return ShipmentScheduleDeliveryDayHandler.INSTANCE.asDeliveryDayAllocable(sched); } @Override public <T extends I_M_ShipmentSchedule> T getShipmentScheduleOrNull( @Nullable final IDeliveryDayAllocable deliveryDayAllocable, @NonNull final Class<T> modelClass) { if (deliveryDayAllocable == null) { return null; } else if (deliveryDayAllocable instanceof ShipmentScheduleDeliveryDayAllocable) { final ShipmentScheduleDeliveryDayAllocable shipmentScheduleDeliveryDayAllocable = (ShipmentScheduleDeliveryDayAllocable)deliveryDayAllocable; final I_M_ShipmentSchedule shipmentSchedule = shipmentScheduleDeliveryDayAllocable.getM_ShipmentSchedule(); return InterfaceWrapperHelper.create(shipmentSchedule, modelClass); } else { return null;
} } @Override public final void updateDeliveryDayInfo(@NonNull final I_M_ShipmentSchedule sched) { // Get Delivery Day Allocation final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(sched); final IDeliveryDayAllocable deliveryDayAllocable = asDeliveryDayAllocable(sched); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable); if (deliveryDayAlloc == null) { return; } InterfaceWrapperHelper.save(deliveryDayAlloc); // make sure is saved } @Override public ZonedDateTime getDeliveryDateCurrent(final I_M_ShipmentSchedule sched) { return Services.get(IShipmentScheduleEffectiveBL.class).getDeliveryDate(sched); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\ShipmentScheduleDeliveryDayBL.java
1
请完成以下Java代码
public class SpringExpressionManager extends ExpressionManager { protected ApplicationContext applicationContext; /** * @param applicationContext * the applicationContext to use. Ignored when 'beans' parameter is not null. * @param beans * a map of custom beans to expose. If null, all beans in the application-context will be exposed. */ public SpringExpressionManager(ApplicationContext applicationContext, Map<Object, Object> beans) { super(beans); this.applicationContext = applicationContext; } @Override protected ELResolver createElResolver(VariableScope variableScope) { CompositeELResolver compositeElResolver = new CompositeELResolver(); compositeElResolver.add(new VariableScopeElResolver(variableScope));
if (beans != null) { // Only expose limited set of beans in expressions compositeElResolver.add(new ReadOnlyMapELResolver(beans)); } else { // Expose full application-context in expressions compositeElResolver.add(new ApplicationContextElResolver(applicationContext)); } compositeElResolver.add(new ArrayELResolver()); compositeElResolver.add(new ListELResolver()); compositeElResolver.add(new MapELResolver()); compositeElResolver.add(new BeanELResolver()); return compositeElResolver; } }
repos\flowable-engine-main\modules\flowable5-spring\src\main\java\org\activiti\spring\SpringExpressionManager.java
1
请在Spring Boot框架中完成以下Java代码
public TokenStore jdbcTokenStore() { return new JdbcTokenStore(dataSource); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .tokenStore(jdbcTokenStore()); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.checkTokenAccess("isAuthenticated()"); // oauthServer.tokenKeyAccess("isAuthenticated()") // .checkTokenAccess("isAuthenticated()");
// oauthServer.tokenKeyAccess("permitAll()") // .checkTokenAccess("permitAll()"); } @Bean public ClientDetailsService jdbcClientDetailsService() { return new JdbcClientDetailsService(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.withClientDetails(jdbcClientDetailsService()); } }
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo11-authorization-server-by-jdbc-store\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\OAuth2AuthorizationServerConfig.java
2
请完成以下Java代码
public CostPrice add(final CostPrice costPrice) { if (!UomId.equals(this.getUomId(), costPrice.getUomId())) { throw new AdempiereException("UOM does not match: " + this + ", " + costPrice); } return builder() .ownCostPrice(getOwnCostPrice().add(costPrice.getOwnCostPrice())) .componentsCostPrice(getComponentsCostPrice().add(costPrice.getComponentsCostPrice())) .uomId(getUomId()) .build(); } public CostAmount multiply(@NonNull final Quantity quantity) { if (!UomId.equals(uomId, quantity.getUomId())) { throw new AdempiereException("UOM does not match: " + this + ", " + quantity); } return toCostAmount().multiply(quantity); } public CostAmount multiply( @NonNull final Duration duration, @NonNull final TemporalUnit durationUnit) { final BigDecimal durationBD = DurationUtils.toBigDecimal(duration, durationUnit); return toCostAmount().multiply(durationBD); }
public CostPrice convertAmounts( @NonNull final UomId toUomId, @NonNull final UnaryOperator<CostAmount> converter) { if (UomId.equals(this.uomId, toUomId)) { return this; } return toBuilder() .uomId(toUomId) .ownCostPrice(converter.apply(getOwnCostPrice())) .componentsCostPrice(converter.apply(getComponentsCostPrice())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostPrice.java
1
请完成以下Java代码
public int getDefaultQueueSizeFullWaitTime() { return defaultQueueSizeFullWaitTime; } public void setDefaultQueueSizeFullWaitTime(int defaultQueueSizeFullWaitTime) { this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime; } public int getTimerLockTimeInMillis() { return timerLockTimeInMillis; } public void setTimerLockTimeInMillis(int timerLockTimeInMillis) { this.timerLockTimeInMillis = timerLockTimeInMillis; } public int getAsyncJobLockTimeInMillis() { return asyncJobLockTimeInMillis; } public void setAsyncJobLockTimeInMillis(int asyncJobLockTimeInMillis) { this.asyncJobLockTimeInMillis = asyncJobLockTimeInMillis; } public int getRetryWaitTimeInMillis() { return retryWaitTimeInMillis; } public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis; } public int getResetExpiredJobsInterval() { return resetExpiredJobsInterval; } public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) { this.resetExpiredJobsInterval = resetExpiredJobsInterval; } public int getResetExpiredJobsPageSize() { return resetExpiredJobsPageSize; } public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { this.resetExpiredJobsPageSize = resetExpiredJobsPageSize; } public int getNumberOfRetries() { return numberOfRetries; } public void setNumberOfRetries(int numberOfRetries) { this.numberOfRetries = numberOfRetries; } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AsyncExecutorProperties.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .passwordEncoder(passwordEncoder) .withClient("client") .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token","password", "implicit") .authorities("ROLE_CLIENT") .resourceIds("apis") .scopes("read") .secret("secret") .accessTokenValiditySeconds(300); } /** * Configure the {@link AuthenticationManagerBuilder} with initial * configuration to setup users. * * @author anilallewar * */ @Configuration @Order(Ordered.LOWEST_PRECEDENCE - 20) protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Autowired private DataSource dataSource; /** * Setup 2 users with different roles */ @Override public void init(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.jdbcAuthentication().dataSource(dataSource).withUser("dave") .password("secret").roles("USER"); auth.jdbcAuthentication().dataSource(dataSource).withUser("anil") .password("password").roles("ADMIN"); // @formatter:on } } }
repos\spring-boot-microservices-master\auth-server\src\main\java\com\rohitghatol\microservice\auth\config\OAuthConfiguration.java
2
请完成以下Java代码
public class JobAcquisitionXmlImpl implements JobAcquisitionXml { private String name; private String jobExecutorClassName; private Map<String, String> properties; public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getProperties() { return properties;
} public void setProperties(Map<String, String> properties) { this.properties = properties; } public String getJobExecutorClassName() { return jobExecutorClassName; } public void setJobExecutorClassName(String jobExecutorClassName) { this.jobExecutorClassName = jobExecutorClassName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\metadata\JobAcquisitionXmlImpl.java
1
请完成以下Java代码
public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Interface. @param IsInterface Interface */ @Override public void setIsInterface (boolean IsInterface) { set_Value (COLUMNNAME_IsInterface, Boolean.valueOf(IsInterface)); } /** Get Interface. @return Interface */ @Override public boolean isInterface () { Object oo = get_Value(COLUMNNAME_IsInterface);
if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass.java
1
请完成以下Java代码
public class ConditionalEventDefinitionImpl extends EventDefinitionImpl implements ConditionalEventDefinition { protected static ChildElement<Condition> conditionChild; protected static Attribute<String> camundaVariableName; protected static Attribute<String> camundaVariableEvents; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ConditionalEventDefinition.class, BPMN_ELEMENT_CONDITIONAL_EVENT_DEFINITION) .namespaceUri(BPMN20_NS) .extendsType(EventDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<ConditionalEventDefinition>() { @Override public ConditionalEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new ConditionalEventDefinitionImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionChild = sequenceBuilder.element(Condition.class) .required() .build(); /** camunda extensions */ camundaVariableName = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VARIABLE_NAME) .namespace(CAMUNDA_NS) .build(); camundaVariableEvents = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VARIABLE_EVENTS) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public ConditionalEventDefinitionImpl(ModelTypeInstanceContext context) { super(context); } @Override
public Condition getCondition() { return conditionChild.getChild(this); } @Override public void setCondition(Condition condition) { conditionChild.setChild(this, condition); } @Override public String getCamundaVariableName() { return camundaVariableName.getValue(this); } @Override public void setCamundaVariableName(String variableName) { camundaVariableName.setValue(this, variableName); } @Override public String getCamundaVariableEvents() { return camundaVariableEvents.getValue(this); } @Override public void setCamundaVariableEvents(String variableEvents) { camundaVariableEvents.setValue(this, variableEvents); } @Override public List<String> getCamundaVariableEventsList() { String variableEvents = camundaVariableEvents.getValue(this); return StringUtil.splitCommaSeparatedList(variableEvents); } @Override public void setCamundaVariableEventsList(List<String> variableEventsList) { String variableEvents = StringUtil.joinCommaSeparatedList(variableEventsList); camundaVariableEvents.setValue(this, variableEvents); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConditionalEventDefinitionImpl.java
1
请完成以下Java代码
public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.ofList( ImmutableList.of( DocumentQueryOrderBy.byFieldName(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate), DocumentQueryOrderBy.byFieldName(I_MD_Cockpit.COLUMNNAME_ProductValue)) ); } @Override protected boolean isEligibleInvalidateEvent(final TableRecordReference recordRef) { final String tableName = recordRef.getTableName(); return I_MD_Cockpit.Table_Name.equals(tableName) || I_MD_Stock.Table_Name.equals(tableName); }
@Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return relatedProcessDescriptors; } @Override public ViewActionDescriptorsList getActions() { return ViewActionDescriptorsFactory.instance .getFromClass(MD_Cockpit_DocumentDetail_Display.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitView.java
1
请完成以下Java代码
public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setSQL_Details_WhereClause (final @Nullable java.lang.String SQL_Details_WhereClause) { set_Value (COLUMNNAME_SQL_Details_WhereClause, SQL_Details_WhereClause); } @Override public java.lang.String getSQL_Details_WhereClause() { return get_ValueAsString(COLUMNNAME_SQL_Details_WhereClause); } @Override public void setSQL_From (final @Nullable java.lang.String SQL_From) { set_Value (COLUMNNAME_SQL_From, SQL_From); } @Override public java.lang.String getSQL_From() { return get_ValueAsString(COLUMNNAME_SQL_From); } @Override public void setSQL_GroupAndOrderBy (final @Nullable java.lang.String SQL_GroupAndOrderBy) { set_Value (COLUMNNAME_SQL_GroupAndOrderBy, SQL_GroupAndOrderBy); }
@Override public java.lang.String getSQL_GroupAndOrderBy() { return get_ValueAsString(COLUMNNAME_SQL_GroupAndOrderBy); } @Override public void setSQL_WhereClause (final @Nullable java.lang.String SQL_WhereClause) { set_Value (COLUMNNAME_SQL_WhereClause, SQL_WhereClause); } @Override public java.lang.String getSQL_WhereClause() { return get_ValueAsString(COLUMNNAME_SQL_WhereClause); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI.java
1
请完成以下Java代码
public void setM_PromotionLine_ID (int M_PromotionLine_ID) { if (M_PromotionLine_ID < 1) set_Value (COLUMNNAME_M_PromotionLine_ID, null); else set_Value (COLUMNNAME_M_PromotionLine_ID, Integer.valueOf(M_PromotionLine_ID)); } /** Get Promotion Line. @return Promotion Line */ public int getM_PromotionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Operation AD_Reference_ID=53294 */ public static final int OPERATION_AD_Reference_ID=53294; /** >= = >= */ public static final String OPERATION_GtEq = ">="; /** <= = <= */ public static final String OPERATION_LeEq = "<="; /** Set Operation. @param Operation Compare Operation */ public void setOperation (String Operation) { set_Value (COLUMNNAME_Operation, Operation); } /** Get Operation. @return Compare Operation */ public String getOperation () { return (String)get_Value(COLUMNNAME_Operation); }
/** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionDistribution.java
1
请完成以下Java代码
private @Nullable MimeType getMediaType(String id, Resource resource) { if (SbomEndpoint.APPLICATION_SBOM_ID.equals(id) && this.properties.getApplication().getMediaType() != null) { return this.properties.getApplication().getMediaType(); } Sbom sbomProperties = this.properties.getAdditional().get(id); if (sbomProperties != null && sbomProperties.getMediaType() != null) { return sbomProperties.getMediaType(); } return this.detectedMediaTypeCache.computeIfAbsent(id, (ignored) -> { try { return detectSbomType(resource); } catch (IOException ex) { throw new UncheckedIOException("Failed to detect type of resource '%s'".formatted(resource), ex); } }).getMediaType(); } private SbomType detectSbomType(Resource resource) throws IOException { String content = resource.getContentAsString(StandardCharsets.UTF_8); for (SbomType candidate : SbomType.values()) { if (candidate.matches(content)) { return candidate; } } return SbomType.UNKNOWN; } enum SbomType { CYCLONE_DX(MimeType.valueOf("application/vnd.cyclonedx+json")) { @Override boolean matches(String content) { return content.replaceAll("\\s", "").contains("\"bomFormat\":\"CycloneDX\""); } }, SPDX(MimeType.valueOf("application/spdx+json")) { @Override boolean matches(String content) { return content.contains("\"spdxVersion\""); } }, SYFT(MimeType.valueOf("application/vnd.syft+json")) { @Override boolean matches(String content) { return content.contains("\"FoundBy\"") || content.contains("\"foundBy\""); } },
UNKNOWN(null) { @Override boolean matches(String content) { return false; } }; private final @Nullable MimeType mediaType; SbomType(@Nullable MimeType mediaType) { this.mediaType = mediaType; } @Nullable MimeType getMediaType() { return this.mediaType; } abstract boolean matches(String content); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomEndpointWebExtension.java
1
请完成以下Java代码
public KeyValues getLowCardinalityKeyValues(DataFetcherObservationContext context) { return KeyValues.of(outcome(context), fieldName(context), errorType(context)); } protected KeyValue outcome(DataFetcherObservationContext context) { if (context.getError() != null) { return OUTCOME_ERROR; } return OUTCOME_SUCCESS; } protected KeyValue fieldName(DataFetcherObservationContext context) { return KeyValue.of(DataFetcherLowCardinalityKeyNames.FIELD_NAME, context.getEnvironment().getField().getName()); } protected KeyValue errorType(DataFetcherObservationContext context) {
if (context.getError() != null) { return KeyValue.of(DataFetcherLowCardinalityKeyNames.ERROR_TYPE, context.getError().getClass().getSimpleName()); } return ERROR_TYPE_NONE; } @Override public KeyValues getHighCardinalityKeyValues(DataFetcherObservationContext context) { return KeyValues.of(fieldPath(context)); } protected KeyValue fieldPath(DataFetcherObservationContext context) { return KeyValue.of(GraphQlObservationDocumentation.DataFetcherHighCardinalityKeyNames.FIELD_PATH, context.getEnvironment().getExecutionStepInfo().getPath().toString()); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultDataFetcherObservationConvention.java
1
请在Spring Boot框架中完成以下Java代码
public String getAdditionalDescription() { return additionalDescription; } public void setAdditionalDescription(String additionalDescription) { this.additionalDescription = additionalDescription; } public DeviceAppraisalLine repairsReason(String repairsReason) { this.repairsReason = repairsReason; return this; } /** * Grund für die Reparatur * @return repairsReason **/ @Schema(example = "Pumpe defekt", description = "Grund für die Reparatur") public String getRepairsReason() { return repairsReason; } public void setRepairsReason(String repairsReason) { this.repairsReason = repairsReason; } public DeviceAppraisalLine repairsResolution(String repairsResolution) { this.repairsResolution = repairsResolution; return this; } /** * Reparaturlösung * @return repairsResolution **/ @Schema(example = "Pumpe getauscht", description = "Reparaturlösung") public String getRepairsResolution() { return repairsResolution; } public void setRepairsResolution(String repairsResolution) { this.repairsResolution = repairsResolution; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceAppraisalLine deviceAppraisalLine = (DeviceAppraisalLine) o;
return Objects.equals(this.description, deviceAppraisalLine.description) && Objects.equals(this.additionalDescription, deviceAppraisalLine.additionalDescription) && Objects.equals(this.repairsReason, deviceAppraisalLine.repairsReason) && Objects.equals(this.repairsResolution, deviceAppraisalLine.repairsResolution); } @Override public int hashCode() { return Objects.hash(description, additionalDescription, repairsReason, repairsResolution); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeviceAppraisalLine {\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" additionalDescription: ").append(toIndentedString(additionalDescription)).append("\n"); sb.append(" repairsReason: ").append(toIndentedString(repairsReason)).append("\n"); sb.append(" repairsResolution: ").append(toIndentedString(repairsResolution)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceAppraisalLine.java
2
请完成以下Java代码
public void setDbPassword(String password) { this.password = password; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public int getAttempts() { return attempts; } public void setAttempts(int attempts) { this.attempts = attempts; } public void encryptPassword() { if (newPassword != null) { salt = generateSalt(); setDbPassword(encryptPassword(newPassword, salt)); } } protected String encryptPassword(String password, String salt) { if (password == null) { return null; } else { String saltedPassword = saltPassword(password, salt); return Context.getProcessEngineConfiguration() .getPasswordManager() .encrypt(saltedPassword); } }
protected String generateSalt() { return Context.getProcessEngineConfiguration() .getSaltGenerator() .generateSalt(); } public boolean checkPasswordAgainstPolicy() { PasswordPolicyResult result = Context.getProcessEngineConfiguration() .getIdentityService() .checkPasswordAgainstPolicy(newPassword, this); return result.isValid(); } public boolean hasNewPassword() { return newPassword != null; } public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", password=******" // sensitive for logging + ", salt=******" // sensitive for logging + ", lockExpirationTime=" + lockExpirationTime + ", attempts=" + attempts + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserEntity.java
1
请完成以下Java代码
private void write(HttpHeaders headers, String name, String value, boolean append) { write(headers, name, value, append, s -> true); } private void write(HttpHeaders headers, String name, @Nullable String value, boolean append, Predicate<String> shouldWrite) { if (append) { if (value != null) { headers.add(name, value); } // these headers should be treated as a single comma separated header List<String> headerValues = headers.get(name); if (headerValues != null) { List<String> values = headerValues.stream().filter(shouldWrite).toList(); String delimitedValue = StringUtils.collectionToCommaDelimitedString(values); headers.set(name, delimitedValue); } } else if (value != null && shouldWrite.test(value)) { headers.set(name, value); } } private int getDefaultPort(String scheme) { return HTTPS_SCHEME.equals(scheme) ? HTTPS_PORT : HTTP_PORT; } private String toHostHeader(ServerHttpRequest request) { int port = request.getURI().getPort(); String host = request.getURI().getHost(); String scheme = request.getURI().getScheme(); if (port < 0 || (port == HTTP_PORT && HTTP_SCHEME.equals(scheme)) || (port == HTTPS_PORT && HTTPS_SCHEME.equals(scheme))) { return host; }
else { return host + ":" + port; } } private String stripTrailingSlash(URI uri) { String path = uri.getPath(); if (path != null && path.endsWith("/")) { return path.substring(0, path.length() - 1); } else { return path; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\XForwardedHeadersFilter.java
1
请完成以下Java代码
class Even implements Runnable { private final SharedPrinter sp; private final int max; Even(SharedPrinter sp, int max) { this.sp = sp; this.max = max; } @Override public void run() { for (int i = 2; i <= max; i = i + 2) { sp.printEvenNum(i); } } } class Odd implements Runnable {
private SharedPrinter sp; private int max; Odd(SharedPrinter sp, int max) { this.sp = sp; this.max = max; } @Override public void run() { for (int i = 1; i <= max; i = i + 2) { sp.printOddNum(i); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\evenandodd\PrintEvenOddSemaphore.java
1
请在Spring Boot框架中完成以下Java代码
public class OAuth2DynamicClientConfiguration { private final OAuth2ClientProperties clientProperties; private final RegistrationProperties registrationProperties; @Bean ClientRegistrationRepository dynamicClientRegistrationRepository( DynamicClientRegistrationRepository.RegistrationRestTemplate restTemplate) { log.info("Creating a dynamic client registration repository"); var registrationDetails = new DynamicClientRegistrationRepository.RegistrationDetails( registrationProperties.getRegistrationEndpoint(), registrationProperties.getRegistrationUsername(), registrationProperties.getRegistrationPassword(), registrationProperties.getRegistrationScopes(), registrationProperties.getGrantTypes(), registrationProperties.getRedirectUris(), registrationProperties.getTokenEndpoint()); // Use standard client registrations as Map<String,ClientRegistration> staticClients = (new OAuth2ClientPropertiesMapper(clientProperties)).asClientRegistrations(); var repo = new DynamicClientRegistrationRepository(registrationDetails, staticClients, restTemplate); repo.doRegistrations(); return repo; } @Bean DynamicClientRegistrationRepository.RegistrationRestTemplate registrationRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.build(DynamicClientRegistrationRepository.RegistrationRestTemplate.class); } // As of Spring Boot 3.2, we could use a record instead of a class. @ConfigurationProperties(prefix = "baeldung.security.client.registration")
@Getter @Setter public static final class RegistrationProperties { URI registrationEndpoint; String registrationUsername; String registrationPassword; List<String> registrationScopes; List<String> grantTypes; List<String> redirectUris; URI tokenEndpoint; } @Bean public OAuth2AuthorizationRequestResolver pkceResolver(ClientRegistrationRepository repo) { var resolver = new DefaultOAuth2AuthorizationRequestResolver(repo, "/oauth2/authorization"); resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()); return resolver; } @Bean SecurityFilterChain oauth2SecurityFilterChain(HttpSecurity http, OAuth2AuthorizationRequestResolver resolver) throws Exception { http.authorizeHttpRequests((requests) -> { requests.anyRequest().authenticated(); }); http.oauth2Login(a -> a.authorizationEndpoint(c -> c.authorizationRequestResolver(resolver))) ; http.oauth2Client(Customizer.withDefaults()); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\java\com\baeldung\spring\security\dynreg\client\config\OAuth2DynamicClientConfiguration.java
2
请完成以下Java代码
public class ShipmentScheduleHUPackingAware implements IHUPackingAware { private final I_M_ShipmentSchedule shipmentSchedule; private final PlainHUPackingAware values = new PlainHUPackingAware(); public ShipmentScheduleHUPackingAware(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { this.shipmentSchedule = shipmentSchedule; } @Override public int getM_Product_ID() { return shipmentSchedule.getM_Product_ID(); } @Override public void setM_Product_ID(final int productId) { shipmentSchedule.setM_Product_ID(productId); } @Override public int getM_AttributeSetInstance_ID() { return shipmentSchedule.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { shipmentSchedule.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return shipmentSchedule.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { shipmentSchedule.setC_UOM_ID(uomId); } } @Override public void setQty(final BigDecimal qty) { shipmentSchedule.setQtyOrdered_Override(qty); } @Override public BigDecimal getQty() { // task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule final BigDecimal qtyOrdered = Services.get(IShipmentScheduleEffectiveBL.class).computeQtyOrdered(shipmentSchedule); return qtyOrdered; } @Override public int getM_HU_PI_Item_Product_ID() { return shipmentSchedule.getM_HU_PI_Item_Product_ID();
} @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return shipmentSchedule.getQtyOrdered_TU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { shipmentSchedule.setQtyOrdered_TU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ShipmentScheduleHUPackingAware.java
1
请完成以下Java代码
protected Class<? extends HttpServiceTask> getExportablePlanItemDefinitionClass() { return HttpServiceTask.class; } } public static class ScriptServiceTaskExport extends AbstractServiceTaskExport<ScriptServiceTask> { @Override protected Class<? extends ScriptServiceTask> getExportablePlanItemDefinitionClass() { return ScriptServiceTask.class; } @Override protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, ScriptServiceTask serviceTask, boolean didWriteExtensionElement, XMLStreamWriter xtw) throws Exception { boolean extensionElementWritten = super.writePlanItemDefinitionExtensionElements(model, serviceTask, didWriteExtensionElement, xtw); extensionElementWritten = CmmnXmlUtil.writeIOParameters(ELEMENT_EXTERNAL_WORKER_IN_PARAMETER, serviceTask.getInParameters(), extensionElementWritten, xtw); return extensionElementWritten; } } public static class FormAwareServiceTaskExport extends AbstractServiceTaskExport<FormAwareServiceTask> { @Override protected Class<? extends FormAwareServiceTask> getExportablePlanItemDefinitionClass() {
return FormAwareServiceTask.class; } @Override public void writePlanItemDefinitionSpecificAttributes(FormAwareServiceTask formAwareServiceTask, XMLStreamWriter xtw) throws Exception { super.writePlanItemDefinitionSpecificAttributes(formAwareServiceTask, xtw); if (StringUtils.isNotBlank(formAwareServiceTask.getFormKey())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_KEY, formAwareServiceTask.getFormKey()); } if (StringUtils.isNotBlank(formAwareServiceTask.getValidateFormFields())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FIELD_VALIDATION, formAwareServiceTask.getValidateFormFields()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\AbstractServiceTaskExport.java
1
请完成以下Java代码
public final Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { return null; } @Override public final void loginFail(HttpServletRequest request, HttpServletResponse response) { logout(request); } @Override public final void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { if (!this.alwaysRemember && !rememberMeRequested(request, this.rememberMeParameterName)) { logger.debug("Remember-me login not requested."); return; } request.setAttribute(REMEMBER_ME_LOGIN_ATTR, true); request.getSession().setMaxInactiveInterval(this.validitySeconds); } /** * Allows customization of whether a remember-me login has been requested. The default * is to return {@code true} if the configured parameter name has been included in the * request and is set to the value {@code true}. * @param request the request submitted from an interactive login, which may include * additional information indicating that a persistent login is desired. * @param parameter the configured remember-me parameter name. * @return true if the request includes information indicating that a persistent login * has been requested. */ protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { String rememberMe = request.getParameter(parameter); if (rememberMe != null) { if (rememberMe.equalsIgnoreCase("true") || rememberMe.equalsIgnoreCase("on") || rememberMe.equalsIgnoreCase("yes") || rememberMe.equals("1")) { return true; } } if (logger.isDebugEnabled()) { logger.debug("Did not send remember-me cookie (principal did not set " + "parameter '" + parameter + "')"); } return false; } /**
* Set the name of the parameter which should be checked for to see if a remember-me * has been requested during a login request. This should be the same name you assign * to the checkbox in your login form. * @param rememberMeParameterName the request parameter */ public void setRememberMeParameterName(String rememberMeParameterName) { Assert.hasText(rememberMeParameterName, "rememberMeParameterName cannot be empty or null"); this.rememberMeParameterName = rememberMeParameterName; } public void setAlwaysRemember(boolean alwaysRemember) { this.alwaysRemember = alwaysRemember; } public void setValiditySeconds(int validitySeconds) { this.validitySeconds = validitySeconds; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { logout(request); } private void logout(HttpServletRequest request) { logger.debug("Interactive login attempt was unsuccessful."); HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\web\authentication\SpringSessionRememberMeServices.java
1
请完成以下Java代码
public frameset addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public frameset addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public frameset addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public frameset removeElement(String hashcode) {
removeElementFromRegistry(hashcode); return(this); } /** The onload event occurs when the user agent finishes loading a window or all frames within a frameset. This attribute may be used with body and frameset elements. @param The script */ public void setOnLoad(String script) { addAttribute ( "onload", script ); } /** The onunload event occurs when the user agent removes a document from a window or frame. This attribute may be used with body and frameset elements. @param The script */ public void setOnUnload(String script) { addAttribute ( "onunload", script ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frameset.java
1
请完成以下Java代码
public class Item { @Field private String id; @Field private String description; @Field private String category; @Field private float price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description;
} public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
repos\tutorials-master\persistence-modules\solr\src\main\java\com\baeldung\solr\fulltext\search\model\Item.java
1
请完成以下Java代码
protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new OracleJdbcDockerComposeConnectionDetails(source.getRunningService(), this.defaultDatabase); } /** * {@link JdbcConnectionDetails} backed by an {@code oracle-xe} or {@code oracle-free} * {@link RunningService}. */ static class OracleJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements JdbcConnectionDetails { private static final String PARAMETERS_LABEL = "org.springframework.boot.jdbc.parameters"; private final OracleEnvironment environment; private final String jdbcUrl; OracleJdbcDockerComposeConnectionDetails(RunningService service, String defaultDatabase) { super(service); this.environment = new OracleEnvironment(service.env(), defaultDatabase); this.jdbcUrl = "jdbc:oracle:thin:@" + service.host() + ":" + service.ports().get(1521) + "/" + this.environment.getDatabase() + getParameters(service); } private String getParameters(RunningService service) { String parameters = service.labels().get(PARAMETERS_LABEL); return (StringUtils.hasLength(parameters)) ? "?" + parameters : ""; } @Override public String getUsername() {
return this.environment.getUsername(); } @Override public String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\OracleJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
private static OptimisticLockingException callFailedJobListenerWithRetries(CommandExecutor commandExecutor, FailedJobListener failedJobListener) { try { commandExecutor.execute(failedJobListener); return null; } catch (OptimisticLockingException ex) { failedJobListener.incrementCountRetries(); if (failedJobListener.getRetriesLeft() > 0) { return callFailedJobListenerWithRetries(commandExecutor, failedJobListener); } return ex; } } protected static void handleJobFailure(final String nextJobId, final JobFailureCollector jobFailureCollector, Throwable exception) { jobFailureCollector.setFailure(exception);
} protected static FailedJobListener createFailedJobListener(CommandExecutor commandExecutor, JobFailureCollector jobFailureCollector) { return new FailedJobListener(commandExecutor, jobFailureCollector); } protected static SuccessfulJobListener createSuccessfulJobListener(CommandExecutor commandExecutor) { return new SuccessfulJobListener(); } public interface ExceptionLoggingHandler { void exceptionWhileExecutingJob(String jobId, Throwable exception); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\ExecuteJobHelper.java
1
请完成以下Java代码
public class ResourceEntity implements Serializable, DbEntity, Resource { private static final long serialVersionUID = 1L; protected String id; protected String name; protected byte[] bytes; protected String deploymentId; protected boolean generated = false; protected String tenantId; protected Integer type; protected Date createTime; 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 byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Object getPersistentState() { return ResourceEntity.class; } public void setGenerated(boolean generated) { this.generated = generated; }
/** * Indicated whether or not the resource has been generated while deploying rather than * being actual part of the deployment. */ public boolean isGenerated() { return generated; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", name=" + name + ", deploymentId=" + deploymentId + ", generated=" + generated + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ResourceEntity.java
1
请完成以下Java代码
protected void notRetryable(Stream<Class<? extends Exception>> notRetryable) { } /** * Add exception types that can be retried. Call this after {@link #defaultFalse()} to * specify those exception types that should be classified as true. * All others will be retried, unless {@link #defaultFalse()} has been called. * @param exceptionTypes the exception types. * @since 2.8.4 * @see #removeClassification(Class) * @see #setClassifications(Map, boolean) */ @SafeVarargs @SuppressWarnings("varargs") public final void addRetryableExceptions(Class<? extends Exception>... exceptionTypes) { add(true, exceptionTypes); } @SafeVarargs @SuppressWarnings("varargs") private void add(boolean classified, Class<? extends Exception>... exceptionTypes) { Assert.notNull(exceptionTypes, "'exceptionTypes' cannot be null"); Assert.noNullElements(exceptionTypes, "'exceptionTypes' cannot contain nulls"); for (Class<? extends Exception> exceptionType : exceptionTypes) { Assert.isTrue(Exception.class.isAssignableFrom(exceptionType), () -> "exceptionType " + exceptionType + " must be an Exception"); this.exceptionMatcher.getEntries().put(exceptionType, classified); } } /** * Remove an exception type from the configured list. By default, the following * exceptions will not be retried: * <ul> * <li>{@link DeserializationException}</li> * <li>{@link MessageConversionException}</li> * <li>{@link ConversionException}</li> * <li>{@link MethodArgumentResolutionException}</li> * <li>{@link NoSuchMethodException}</li> * <li>{@link ClassCastException}</li> * </ul> * All others will be retried, unless {@link #defaultFalse()} has been called. * @param exceptionType the exception type.
* @return the classification of the exception if removal was successful; * null otherwise. * @since 2.8.4 * @see #addNotRetryableExceptions(Class...) * @see #setClassifications(Map, boolean) */ @Nullable public Boolean removeClassification(Class<? extends Exception> exceptionType) { return this.exceptionMatcher.getEntries().remove(exceptionType); } /** * Extended to provide visibility to the current classified exceptions. * * @author Gary Russell * */ @SuppressWarnings("serial") private static final class ExtendedExceptionMatcher extends ExceptionMatcher { ExtendedExceptionMatcher(Map<Class<? extends Throwable>, Boolean> typeMap, boolean defaultValue) { super(typeMap, defaultValue, true); } @Override protected Map<Class<? extends Throwable>, Boolean> getEntries() { // NOSONAR worthless override return super.getEntries(); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ExceptionClassifier.java
1
请完成以下Java代码
public void setM_CostElement_ID (int M_CostElement_ID) { if (M_CostElement_ID < 1) set_Value (COLUMNNAME_M_CostElement_ID, null); else set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID)); } /** Get Cost Element. @return Product Cost Element */ public int getM_CostElement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ 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 Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCostAllocation.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableList<ShipmentSchedule> getBy(@NonNull final ShipmentScheduleQuery query) { return shipmentScheduleRepository.getBy(query); } private ShipmentScheduleInfo fromRecord(final I_M_ShipmentSchedule shipmentSchedule) { return ShipmentScheduleInfo.builder() .clientAndOrgId(ClientAndOrgId.ofClientAndOrg(shipmentSchedule.getAD_Client_ID(), shipmentSchedule.getAD_Org_ID())) .warehouseId(shipmentScheduleBL.getWarehouseId(shipmentSchedule)) .bpartnerId(shipmentScheduleBL.getBPartnerId(shipmentSchedule)) .salesOrderLineId(Optional.ofNullable(OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID()))) .productId(ProductId.ofRepoId(shipmentSchedule.getM_Product_ID())) .asiId(AttributeSetInstanceId.ofRepoIdOrNone(shipmentSchedule.getM_AttributeSetInstance_ID())) .bestBeforePolicy(ShipmentAllocationBestBeforePolicy.optionalOfNullableCode(shipmentSchedule.getShipmentAllocation_BestBefore_Policy())) .record(shipmentSchedule) .build(); } public void addQtyPickedAndUpdateHU(final AddQtyPickedRequest request) { huShipmentScheduleBL.addQtyPickedAndUpdateHU(request); } public void deleteByTopLevelHUsAndShipmentScheduleId(@NonNull final Collection<I_M_HU> topLevelHUs, @NonNull final ShipmentScheduleId shipmentScheduleId) {
huShipmentScheduleBL.deleteByTopLevelHUsAndShipmentScheduleId(topLevelHUs, shipmentScheduleId); } public Stream<Packageable> stream(@NonNull final PackageableQuery query) { return packagingDAO.stream(query); } public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord) { return huShipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord); } public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { huShipmentScheduleBL.flagForRecompute(shipmentScheduleIds); } public ShipmentScheduleLoadingCache<de.metas.handlingunits.model.I_M_ShipmentSchedule> newHuShipmentLoadingCache() { return huShipmentScheduleBL.newLoadingCache(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\shipmentschedule\PickingJobShipmentScheduleService.java
2
请完成以下Java代码
private void notifyViewOfCacheReset(@NonNull final CacheInvalidateMultiRequest cacheInvalidateRequest) { for (final IView view : getAllViews()) { if (cacheInvalidateRequest.isResetAll()) { view.invalidateAll(); } else { final TableRecordReferenceSet recordsEffective = cacheInvalidateRequest.getRecordsEffective(); view.notifyRecordsChanged(recordsEffective, true); } } } /** * @return {@link MaterialCockpitUtil#WINDOWID_MaterialCockpitView} since that'S what we want to store inside this service. */ @Override public WindowId getWindowId() { return MaterialCockpitUtil.WINDOWID_MaterialCockpitView; } @Override public void put(final IView view) { defaultViewsRepositoryStorage.put(view); } @Nullable @Override
public IView getByIdOrNull(final ViewId viewId) { return defaultViewsRepositoryStorage.getByIdOrNull(viewId); } @Override public void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { defaultViewsRepositoryStorage.closeById(viewId, closeAction); } @Override public Stream<IView> streamAllViews() { return defaultViewsRepositoryStorage.streamAllViews(); } @Override public void invalidateView(final ViewId viewId) { defaultViewsRepositoryStorage.invalidateView(viewId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitViewsIndexStorage.java
1
请完成以下Java代码
public boolean isRunning() { return this.server != null && !this.server.isShutdown(); } @Override public int getPhase() { return Integer.MAX_VALUE; } @Override public boolean isAutoStartup() { return true; } /** * Creates and starts the grpc server. * * @throws IOException If the server is unable to bind the port. */ protected void createAndStartGrpcServer() throws IOException { if (this.server == null) { final Server localServer = this.factory.createServer(); this.server = localServer; localServer.start(); final String address = this.factory.getAddress(); final int port = this.factory.getPort(); log.info("gRPC Server started, listening on address: {}, port: {}", address, port); this.eventPublisher.publishEvent(new GrpcServerStartedEvent(this, localServer, address, port)); // Prevent the JVM from shutting down while the server is running final Thread awaitThread = new Thread(() -> { try { localServer.awaitTermination(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } }); awaitThread.setName("grpc-server-container-" + (serverCounter.incrementAndGet()));
awaitThread.setDaemon(false); awaitThread.start(); } } /** * Initiates an orderly shutdown of the grpc server and releases the references to the server. This call waits for * the server to be completely shut down. */ protected void stopAndReleaseGrpcServer() { final Server localServer = this.server; if (localServer != null) { final long millis = this.shutdownGracePeriod.toMillis(); log.debug("Initiating gRPC server shutdown"); this.eventPublisher.publishEvent(new GrpcServerShutdownEvent(this, localServer)); localServer.shutdown(); // Wait for the server to shutdown completely before continuing with destroying the spring context try { if (millis > 0) { localServer.awaitTermination(millis, MILLISECONDS); } else if (millis == 0) { // Do not wait } else { // Wait infinitely localServer.awaitTermination(); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } finally { localServer.shutdownNow(); this.server = null; } log.info("Completed gRPC server shutdown"); this.eventPublisher.publishEvent(new GrpcServerTerminatedEvent(this, localServer)); } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\serverfactory\GrpcServerLifecycle.java
1
请完成以下Java代码
public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public org.compiere.model.I_M_AttributeSet getM_AttributeSet() { return get_ValueAsPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class); } @Override public void setM_AttributeSet(final org.compiere.model.I_M_AttributeSet M_AttributeSet) { set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet); } @Override public void setM_AttributeSet_ID (final int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID); } @Override public int getM_AttributeSet_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID); } @Override public void setM_AttributeSet_IncludedTab_ID (final int M_AttributeSet_IncludedTab_ID)
{ if (M_AttributeSet_IncludedTab_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, M_AttributeSet_IncludedTab_ID); } @Override public int getM_AttributeSet_IncludedTab_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSet_IncludedTab_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSet_IncludedTab.java
1
请完成以下Java代码
public class PlainProductStorage extends AbstractProductStorage { private final Capacity capacityTotal; private BigDecimal qtyInitial; public PlainProductStorage( final ProductId productId, @NonNull final Quantity qtyTotal) { this(productId, qtyTotal.getUOM(), qtyTotal.toBigDecimal(), BigDecimal.ZERO // qtyInitial=0 => empty by default ); } public PlainProductStorage(final ProductId productId, final I_C_UOM uom, final BigDecimal qtyTotal) { this(productId, uom, qtyTotal, BigDecimal.ZERO // qtyInitial=0 => empty by default ); } public PlainProductStorage(final ProductId productId, final I_C_UOM uom, final BigDecimal qtyTotal, final BigDecimal qtyInitial) { capacityTotal = Capacity.createCapacity(qtyTotal, productId, uom, false // allowNegativeCapacity ); Check.assumeNotNull(qtyInitial, "qtyInitial not null"); this.qtyInitial = qtyInitial; } public PlainProductStorage(final Capacity capacity, final BigDecimal qtyInitial) {
capacityTotal = capacity; Check.assumeNotNull(qtyInitial, "qtyInitial not null"); this.qtyInitial = qtyInitial; } @Override protected Capacity retrieveTotalCapacity() { return capacityTotal; } @Override protected BigDecimal retrieveQtyInitial() { return qtyInitial; } @Override protected void beforeMarkingStalled() { // we are just saving current qty as next qtyInitialO qtyInitial = getQty().toBigDecimal(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\PlainProductStorage.java
1
请完成以下Java代码
public String getAttributeValueType() { return HUSubProducerBPartnerAttributeValuesProvider.ATTRIBUTEVALUETYPE; } @Override public IAttributeValuesProvider createAttributeValuesProvider(final @NotNull Attribute attribute) { return new HUSubProducerBPartnerAttributeValuesProvider(attribute.getAttributeCode()); } /** * Calls {@link ISubProducerAttributeBL#updateAttributesOnSubProducerChanged(Properties, IAttributeSet, boolean)} if at least one of valueOld and valueNew can be converted to not-zero BigDecimals. * * @param valueOld old attribute value. converted to BigDecimal using {@link ConversionHelper#toBigDecimal(Object)} * @param valueNew analog to valueOld */ @Override public void onValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute, final Object valueOld, final Object valueNew) { final BigDecimal valueOldBD = ConversionHelper.toBigDecimal(valueOld); final BigDecimal valueNewBD = ConversionHelper.toBigDecimal(valueNew); if (valueNewBD.signum() == 0 && valueOldBD.signum() == 0) { // nothing to change in this case return; } // task 08782: goal of this parameter: we don't want to reset a pre-existing value unless the procuser is actually changed. final boolean subProducerInitialized = valueNewBD.signum() != 0 && valueOldBD.signum() == 0;
final Properties ctx = InterfaceWrapperHelper.getCtx(attribute); Services.get(ISubProducerAttributeBL.class).updateAttributesOnSubProducerChanged(ctx, attributeSet, subProducerInitialized); } @Override public Object generateSeedValue(final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute, final Object valueInitialDefault) { // we don't support a value different from null Check.assumeNull(valueInitialDefault, "valueInitialDefault null"); return HUSubProducerBPartnerAttributeValuesProvider.staticNullValue(); } @Override public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute) { final I_M_HU hu = Services.get(IHUAttributesBL.class).getM_HU_OrNull(attributeSet); if (hu == null) { // If there is no HU (e.g. ASI), consider it editable return false; } final String huStatus = hu.getHUStatus(); if (!X_M_HU.HUSTATUS_Planning.equals(huStatus)) { // Allow editing only Planning HUs return true; } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUSubProducerBPartnerAttributeHandler.java
1
请在Spring Boot框架中完成以下Java代码
private void gatherBPartnerResponseItems(@NonNull final Exchange exchange) { final JsonResponseBPartnerCompositeUpsert bPartnerUpsertResult = exchange.getIn().getBody(JsonResponseBPartnerCompositeUpsert.class); if (bPartnerUpsertResult == null) { throw new RuntimeCamelException("Missing exchange body! No JsonResponseBPartnerCompositeUpsert found!"); } final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); routeContext.addResponseItems(bPartnerUpsertResult.getResponseItems()); } private void cleanupResponseItems(@NonNull final Exchange exchange) {
final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); routeContext.removeAllResponseItems(); } private void resetBodyToJsonExternalRequest(@NonNull final Exchange exchange) { final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); exchange.getIn().setBody(routeContext.getRequest()); } }
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\patient\GetAlbertaPatientsRoute.java
2
请完成以下Java代码
private MRoleMenu addUpdateRole(Properties ctx, int roleId, int menuId, boolean active, String trxName) { String whereClause = "AD_Role_ID=" + roleId + " AND U_WebMenu_ID=" + menuId; int roleMenuIds[] = MRoleMenu.getAllIDs(MRoleMenu.Table_Name, whereClause, trxName); MRoleMenu roleMenu; if ( roleMenuIds.length == 1) { roleMenu = new MRoleMenu(ctx, roleMenuIds[0],trxName); } else if ( roleMenuIds.length == 0) { roleMenu = new MRoleMenu(ctx, 0,trxName); } else { throw new IllegalStateException("More than one role menu defined."); } roleMenu.setAD_Role_ID(roleId); roleMenu.setU_WebMenu_ID(menuId); roleMenu.setIsActive(active); if (!roleMenu.save()) { throw new IllegalStateException("Could not create/update role menu, RoleMenuId: " + roleMenu.get_ID()); } return roleMenu; } @Override protected String doIt() throws Exception { if (p_role_id == 0) { throw new Exception("No Role defined or cannot assign menus to System Administrator"); } String sqlStmt = "SELECT U_WebMenu_ID, IsActive FROM U_WebMenu"; PreparedStatement pstmt = null; ResultSet rs = null;
try { pstmt = DB.prepareStatement(sqlStmt, get_TrxName()); rs = pstmt.executeQuery(); while (rs.next()) { int menuId = rs.getInt(1); boolean active = "Y".equals(rs.getString(2)); addUpdateRole(getCtx(), p_role_id, menuId, active, get_TrxName()); } } finally { DB.close(rs, pstmt); } return "Role updated successfully"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\UpdateRoleMenu.java
1
请完成以下Java代码
public I_M_QualityNote retrieveQualityNoteForValue(final Properties ctx, final String value) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_QualityNote.class, ctx, ITrx.TRXNAME_None) .addEqualsFilter(I_M_QualityNote.COLUMN_Value, value) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_M_QualityNote.class); } @Override public AttributeId getQualityNoteAttributeId() { final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class); return attributeDAO.retrieveActiveAttributeIdByValueOrNull(QualityNoteAttribute); } @Override public AttributeListValue retrieveAttribueValueForQualityNote(final I_M_QualityNote qualityNote) { final AttributeId attributeId = getQualityNoteAttributeId(); return Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(attributeId, qualityNote.getValue()); } @Override public void deleteAttribueValueForQualityNote(final I_M_QualityNote qualityNote) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); final AttributeId attributeId = getQualityNoteAttributeId(); attributesRepo.deleteAttributeValueByCode(attributeId, qualityNote.getValue()); } @Override public void modifyAttributeValueName(final I_M_QualityNote qualityNote) {
final AttributeListValue attributeValueForQualityNote = retrieveAttribueValueForQualityNote(qualityNote); if (attributeValueForQualityNote == null) { // shall not happen. All M_QualityNote entries shall have a similar M_AttributeValue return; } final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValueForQualityNote.getId()) .name(qualityNote.getName()) .active(qualityNote.isActive()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\impl\QualityNoteDAO.java
1
请在Spring Boot框架中完成以下Java代码
public Pool getPool() { return this.pool; } } /** * Lettuce client properties. */ public static class Lettuce { /** * Shutdown timeout. */ private Duration shutdownTimeout = Duration.ofMillis(100); /** * Defines from which Redis nodes data is read. */ private @Nullable String readFrom; /** * Lettuce pool configuration. */ private final Pool pool = new Pool(); private final Cluster cluster = new Cluster(); public Duration getShutdownTimeout() { return this.shutdownTimeout; } public void setShutdownTimeout(Duration shutdownTimeout) { this.shutdownTimeout = shutdownTimeout; } public @Nullable String getReadFrom() { return this.readFrom; } public void setReadFrom(@Nullable String readFrom) { this.readFrom = readFrom; } public Pool getPool() { return this.pool; } public Cluster getCluster() { return this.cluster; } public static class Cluster { private final Refresh refresh = new Refresh(); public Refresh getRefresh() { return this.refresh; } public static class Refresh { /** * Whether to discover and query all cluster nodes for obtaining the * cluster topology. When set to false, only the initial seed nodes are * used as sources for topology discovery. */ private boolean dynamicRefreshSources = true;
/** * Cluster topology refresh period. */ private @Nullable Duration period; /** * Whether adaptive topology refreshing using all available refresh * triggers should be used. */ private boolean adaptive; public boolean isDynamicRefreshSources() { return this.dynamicRefreshSources; } public void setDynamicRefreshSources(boolean dynamicRefreshSources) { this.dynamicRefreshSources = dynamicRefreshSources; } public @Nullable Duration getPeriod() { return this.period; } public void setPeriod(@Nullable Duration period) { this.period = period; } public boolean isAdaptive() { return this.adaptive; } public void setAdaptive(boolean adaptive) { this.adaptive = adaptive; } } } } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisProperties.java
2
请完成以下Java代码
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_TASK_MULE, MuleTaskJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) {} protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_MULE; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { // done in service task }
protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { ServiceTask task = new ServiceTask(); task.setType("mule"); addField("endpointUrl", PROPERTY_MULETASK_ENDPOINT_URL, elementNode, task); addField("language", PROPERTY_MULETASK_LANGUAGE, elementNode, task); addField("payloadExpression", PROPERTY_MULETASK_PAYLOAD_EXPRESSION, elementNode, task); addField("resultVariable", PROPERTY_MULETASK_RESULT_VARIABLE, elementNode, task); return task; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\MuleTaskJsonConverter.java
1
请完成以下Java代码
public void init() { jdbcTemplate.setResultsMapCaseInsensitive(true); simpleJdbcCallFunction1 = new SimpleJdbcCall(jdbcTemplate).withFunctionName("get_price_by_id"); simpleJdbcCallFunction2 = new SimpleJdbcCall(jdbcTemplate).withFunctionName("get_database_time"); } private static final String SQL_STORED_FUNCTION_1 = "" + " CREATE OR REPLACE FUNCTION get_price_by_id(p_id IN BOOKS.ID%TYPE) " + " RETURN NUMBER" + " IS o_price BOOKS.PRICE%TYPE;" + " BEGIN" + " SELECT PRICE INTO o_price from BOOKS WHERE ID = p_id;" + " RETURN(o_price);" + " END;"; private static final String SQL_STORED_FUNCTION_2 = "" + " CREATE OR REPLACE FUNCTION get_database_time " + " RETURN VARCHAR2" + " IS o_date VARCHAR2(20);" + " BEGIN" + " SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH:MI:SS') INTO o_date FROM dual;" + " RETURN(o_date);" + " END;";
public void start() { log.info("Creating Store Procedures and Function..."); jdbcTemplate.execute(SQL_STORED_FUNCTION_1); jdbcTemplate.execute(SQL_STORED_FUNCTION_2); /* Test Stored Function 1 */ SqlParameterSource in = new MapSqlParameterSource() .addValue("p_id", 3L); BigDecimal price = simpleJdbcCallFunction1.executeFunction(BigDecimal.class, in); System.out.println(price); // 37.3 /* Test Stored Function 2 */ String database_time = simpleJdbcCallFunction2.executeFunction(String.class); System.out.println(database_time); // e.g current date, 23-JUL-2019 05:08:44 } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\sp\StoredFunction.java
1
请完成以下Java代码
public void referenceMaterialTracking(final I_C_Invoice_Candidate ic) { final Object referencedObject = getReferencedObjectOrNull(ic); Services.get(IQualityInspectionHandlerDAO.class).updateICFromMaterialTracking(ic, referencedObject); } private Object getReferencedObjectOrNull(final I_C_Invoice_Candidate ic) { final Object referencedObject; if (ic.getC_OrderLine_ID() > 0) { referencedObject = ic.getC_OrderLine(); } else { final AdTableId adTableId = AdTableId.ofRepoIdOrNull(ic.getAD_Table_ID()); final String tableName = adTableId != null ? Services.get(IADTableDAO.class).retrieveTableName(adTableId) : null; if (tableName != null && I_M_InOutLine.Table_Name.equals(tableName)) { referencedObject = TableRecordCacheLocal.getReferencedValue(ic, I_M_InOutLine.class); } else { referencedObject = null; } } return referencedObject; } /** * Checks if the given <code>ic</code> has {@link I_C_Invoice_Candidate#COLUMNNAME_M_Material_Tracking_ID M_Material_Tracking_ID} <code>>0</code>. If that is the * case, it is also linked to the tracking using {@link IMaterialTrackingBL#linkModelToMaterialTracking(Object, I_M_Material_Tracking)}. *
* @param ic */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW }) public void linkToMaterialTracking(final I_C_Invoice_Candidate ic) { final boolean createLink = true; updateLinkToTrackingIfNotNull(ic, createLink); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void unlinkFromMaterialTracking(final I_C_Invoice_Candidate ic) { final boolean createLink = false; // i.e. remove the link updateLinkToTrackingIfNotNull(ic, createLink); } private void updateLinkToTrackingIfNotNull(final I_C_Invoice_Candidate ic, final boolean createLink) { final IMaterialTrackingAware materialTrackingAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(ic, IMaterialTrackingAware.class); if (materialTrackingAware.getM_Material_Tracking_ID() <= 0) { return; } final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class); if (createLink) { materialTrackingBL.linkModelToMaterialTracking(MTLinkRequest.builder() .model(ic) .materialTrackingRecord(ic.getM_Material_Tracking()) .build()); } else { materialTrackingBL.unlinkModelFromMaterialTrackings(ic); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_Invoice_Candidate.java
1
请完成以下Java代码
public static JSONOptions of(final UserSession userSession) { return prepareFrom(userSession).build(); } static JSONOptions ofAdLanguage(final String adLanguage) { return builder().adLanguage(adLanguage).build(); } public static JSONOptions newInstance() { final UserSession userSession = UserSession.getCurrentOrNull(); return userSession != null ? of(userSession) : ofAdLanguage(Language.getBaseAD_Language()); } public static final String DEBUG_ATTRNAME = "json-options"; private final String adLanguage; private final ZoneId zoneId; @Nullable private final JSONDocumentPermissions documentPermissions; @Builder(toBuilder = true) private JSONOptions( @NonNull final String adLanguage, @Nullable final ZoneId zoneId, @Nullable final JSONDocumentPermissions documentPermissions) { this.adLanguage = adLanguage; this.zoneId = zoneId != null ? zoneId : SystemTime.zoneId(); this.documentPermissions = documentPermissions; } public JSONOptions withAdLanguage(@NonNull final String adLanguage) { if (this.adLanguage.equals(adLanguage)) { return this; } else { return toBuilder().adLanguage(adLanguage).build(); } } private static String extractAdLanguageFromUserSession(@NonNull final UserSession userSession) { final String sessionADLanguage = userSession.getAD_Language(); if (sessionADLanguage != null) { return sessionADLanguage; } // // Try fetching the AD_Language from "Accept-Language" HTTP header if (userSession.isUseHttpAcceptLanguage()) {
HttpServletRequest httpServletRequest = getHttpServletRequest(); if (httpServletRequest != null) { final String httpAcceptLanguage = httpServletRequest.getHeader(HttpHeaders.ACCEPT_LANGUAGE); if (!Check.isEmpty(httpAcceptLanguage, true)) { final String requestLanguage = Services.get(ILanguageDAO.class).retrieveAvailableLanguages() .getAD_LanguageFromHttpAcceptLanguage(httpAcceptLanguage, null); if (requestLanguage != null) { return requestLanguage; } } } } throw new IllegalStateException("Cannot extract the AD_Language from user session"); } private static HttpServletRequest getHttpServletRequest() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes == null) { return null; } if (!(requestAttributes instanceof ServletRequestAttributes)) { return null; } return ((ServletRequestAttributes)requestAttributes).getRequest(); } public DocumentFieldLogicExpressionResultRevaluator getLogicExpressionResultRevaluator() { return documentPermissions != null ? documentPermissions.getLogicExpressionResultRevaluator() : DocumentFieldLogicExpressionResultRevaluator.DEFAULT; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONOptions.java
1
请完成以下Java代码
public int getBatchSize() { return events.size(); } }; } private BatchPreparedStatementSetter getRuleChainEventSetter(List<Event> events) { return new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { RuleChainDebugEvent event = (RuleChainDebugEvent) events.get(i); setCommonEventFields(ps, event); safePutString(ps, 6, event.getMessage()); safePutString(ps, 7, event.getError()); } @Override public int getBatchSize() { return events.size(); } }; } private BatchPreparedStatementSetter getCalculatedFieldEventSetter(List<Event> events) { return new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { CalculatedFieldDebugEvent event = (CalculatedFieldDebugEvent) events.get(i); setCommonEventFields(ps, event); safePutUUID(ps, 6, event.getCalculatedFieldId().getId()); safePutUUID(ps, 7, event.getEventEntity() != null ? event.getEventEntity().getId() : null); safePutString(ps, 8, event.getEventEntity() != null ? event.getEventEntity().getEntityType().name() : null); safePutUUID(ps, 9, event.getMsgId()); safePutString(ps, 10, event.getMsgType()); safePutString(ps, 11, event.getArguments()); safePutString(ps, 12, event.getResult()); safePutString(ps, 13, event.getError()); } @Override public int getBatchSize() { return events.size(); }
}; } void safePutString(PreparedStatement ps, int parameterIdx, String value) throws SQLException { if (value != null) { ps.setString(parameterIdx, replaceNullChars(value)); } else { ps.setNull(parameterIdx, Types.VARCHAR); } } void safePutUUID(PreparedStatement ps, int parameterIdx, UUID value) throws SQLException { if (value != null) { ps.setObject(parameterIdx, value); } else { ps.setNull(parameterIdx, Types.OTHER); } } private void setCommonEventFields(PreparedStatement ps, Event event) throws SQLException { ps.setObject(1, event.getId().getId()); ps.setObject(2, event.getTenantId().getId()); ps.setLong(3, event.getCreatedTime()); ps.setObject(4, event.getEntityId()); ps.setString(5, event.getServiceId()); } private String replaceNullChars(String strValue) { if (removeNullChars && strValue != null) { return PATTERN_THREAD_LOCAL.get().matcher(strValue).replaceAll(EMPTY_STR); } return strValue; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\EventInsertRepository.java
1
请完成以下Java代码
public int getM_InOutLine_To_C_Customs_Invoice_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** 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_Value (COLUMNNAME_M_Product_ID, null); else set_Value (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(); } /** Set Bewegungs-Menge. @param MovementQty Menge eines bewegten Produktes. */ @Override public void setMovementQty (java.math.BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Bewegungs-Menge. @return Menge eines bewegten Produktes. */ @Override public java.math.BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return BigDecimal.ZERO; return bd;
} /** Set Einzelpreis. @param PriceActual Effektiver Preis */ @Override public void setPriceActual (java.math.BigDecimal PriceActual) { set_Value (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ @Override public java.math.BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLine_To_C_Customs_Invoice_Line.java
1
请在Spring Boot框架中完成以下Java代码
public class M_InOutLine { @NonNull private final MatchInvoiceService matchInvoiceService; /** * Sets <code>M_PackingMaterial_InOutLine_ID</code> to <code>null</code> for all inOutLines that reference the given <code>packingMaterialLine</code>. * * Note: we don't even check if <code>packingMaterialLine</code> has <code>IsPackagingMaterial='Y'</code>,<br> * because we want to make sure that the FK-constrain violation is avoided, even if due to whatever reason, the IsPackagingMaterial value was already set to 'N' earlier. */ @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void processorDeleted(final I_M_InOutLine packingMaterialLine) { final IInOutDAO inOutDAO = Services.get(IInOutDAO.class); final List<I_M_InOutLine> allReferencingLines = inOutDAO.retrieveAllReferencingLinesBuilder(packingMaterialLine) .create() .list(I_M_InOutLine.class); for (final I_M_InOutLine referencingIol : allReferencingLines) { referencingIol.setM_PackingMaterial_InOutLine(null); InterfaceWrapperHelper.save(referencingIol); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void handleInOutLineDelete(final I_M_InOutLine iol) { matchInvoiceService.deleteByInOutLineId(InOutLineId.ofRepoId(iol.getM_InOutLine_ID())); } /**
* If the <code>C_Order_ID</code> of the given line is at odds with the <code>C_Order_ID</code> of the line's <code>M_InOut</code>, then <code>M_InOut.C_Order</code> is set to <code>null</code>. * * @implSpec task 08451 */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_InOutLine.COLUMNNAME_M_InOut_ID, I_M_InOutLine.COLUMNNAME_C_OrderLine_ID }) public void unsetM_InOut_C_Order_ID(final I_M_InOutLine inOutLine) { if (inOutLine.getC_OrderLine_ID() <= 0) { return; // nothing to do } final I_M_InOut inOut = inOutLine.getM_InOut(); final int headerOrderId = inOut.getC_Order_ID(); if (headerOrderId <= 0) { return; // nothing to do } final int lineOrderId = inOutLine.getC_OrderLine().getC_Order_ID(); if (lineOrderId == headerOrderId) { return; // nothing to do } inOut.setC_Order_ID(0); // they are at odds. unset the reference } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\model\validator\M_InOutLine.java
2
请完成以下Java代码
public class TbResultSetFuture implements ListenableFuture<TbResultSet> { private final SettableFuture<TbResultSet> mainFuture; public TbResultSetFuture(SettableFuture<TbResultSet> mainFuture) { this.mainFuture = mainFuture; } public TbResultSet getUninterruptibly() { return getSafe(); } public TbResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException { return getSafe(timeout, unit); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return mainFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return mainFuture.isCancelled(); } @Override public boolean isDone() { return mainFuture.isDone(); } @Override public TbResultSet get() throws InterruptedException, ExecutionException { return mainFuture.get(); }
@Override public TbResultSet get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mainFuture.get(timeout, unit); } @Override public void addListener(Runnable listener, Executor executor) { mainFuture.addListener(listener, executor); } private TbResultSet getSafe() { try { return mainFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } private TbResultSet getSafe(long timeout, TimeUnit unit) throws TimeoutException { try { return mainFuture.get(timeout, unit); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSetFuture.java
1
请在Spring Boot框架中完成以下Java代码
protected boolean getValidateTransactionState() { return this.properties.isValidateTransactionState(); } @Override protected Isolation getIsolationLevelForCreate() { Isolation isolation = this.properties.getIsolationLevelForCreate(); return (isolation != null) ? isolation : super.getIsolationLevelForCreate(); } @Override protected ConfigurableConversionService getConversionService() { ConfigurableConversionService conversionService = super.getConversionService(); for (BatchConversionServiceCustomizer customizer : this.batchConversionServiceCustomizers) { customizer.customize(conversionService); } return conversionService; } @Override protected ExecutionContextSerializer getExecutionContextSerializer() { return (this.executionContextSerializer != null) ? this.executionContextSerializer : super.getExecutionContextSerializer(); } @Override @Deprecated(since = "4.0.0", forRemoval = true) @SuppressWarnings("removal") protected JobParametersConverter getJobParametersConverter() { return (this.jobParametersConverter != null) ? this.jobParametersConverter : super.getJobParametersConverter(); } @Override protected TaskExecutor getTaskExecutor() { return (this.taskExecutor != null) ? this.taskExecutor : super.getTaskExecutor(); } @Configuration(proxyBeanMethods = false) @Conditional(OnBatchDatasourceInitializationCondition.class)
static class DataSourceInitializerConfiguration { @Bean @ConditionalOnMissingBean BatchDataSourceScriptDatabaseInitializer batchDataSourceInitializer(DataSource dataSource, @BatchDataSource ObjectProvider<DataSource> batchDataSource, BatchJdbcProperties properties) { return new BatchDataSourceScriptDatabaseInitializer(batchDataSource.getIfAvailable(() -> dataSource), properties); } } static class OnBatchDatasourceInitializationCondition extends OnDatabaseInitializationCondition { OnBatchDatasourceInitializationCondition() { super("Batch", "spring.batch.jdbc.initialize-schema"); } } } }
repos\spring-boot-4.0.1\module\spring-boot-batch-jdbc\src\main\java\org\springframework\boot\batch\jdbc\autoconfigure\BatchJdbcAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class ExecutionVariableDataResource extends BaseExecutionVariableResource { public ExecutionVariableDataResource() { super(RestResponseFactory.VARIABLE_EXECUTION); } @ApiOperation(value = "Get the binary data for an execution", tags = { "Executions" }, nickname = "getExecutionVariableData") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the execution was found and the requested variables are returned."), @ApiResponse(code = 404, message = "Indicates the requested execution was not found or the task does not have a variable with the given name (in the given scope). Status message provides additional information.") }) @GetMapping(value = "/runtime/executions/{executionId}/variables/{variableName}/data") @ResponseBody public byte[] getVariableData(@ApiParam(name = "executionId") @PathVariable("executionId") String executionId, @ApiParam(name = "variableName") @PathVariable("variableName") String variableName, @RequestParam(value = "scope", required = false) String scope, HttpServletResponse response) { try { byte[] result = null; Execution execution = getExecutionFromRequestWithoutAccessCheck(executionId); RestVariable variable = getVariableFromRequest(execution, variableName, scope, true); if (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
result = (byte[]) variable.getValue(); response.setContentType("application/octet-stream"); } else if (RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(buffer); outputStream.writeObject(variable.getValue()); outputStream.close(); result = buffer.toByteArray(); response.setContentType("application/x-java-serialized-object"); } else { throw new FlowableObjectNotFoundException("The variable does not have a binary data stream.", null); } return result; } catch (IOException ioe) { throw new FlowableException("Error getting variable " + variableName, ioe); } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionVariableDataResource.java
2
请在Spring Boot框架中完成以下Java代码
public class PackageablesView_UnlockFromLoggedUser extends PackageablesViewBasedProcess { @Autowired private ShipmentScheduleLockRepository locksRepo; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { return acceptIfSingleSelectedRow() .and(this::acceptIfLockedByCurrentUser); } private ProcessPreconditionsResolution acceptIfSingleSelectedRow() { final DocumentIdsSelection rowIds = getSelectedRowIds(); if (!rowIds.isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectWithInternalReason("select a single row"); } else { return ProcessPreconditionsResolution.accept(); } } private ProcessPreconditionsResolution acceptIfLockedByCurrentUser() { final PackageableRow row = getSingleSelectedRow(); if (!row.isLockedBy(getLoggedUserId())) {
return ProcessPreconditionsResolution.rejectWithInternalReason("not locked by current user"); } else { return ProcessPreconditionsResolution.accept(); } } @Override protected String doIt() { final PackageableRow row = getSingleSelectedRow(); locksRepo.unlock(ShipmentScheduleUnLockRequest.builder() .shipmentScheduleIds(row.getShipmentScheduleIds()) .lockType(ShipmentScheduleLockType.PICKING) .lockedBy(getLoggedUserId()) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesView_UnlockFromLoggedUser.java
2
请完成以下Java代码
private static RetrieveAvailableForSalesQuery buildRetrieveAvailableForSalesQuery(@NonNull final AvailableForSalesQuery availableForSalesQuery) { return RetrieveAvailableForSalesQuery.builder() .productId(availableForSalesQuery.getProductId()) .orgId(availableForSalesQuery.getOrgId()) .storageAttributesKeyPattern(availableForSalesQuery.getStorageAttributesKeyPattern()) .warehouseId(availableForSalesQuery.getWarehouseId()) .build(); } @NonNull private static AvailableForSalesMergeResult computeAvailableForSalesMergeResult( @NonNull final ImmutableMap<AvailableForSalesId, I_MD_Available_For_Sales> availableForSalesIds2Records, @NonNull final ImmutableList<AvailableForSalesResult> availableForSalesResults) { final ImmutableMap.Builder<AvailableForSalesId, AvailableForSalesResult> recordId2ResultCollector = ImmutableMap.builder(); final ImmutableList.Builder<AvailableForSalesResult> resultsToInsertCollector = ImmutableList.builder(); for (final AvailableForSalesResult availableForSalesResult : availableForSalesResults) { AvailableForSalesId idForCurrentResult = null; final Iterator<AvailableForSalesId> availableForSalesIdIterator = availableForSalesIds2Records.keySet().iterator(); while (availableForSalesIdIterator.hasNext() && idForCurrentResult == null) { final AvailableForSalesId availableForSalesId = availableForSalesIdIterator.next(); final I_MD_Available_For_Sales availableForSalesRecord = availableForSalesIds2Records.get(availableForSalesId); if (availableForSalesRecord.getStorageAttributesKey().equals(availableForSalesResult.getStorageAttributesKey().getAsString()) && availableForSalesRecord.getM_Warehouse_ID() == availableForSalesResult.getWarehouseId().getRepoId()) { idForCurrentResult = AvailableForSalesId.ofRepoId(availableForSalesRecord.getMD_Available_For_Sales_ID()); } } if (idForCurrentResult == null) { resultsToInsertCollector.add(availableForSalesResult); } else { recordId2ResultCollector.put(idForCurrentResult, availableForSalesResult); } } final Map<AvailableForSalesId, AvailableForSalesResult> recordId2Result = recordId2ResultCollector.build();
final List<I_MD_Available_For_Sales> recordsToBeDeleted = availableForSalesIds2Records .entrySet() .stream() .filter(id2Record -> !recordId2Result.containsKey(id2Record.getKey())) .map(Map.Entry::getValue) .collect(ImmutableList.toImmutableList()); return AvailableForSalesMergeResult.builder() .recordId2Result(recordId2Result) .recordsToDelete(recordsToBeDeleted) .resultsToInsert(resultsToInsertCollector.build()) .build(); } @Value @Builder private static class AvailableForSalesMergeResult { @NonNull Map<AvailableForSalesId, AvailableForSalesResult> recordId2Result; @NonNull List<AvailableForSalesResult> resultsToInsert; @NonNull List<I_MD_Available_For_Sales> recordsToDelete; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesService.java
1
请完成以下Java代码
public class BpmPlatformXmlParse extends DeploymentMetadataParse { /** the parsed {@link BpmPlatformXml} */ protected BpmPlatformXml bpmPlatformXml; public BpmPlatformXmlParse(Parser parser) { super(parser); } public BpmPlatformXmlParse execute() { super.execute(); return this; } /** We know this is a <code>&lt;bpm-platform ../&gt;</code> element */ protected void parseRootElement() { JobExecutorXmlImpl jobExecutor = new JobExecutorXmlImpl(); List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>(); for (Element element : rootElement.elements()) { if(JOB_EXECUTOR.equals(element.getTagName())) { parseJobExecutor(element, jobExecutor); } else if(PROCESS_ENGINE.equals(element.getTagName())) { parseProcessEngine(element, processEngines); } } bpmPlatformXml = new BpmPlatformXmlImpl(jobExecutor, processEngines); } /** * parse a <code>&lt;job-executor .../&gt;</code> element and add it to the list of parsed elements */ protected void parseJobExecutor(Element element, JobExecutorXmlImpl jobExecutorXml) { List<JobAcquisitionXml> jobAcquisitions = new ArrayList<JobAcquisitionXml>(); Map<String, String> properties = new HashMap<String, String>(); for (Element childElement : element.elements()) { if(JOB_ACQUISITION.equals(childElement.getTagName())) { parseJobAcquisition(childElement, jobAcquisitions); }else if(PROPERTIES.equals(childElement.getTagName())){ parseProperties(childElement, properties); } } jobExecutorXml.setJobAcquisitions(jobAcquisitions); jobExecutorXml.setProperties(properties);
} /** * parse a <code>&lt;job-acquisition .../&gt;</code> element and add it to the * list of parsed elements */ protected void parseJobAcquisition(Element element, List<JobAcquisitionXml> jobAcquisitions) { JobAcquisitionXmlImpl jobAcquisition = new JobAcquisitionXmlImpl(); // set name jobAcquisition.setName(element.attribute(NAME)); Map<String, String> properties = new HashMap<String, String>(); for (Element childElement : element.elements()) { if (JOB_EXECUTOR_CLASS_NAME.equals(childElement.getTagName())) { jobAcquisition.setJobExecutorClassName(childElement.getText()); } else if (PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); } } // set collected properties jobAcquisition.setProperties(properties); // add to list jobAcquisitions.add(jobAcquisition); } public BpmPlatformXml getBpmPlatformXml() { return bpmPlatformXml; } public BpmPlatformXmlParse sourceUrl(URL url) { super.sourceUrl(url); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\metadata\BpmPlatformXmlParse.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<Article> getArticleBySlug(String slug) { return articleRepository.findFirstByContentsTitleSlug(slug); } @Transactional public Article updateArticle(long userId, String slug, ArticleUpdateRequest request) { return mapIfAllPresent(userFindService.findById(userId), getArticleBySlug(slug), (user, article) -> user.updateArticle(article, request)) .orElseThrow(NoSuchElementException::new); } @Transactional public Article favoriteArticle(long userId, String articleSlugToFavorite) { return mapIfAllPresent( userFindService.findById(userId), getArticleBySlug(articleSlugToFavorite), User::favoriteArticle) .orElseThrow(NoSuchElementException::new); }
@Transactional public Article unfavoriteArticle(long userId, String articleSlugToUnFavorite) { return mapIfAllPresent( userFindService.findById(userId), getArticleBySlug(articleSlugToUnFavorite), User::unfavoriteArticle) .orElseThrow(NoSuchElementException::new); } @Transactional public void deleteArticleBySlug(long userId, String slug) { userFindService.findById(userId) .ifPresentOrElse(user -> articleRepository.deleteArticleByAuthorAndContentsTitleSlug(user, slug), () -> {throw new NoSuchElementException();}); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\ArticleService.java
2
请在Spring Boot框架中完成以下Java代码
public class CoapTransportHealthChecker extends TransportHealthChecker<CoapTransportMonitoringConfig> { static { SystemConfig.register(); } private CoapClient coapClient; protected CoapTransportHealthChecker(CoapTransportMonitoringConfig config, TransportMonitoringTarget target) { super(config, target); } @Override protected void initClient() throws Exception { if (coapClient == null) { String accessToken = target.getDevice().getCredentials().getCredentialsId(); String uri = target.getBaseUrl() + "/api/v1/" + accessToken + "/telemetry"; coapClient = new CoapClient(uri); coapClient.setTimeout((long) config.getRequestTimeoutMs()); log.debug("Initialized CoAP client for URI {}", uri); } } @Override protected void sendTestPayload(String payload) throws Exception { CoapResponse response = coapClient.post(payload, MediaTypeRegistry.APPLICATION_JSON); CoAP.ResponseCode code = response.getCode(); if (code.codeClass != CoAP.CodeClass.SUCCESS_RESPONSE.value) { throw new IOException("COAP client didn't receive success response from transport"); } }
@Override protected void destroyClient() throws Exception { if (coapClient != null) { coapClient.shutdown(); coapClient = null; log.info("Disconnected CoAP client"); } } @Override protected TransportType getTransportType() { return TransportType.COAP; } }
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\transport\impl\CoapTransportHealthChecker.java
2
请完成以下Java代码
public boolean hasAlias() { return !m_columnName.equals(m_alias); } // hasAlias /** * Column value forces page break * @return true if page break */ public boolean isPageBreak() { return m_pageBreak; } // isPageBreak /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer("PrintDataColumn["); sb.append("ID=").append(m_AD_Column_ID) .append("-").append(m_columnName); if (hasAlias())
sb.append("(").append(m_alias).append(")"); sb.append(",DisplayType=").append(m_displayType) .append(",Size=").append(m_columnSize) .append("]"); return sb.toString(); } // toString public void setFormatPattern(String formatPattern) { m_FormatPattern = formatPattern; } public String getFormatPattern() { return m_FormatPattern; } } // PrintDataColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataColumn.java
1
请完成以下Java代码
private boolean isPublicClientType() { return this.authorizationGrantTypes.contains(AuthorizationGrantType.AUTHORIZATION_CODE) && this.clientAuthenticationMethods.size() == 1 && this.clientAuthenticationMethods.contains(ClientAuthenticationMethod.NONE); } private RegisteredClient create() { RegisteredClient registeredClient = new RegisteredClient(); registeredClient.id = this.id; registeredClient.clientId = this.clientId; registeredClient.clientIdIssuedAt = this.clientIdIssuedAt; registeredClient.clientSecret = this.clientSecret; registeredClient.clientSecretExpiresAt = this.clientSecretExpiresAt; registeredClient.clientName = this.clientName; registeredClient.clientAuthenticationMethods = Collections .unmodifiableSet(new HashSet<>(this.clientAuthenticationMethods)); registeredClient.authorizationGrantTypes = Collections .unmodifiableSet(new HashSet<>(this.authorizationGrantTypes)); registeredClient.redirectUris = Collections.unmodifiableSet(new HashSet<>(this.redirectUris)); registeredClient.postLogoutRedirectUris = Collections .unmodifiableSet(new HashSet<>(this.postLogoutRedirectUris)); registeredClient.scopes = Collections.unmodifiableSet(new HashSet<>(this.scopes)); registeredClient.clientSettings = this.clientSettings; registeredClient.tokenSettings = this.tokenSettings; return registeredClient; } private void validateScopes() { if (CollectionUtils.isEmpty(this.scopes)) { return; } for (String scope : this.scopes) { Assert.isTrue(validateScope(scope), "scope \"" + scope + "\" contains invalid characters"); } } private static boolean validateScope(String scope) { return scope == null || scope.chars() .allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); } private static boolean withinTheRangeOf(int c, int min, int max) { return c >= min && c <= max; } private void validateRedirectUris() { if (CollectionUtils.isEmpty(this.redirectUris)) {
return; } for (String redirectUri : this.redirectUris) { Assert.isTrue(validateRedirectUri(redirectUri), "redirect_uri \"" + redirectUri + "\" is not a valid redirect URI or contains fragment"); } } private void validatePostLogoutRedirectUris() { if (CollectionUtils.isEmpty(this.postLogoutRedirectUris)) { return; } for (String postLogoutRedirectUri : this.postLogoutRedirectUris) { Assert.isTrue(validateRedirectUri(postLogoutRedirectUri), "post_logout_redirect_uri \"" + postLogoutRedirectUri + "\" is not a valid post logout redirect URI or contains fragment"); } } private static boolean validateRedirectUri(String redirectUri) { try { URI validRedirectUri = new URI(redirectUri); return validRedirectUri.getFragment() == null; } catch (URISyntaxException ex) { return false; } } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\RegisteredClient.java
1
请在Spring Boot框架中完成以下Java代码
public class JdbcXlsDataSource implements IXlsDataSource { public static final JdbcXlsDataSource of(final String sql) { return new JdbcXlsDataSource(sql); } private static final String COLUMNNAME_ReportFileName = "ReportFileName"; private final String sql; private final Supplier<Collection<Object>> rowsSupplier = Suppliers.memoize(() -> retrieveRows()); private JdbcXlsDataSource(final String sql) { super(); Check.assumeNotNull(sql, "sql not null"); this.sql = sql; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("sql", sql) .toString(); } @Override public Collection<Object> getRows() { return rowsSupplier.get(); } protected Collection<Object> retrieveRows() { final List<Object> result = new LinkedList<>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); while (rs.next()) { final Map<String, Object> row = retrieveRow(rs); result.add(row); } } catch (final SQLException e) { final Object[] sqlParams = new Object[] {}; throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); } return result; } private Map<String, Object> retrieveRow(final ResultSet rs) throws SQLException { final Map<String, Object> row = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); final ResultSetMetaData rsMetaData = rs.getMetaData(); final int columnCount = rsMetaData.getColumnCount(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { final String columnName = rsMetaData.getColumnName(columnIndex);
Object cellValue = rs.getObject(columnIndex); if (rs.wasNull()) { cellValue = null; } row.put(columnName, cellValue); } return row; } @Override public Optional<String> getSuggestedFilename() { final Collection<Object> rows = getRows(); if (rows.isEmpty()) { return Optional.empty(); } @SuppressWarnings("unchecked") final Map<String, Object> row = (Map<String, Object>)rows.iterator().next(); final Object reportFileNameObj = row.get(COLUMNNAME_ReportFileName); if (reportFileNameObj == null) { return Optional.empty(); } final String reportFileName = StringUtils.trimBlankToNull(reportFileNameObj.toString()); if (reportFileName == null) { return Optional.empty(); } return Optional.of(reportFileName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JdbcXlsDataSource.java
2
请完成以下Java代码
public ConditionExpression getCondition() { return conditionChild.getChild(this); } public void setCondition(ConditionExpression condition) { conditionChild.setChild(this, condition); } public String getCamundaRepeatOnStandardEvent() { return camundaRepeatOnStandardEventAttribute.getValue(this); } public void setCamundaRepeatOnStandardEvent(String standardEvent) { camundaRepeatOnStandardEventAttribute.setValue(this, standardEvent); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(RepetitionRule.class, CMMN_ELEMENT_REPETITION_RULE) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<RepetitionRule>() { public RepetitionRule newInstance(ModelTypeInstanceContext instanceContext) { return new RepetitionRuleImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF) .idAttributeReference(CaseFileItem.class) .build();
/** Camunda extensions */ camundaRepeatOnStandardEventAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_REPEAT_ON_STANDARD_EVENT) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionChild = sequenceBuilder.element(ConditionExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\RepetitionRuleImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class VariableInitializingList extends ArrayList<VariableInstanceEntity> { private static final long serialVersionUID = 1L; @Override public void add(int index, VariableInstanceEntity e) { super.add(index, e); initializeVariable(e); } @Override public boolean add(VariableInstanceEntity e) { initializeVariable(e); return super.add(e); } @Override public boolean addAll(Collection<? extends VariableInstanceEntity> c) { for (VariableInstanceEntity e : c) { initializeVariable(e); } return super.addAll(c); } @Override public boolean addAll(int index, Collection<? extends VariableInstanceEntity> c) { for (VariableInstanceEntity e : c) {
initializeVariable(e); } return super.addAll(index, c); } /** * If the passed {@link VariableInstanceEntity} is a binary variable and the command-context is active, the variable value is fetched to ensure the byte-array is populated. */ protected void initializeVariable(VariableInstanceEntity e) { if (Context.getCommandContext() != null && e != null && e.getType() != null) { e.getValue(); // make sure JPA entities are cached for later retrieval if (JPAEntityVariableType.TYPE_NAME.equals(e.getType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(e.getType().getTypeName())) { ((CacheableVariable) e.getType()).setForceCacheable(true); } } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInitializingList.java
2
请完成以下Java代码
private void add(Map<?, ?> properties) { Map<String, Pattern> includes = getPatterns(properties, "restart.include."); this.restartIncludePatterns.addAll(includes.values()); Map<String, Pattern> excludes = getPatterns(properties, "restart.exclude."); this.restartExcludePatterns.addAll(excludes.values()); properties.forEach((key, value) -> { String name = String.valueOf(key); if (name.startsWith("defaults.")) { name = name.substring("defaults.".length()); this.propertyDefaults.put(name, value); } }); } private Map<String, Pattern> getPatterns(Map<?, ?> properties, String prefix) { Map<String, Pattern> patterns = new LinkedHashMap<>(); properties.forEach((key, value) -> { String name = String.valueOf(key); if (name.startsWith(prefix)) { Pattern pattern = Pattern.compile((String) value); patterns.put(name, pattern); } }); return patterns; } public boolean isRestartInclude(URL url) { return isMatch(url.toString(), this.restartIncludePatterns); } public boolean isRestartExclude(URL url) { return isMatch(url.toString(), this.restartExcludePatterns); } public Map<String, Object> getPropertyDefaults() { return Collections.unmodifiableMap(this.propertyDefaults); } private boolean isMatch(String url, List<Pattern> patterns) {
for (Pattern pattern : patterns) { if (pattern.matcher(url).find()) { return true; } } return false; } public static DevToolsSettings get() { if (settings == null) { settings = load(); } return settings; } static DevToolsSettings load() { return load(SETTINGS_RESOURCE_LOCATION); } static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(location); while (urls.hasMoreElements()) { settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { throw new IllegalStateException("Unable to load devtools settings from location [" + location + "]", ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\settings\DevToolsSettings.java
1
请完成以下Java代码
public class GraphExperiments { public static Map<Long, User> USERS = new HashMap<>(); public static void main(String[] args) throws IOException { Logger.getLogger("org").setLevel(Level.OFF); GraphLoader loader = new GraphLoader(); GraphFrame graph = loader.getGraphFrameUserRelationship(); GraphExperiments experiments = new GraphExperiments(); experiments.doGraphFrameOperations(graph); experiments.doGraphFrameAlgorithms(graph); } private void doGraphFrameOperations(GraphFrame graph) { graph.vertices().show(); graph.edges().show(); graph.vertices().filter("name = 'Martin'").show();
graph.filterEdges("type = 'Friend'") .dropIsolatedVertices().vertices().show(); graph.degrees().show(); graph.inDegrees().show(); graph.outDegrees().show(); } private void doGraphFrameAlgorithms(GraphFrame graph) { graph.pageRank().maxIter(20).resetProbability(0.15).run().vertices().show(); graph.connectedComponents().run().show(); graph.triangleCount().run().show(); } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\graphframes\GraphExperiments.java
1
请完成以下Java代码
public class BaseUrlFilter implements Filter { private static String BASE_URL; public static String getBaseUrl() { String baseUrl; try { baseUrl = (String) RequestContextHolder.currentRequestAttributes().getAttribute("baseUrl", 0); } catch (Exception e) { baseUrl = BASE_URL; } return baseUrl; } @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { String baseUrl; String configBaseUrl = ConfigConstants.getBaseUrl(); final HttpServletRequest servletRequest = (HttpServletRequest) request; //1、支持通过 http header 中 X-Base-Url 来动态设置 baseUrl 以支持多个域名/项目的共享使用 final String urlInHeader = servletRequest.getHeader("X-Base-Url"); if (StringUtils.isNotEmpty(urlInHeader)) { baseUrl = urlInHeader; } else if (configBaseUrl != null && !ConfigConstants.DEFAULT_VALUE.equalsIgnoreCase(configBaseUrl)) { //2、如果配置文件中配置了 baseUrl 且不为 default 则以配置文件为准 baseUrl = configBaseUrl; } else { //3、默认动态拼接 baseUrl
baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + servletRequest.getContextPath() + "/"; } if (!baseUrl.endsWith("/")) { baseUrl = baseUrl.concat("/"); } BASE_URL = baseUrl; request.setAttribute("baseUrl", baseUrl); filterChain.doFilter(request, response); } @Override public void destroy() { } }
repos\kkFileView-master\server\src\main\java\cn\keking\web\filter\BaseUrlFilter.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult info(Principal principal) { if(principal==null){ return CommonResult.unauthorized(null); } UmsMember member = memberService.getCurrentMember(); return CommonResult.success(member); } @ApiOperation("获取验证码") @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET) @ResponseBody public CommonResult getAuthCode(@RequestParam String telephone) { String authCode = memberService.generateAuthCode(telephone); return CommonResult.success(authCode,"获取验证码成功"); } @ApiOperation("会员修改密码") @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) @ResponseBody public CommonResult updatePassword(@RequestParam String telephone, @RequestParam String password, @RequestParam String authCode) { memberService.updatePassword(telephone,password,authCode); return CommonResult.success(null,"密码修改成功"); }
@ApiOperation(value = "刷新token") @RequestMapping(value = "/refreshToken", method = RequestMethod.GET) @ResponseBody public CommonResult refreshToken(HttpServletRequest request) { String token = request.getHeader(tokenHeader); String refreshToken = memberService.refreshToken(token); if (refreshToken == null) { return CommonResult.failed("token已经过期!"); } Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", refreshToken); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\UmsMemberController.java
2
请完成以下Java代码
public void setDunningGraceOnInvoice(final I_C_Dunning_Candidate candidate) { if (candidate.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Invoice.class)) { return; } final Properties ctx = InterfaceWrapperHelper.getCtx(candidate); final String trxName = InterfaceWrapperHelper.getTrxName(candidate); final I_C_Invoice invoice = InterfaceWrapperHelper.create(ctx, candidate.getRecord_ID(), I_C_Invoice.class, trxName); invoice.setDunningGrace(candidate.getDunningGrace()); InterfaceWrapperHelper.setDynAttribute(invoice, POATTR_CallerPO, candidate); InterfaceWrapperHelper.save(invoice); } @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE
, ifColumnsChanged = I_C_Dunning_Candidate.COLUMNNAME_IsDunningDocProcessed) public void setDunningLevelOnInvoice(final I_C_Dunning_Candidate candidate) { if (candidate.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Invoice.class) || !candidate.isDunningDocProcessed()) { return; } final Properties ctx = InterfaceWrapperHelper.getCtx(candidate); final String trxName = InterfaceWrapperHelper.getTrxName(candidate); final I_C_Invoice invoice = InterfaceWrapperHelper.create(ctx, candidate.getRecord_ID(), I_C_Invoice.class, trxName); invoice.setC_DunningLevel(candidate.getC_DunningLevel()); InterfaceWrapperHelper.save(invoice); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\model\validator\C_Dunning_Candidate.java
1
请完成以下Java代码
public Integer getId() { return id; } public UserDO setId(Integer id) { this.id = id; return this; } public String getUsername() { return username; } public UserDO setUsername(String username) { this.username = username; return this; } public String getPassword() { return password; } public UserDO setPassword(String password) { this.password = password; return this; } public Date getCreateTime() { return createTime; }
public UserDO setCreateTime(Date createTime) { this.createTime = createTime; return this; } public Profile getProfile() { return profile; } public UserDO setProfile(Profile profile) { this.profile = profile; return this; } @Override public String toString() { return "UserDO{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", createTime=" + createTime + ", profile=" + profile + '}'; } }
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\dataobject\UserDO.java
1
请完成以下Java代码
public Incident createIncident(String incidentType, String configuration) { return createIncident(incidentType, configuration, null); } public Incident createIncident(String incidentType, String configuration, String message) { IncidentContext incidentContext = createIncidentContext(configuration); return IncidentHandling.createIncident(incidentType, incidentContext, message); } protected IncidentContext createIncidentContext(String configuration) { IncidentContext incidentContext = new IncidentContext(); incidentContext.setTenantId(this.getTenantId()); incidentContext.setProcessDefinitionId(this.getProcessDefinitionId()); incidentContext.setExecutionId(this.getId()); incidentContext.setActivityId(this.getActivityId()); incidentContext.setConfiguration(configuration); return incidentContext; } /** * Resolves an incident with given id. * * @param incidentId */ @Override public void resolveIncident(final String incidentId) { IncidentEntity incident = (IncidentEntity) Context .getCommandContext() .getIncidentManager() .findIncidentById(incidentId); IncidentContext incidentContext = new IncidentContext(incident); IncidentHandling.removeIncidents(incident.getIncidentType(), incidentContext, true); }
public IncidentHandler findIncidentHandler(String incidentType) { Map<String, IncidentHandler> incidentHandlers = Context.getProcessEngineConfiguration().getIncidentHandlers(); return incidentHandlers.get(incidentType); } public boolean isExecutingScopeLeafActivity() { return isActive && getActivity() != null && getActivity().isScope() && activityInstanceId != null && !(getActivity().getActivityBehavior() instanceof CompositeActivityBehavior); } /** * This case is special, because the execution tree is different if an async after * activity is left via transition (case 1) or not (case 2). In case 1, when the * execution becomes async, the scope execution is already removed. In case 2 it is not. * * @return true if * <ul> * <li>the execution is in asyncAfter state and completes * <li>leaves a scope activity * <li>completes the parent scope (i.e. does not leave via a transition * but propagates control to the parent) * </ul> */ public boolean isAsyncAfterScopeWithoutTransition() { return activityInstanceId == null && activity.isScope() && !isActive; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\PvmExecutionImpl.java
1
请完成以下Java代码
public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setQty (final BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setQtyInUOM (final @Nullable BigDecimal QtyInUOM) { set_Value (COLUMNNAME_QtyInUOM, QtyInUOM); } @Override public BigDecimal getQtyInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInUOM); return bd != null ? bd : BigDecimal.ZERO; } /** * Type AD_Reference_ID=541716 * Reference name: M_MatchInv_Type */ public static final int TYPE_AD_Reference_ID=541716; /** Material = M */ public static final String TYPE_Material = "M"; /** Cost = C */ public static final String TYPE_Cost = "C"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchInv.java
1
请完成以下Java代码
public boolean isTaxExempt() { return get_ValueAsBoolean(COLUMNNAME_IsTaxExempt); } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSurchargeAmt (final BigDecimal SurchargeAmt) { set_ValueNoCheck (COLUMNNAME_SurchargeAmt, SurchargeAmt); } @Override public BigDecimal getSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxAmt (final @Nullable BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxAmtWithSurchargeAmt (final BigDecimal TaxAmtWithSurchargeAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmtWithSurchargeAmt, TaxAmtWithSurchargeAmt);
} @Override public BigDecimal getTaxAmtWithSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtWithSurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final @Nullable BigDecimal TaxBaseAmt) { set_Value (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmtWithSurchargeAmt (final BigDecimal TaxBaseAmtWithSurchargeAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmtWithSurchargeAmt, TaxBaseAmtWithSurchargeAmt); } @Override public BigDecimal getTaxBaseAmtWithSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmtWithSurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalAmt (final @Nullable BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } @Override public BigDecimal getTotalAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_901_991_v.java
1
请完成以下Java代码
public void setId(@NonNull final PPOrderCostId id) { this.id = id; } public ProductId getProductId() { return getCostSegmentAndElement().getProductId(); } public UomId getUomId() { return getPrice().getUomId(); } public CostElementId getCostElementId() { return getCostSegmentAndElement().getCostElementId(); } public boolean isInboundCost() { return !getTrxType().isOutboundCost(); } public boolean isMainProduct() { return getTrxType() == PPOrderCostTrxType.MainProduct; } public boolean isCoProduct() { return getTrxType().isCoProduct(); } public boolean isByProduct() { return getTrxType() == PPOrderCostTrxType.ByProduct; } @NonNull public PPOrderCost addingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { if (amt.isZero() && qty.isZero()) { return this; } final boolean amtIsPositiveOrZero = amt.signum() >= 0;
final boolean amtIsNotZero = amt.signum() != 0; final boolean qtyIsPositiveOrZero = qty.signum() >= 0; if (amtIsNotZero && amtIsPositiveOrZero != qtyIsPositiveOrZero ) { throw new AdempiereException("Amount and Quantity shall have the same sign: " + amt + ", " + qty); } final Quantity accumulatedQty = getAccumulatedQty(); final Quantity qtyConv = uomConverter.convertQuantityTo(qty, getProductId(), accumulatedQty.getUomId()); return toBuilder() .accumulatedAmount(getAccumulatedAmount().add(amt)) .accumulatedQty(accumulatedQty.add(qtyConv)) .build(); } public PPOrderCost subtractingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter); } public PPOrderCost withPrice(@NonNull final CostPrice newPrice) { if (this.getPrice().equals(newPrice)) { return this; } return toBuilder().price(newPrice).build(); } /* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount) { this.postCalculationAmount = postCalculationAmount; } /* package */void setPostCalculationAmountAsAccumulatedAmt() { setPostCalculationAmount(getAccumulatedAmount()); } /* package */void setPostCalculationAmountAsZero() { setPostCalculationAmount(getPostCalculationAmount().toZero()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java
1
请完成以下Java代码
public String getUsername() { return username; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public OAuth2AccessToken getToken() { return token; } public void setToken(OAuth2AccessToken token) { this.token = token; } public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return null; }
@Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectUserDetails.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public UserEntity getCompany() { return company; } public void setCompany(UserEntity company) { this.company = company; } public List<ProductOrderEntity> getProductOrderList() { return productOrderList; } public void setProductOrderList(List<ProductOrderEntity> productOrderList) { this.productOrderList = productOrderList; } public OrderStateEnum getOrderStateEnum() { return orderStateEnum; } public void setOrderStateEnum(OrderStateEnum orderStateEnum) { this.orderStateEnum = orderStateEnum; } public List<OrderStateTimeEntity> getOrderStateTimeList() { return orderStateTimeList; } public void setOrderStateTimeList(List<OrderStateTimeEntity> orderStateTimeList) { this.orderStateTimeList = orderStateTimeList; } public PayModeEnum getPayModeEnum() { return payModeEnum; } public void setPayModeEnum(PayModeEnum payModeEnum) { this.payModeEnum = payModeEnum; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public ReceiptEntity getReceiptEntity() { return receiptEntity; } public void setReceiptEntity(ReceiptEntity receiptEntity) { this.receiptEntity = receiptEntity; } public LocationEntity getLocationEntity() { return locationEntity; }
public void setLocationEntity(LocationEntity locationEntity) { this.locationEntity = locationEntity; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getExpressNo() { return expressNo; } public void setExpressNo(String expressNo) { this.expressNo = expressNo; } public UserEntity getBuyer() { return buyer; } public void setBuyer(UserEntity buyer) { this.buyer = buyer; } @Override public String toString() { return "OrdersEntity{" + "id='" + id + '\'' + ", buyer=" + buyer + ", company=" + company + ", productOrderList=" + productOrderList + ", orderStateEnum=" + orderStateEnum + ", orderStateTimeList=" + orderStateTimeList + ", payModeEnum=" + payModeEnum + ", totalPrice='" + totalPrice + '\'' + ", receiptEntity=" + receiptEntity + ", locationEntity=" + locationEntity + ", remark='" + remark + '\'' + ", expressNo='" + expressNo + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java
2
请在Spring Boot框架中完成以下Java代码
public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { String location = registration.getAssertingPartyMetadata().getSingleSignOnServiceLocation(); return new Builder(registration).authenticationRequestUri(location); } /** * Builder class for a {@link Saml2RedirectAuthenticationRequest} object. */ public static final class Builder extends AbstractSaml2AuthenticationRequest.Builder<Builder> { private String sigAlg; private String signature; private Builder(RelyingPartyRegistration registration) { super(registration); } /** * Sets the {@code SigAlg} parameter that will accompany this AuthNRequest * @param sigAlg the SigAlg parameter value. * @return this object */ public Builder sigAlg(String sigAlg) { this.sigAlg = sigAlg; return _this(); }
/** * Sets the {@code Signature} parameter that will accompany this AuthNRequest * @param signature the Signature parameter value. * @return this object */ public Builder signature(String signature) { this.signature = signature; return _this(); } /** * Constructs an immutable {@link Saml2RedirectAuthenticationRequest} object. * @return an immutable {@link Saml2RedirectAuthenticationRequest} object. */ public Saml2RedirectAuthenticationRequest build() { return new Saml2RedirectAuthenticationRequest(this.samlRequest, this.sigAlg, this.signature, this.relayState, this.authenticationRequestUri, this.relyingPartyRegistrationId, this.id); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2RedirectAuthenticationRequest.java
2
请完成以下Java代码
public void setPlannedQty (java.math.BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public java.math.BigDecimal getPlannedQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPP_Product_Planning_ID (int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_Value (COLUMNNAME_PP_Product_Planning_ID, null); else set_Value (COLUMNNAME_PP_Product_Planning_ID, Integer.valueOf(PP_Product_Planning_ID)); }
@Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQtyOrdered (java.math.BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public java.math.BigDecimal getQtyOrdered() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Purchase_Detail.java
1
请完成以下Java代码
public void setWEBUI_Role (boolean WEBUI_Role) { set_Value (COLUMNNAME_WEBUI_Role, Boolean.valueOf(WEBUI_Role)); } /** Get Is webui role. @return Is webui role */ @Override public boolean isWEBUI_Role () { Object oo = get_Value(COLUMNNAME_WEBUI_Role); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } @Override public void setIsAllowPasswordChangeForOthers (final boolean IsAllowPasswordChangeForOthers) { set_Value (COLUMNNAME_IsAllowPasswordChangeForOthers, IsAllowPasswordChangeForOthers); } @Override public boolean isAllowPasswordChangeForOthers() { return get_ValueAsBoolean(COLUMNNAME_IsAllowPasswordChangeForOthers); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role.java
1
请完成以下Java代码
public CaseInstanceQuery orderByCaseDefinitionId() { orderBy(CaseInstanceQueryProperty.CASE_DEFINITION_ID); return this; } public CaseInstanceQuery orderByTenantId() { orderBy(CaseInstanceQueryProperty.TENANT_ID); return this; } //results ///////////////////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getCaseExecutionManager() .findCaseInstanceCountByQueryCriteria(this); } public List<CaseInstance> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getCaseExecutionManager() .findCaseInstanceByQueryCriteria(this, page); } //getters ///////////////////////////////////////////////////////////////// public String getCaseInstanceId() { return caseExecutionId; } public String getCaseExecutionId() { return caseExecutionId; } public String getActivityId() { return null; } public String getBusinessKey() { return businessKey; } public String getCaseDefinitionId() { return caseDefinitionId;
} public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getDeploymentId() { return deploymentId; } public CaseExecutionState getState() { return state; } public boolean isCaseInstancesOnly() { return true; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public Boolean isRequired() { return required; } public Boolean isRepeatable() { return repeatable; } public Boolean isRepetition() { return repetition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseInstanceQueryImpl.java
1
请完成以下Java代码
public void onLogin(final LoginEvent event) { try { loginViewSupport.authenticate( AuthDetails.of(event.getUsername(), event.getPassword()) .withLocale(login.getSelectedLocale()) .withRememberMe(login.isRememberMe()) ); } catch (final BadCredentialsException | DisabledException | LockedException | AccessDeniedException e) { log.warn("Login failed for user '{}': {}", event.getUsername(), e.toString()); event.getSource().setError(true); } } @Override public void localeChange(final LocaleChangeEvent event) { UI.getCurrent().getPage().setTitle(messageBundle.getMessage("LoginView.title")); final JmixLoginI18n loginI18n = JmixLoginI18n.createDefault(); final JmixLoginI18n.JmixForm form = new JmixLoginI18n.JmixForm(); form.setTitle(messageBundle.getMessage("loginForm.headerTitle"));
form.setUsername(messageBundle.getMessage("loginForm.username")); form.setPassword(messageBundle.getMessage("loginForm.password")); form.setSubmit(messageBundle.getMessage("loginForm.submit")); form.setForgotPassword(messageBundle.getMessage("loginForm.forgotPassword")); form.setRememberMe(messageBundle.getMessage("loginForm.rememberMe")); loginI18n.setForm(form); final LoginI18n.ErrorMessage errorMessage = new LoginI18n.ErrorMessage(); errorMessage.setTitle(messageBundle.getMessage("loginForm.errorTitle")); errorMessage.setMessage(messageBundle.getMessage("loginForm.badCredentials")); errorMessage.setUsername(messageBundle.getMessage("loginForm.errorUsername")); errorMessage.setPassword(messageBundle.getMessage("loginForm.errorPassword")); loginI18n.setErrorMessage(errorMessage); login.setI18n(loginI18n); } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\view\login\LoginView.java
1
请完成以下Java代码
public WebuiEmail createNewEmail( @NonNull final UserId ownerUserId, @NonNull final LookupValue from, @NonNull final LookupValuesList toList, @Nullable final DocumentPath contextDocumentPath) { final String emailId = String.valueOf(nextEmailId.getAndIncrement()); final WebuiEmail email = WebuiEmail.builder() .emailId(emailId) .ownerUserId(ownerUserId) .from(from) .to(toList) .contextDocumentPath(contextDocumentPath) .build(); emailsById.put(emailId, new WebuiEmailEntry(email)); return email; } private WebuiEmailEntry getEmailEntry(final String emailId) { final WebuiEmailEntry emailEntry = emailsById.getIfPresent(emailId); if (emailEntry == null) { throw new EntityNotFoundException("Email not found") .setParameter("emailId", emailId); } return emailEntry; } public WebuiEmail getEmail(final String emailId) { return getEmailEntry(emailId).getEmail(); } WebuiEmailChangeResult changeEmail(final String emailId, final UnaryOperator<WebuiEmail> emailModifier) { return getEmailEntry(emailId).compute(emailModifier); } public void removeEmailById(final String emailId) { emailsById.invalidate(emailId); } /** * Called when the email was removed from our internal cache. */ private void onEmailRemoved(final WebuiEmail email) { eventPublisher.publishEvent(new WebuiEmailRemovedEvent(email)); } public LookupValuesPage getToTypeahead(final String ignoredEmailId, final String query) { final Evaluatee ctx = Evaluatees.empty(); // TODO // TODO: filter only those which have a valid email address return emailToLookup.findEntities(ctx, query);
} public LookupValue getToByUserId(final Integer adUserId) { return emailToLookup.findById(adUserId); } @ToString private static final class WebuiEmailEntry { private WebuiEmail email; public WebuiEmailEntry(@NonNull final WebuiEmail email) { this.email = email; } public synchronized WebuiEmail getEmail() { return email; } public synchronized WebuiEmailChangeResult compute(final UnaryOperator<WebuiEmail> modifier) { final WebuiEmail emailOld = email; final WebuiEmail emailNew = modifier.apply(emailOld); if (emailNew == null) { throw new NullPointerException("email"); } email = emailNew; return WebuiEmailChangeResult.builder().email(emailNew).originalEmail(emailOld).build(); } } @Value @AllArgsConstructor public static class WebuiEmailRemovedEvent { @NonNull WebuiEmail email; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailRepository.java
1
请完成以下Java代码
public static ServerWebExchangeMatcher pathMatchers(String... patterns) { return pathMatchers(null, patterns); } /** * Creates a matcher that matches on any of the provided {@link PathPattern}s. * @param pathPatterns the {@link PathPattern}s to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(PathPattern... pathPatterns) { return pathMatchers(null, pathPatterns); } /** * Creates a matcher that matches on the specific method and any of the provided * {@link PathPattern}s. * @param method the method to match on. If null, any method will be matched. * @param pathPatterns the {@link PathPattern}s to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(@Nullable HttpMethod method, PathPattern... pathPatterns) { List<ServerWebExchangeMatcher> matchers = new ArrayList<>(pathPatterns.length); for (PathPattern pathPattern : pathPatterns) { matchers.add(new PathPatternParserServerWebExchangeMatcher(pathPattern, method)); } return new OrServerWebExchangeMatcher(matchers); } /** * Creates a matcher that will match on any of the provided matchers * @param matchers the matchers to match on * @return the matcher to use */ public static ServerWebExchangeMatcher matchers(ServerWebExchangeMatcher... matchers) { return new OrServerWebExchangeMatcher(matchers);
} /** * Matches any exchange * @return the matcher to use */ @SuppressWarnings("Convert2Lambda") public static ServerWebExchangeMatcher anyExchange() { // we don't use a lambda to ensure a unique equals and hashcode // which otherwise can cause problems with adding multiple entries to an ordered // LinkedHashMap return new ServerWebExchangeMatcher() { @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return ServerWebExchangeMatcher.MatchResult.match(); } }; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\ServerWebExchangeMatchers.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() {
return phone; } public void setPhone(String phone) { this.phone = phone; } public ContactPerson getContactPerson() { return contactPerson; } public void setContactPerson(ContactPerson contactPerson) { this.contactPerson = contactPerson; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-annotations\src\main\java\com\baeldung\embeddable\model\Company.java
1
请完成以下Java代码
public LookupValuesList retrieveHUPIItemProducts( @NonNull final Properties ctx, @NonNull final ProductId productId, @Nullable final BPartnerId bpartnerId, final boolean includeVirtualItem) { final List<I_M_HU_PI_Item_Product> list = retrieveHUPIItemProductRecords(ctx, productId, bpartnerId, includeVirtualItem); return list.stream() .sorted(Comparator.comparing(I_M_HU_PI_Item_Product::getName)) .map(huPIItemProduct -> IntegerLookupValue.of(huPIItemProduct.getM_HU_PI_Item_Product_ID(), huPIItemProduct.getName())) .collect(LookupValuesList.collect()); } public List<I_M_HU_PI_Item_Product> retrieveHUPIItemProductRecords( @NonNull final Properties ctx, @NonNull final ProductId productId, @Nullable final BPartnerId bpartnerId, final boolean includeVirtualItem) { final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class); final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final boolean allowInfiniteCapacity = sysConfigBL.getBooleanValue(SYSCONFIG_ALLOW_INFINIT_CAPACITY_TUS, true, Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx)); final List<I_M_HU_PI_Item_Product> list = hupiItemProductDAO .retrieveTUs(ctx, productId, bpartnerId, allowInfiniteCapacity);
if (includeVirtualItem) { list.add(hupiItemProductDAO.retrieveVirtualPIMaterialItemProduct(ctx)); } return list; } /** * Creates a string of the form "PI-Version-Name (Qty x Included-PI)", e.g. "Palette (20 x IFCO)". * * @param huPIItem may not be {@code null} * @return */ public String buildHUPIItemString(@NonNull final I_M_HU_PI_Item huPIItem) { final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final I_M_HU_PI includedPI = handlingUnitsDAO.getIncludedPI(huPIItem); final String result = StringUtils.formatMessage("{} ({} x {})", huPIItem.getM_HU_PI_Version().getName(), huPIItem.getQty().setScale(0, RoundingMode.HALF_UP), // it's always integer quantities includedPI.getName()); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\WEBUI_ProcessHelper.java
1
请完成以下Java代码
public void setCostAmount (final BigDecimal CostAmount) { set_Value (COLUMNNAME_CostAmount, CostAmount); } @Override public BigDecimal getCostAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setCostAmountReceived (final BigDecimal CostAmountReceived) { set_Value (COLUMNNAME_CostAmountReceived, CostAmountReceived); } @Override public BigDecimal getCostAmountReceived() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmountReceived); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setLineNetAmt (final BigDecimal LineNetAmt) { set_Value (COLUMNNAME_LineNetAmt, LineNetAmt); } @Override public BigDecimal getLineNetAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_LineNetAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() {
return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyOrdered (final BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReceived (final BigDecimal QtyReceived) { set_Value (COLUMNNAME_QtyReceived, QtyReceived); } @Override public BigDecimal getQtyReceived() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java
1
请完成以下Java代码
protected BatchElementConfiguration collectHistoricDecisionInstanceIds(CommandContext commandContext) { BatchElementConfiguration elementConfiguration = new BatchElementConfiguration(); if (!CollectionUtil.isEmpty(historicDecisionInstanceIds)) { HistoricDecisionInstanceQueryImpl query = new HistoricDecisionInstanceQueryImpl(); query.decisionInstanceIdIn(historicDecisionInstanceIds.toArray(new String[0])); elementConfiguration.addDeploymentMappings( commandContext.runWithoutAuthorization(query::listDeploymentIdMappings), historicDecisionInstanceIds); } final HistoricDecisionInstanceQueryImpl decisionInstanceQuery = (HistoricDecisionInstanceQueryImpl) historicDecisionInstanceQuery; if (decisionInstanceQuery != null) { elementConfiguration.addDeploymentMappings(decisionInstanceQuery.listDeploymentIdMappings()); } return elementConfiguration; }
protected void writeUserOperationLog(CommandContext commandContext, int numInstances) { List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances)); propertyChanges.add(new PropertyChange("async", null, true)); propertyChanges.add(new PropertyChange("deleteReason", null, deleteReason)); commandContext.getOperationLogManager() .logDecisionInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY, null, propertyChanges); } public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) { return new BatchConfiguration(elementConfiguration.getIds(), elementConfiguration.getMappings()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\cmd\DeleteHistoricDecisionInstancesBatchCmd.java
1
请完成以下Java代码
public String getDigest(String value) { if (m_md == null) { try { m_md = MessageDigest.getInstance("MD5"); // m_md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } // Reset MessageDigest object m_md.reset(); // Convert String to array of bytes byte[] input = value.getBytes(StandardCharsets.UTF_8); // feed this array of bytes to the MessageDigest object m_md.update(input); // Get the resulting bytes after the encryption process byte[] output = m_md.digest(); m_md.reset(); // return convertToHexString(output); } // getDigest /** * Checks, if value is a valid digest * * @param value digest string * @return true if valid digest */ @Override public boolean isDigest(String value) { if (value == null || value.length() != 32) return false;
// needs to be a hex string, so try to convert it return (convertHexString(value) != null); } // isDigest /** * String Representation * * @return info */ @Override public String toString() { return MoreObjects.toStringHelper(this) .add("cipher", m_cipher) .toString(); } } // Secure
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Secure.java
1
请完成以下Java代码
public void setAD_Role(final org.compiere.model.I_AD_Role AD_Role) { set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role); } @Override public void setAD_Role_ID (final int AD_Role_ID) { if (AD_Role_ID < 0) set_Value (COLUMNNAME_AD_Role_ID, null); else set_Value (COLUMNNAME_AD_Role_ID, AD_Role_ID); } @Override public int getAD_Role_ID() { return get_ValueAsInt(COLUMNNAME_AD_Role_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_WF_Responsible_ID (final int AD_WF_Responsible_ID) { if (AD_WF_Responsible_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Responsible_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Responsible_ID, AD_WF_Responsible_ID); } @Override public int getAD_WF_Responsible_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Responsible_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */
public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @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); } /** * ResponsibleType AD_Reference_ID=304 * Reference name: WF_Participant Type */ public static final int RESPONSIBLETYPE_AD_Reference_ID=304; /** Organisation = O */ public static final String RESPONSIBLETYPE_Organisation = "O"; /** Human = H */ public static final String RESPONSIBLETYPE_Human = "H"; /** Rolle = R */ public static final String RESPONSIBLETYPE_Rolle = "R"; /** Systemressource = S */ public static final String RESPONSIBLETYPE_Systemressource = "S"; /** Other = X */ public static final String RESPONSIBLETYPE_Other = "X"; @Override public void setResponsibleType (final java.lang.String ResponsibleType) { set_Value (COLUMNNAME_ResponsibleType, ResponsibleType); } @Override public java.lang.String getResponsibleType() { return get_ValueAsString(COLUMNNAME_ResponsibleType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Responsible.java
1
请完成以下Java代码
public IntermediateThrowCompensationEventActivityBehavior createIntermediateThrowCompensationEventActivityBehavior(ThrowEvent throwEvent, CompensateEventDefinition compensateEventDefinition) { return new IntermediateThrowCompensationEventActivityBehavior(compensateEventDefinition); } // End events @Override public NoneEndEventActivityBehavior createNoneEndEventActivityBehavior(EndEvent endEvent) { return new NoneEndEventActivityBehavior(); } @Override public ErrorEndEventActivityBehavior createErrorEndEventActivityBehavior(EndEvent endEvent, ErrorEventDefinition errorEventDefinition) { return new ErrorEndEventActivityBehavior(errorEventDefinition.getErrorCode()); } @Override public CancelEndEventActivityBehavior createCancelEndEventActivityBehavior(EndEvent endEvent) { return new CancelEndEventActivityBehavior(); } @Override public TerminateEndEventActivityBehavior createTerminateEndEventActivityBehavior(EndEvent endEvent) {
return new TerminateEndEventActivityBehavior(endEvent); } // Boundary Events @Override public BoundaryEventActivityBehavior createBoundaryEventActivityBehavior(BoundaryEvent boundaryEvent, boolean interrupting, ActivityImpl activity) { return new BoundaryEventActivityBehavior(interrupting, activity.getId()); } @Override public CancelBoundaryEventActivityBehavior createCancelBoundaryEventActivityBehavior(CancelEventDefinition cancelEventDefinition) { return new CancelBoundaryEventActivityBehavior(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
1
请完成以下Java代码
public class MemberDetails implements UserDetails { private final UmsMember umsMember; public MemberDetails(UmsMember umsMember) { this.umsMember = umsMember; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { //返回当前用户的权限 return Arrays.asList(new SimpleGrantedAuthority("TEST")); } @Override public String getPassword() { return umsMember.getPassword(); } @Override public String getUsername() { return umsMember.getUsername(); } @Override
public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return umsMember.getStatus()==1; } public UmsMember getUmsMember() { return umsMember; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\domain\MemberDetails.java
1
请完成以下Java代码
protected String buildMappings(List<String> mappingFiles) { List<String> mappings = new ArrayList<String>(mappingFiles); mappings.addAll(Arrays.asList(DEFAULT_MAPPING_FILES)); StringBuilder builder = new StringBuilder(); for (String mappingFile: mappings) { builder.append(String.format("<mapper resource=\"%s\" />\n", mappingFile)); } String mappingsFileTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "\n" + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n" + "\n" + "<configuration>\n" + " <settings>\n" +
" <setting name=\"lazyLoadingEnabled\" value=\"false\" />\n" + " </settings>\n" + " <mappers>\n" + "%s\n" + " </mappers>\n" + "</configuration>"; return String.format(mappingsFileTemplate, builder.toString()); } public ProcessEngineConfigurationImpl getWrappedConfiguration() { return wrappedConfiguration; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\db\QuerySessionFactory.java
1
请在Spring Boot框架中完成以下Java代码
public Object execute(CommandContext commandContext) { SuspendedJobEntity jobToDelete = getJobToDelete(commandContext); sendCancelEvent(jobToDelete); jobServiceConfiguration.getSuspendedJobEntityManager().delete(jobToDelete); return null; } protected void sendCancelEvent(SuspendedJobEntity jobToDelete) { FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete), jobServiceConfiguration.getEngineName()); } } protected SuspendedJobEntity getJobToDelete(CommandContext commandContext) { if (suspendedJobId == null) {
throw new FlowableIllegalArgumentException("jobId is null"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deleting job {}", suspendedJobId); } SuspendedJobEntity job = jobServiceConfiguration.getSuspendedJobEntityManager().findById(suspendedJobId); if (job == null) { throw new FlowableObjectNotFoundException("No suspended job found with id '" + suspendedJobId + "'", Job.class); } return job; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteSuspendedJobCmd.java
2
请完成以下Java代码
public String inline(@NonNull final String sql, @Nullable final List<Object> params) { try { return inline0(sql, params); } catch (final Exception ex) { //noinspection ConstantConditions throw AdempiereException.wrapIfNeeded(ex) .setParameter("sql", sql) .setParameter("sqlParams", params) .appendParametersToMessage(); } } private String inline0(@NonNull final String sql, @Nullable final List<Object> params) { final int paramsCount = params != null ? params.size() : 0; final int sqlLength = sql.length(); final StringBuilder sqlFinal = new StringBuilder(sqlLength); boolean insideQuotes = false; int nextParamIndex = 0; for (int i = 0; i < sqlLength; i++) { final char ch = sql.charAt(i); if (ch == '?') { if (insideQuotes) { sqlFinal.append(ch); } else { if (params != null && nextParamIndex < paramsCount) { sqlFinal.append(DB.TO_SQL(params.get(nextParamIndex))); } else { // error: parameter index is invalid appendMissingParam(sqlFinal, nextParamIndex); } nextParamIndex++; } } else if (ch == '\'') { sqlFinal.append(ch); insideQuotes = !insideQuotes; } else { sqlFinal.append(ch); } } if (params != null && nextParamIndex < paramsCount) { appendExceedingParams(sqlFinal, nextParamIndex, paramsCount, params); } return sqlFinal.toString(); } private void appendMissingParam( final StringBuilder sql, final int missingParamIndexZeroBased) { final int missingParamIndexOneBased = missingParamIndexZeroBased + 1;
if (failOnError) { throw new AdempiereException("Missing SQL parameter with index=" + missingParamIndexOneBased); } sql.append("?missing").append(missingParamIndexOneBased).append("?"); } private void appendExceedingParams( final StringBuilder sql, final int firstExceedingParamIndex, final int paramsCount, final List<Object> allParams) { if (failOnError) { throw new AdempiereException("Got more SQL params than needed: " + allParams.subList(firstExceedingParamIndex, allParams.size())); } sql.append(" -- Exceeding params: "); boolean firstExceedingParam = true; for (int i = firstExceedingParamIndex; i < paramsCount; i++) { if (firstExceedingParam) { firstExceedingParam = false; } else { sql.append(", "); } sql.append(DB.TO_SQL(allParams.get(i))); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\sql\SqlParamsInliner.java
1