instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
DefaultTracingObservationHandler defaultTracingObservationHandler(Tracer tracer) { return new DefaultTracingObservationHandler(tracer); } @Bean @ConditionalOnMissingBean @ConditionalOnBean(Propagator.class) @Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER) PropagatingSenderTracingObservationHandler<?> propagatingSenderTracingObservationHandler(Tracer tracer, Propagator propagator) { return new PropagatingSenderTracingObservationHandler<>(tracer, propagator); } @Bean @ConditionalOnMissingBean @ConditionalOnBean(Propagator.class) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) PropagatingReceiverTracingObservationHandler<?> propagatingReceiverTracingObservationHandler(Tracer tracer, Propagator propagator) { return new PropagatingReceiverTracingObservationHandler<>(tracer, propagator); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Advice.class) @ConditionalOnBooleanProperty("management.observations.annotations.enabled") static class SpanAspectConfiguration { @Bean @ConditionalOnMissingBean(NewSpanParser.class) DefaultNewSpanParser newSpanParser() { return new DefaultNewSpanParser(); } @Bean @ConditionalOnMissingBean @ConditionalOnBean(ValueExpressionResolver.class) SpanTagAnnotationHandler spanTagAnnotationHandler(BeanFactory beanFactory,
ValueExpressionResolver valueExpressionResolver) { return new SpanTagAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver); } @Bean @ConditionalOnMissingBean(MethodInvocationProcessor.class) ImperativeMethodInvocationProcessor imperativeMethodInvocationProcessor(NewSpanParser newSpanParser, Tracer tracer, ObjectProvider<SpanTagAnnotationHandler> spanTagAnnotationHandler) { return new ImperativeMethodInvocationProcessor(newSpanParser, tracer, spanTagAnnotationHandler.getIfAvailable()); } @Bean @ConditionalOnMissingBean SpanAspect spanAspect(MethodInvocationProcessor methodInvocationProcessor) { return new SpanAspect(methodInvocationProcessor); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\MicrometerTracingAutoConfiguration.java
2
请完成以下Java代码
public void init(final IModelValidationEngine engine) { CopyRecordFactory.enableForTableName(I_PP_Product_BOM.Table_Name); Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(new org.eevolution.callout.PP_Product_BOM(bomVersionsDAO)); Services.get(ITabCalloutFactory.class).registerTabCalloutForTable(I_PP_Product_BOM.Table_Name, PP_Product_BOM_TabCallout.class); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE }) public void updateProduct(final I_PP_Product_BOM bom) { final ProductId productId = ProductId.ofRepoId(bom.getM_Product_ID()); bomService.updateIsBOMFlag(productId); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_PP_Product_BOM.COLUMNNAME_PP_Product_BOMVersions_ID, I_PP_Product_BOM.COLUMNNAME_M_Product_ID }) public void validateBOMVersions(final I_PP_Product_BOM bom) { final int productId = bom.getM_Product_ID(); final ProductBOMVersionsId bomVersionsId = ProductBOMVersionsId.ofRepoId(bom.getPP_Product_BOMVersions_ID()); final I_PP_Product_BOMVersions bomVersions = bomVersionsDAO.getBOMVersions(bomVersionsId); if (productId != bomVersions.getM_Product_ID()) { throw new AdempiereException(AdMessageKey.of("PP_Product_BOMVersions_BOM_Doesnt_Match")) .markAsUserValidationError() .appendParametersToMessage() .setParameter("PP_Product_BOM", bom) .setParameter("PP_Product_BOMVersions", bomVersions);
} } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_PP_Product_BOM.COLUMNNAME_M_AttributeSetInstance_ID }) public void validateBOMAttributes(final I_PP_Product_BOM productBom) { final ProductBOMVersionsId productBOMVersionsId = ProductBOMVersionsId.ofRepoId(productBom.getPP_Product_BOMVersions_ID()); productPlanningDAO.retrieveProductPlanningForBomVersions(productBOMVersionsId) .forEach(productPlanning -> productBOMService.verifyBOMAssignment(productPlanning, productBom)); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_PP_Product_BOM.COLUMNNAME_SerialNo_Sequence_ID, I_PP_Product_BOM.COLUMNNAME_C_UOM_ID }) public void validateSeqNo(final I_PP_Product_BOM productBom) { if (DocSequenceId.ofRepoIdOrNull(productBom.getSerialNo_Sequence_ID()) != null && !UomId.ofRepoId(productBom.getC_UOM_ID()).isEach()) { throw new AdempiereException(UOM_ID_MUST_BE_EACH_IF_SEQ_NO_IS_SET); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Product_BOM.java
1
请在Spring Boot框架中完成以下Java代码
public AsyncReporter<Span> spanReporter() { return AsyncReporter.create(sender()); } /** * Controls aspects of tracing such as the service name that shows up in the UI */ @Bean public Tracing tracing(@Value("${spring.application.name}") String serviceName) { return Tracing.newBuilder() .localServiceName(serviceName) .spanReporter(spanReporter()).build(); } @Bean public Tracer openTracer(Tracing tracing) { return BraveTracer.create(tracing); } /** * Allows someone to add tags to a span if a trace is in progress */ @Bean public SpanCustomizer spanCustomizer(Tracing tracing) { return CurrentSpanCustomizer.create(tracing); } // ==================== HTTP 相关 ==================== /** * Decides how to name and tag spans. By default they are named the same as the http method */ @Bean public HttpTracing httpTracing(Tracing tracing) { return HttpTracing.create(tracing); } /** * Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { return TracingFilter.create(httpTracing); }
// ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) // ==================== Elasticsearch 相关 ==================== @Bean public TransportClient elasticsearchClient(Tracer tracer, ElasticsearchProperties elasticsearchProperties) throws Exception { // 创建 TracingTransportClientFactoryBean 对象 TracingTransportClientFactoryBean factory = new TracingTransportClientFactoryBean(tracer); // 设置其属性 factory.setClusterNodes(elasticsearchProperties.getClusterNodes()); factory.setProperties(this.createElasticsearch(elasticsearchProperties)); // 创建 TransportClient 对象,并返回 factory.afterPropertiesSet(); return factory.getObject(); } private Properties createElasticsearch(ElasticsearchProperties elasticsearchProperties) { Properties properties = new Properties(); properties.put("cluster.name", elasticsearchProperties.getClusterName()); properties.putAll(elasticsearchProperties.getProperties()); return properties; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-elasticsearch\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public void setDATEV_Export_ID (final int DATEV_Export_ID) { if (DATEV_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_DATEV_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_DATEV_Export_ID, DATEV_Export_ID); } @Override public int getDATEV_Export_ID() { return get_ValueAsInt(COLUMNNAME_DATEV_Export_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsExcludeAlreadyExported (final boolean IsExcludeAlreadyExported) { set_Value (COLUMNNAME_IsExcludeAlreadyExported, IsExcludeAlreadyExported); } @Override public boolean isExcludeAlreadyExported() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeAlreadyExported); } @Override public void setIsNegateInboundAmounts (final boolean IsNegateInboundAmounts) { set_Value (COLUMNNAME_IsNegateInboundAmounts, IsNegateInboundAmounts); } @Override public boolean isNegateInboundAmounts() { return get_ValueAsBoolean(COLUMNNAME_IsNegateInboundAmounts); } @Override public void setIsPlaceBPAccountsOnCredit (final boolean IsPlaceBPAccountsOnCredit) { set_Value (COLUMNNAME_IsPlaceBPAccountsOnCredit, IsPlaceBPAccountsOnCredit); } @Override public boolean isPlaceBPAccountsOnCredit() { return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit); } /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */
public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); } @Override public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo) { set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo); } @Override public boolean isSwitchCreditMemo() { return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
1
请完成以下Java代码
public class Md5Util { private static final String[] HEXDIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++){ resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) { n += 256; } int d1 = n / 16; int d2 = n % 16;
return HEXDIGITS[d1] + HEXDIGITS[d2]; } public static String md5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)) { resultString = byteArrayToHexString(md.digest(resultString.getBytes())); } else { resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname))); } } catch (Exception exception) { } return resultString; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\Md5Util.java
1
请完成以下Java代码
public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setPassword (final @Nullable java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public java.lang.String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setServiceLevel (final @Nullable java.lang.String ServiceLevel) { set_Value (COLUMNNAME_ServiceLevel, ServiceLevel); }
@Override public java.lang.String getServiceLevel() { return get_ValueAsString(COLUMNNAME_ServiceLevel); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Config.java
1
请完成以下Java代码
public void setUpdateStorageValue(final boolean updateStorageValue) { this.updateStorageValue = updateStorageValue; } @Override public boolean isUpdateStorageValue() { return updateStorageValue; } @Override public void setValueUpdateInvocation() { valueUpdateInvocation = true; } @Override public boolean isValueUpdateInvocation() { return valueUpdateInvocation; } @Override public boolean isValueUpdatedBefore() { return isValueUpdatedBefore(getAttributeCode()); } @Override public boolean isValueUpdatedBefore(final AttributeCode attributeCode) { return getLastPropagatorOrNull(attributeCode) != null; } @Override public IHUAttributePropagator getLastPropagatorOrNull(@NonNull final AttributeCode attributeCode) { // Iterate up chain of parents, starting with the parent context. for each parent context, we check if the attribute was updated in that context // NOTE: we are skipping current node because we want to check if that attribute was updated before for (IHUAttributePropagationContext currentParentContext = parent; currentParentContext != null; currentParentContext = currentParentContext.getParent()) {
if (!currentParentContext.isValueUpdateInvocation()) { continue; } final IAttributeStorage currentAttributeStorage = currentParentContext.getAttributeStorage(); if (!currentAttributeStorage.equals(attributeStorage)) { continue; } final AttributeCode currentAttributeCode = currentParentContext.getAttributeCode(); if (!AttributeCode.equals(currentAttributeCode, attributeCode)) { continue; } return currentParentContext.getPropagator(); } return null; } @Override public IAttributeValueContext copy() { return cloneForPropagation(getAttributeStorage(), getAttribute(), getPropagator()); } @Override public IHUAttributePropagationContext cloneForPropagation(final IAttributeStorage attributeStorage, final I_M_Attribute attribute, final IHUAttributePropagator propagatorToUse) { final HUAttributePropagationContext propagationContextClone = new HUAttributePropagationContext(this, attributeStorage, propagatorToUse, attribute, getParameters()); return propagationContextClone; } @Override public boolean isExternalInput() { // NOTE: we consider External Input if this is the first context created (i.e. has no parents => no previous calls) return Util.same(getParent(), IHUAttributePropagationContext.NULL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\HUAttributePropagationContext.java
1
请在Spring Boot框架中完成以下Java代码
public ProductInfo getById(@NonNull final ProductId productId) { final I_M_Product product = productBL.getById(productId); final GS1ProductCodesCollection gs1ProductCodes = productBL.getGS1ProductCodesCollection(product); return ProductInfo.builder() .productId(productId) .productNo(product.getValue()) .gs1ProductCodes(gs1ProductCodes) .productCategoryId(ProductCategoryId.ofRepoId(product.getM_Product_Category_ID())) .name(InterfaceWrapperHelper.getModelTranslationMap(product).getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName())) .build(); } public ProductId getProductIdByGTINStrictlyNotNull(@NonNull final GTIN gtin, @NonNull final ClientId clientId) { return productBL.getProductIdByGTINStrictlyNotNull(gtin, clientId); }
public String getProductValue(@NonNull final ProductId productId) { return productBL.getProductValue(productId); } public boolean isValidEAN13Product(@NonNull final EAN13 ean13, @NonNull final ProductId expectedProductId, @Nullable final BPartnerId bpartnerId) { return productBL.isValidEAN13Product(ean13, expectedProductId, bpartnerId); } public ITranslatableString getUOMSymbolById(@NonNull final UomId uomId) {return uomDAO.getUOMSymbolById(uomId);} @NonNull public ImmutableMap<ProductId, Product> getByIdsAsMap(@NonNull final Set<ProductId> ids) { return productRepository.getByIdsAsMap(ids); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\product\PickingJobProductService.java
2
请在Spring Boot框架中完成以下Java代码
public class AuthorizePayloadsSpec { private PayloadExchangeMatcherReactiveAuthorizationManager.Builder authzBuilder = PayloadExchangeMatcherReactiveAuthorizationManager .builder(); public Access setup() { return matcher(PayloadExchangeMatchers.setup()); } /** * Matches if * {@link org.springframework.security.rsocket.api.PayloadExchangeType#isRequest()} * is true, else not a match * @return the Access to set up the authorization rule. */ public Access anyRequest() { return matcher(PayloadExchangeMatchers.anyRequest()); } /** * Always matches * @return the Access to set up the authorization rule. */ public Access anyExchange() { return matcher(PayloadExchangeMatchers.anyExchange()); } protected AuthorizationPayloadInterceptor build() { AuthorizationPayloadInterceptor result = new AuthorizationPayloadInterceptor(this.authzBuilder.build()); result.setOrder(PayloadInterceptorOrder.AUTHORIZATION.getOrder()); return result; } public Access route(String pattern) { RSocketMessageHandler handler = getBean(RSocketMessageHandler.class); PayloadExchangeMatcher matcher = new RoutePayloadExchangeMatcher(handler.getMetadataExtractor(), handler.getRouteMatcher(), pattern); return matcher(matcher); } public Access matcher(PayloadExchangeMatcher matcher) { return new Access(matcher); } public final class Access { private final PayloadExchangeMatcher matcher; private Access(PayloadExchangeMatcher matcher) { this.matcher = matcher; }
public AuthorizePayloadsSpec authenticated() { return access(AuthenticatedReactiveAuthorizationManager.authenticated()); } public AuthorizePayloadsSpec hasAuthority(String authority) { return access(AuthorityReactiveAuthorizationManager.hasAuthority(authority)); } public AuthorizePayloadsSpec hasRole(String role) { return access(AuthorityReactiveAuthorizationManager.hasRole(role)); } public AuthorizePayloadsSpec hasAnyRole(String... roles) { return access(AuthorityReactiveAuthorizationManager.hasAnyRole(roles)); } public AuthorizePayloadsSpec permitAll() { return access((a, ctx) -> Mono.just(new AuthorizationDecision(true))); } public AuthorizePayloadsSpec hasAnyAuthority(String... authorities) { return access(AuthorityReactiveAuthorizationManager.hasAnyAuthority(authorities)); } public AuthorizePayloadsSpec access( ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authorization) { AuthorizePayloadsSpec.this.authzBuilder .add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization)); return AuthorizePayloadsSpec.this; } public AuthorizePayloadsSpec denyAll() { return access((a, ctx) -> Mono.just(new AuthorizationDecision(false))); } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurity.java
2
请完成以下Java代码
String getXml() { return "<user>".concat(XML_PAYLOAD).concat("</user>"); } /** * Returns the payload of {@link #getXml()} wrapped into another XML element to simulate a change in the * representation structure. * * @return */ @GetMapping(path = "/changed", produces = MediaType.APPLICATION_XML_VALUE) String getChangedXml() { return "<user><username>".concat(XML_PAYLOAD).concat("</username></user>"); } /**
* The projection interface using XPath and JSON Path expression to selectively pick elements from the payload. * * @author Oliver Gierke */ @ProjectedPayload public interface UserPayload { @XBRead("//firstname") @JsonPath("$..firstname") String getFirstname(); @XBRead("//lastname") @JsonPath("$..lastname") String getLastname(); } }
repos\spring-data-examples-main\web\projection\src\main\java\example\users\UserController.java
1
请完成以下Java代码
public class Mapping { private SourceMappingType type; private Object value; public SourceMappingType getType() { return type; } public void setType(SourceMappingType type) { this.type = type; } public Object getValue() {
return value; } public void setValue(Object value) { this.value = value; } public enum SourceMappingType { VARIABLE, VALUE, JSONPATCH, } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\Mapping.java
1
请完成以下Java代码
public void setMargin (Insets m) { if (m_textPane != null) m_textPane.setMargin(m); } // setMargin /** * Set Opaque * @param isOpaque opaque */ @Override public void setOpaque (boolean isOpaque) { // JScrollPane & Viewport is always not Opaque if (m_textPane == null) // during init of JScrollPane super.setOpaque(isOpaque); else m_textPane.setOpaque(isOpaque); } // setOpaque /** * Add Focus Listener * @param l listener */ @Override public void addFocusListener (FocusListener l) { if (m_textPane == null) // during init super.addFocusListener(l); else m_textPane.addFocusListener(l); } /** * Add Mouse Listener * @param l listner */ @Override public void addMouseListener (MouseListener l) { m_textPane.addMouseListener(l); } /** * Add Key Listener * @param l listner */ @Override public void addKeyListener (KeyListener l) { m_textPane.addKeyListener(l); } /** * Add Input Method Listener * @param l listener */ @Override public void addInputMethodListener (InputMethodListener l) { m_textPane.addInputMethodListener(l); } /** * Get Input Method Requests * @return requests */ @Override public InputMethodRequests getInputMethodRequests() { return m_textPane.getInputMethodRequests(); } /** * Set Input Verifier
* @param l verifyer */ @Override public void setInputVerifier (InputVerifier l) { m_textPane.setInputVerifier(l); } // metas: begin public String getContentType() { if (m_textPane != null) return m_textPane.getContentType(); return null; } private void setHyperlinkListener() { if (hyperlinkListenerClass == null) { return; } try { final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance(); m_textPane.addHyperlinkListener(listener); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e); } } private static Class<?> hyperlinkListenerClass; static { final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler"; try { hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e); } } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } // metas: end } // CTextPane
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java
1
请完成以下Java代码
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @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 setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override
public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQM_Analysis_Report_ID (final int QM_Analysis_Report_ID) { if (QM_Analysis_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, QM_Analysis_Report_ID); } @Override public int getQM_Analysis_Report_ID() { return get_ValueAsInt(COLUMNNAME_QM_Analysis_Report_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_QM_Analysis_Report.java
1
请完成以下Java代码
public void init() { final IProgramaticCalloutProvider programaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programaticCalloutProvider.registerAnnotatedCallout(new de.metas.freighcost.callout.C_Order(orderFreightCostService)); } // NOTE: adding the freight rate line before prepare to cover the case when the order goes to WaitingPayment status (not yet completed) @DocValidate(timings = ModelValidator.TIMING_BEFORE_PREPARE) public void beforePrepare(final I_C_Order order) { orderFreightCostService.addFreightRateLineIfNeeded(order); } @DocValidate(timings = ModelValidator.TIMING_AFTER_REACTIVATE) public void afterReActivate(final I_C_Order order) { BigDecimal deletedFreightAmt = BigDecimal.ZERO; // making sure that (all) freight cost order lines are deleted for (final I_C_OrderLine orderLine : ordersRepo.retrieveOrderLines(order))
{ if (orderFreightCostService.isFreightCostOrderLine(orderLine)) { deletedFreightAmt = deletedFreightAmt.add(orderLine.getPriceActual()); ordersRepo.delete(orderLine); } } final FreightCostRule freightCostRule = FreightCostRule.ofCode(order.getFreightCostRule()); if (freightCostRule.isFixPrice() && deletedFreightAmt.signum() != 0) { // reinsert the freight amount value in the field order.setFreightAmt(deletedFreightAmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\interceptor\C_Order.java
1
请完成以下Java代码
private void renderAll() { final Container actionsPanel = getActionsPanel(); actionsPanel.removeAll(); if (model != null) { final ListModel<ISideAction> actionsList = model.getActions(); for (int i = 0; i < actionsList.getSize(); i++) { final ISideAction action = actionsList.getElementAt(i); final Component actionComp = createActionComponent(action); actionsPanel.add(actionComp); } } refreshUI(); } private Component createActionComponent(final ISideAction action) { final SideActionType type = action.getType(); if (type == SideActionType.Toggle) { return new CheckableSideActionComponent(action); } else if (type == SideActionType.ExecutableAction) { return new HyperlinkSideActionComponent(action); } else if (type == SideActionType.Label) { return new LabelSideActionComponent(action); } else { throw new IllegalArgumentException("Unknown action type: " + type); } } protected void updateActionComponent(final Component actionComp, final ISideAction action) { // TODO Auto-generated method stub }
private final boolean hasActions() { return model != null && model.getActions().getSize() > 0; } private final void refreshUI() { // Auto-hide if no actions setVisible(hasActions()); final Container actionsPanel = getActionsPanel(); actionsPanel.revalidate(); } @Override public void setVisible(final boolean visible) { final boolean visibleOld = isVisible(); super.setVisible(visible); firePropertyChange(PROPERTY_Visible, visibleOld, isVisible()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupPanel.java
1
请完成以下Java代码
protected static void configureAcceptedClientCertificates( final Security security, final SslContextBuilder sslContextBuilder) { if (security.getClientAuth() != ClientAuth.NONE) { sslContextBuilder.clientAuth(of(security.getClientAuth())); try { final Resource trustCertCollection = security.getTrustCertCollection(); final Resource trustStore = security.getTrustStore(); if (trustCertCollection != null) { try (InputStream trustCertCollectionStream = trustCertCollection.getInputStream()) { sslContextBuilder.trustManager(trustCertCollectionStream); } } else if (trustStore != null) { final TrustManagerFactory trustManagerFactory = KeyStoreUtils.loadTrustManagerFactory( security.getTrustStoreFormat(), trustStore, security.getTrustStorePassword()); sslContextBuilder.trustManager(trustManagerFactory); } else { // Use system default } } catch (final Exception e) { throw new IllegalArgumentException("Failed to create SSLContext (TrustStore)", e); } } } /** * Converts the given client auth option to netty's client auth. * * @param clientAuth The client auth option to convert.
* @return The converted client auth option. */ // Keep this in sync with NettyGrpcServerFactory#configureAcceptedClientCertificates protected static io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth of(final ClientAuth clientAuth) { switch (clientAuth) { case NONE: return io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.NONE; case OPTIONAL: return io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.OPTIONAL; case REQUIRE: return io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.REQUIRE; default: throw new IllegalArgumentException("Unsupported ClientAuth: " + clientAuth); } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\serverfactory\ShadedNettyGrpcServerFactory.java
1
请完成以下Java代码
public class X_C_CyclePhase extends PO implements I_C_CyclePhase, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_C_CyclePhase (Properties ctx, int C_CyclePhase_ID, String trxName) { super (ctx, C_CyclePhase_ID, trxName); /** if (C_CyclePhase_ID == 0) { setC_CycleStep_ID (0); setC_Phase_ID (0); } */ } /** Load Constructor */ public X_C_CyclePhase (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_CyclePhase[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_CycleStep getC_CycleStep() throws RuntimeException { return (I_C_CycleStep)MTable.get(getCtx(), I_C_CycleStep.Table_Name) .getPO(getC_CycleStep_ID(), get_TrxName()); } /** Set Cycle Step. @param C_CycleStep_ID The step for this Cycle */ public void setC_CycleStep_ID (int C_CycleStep_ID) { if (C_CycleStep_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID)); } /** Get Cycle Step. @return The step for this Cycle */ public int getC_CycleStep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID); if (ii == null) return 0;
return ii.intValue(); } public I_C_Phase getC_Phase() throws RuntimeException { return (I_C_Phase)MTable.get(getCtx(), I_C_Phase.Table_Name) .getPO(getC_Phase_ID(), get_TrxName()); } /** Set Standard Phase. @param C_Phase_ID Standard Phase of the Project Type */ public void setC_Phase_ID (int C_Phase_ID) { if (C_Phase_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Phase_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Phase_ID, Integer.valueOf(C_Phase_ID)); } /** Get Standard Phase. @return Standard Phase of the Project Type */ public int getC_Phase_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Phase_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CyclePhase.java
1
请在Spring Boot框架中完成以下Java代码
public GitIgnoreCustomizer gradleGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add(".gradle", "build/", "!gradle/wrapper/gradle-wrapper.jar", "!**/src/main/**/build/", "!**/src/test/**/build/"); gitIgnore.getIntellijIdea().add("out/", "!**/src/main/**/out/", "!**/src/test/**/out/"); gitIgnore.getSts().add("bin/", "!**/src/main/**/bin/", "!**/src/test/**/bin/"); }; } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public GitAttributesCustomizer mavenGitAttributesCustomizer() { return (gitAttributes) -> { gitAttributes.add("/mvnw", "text", "eol=lf"); gitAttributes.add("*.cmd", "text", "eol=crlf"); }; } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitAttributesCustomizer gradleGitAttributesCustomizer() { return (gitAttributes) -> { gitAttributes.add("/gradlew", "text", "eol=lf"); gitAttributes.add("*.bat", "text", "eol=crlf");
gitAttributes.add("*.jar", "binary"); }; } private GitIgnore createGitIgnore() { GitIgnore gitIgnore = new GitIgnore(); gitIgnore.getSts() .add(".apt_generated", ".classpath", ".factorypath", ".project", ".settings", ".springBeans", ".sts4-cache"); gitIgnore.getIntellijIdea().add(".idea", "*.iws", "*.iml", "*.ipr"); gitIgnore.getNetBeans().add("/nbproject/private/", "/nbbuild/", "/dist/", "/nbdist/", "/.nb-gradle/"); gitIgnore.getVscode().add(".vscode/"); return gitIgnore; } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitProjectGenerationConfiguration.java
2
请完成以下Spring Boot application配置
spring: application: name: demo-consumer # Spring 应用名 cloud: zookeeper: connect-string: 127.0.0.1:2181 # Zookeeper 作为注册中心的配置项,对应 ZookeeperDiscoveryProperties 配置类 discovery:
root: /services # Zookeeper 数据存储的根节点,默认为 /services server: port: 28080 # 服务器端口。默认为 8080
repos\SpringBoot-Labs-master\labx-25\labx-25-sc-zookeeper-discovery-demo01-consumer\src\main\resources\application.yaml
2
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Measure.java
1
请完成以下Java代码
public ITableCacheConfigBuilder setCacheMapType(final CacheMapType cacheMapType) { this.cacheMapType = cacheMapType; return this; } public CacheMapType getCacheMapType() { if (cacheMapType != null) { return cacheMapType; } if (template != null) { return template.getCacheMapType(); } throw new IllegalStateException("Cannot get CacheMapType"); } public int getInitialCapacity() { if (initialCapacity > 0) { return initialCapacity; } else if (template != null) { return template.getInitialCapacity(); } throw new IllegalStateException("Cannot get InitialCapacity"); } @Override public ITableCacheConfigBuilder setInitialCapacity(final int initialCapacity) { this.initialCapacity = initialCapacity; return this; } public int getMaxCapacity() { if (maxCapacity > 0)
{ return maxCapacity; } else if (template != null) { return template.getMaxCapacity(); } return -1; } @Override public ITableCacheConfigBuilder setMaxCapacity(final int maxCapacity) { this.maxCapacity = maxCapacity; return this; } public int getExpireMinutes() { if (expireMinutes > 0 || expireMinutes == ITableCacheConfig.EXPIREMINUTES_Never) { return expireMinutes; } else if (template != null) { return template.getExpireMinutes(); } throw new IllegalStateException("Cannot get ExpireMinutes"); } @Override public ITableCacheConfigBuilder setExpireMinutes(final int expireMinutes) { this.expireMinutes = expireMinutes; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheConfigBuilder.java
1
请完成以下Java代码
public class CreateProcessInstanceCmd implements Command<ProcessInstance> { private static final long serialVersionUID = 1L; protected String processDefinitionKey; protected String processDefinitionId; protected Map<String, Object> variables; protected Map<String, Object> transientVariables; protected String businessKey; protected String tenantId; protected String processInstanceName; protected ProcessInstanceHelper processInstanceHelper; public CreateProcessInstanceCmd( String processDefinitionKey, String processDefinitionId, String businessKey, Map<String, Object> variables ) { this.processDefinitionKey = processDefinitionKey; this.processDefinitionId = processDefinitionId; this.businessKey = businessKey; this.variables = variables; } public CreateProcessInstanceCmd( String processDefinitionKey, String processDefinitionId, String businessKey, Map<String, Object> variables, String tenantId ) { this(processDefinitionKey, processDefinitionId, businessKey, variables); this.tenantId = tenantId; } public CreateProcessInstanceCmd(ProcessInstanceBuilderImpl processInstanceBuilder) { this(
processInstanceBuilder.getProcessDefinitionKey(), processInstanceBuilder.getProcessDefinitionId(), processInstanceBuilder.getBusinessKey(), processInstanceBuilder.getVariables(), processInstanceBuilder.getTenantId() ); this.processInstanceName = processInstanceBuilder.getProcessInstanceName(); this.transientVariables = processInstanceBuilder.getTransientVariables(); } public ProcessInstance execute(CommandContext commandContext) { DeploymentManager deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentManager(); ProcessDefinitionRetriever processRetriever = new ProcessDefinitionRetriever(this.tenantId, deploymentCache); ProcessDefinition processDefinition = processRetriever.getProcessDefinition( this.processDefinitionId, this.processDefinitionKey ); processInstanceHelper = commandContext.getProcessEngineConfiguration().getProcessInstanceHelper(); return processInstanceHelper.createProcessInstance( processDefinition, businessKey, processInstanceName, variables, transientVariables); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\CreateProcessInstanceCmd.java
1
请完成以下Java代码
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer { @Override public void customize(RestTemplate restTemplate) { HttpRoutePlanner routePlanner = new CustomRoutePlanner(new HttpHost("proxy.javastack.cn")); RequestConfig requestConfig = RequestConfig.custom().build(); HttpClient httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig) .setRoutePlanner(routePlanner).build(); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } static class CustomRoutePlanner extends DefaultProxyRoutePlanner { CustomRoutePlanner(HttpHost proxy) {
super(proxy); } @Override protected HttpHost determineProxy(HttpHost target, HttpContext context) throws HttpException { log.info("hostName is {}", target.getHostName()); if ("localhost".equals(target.getHostName())) { return null; } return super.determineProxy(target, context); } } }
repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\handler\CustomRestTemplateCustomizer.java
1
请完成以下Java代码
public String getAnchorValue() { return "top left"; } @Override public String getStrokeValue() { return null; } @Override public String getFillValue() { return null; } @Override public Integer getWidth() { return null; } @Override public Integer getHeight() { return null; } @Override public String getStrokeWidth() { return null;
} public void drawIcon( final int imageX, final int imageY, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS( null, "transform", "translate(" + (imageX + iconPadding) + "," + (imageY + iconPadding) + ")" ); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "anchors", this.getAnchorValue()); pathTag.setAttributeNS(null, "style", this.getStyleValue()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag); } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\TaskIconType.java
1
请完成以下Java代码
public Image getImage() { if (m_image != null) { return m_image; } // if (isImageIsAttached()) { final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class); final List<AttachmentEntry> entries = attachmentEntryService.getByReferencedRecord(TableRecordReference.of(Table_Name, getAD_PrintTableFormat_ID())); if (entries.isEmpty()) { log.warn("No Attachment entry - ID=" + get_ID()); return null; } final byte[] imageData = attachmentEntryService.retrieveData(entries.get(0).getId()); if (imageData != null) { m_image = Toolkit.getDefaultToolkit().createImage(imageData); } if (m_image != null) { log.debug(entries.get(0).getFilename() + " - Size=" + imageData.length); } else { log.warn(entries.get(0).getFilename() + " - not loaded (must be gif or jpg) - ID=" + get_ID()); } } else if (getImageURL() != null) { URL url; try { url = new URL(getImageURL()); Toolkit tk = Toolkit.getDefaultToolkit(); m_image = tk.getImage(url); }
catch (MalformedURLException e) { log.warn("Malformed URL - " + getImageURL(), e); } } return m_image; } // getImage /** * Get the Image * * @return image */ public Image getImageWaterMark() { if (m_image_water_mark != null) { return m_image_water_mark; } // if (getAD_Image_ID() > 0) { m_image_water_mark = MImage.get(getCtx(), getAD_Image_ID()).getImage(); } return m_image_water_mark; } // getImage } // MPrintTableFormat
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintTableFormat.java
1
请完成以下Java代码
protected void prepareSocket(SSLSocket socket) { String hostname = socket.getInetAddress().getHostName(); if (hostname.endsWith("internal.system.com")) { socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }); } else { socket.setEnabledProtocols(new String[] { "TLSv1.3" }); } } }; return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } // To configure the TLS versions for the client, set the https.protocols system property during runtime. // For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem(); // Alternatively: // return HttpClients.custom().useSystemProperties().build(); } public static void main(String[] args) throws IOException { // Alternatively: // CloseableHttpClient httpClient = setTlsVersionPerConnection(); // CloseableHttpClient httpClient = setViaSystemProperties(); try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } } }
repos\tutorials-master\apache-httpclient4\src\main\java\com\baeldung\tlsversion\ClientTlsVersionExamples.java
1
请在Spring Boot框架中完成以下Java代码
public void logout() { loginService.logout(); } @GetMapping("/resetUserPassword") public void resetUserPasswordRequest(@RequestParam("email") final String email) { final String passwordResetToken = loginService.generatePasswordResetKey(email); loginService.sendPasswordResetKey(email, passwordResetToken); } @GetMapping("/resetUserPasswordConfirm") public JsonPasswordResetResponse resetUserPasswordConfirm(@RequestParam("token") final String token) { final User user = loginService.resetPassword(token); loginService.login(user); return JsonPasswordResetResponse.builder() .email(user.getEmail())
.language(user.getLanguageKeyOrDefault().getAsString()) .newPassword(user.getPassword()) .build(); } @PostMapping("/confirmDataEntry") public ConfirmDataEntryResponse confirmDataEntry() { final User user = loginService.getLoggedInUser(); userConfirmationService.confirmUserEntries(user); return ConfirmDataEntryResponse.builder() .countUnconfirmed(userConfirmationService.getCountUnconfirmed(user)) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\session\SessionRestController.java
2
请完成以下Java代码
public void execute(final ICalloutExecutor executor, final ICalloutField field) { try { legacyCallout.start(methodName, field); } catch (final CalloutException e) { throw e.setCalloutExecutor(executor) .setCalloutInstance(this) .setField(field); } catch (final Exception e) { throw CalloutExecutionException.wrapIfNeeded(e) .setCalloutExecutor(executor)
.setCalloutInstance(this) .setField(field); } } @VisibleForTesting public org.compiere.model.Callout getLegacyCallout() { return legacyCallout; } public String getMethodName() { return methodName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\MethodNameCalloutInstance.java
1
请完成以下Java代码
public Builder setSource_Reference_ID(final int sourceReferenceId) { this.sourceReferenceId = ReferenceId.ofRepoIdOrNull(sourceReferenceId); sourceTableRefInfo = null; // reset return this; } private ReferenceId getSource_Reference_ID() { return Check.assumeNotNull(sourceReferenceId, "sourceReferenceId is set"); } @Nullable private ADRefTable getSourceTableRefInfoOrNull() { if (sourceTableRefInfo == null) { sourceTableRefInfo = retrieveTableRefInfo(getSource_Reference_ID()); } return sourceTableRefInfo; } @Nullable private ADRefTable retrieveTableRefInfo(final ReferenceId adReferenceId) { final ADRefTable tableRefInfo = adReferenceService.retrieveTableRefInfo(adReferenceId); if (tableRefInfo == null) { return null; } return tableRefInfo.mapWindowIds(this::getCustomizationWindowId); } @Nullable private AdWindowId getCustomizationWindowId(@Nullable final AdWindowId adWindowId) { return adWindowId != null ? customizedWindowInfoMap.getCustomizedWindowInfo(adWindowId).map(CustomizedWindowInfo::getCustomizationWindowId).orElse(adWindowId) : null; } public Builder setSourceRoleDisplayName(final ITranslatableString sourceRoleDisplayName) { this.sourceRoleDisplayName = sourceRoleDisplayName; return this; } public Builder setTarget_Reference_AD(final int targetReferenceId) { this.targetReferenceId = ReferenceId.ofRepoIdOrNull(targetReferenceId); targetTableRefInfo = null; // lazy return this; } private ReferenceId getTarget_Reference_ID() { return Check.assumeNotNull(targetReferenceId, "targetReferenceId is set"); }
private ADRefTable getTargetTableRefInfoOrNull() { if (targetTableRefInfo == null) { targetTableRefInfo = retrieveTableRefInfo(getTarget_Reference_ID()); } return targetTableRefInfo; } public Builder setTargetRoleDisplayName(final ITranslatableString targetRoleDisplayName) { this.targetRoleDisplayName = targetRoleDisplayName; return this; } public ITranslatableString getTargetRoleDisplayName() { return targetRoleDisplayName; } public Builder setIsTableRecordIdTarget(final boolean isReferenceTarget) { isTableRecordIDTarget = isReferenceTarget; return this; } private boolean isTableRecordIdTarget() { return isTableRecordIDTarget; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\relation_type\SpecificRelationTypeRelatedDocumentsProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaTaskProcessorQueueFactory implements TaskProcessorQueueFactory { private final TopicService topicService; private final TbServiceInfoProvider serviceInfoProvider; private final TasksQueueConfig tasksQueueConfig; private final TbKafkaSettings kafkaSettings; private final TbKafkaConsumerStatsService consumerStatsService; private final TbQueueAdmin tasksAdmin; public KafkaTaskProcessorQueueFactory(TopicService topicService, TbServiceInfoProvider serviceInfoProvider, TasksQueueConfig tasksQueueConfig, TbKafkaSettings kafkaSettings, TbKafkaConsumerStatsService consumerStatsService, TbKafkaTopicConfigs kafkaTopicConfigs) { this.topicService = topicService; this.serviceInfoProvider = serviceInfoProvider; this.tasksQueueConfig = tasksQueueConfig; this.kafkaSettings = kafkaSettings; this.consumerStatsService = consumerStatsService; this.tasksAdmin = new TbKafkaAdmin(kafkaSettings, kafkaTopicConfigs.getTasksConfigs()); } @Override public TbQueueConsumer<TbProtoQueueMsg<TaskProto>> createTaskConsumer(JobType jobType) {
return TbKafkaConsumerTemplate.<TbProtoQueueMsg<TaskProto>>builder() .settings(kafkaSettings) .topic(topicService.buildTopicName(jobType.getTasksTopic())) .clientId(jobType.name().toLowerCase() + "-task-consumer-" + serviceInfoProvider.getServiceId()) .groupId(topicService.buildTopicName(jobType.name().toLowerCase() + "-task-consumer-group")) .decoder(msg -> new TbProtoQueueMsg<>(msg.getKey(), TaskProto.parseFrom(msg.getData()), msg.getHeaders())) .admin(tasksAdmin) .statsService(consumerStatsService) .build(); } @Override public TbQueueProducer<TbProtoQueueMsg<JobStatsMsg>> createJobStatsProducer() { return TbKafkaProducerTemplate.<TbProtoQueueMsg<JobStatsMsg>>builder() .clientId("job-stats-producer-" + serviceInfoProvider.getServiceId()) .defaultTopic(topicService.buildTopicName(tasksQueueConfig.getStatsTopic())) .settings(kafkaSettings) .admin(tasksAdmin) .build(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\task\KafkaTaskProcessorQueueFactory.java
2
请完成以下Java代码
public void removeColumnsWithBlankValues() { header.removeIf(this::isBlankColumn); } private boolean isBlankColumn(final String columnName) { return rowsList.stream().allMatch(row -> row.isBlankColumn(columnName)); } public void moveColumnsToStart(final String... columnNamesToMove) { if (columnNamesToMove == null || columnNamesToMove.length == 0) { return; } for (int i = columnNamesToMove.length - 1; i >= 0; i--) { if (columnNamesToMove[i] == null) { continue; } final String columnNameToMove = columnNamesToMove[i]; if (header.remove(columnNameToMove)) { header.add(0, columnNameToMove); } } } public void moveColumnsToEnd(final String... columnNamesToMove) { if (columnNamesToMove == null) { return; } for (final String columnNameToMove : columnNamesToMove) { if (columnNameToMove == null) { continue; } if (header.remove(columnNameToMove)) { header.add(columnNameToMove); } } } public Optional<Table> removeColumnsWithSameValue() { if (rowsList.isEmpty()) { return Optional.empty(); } final Table removedTable = new Table(); for (final String columnName : new ArrayList<>(header)) { final Cell commonValue = getCommonValue(columnName).orElse(null); if (commonValue != null) { header.remove(columnName); removedTable.addHeader(columnName); removedTable.setCell(0, columnName, commonValue);
} } if (removedTable.isEmpty()) { return Optional.empty(); } return Optional.of(removedTable); } private Optional<Cell> getCommonValue(@NonNull final String columnName) { if (rowsList.isEmpty()) { return Optional.empty(); } final Cell firstValue = rowsList.get(0).getCell(columnName); for (int i = 1; i < rowsList.size(); i++) { final Cell value = rowsList.get(i).getCell(columnName); if (!Objects.equals(value, firstValue)) { return Optional.empty(); } } return Optional.of(firstValue); } public TablePrinter toPrint() { return new TablePrinter(this); } public String toTabularString() { return toPrint().toString(); } @Override @Deprecated public String toString() {return toTabularString();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Table.java
1
请完成以下Java代码
public long findHistoricActivityInstanceCountByQueryCriteria(HistoricActivityInstanceQueryImpl historicActivityInstanceQuery) { return dataManager.findHistoricActivityInstanceCountByQueryCriteria(historicActivityInstanceQuery); } @Override public List<HistoricActivityInstance> findHistoricActivityInstancesByQueryCriteria(HistoricActivityInstanceQueryImpl historicActivityInstanceQuery) { return dataManager.findHistoricActivityInstancesByQueryCriteria(historicActivityInstanceQuery); } @Override public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findHistoricActivityInstancesByNativeQuery(parameterMap); } @Override public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findHistoricActivityInstanceCountByNativeQuery(parameterMap); } @Override public void deleteHistoricActivityInstances(HistoricActivityInstanceQueryImpl historicActivityInstanceQuery) { dataManager.deleteHistoricActivityInstances(historicActivityInstanceQuery);
} @Override public void bulkDeleteHistoricActivityInstancesByProcessInstanceIds(Collection<String> historicProcessInstanceIds) { dataManager.bulkDeleteHistoricActivityInstancesByProcessInstanceIds(historicProcessInstanceIds); } @Override public void deleteHistoricActivityInstancesForNonExistingProcessInstances() { dataManager.deleteHistoricActivityInstancesForNonExistingProcessInstances(); } protected HistoryManager getHistoryManager() { return engineConfiguration.getHistoryManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricActivityInstanceEntityManagerImpl.java
1
请完成以下Java代码
public CaseTask newInstance(ModelTypeInstanceContext instanceContext) { return new CaseTaskImpl(instanceContext); } }); caseRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CASE_REF) .build(); /** camunda extensions */ camundaCaseBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_BINDING) .namespace(CAMUNDA_NS) .build(); camundaCaseVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_VERSION) .namespace(CAMUNDA_NS) .build();
camundaCaseTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_TENANT_ID) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class) .build(); caseRefExpressionChild = sequenceBuilder.element(CaseRefExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseTaskImpl.java
1
请完成以下Java代码
public class ColumnInfo implements Serializable { @Id @Column(name = "column_id") @ApiModelProperty(value = "ID", hidden = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ApiModelProperty(value = "表名") private String tableName; @ApiModelProperty(value = "数据库字段名称") private String columnName; @ApiModelProperty(value = "数据库字段类型") private String columnType; @ApiModelProperty(value = "数据库字段键类型") private String keyType; @ApiModelProperty(value = "字段额外的参数") private String extra; @ApiModelProperty(value = "数据库字段描述") private String remark; @ApiModelProperty(value = "是否必填") private Boolean notNull; @ApiModelProperty(value = "是否在列表显示") private Boolean listShow; @ApiModelProperty(value = "是否表单显示") private Boolean formShow; @ApiModelProperty(value = "表单类型") private String formType; @ApiModelProperty(value = "查询 1:模糊 2:精确") private String queryType; @ApiModelProperty(value = "字典名称") private String dictName;
@ApiModelProperty(value = "日期注解") private String dateAnnotation; public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { this.tableName = tableName; this.columnName = columnName; this.columnType = columnType; this.keyType = keyType; this.extra = extra; this.notNull = notNull; if(GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)){ this.notNull = false; } this.remark = remark; this.listShow = true; this.formShow = true; } }
repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\domain\ColumnInfo.java
1
请完成以下Java代码
public void setOperationType(String operationType) { this.operationType = operationType; } @CamundaQueryParam("assignerId") public void setAssignerId(String assignerId) { this.assignerId = assignerId; } @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) public void setTenantIdIn(List<String> tenantIds) { this.tenantIds = tenantIds; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @Override protected void applyFilters(HistoricIdentityLinkLogQuery query) { if (dateBefore != null) { query.dateBefore(dateBefore); } if (dateAfter != null) { query.dateAfter(dateAfter); } if (type != null) { query.type(type); } if (userId != null) { query.userId(userId); } if (groupId != null) { query.groupId(groupId); } if (taskId != null) { query.taskId(taskId); } if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } if (operationType != null) { query.operationType(operationType); } if (assignerId != null) { query.assignerId(assignerId);
} if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } } @Override protected void applySortBy(HistoricIdentityLinkLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_TIME)) { query.orderByTime(); } else if (sortBy.equals(SORT_BY_TYPE)) { query.orderByType(); } else if (sortBy.equals(SORT_BY_USER_ID)) { query.orderByUserId(); } else if (sortBy.equals(SORT_BY_GROUP_ID)) { query.orderByGroupId(); } else if (sortBy.equals(SORT_BY_TASK_ID)) { query.orderByTaskId(); } else if (sortBy.equals(SORT_BY_OPERATION_TYPE)) { query.orderByOperationType(); } else if (sortBy.equals(SORT_BY_ASSIGNER_ID)) { query.orderByAssignerId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogQueryDto.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("saved", saved ? true : null) .add("presentInDatabase", isPresentInDatabase ? true : null) .add("deleted", deleted ? true : null) .add("hasChangesToBeSaved", hasChangesToBeSaved ? true : null) .add("error", error ? true : null) .add("reason", reason) .toString(); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isSavedOrDeleted() { return isSaved() || isDeleted(); } public DocumentSaveStatus throwIfError() { if (!error) { return this; } if (exception != null) { throw AdempiereException.wrapIfNeeded(exception); } else { throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Error"));
} } public void throwIfNotSavedNorDelete() { if (isSavedOrDeleted()) { return; } if (exception != null) { throw AdempiereException.wrapIfNeeded(exception); } else { throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Not saved")); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentSaveStatus.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** * ReplenishType AD_Reference_ID=164 * Reference name: M_Replenish Type */ public static final int REPLENISHTYPE_AD_Reference_ID=164; /** Maximalbestand beibehalten = 2 */ public static final String REPLENISHTYPE_MaximalbestandBeibehalten = "2"; /** Manuell = 0 */ public static final String REPLENISHTYPE_Manuell = "0"; /** Bei Unterschreitung Minimalbestand = 1 */ public static final String REPLENISHTYPE_BeiUnterschreitungMinimalbestand = "1";
/** Custom = 9 */ public static final String REPLENISHTYPE_Custom = "9"; /** Zuk?nftigen Bestand sichern = 7 */ public static final String REPLENISHTYPE_ZukNftigenBestandSichern = "7"; @Override public void setReplenishType (java.lang.String ReplenishType) { set_Value (COLUMNNAME_ReplenishType, ReplenishType); } @Override public java.lang.String getReplenishType() { return (java.lang.String)get_Value(COLUMNNAME_ReplenishType); } @Override public void setTimeToMarket (int TimeToMarket) { set_Value (COLUMNNAME_TimeToMarket, Integer.valueOf(TimeToMarket)); } @Override public int getTimeToMarket() { return get_ValueAsInt(COLUMNNAME_TimeToMarket); } @Override public void setWarehouseValue (java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return (java.lang.String)get_Value(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Replenish.java
1
请完成以下Java代码
public void setTargetJobDefinitionId(String targetJobDefinitionId) { this.targetJobDefinitionId = targetJobDefinitionId; } @Override public boolean isDetached() { return incident.getExecutionId() == null; } public void detachState() { incident.setExecution(null); } public void attachState(MigratingScopeInstance newOwningInstance) { attachTo(newOwningInstance.resolveRepresentativeExecution()); } @Override public void attachState(MigratingTransitionInstance targetTransitionInstance) { attachTo(targetTransitionInstance.resolveRepresentativeExecution()); } public void migrateState() { incident.setActivityId(targetScope.getId()); incident.setProcessDefinitionId(targetScope.getProcessDefinition().getId());
incident.setJobDefinitionId(targetJobDefinitionId); migrateHistory(); } protected void migrateHistory() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); if (historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, this)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricIncidentMigrateEvt(incident); } }); } } public void migrateDependentEntities() { // nothing to do } protected void attachTo(ExecutionEntity execution) { incident.setExecution(execution); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingIncident.java
1
请完成以下Java代码
public class EventingProperty { /** * Controls events of execution listener. */ private Boolean execution = Boolean.TRUE; /** * Controls events of task listener. */ private Boolean task = Boolean.TRUE; /** * Controls events of history handler. */ private Boolean history = Boolean.TRUE; /** * Controls if the event listeners for tasks and executions are can be skipped (controlled by `skipCustomListeners` * property in Cockpit and in various APIs). Defaults to true. */ private Boolean skippable = Boolean.TRUE; public EventingProperty() { } public boolean isExecution() { return BooleanUtils.isTrue(execution); } public void setExecution(Boolean execution) { this.execution = execution; } public Boolean isTask() { return BooleanUtils.isTrue(task); } public void setTask(Boolean task) {
this.task = task; } public Boolean isHistory() { return BooleanUtils.isTrue(history); } public void setHistory(Boolean history) { this.history = history; } public boolean isSkippable() { return BooleanUtils.isTrue(skippable); } public void setSkippable(Boolean skippable) { this.skippable = skippable; } @Override public String toString() { return joinOn(this.getClass()) .add("execution=" + execution) .add("task=" + task) .add("history=" + history) .add("skippable=" + skippable) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\EventingProperty.java
1
请完成以下Java代码
public class UserProfileDO { /** * 编号 */ private Integer id; /** * 用户编号 */ private Integer userId; /** * 性别 */ private Integer gender; /** * 是否删除 */ @TableLogic private Integer deleted; /** * 租户编号 */ private Integer tenantId; public Integer getId() { return id; } public UserProfileDO setId(Integer id) { this.id = id; return this; } public Integer getGender() { return gender; }
public UserProfileDO setGender(Integer gender) { this.gender = gender; return this; } public Integer getDeleted() { return deleted; } public UserProfileDO setDeleted(Integer deleted) { this.deleted = deleted; return this; } public Integer getTenantId() { return tenantId; } public UserProfileDO setTenantId(Integer tenantId) { this.tenantId = tenantId; return this; } public Integer getUserId() { return userId; } public UserProfileDO setUserId(Integer userId) { this.userId = userId; return this; } }
repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\dataobject\UserProfileDO.java
1
请完成以下Java代码
LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; } LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) { LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT); return startofDay; } LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) { LocalDateTime startofDay = localDate.atTime(LocalTime.MIN); return startofDay; } LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) {
LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT); return startofDay; } LocalDateTime getEndOfDay(LocalDate localDate) { LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX); return endOfDay; } LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) { LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate); return endOfDate; } }
repos\tutorials-master\core-java-modules\core-java-8-datetime\src\main\java\com\baeldung\datetime\UseLocalDate.java
1
请完成以下Java代码
public boolean accept(ImmutablePair<org.compiere.model.I_C_Invoice, org.compiere.model.I_C_Invoice> model) { return true; } }, new EdiInvoiceCopyHandler()); } @Override public int getAD_Client_ID() { return adClientId; } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{ return null; } @Override public String modelChange(final PO po, final int type) { return null; } @Override public String docValidate(final PO po, final int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\Main.java
1
请完成以下Java代码
private static class SecurityContextAsyncContext implements AsyncContext { private final AsyncContext asyncContext; SecurityContextAsyncContext(AsyncContext asyncContext) { this.asyncContext = asyncContext; } @Override public ServletRequest getRequest() { return this.asyncContext.getRequest(); } @Override public ServletResponse getResponse() { return this.asyncContext.getResponse(); } @Override public boolean hasOriginalRequestAndResponse() { return this.asyncContext.hasOriginalRequestAndResponse(); } @Override public void dispatch() { this.asyncContext.dispatch(); } @Override public void dispatch(String path) { this.asyncContext.dispatch(path); } @Override public void dispatch(ServletContext context, String path) { this.asyncContext.dispatch(context, path); } @Override public void complete() { this.asyncContext.complete(); }
@Override public void start(Runnable run) { this.asyncContext.start(new DelegatingSecurityContextRunnable(run)); } @Override public void addListener(AsyncListener listener) { this.asyncContext.addListener(listener); } @Override public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) { this.asyncContext.addListener(listener, request, response); } @Override public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException { return this.asyncContext.createListener(clazz); } @Override public long getTimeout() { return this.asyncContext.getTimeout(); } @Override public void setTimeout(long timeout) { this.asyncContext.setTimeout(timeout); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\HttpServlet3RequestFactory.java
1
请完成以下Java代码
public I_R_Group getR_Group() throws RuntimeException { return (I_R_Group)MTable.get(getCtx(), I_R_Group.Table_Name) .getPO(getR_Group_ID(), get_TrxName()); } /** Set Group. @param R_Group_ID Request Group */ public void setR_Group_ID (int R_Group_ID) { if (R_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_R_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID)); } /** Get Group. @return Request Group */ public int getR_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_Request getR_Request() throws RuntimeException { return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name) .getPO(getR_Request_ID(), get_TrxName()); } /** Set Request. @param R_Request_ID Request from a Business Partner or Prospect */ public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Request. @return Request from a Business Partner or Prospect */ public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null)
return 0; return ii.intValue(); } public I_R_Status getR_Status() throws RuntimeException { return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name) .getPO(getR_Status_ID(), get_TrxName()); } /** Set Status. @param R_Status_ID Request Status */ public void setR_Status_ID (int R_Status_ID) { throw new IllegalArgumentException ("R_Status_ID is virtual column"); } /** Get Status. @return Request Status */ public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_R_Group_Prospect.java
1
请在Spring Boot框架中完成以下Java代码
public String buildUserNo() { String userNo = USER_NO_PREFIX + IdWorker.getId() ; return userNo; } /** 获取账户编号 **/ @Transactional(rollbackFor = Exception.class) public String buildAccountNo() { String accountNo = ACCOUNT_NO_PREFIX + IdWorker.getId(); return accountNo; } /** * 获取支付流水号 **/ @Override public String buildTrxNo() { String trxNo = TRX_NO_PREFIX + IdWorker.getId(); return trxNo;
} /** * 获取银行订单号 **/ @Override public String buildBankOrderNo() { String bankOrderNo = BANK_ORDER_NO_PREFIX + IdWorker.getId(); return bankOrderNo; } /** 获取对账批次号 **/ public String buildReconciliationNo() { String batchNo = RECONCILIATION_BATCH_NO + IdWorker.getId(); return batchNo; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\BuildNoServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
private void prepareContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); exchange.getIn().setHeader(HEADER_ORG_CODE, request.getOrgCode()); if (request.getAdPInstanceId() != null) { exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue()); processLogger.logMessage("Shopware6:GetCustomers process started!" + Instant.now(), request.getAdPInstanceId().getValue()); } final String clientSecret = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_SECRET); final String clientId = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_ID); final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH); final PInstanceLogger pInstanceLogger = PInstanceLogger.builder() .processLogger(processLogger) .pInstanceId(request.getAdPInstanceId()) .build(); final ShopwareClient shopwareClient = ShopwareClient.of(clientId, clientSecret, basePath, pInstanceLogger); final String updatedAfterOverride = request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER_OVERRIDE); final String updatedAfter = CoalesceUtil.coalesceNotNull( updatedAfterOverride, request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER), Instant.ofEpochSecond(0).toString()); final boolean skipNextImportTimestamp = Optional.ofNullable(updatedAfterOverride).isPresent(); final ImportCustomersRouteContext customersRouteContext = ImportCustomersRouteContext.builder() .orgCode(request.getOrgCode()) .shopwareClient(shopwareClient) .request(request) .updatedAfter(updatedAfter) .priceListBasicInfo(GetProductsRouteHelper.getTargetPriceListInfo(request)) .skipNextImportTimestamp(skipNextImportTimestamp)
.responsePageIndex(1) .pageLimit(ExternalSystemConstants.DEFAULT_SW6_ORDER_PAGE_SIZE) .build(); exchange.setProperty(ROUTE_PROPERTY_IMPORT_CUSTOMERS_CONTEXT, customersRouteContext); } private void processError(@NonNull final Exchange exchange) { final ImportCustomersRouteContext routeContext = getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_CUSTOMERS_CONTEXT, ImportCustomersRouteContext.class); routeContext.recomputeOldestFailingCustomer(routeContext.getCustomerUpdatedAt()); } private Predicate areMoreCustomersLeftToBeRetrieved() { return (exchange) -> { final ImportCustomersRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_CUSTOMERS_CONTEXT, ImportCustomersRouteContext.class); return routeContext.isMoreCustomersAvailable(); }; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\customer\GetCustomersRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public Iterator<ConditionAndOutcome> iterator() { return Collections.unmodifiableSet(this.outcomes).iterator(); } } /** * Provides access to a single {@link Condition} and {@link ConditionOutcome}. */ public static class ConditionAndOutcome { private final Condition condition; private final ConditionOutcome outcome; public ConditionAndOutcome(Condition condition, ConditionOutcome outcome) { this.condition = condition; this.outcome = outcome; } public Condition getCondition() { return this.condition; } public ConditionOutcome getOutcome() { return this.outcome; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false;
} ConditionAndOutcome other = (ConditionAndOutcome) obj; return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass()) && ObjectUtils.nullSafeEquals(this.outcome, other.outcome)); } @Override public int hashCode() { return this.condition.getClass().hashCode() * 31 + this.outcome.hashCode(); } @Override public String toString() { return this.condition.getClass() + " " + this.outcome; } } private static final class AncestorsMatchedCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { throw new UnsupportedOperationException(); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionEvaluationReport.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @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 setC_User_Assigned_Role_ID (final int C_User_Assigned_Role_ID) { if (C_User_Assigned_Role_ID < 1) set_ValueNoCheck (COLUMNNAME_C_User_Assigned_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_C_User_Assigned_Role_ID, C_User_Assigned_Role_ID); } @Override public int getC_User_Assigned_Role_ID() { return get_ValueAsInt(COLUMNNAME_C_User_Assigned_Role_ID); } @Override public org.compiere.model.I_C_User_Role getC_User_Role() { return get_ValueAsPO(COLUMNNAME_C_User_Role_ID, org.compiere.model.I_C_User_Role.class); }
@Override public void setC_User_Role(final org.compiere.model.I_C_User_Role C_User_Role) { set_ValueFromPO(COLUMNNAME_C_User_Role_ID, org.compiere.model.I_C_User_Role.class, C_User_Role); } @Override public void setC_User_Role_ID (final int C_User_Role_ID) { if (C_User_Role_ID < 1) set_Value (COLUMNNAME_C_User_Role_ID, null); else set_Value (COLUMNNAME_C_User_Role_ID, C_User_Role_ID); } @Override public int getC_User_Role_ID() { return get_ValueAsInt(COLUMNNAME_C_User_Role_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_User_Assigned_Role.java
1
请完成以下Java代码
public class HUQRCodeGenerateForExistingHUsResult { private final ImmutableSetMultimap<HuId, HUQRCode> huQRCodes; HUQRCodeGenerateForExistingHUsResult(@NonNull final SetMultimap<HuId, HUQRCode> huQRCodes) { this.huQRCodes = ImmutableSetMultimap.copyOf(huQRCodes); } public HUQRCode getSingleQRCode(@NonNull final HuId huId) { final ImmutableSet<HUQRCode> qrCodes = huQRCodes.get(huId); if (qrCodes.size() != 1) { throw new AdempiereException("Expected only one QR code to be generated for " + huId + " but found " + qrCodes); } return qrCodes.iterator().next();
} public ImmutableList<HUQRCode> toList() { return huQRCodes.values().asList(); } @NonNull public HUQRCode getFirstQRCode(final @NonNull HuId huId) { if (Check.isEmpty(huQRCodes.get(huId))) { throw new AdempiereException("No QRCode was generated for HuId=" + huId.getRepoId()); } return huQRCodes.get(huId).iterator().next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateForExistingHUsResult.java
1
请完成以下Java代码
public org.compiere.model.I_M_HazardSymbol getM_HazardSymbol() { return get_ValueAsPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class); } @Override public void setM_HazardSymbol(final org.compiere.model.I_M_HazardSymbol M_HazardSymbol) { set_ValueFromPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class, M_HazardSymbol); } @Override public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID) { if (M_HazardSymbol_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID); } @Override public int getM_HazardSymbol_ID()
{ return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_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_HazardSymbol_Trl.java
1
请完成以下Java代码
private void setDataNewCopyMode(final DataNewCopyMode copyMode) { Check.assumeNotNull(copyMode, "copyMode not null"); this._dataNewCopyMode = copyMode; } public void resetDataNewCopyMode() { this._dataNewCopyMode = null; // // Make sure the suggested child tables to be copied list is reset // if (m_gridTab != null) // { // m_gridTab.resetSuggestedCopyWithDetailsList(); // } } /** * Checks if we are currenty copying the current row <b>with details</b>. * <p>
* NOTE: this information will be available even after {@link #dataNew(int, DataNewCopyMode)} until the record is saved or discarded. * * @return true if we are currenty copying the current row <b>with details</b> */ public boolean isCopyWithDetails() { return DataNewCopyMode.isCopyWithDetails(_dataNewCopyMode); } /** * @return true if we are currenty copying the current row (with or without details) */ public boolean isRecordCopyingMode() { return DataNewCopyMode.isCopy(_dataNewCopyMode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTable.java
1
请在Spring Boot框架中完成以下Java代码
public class CourseResource { @Autowired private CoursesHardcodedService courseManagementService; @GetMapping() public List<Course> getAllCourses(@PathVariable String username) { return courseManagementService.findAll(); } @GetMapping("/{id}") public Course getCourse(@PathVariable String username, @PathVariable long id) { return courseManagementService.findById(id); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteCourse(@PathVariable String username, @PathVariable long id) { Course course = courseManagementService.deleteById(id); if (course != null) { return ResponseEntity.noContent().build(); } return ResponseEntity.notFound().build();
} @PutMapping("/{id}") public ResponseEntity<Course> updateCourse(@PathVariable String username, @PathVariable long id, @RequestBody Course course) { Course courseUpdated = courseManagementService.save(course); return new ResponseEntity<Course>(course, HttpStatus.OK); } @PostMapping() public ResponseEntity<Void> createCourse(@PathVariable String username, @RequestBody Course course) { Course createdCourse = courseManagementService.save(course); // Location // Get current resource url /// {id} URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(createdCourse.getId()) .toUri(); System.out.println(courseManagementService.findById(createdCourse.getId())); return ResponseEntity.created(uri).build(); } }
repos\spring-boot-examples-master\spring-boot-react-examples\spring-boot-react-crud-full-stack-with-maven\backend-spring-boot-react-crud-full-stack-with-maven\src\main\java\com\in28minutes\fullstack\springboot\maven\crud\springbootcrudfullstackwithmaven\course\CourseResource.java
2
请完成以下Java代码
public void actedIn(Movie movie, List<String> roleNames) { var movieRoles = new Roles(roleNames); movieRoles.setMovie(movie); this.roles.add(movieRoles); } public Long getId() { return id; } public String getName() { return name; }
public List<Roles> getRoles() { return roles; } public void setRoles(List<Roles> roles) { this.roles = roles; } @Override public String toString() { return "Actor{" + "name='" + name + '\'' + '}'; } }
repos\spring-data-examples-main\neo4j\example\src\main\java\example\springdata\neo4j\Actor.java
1
请完成以下Java代码
public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public Integer getDeleteStatus() { return deleteStatus; } public void setDeleteStatus(Integer deleteStatus) { this.deleteStatus = deleteStatus; } public Long getProductCategoryId() { return productCategoryId; } public void setProductCategoryId(Long productCategoryId) { this.productCategoryId = productCategoryId; } public String getProductBrand() { return productBrand; } public void setProductBrand(String productBrand) { this.productBrand = productBrand; } public String getProductSn() { return productSn; } public void setProductSn(String productSn) { this.productSn = productSn; } public String getProductAttr() { return productAttr; } public void setProductAttr(String productAttr) { this.productAttr = productAttr;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", productSkuId=").append(productSkuId); sb.append(", memberId=").append(memberId); sb.append(", quantity=").append(quantity); sb.append(", price=").append(price); sb.append(", productPic=").append(productPic); sb.append(", productName=").append(productName); sb.append(", productSubTitle=").append(productSubTitle); sb.append(", productSkuCode=").append(productSkuCode); sb.append(", memberNickname=").append(memberNickname); sb.append(", createDate=").append(createDate); sb.append(", modifyDate=").append(modifyDate); sb.append(", deleteStatus=").append(deleteStatus); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", productBrand=").append(productBrand); sb.append(", productSn=").append(productSn); sb.append(", productAttr=").append(productAttr); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItem.java
1
请完成以下Java代码
public String getVehicleName() { return vehicleName; } public void setVehicleName(String vehicleName) { this.vehicleName = vehicleName; } public String getVehicleModel() { return vehicleModel; } public void setVehicleModel(String vehicleModel) { this.vehicleModel = vehicleModel; } public Long getMakeYear() { return makeYear; }
public void setMakeYear(Long makeYear) { this.makeYear = makeYear; } protected abstract void start(); protected abstract void stop(); protected abstract void drive(); protected abstract void changeGear(); protected abstract void reverse(); }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\interfacevsabstractclass\Vehicle.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (!(o instanceof Post)) { return false; } Post post = (Post) o; return getId().equals(post.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\aggregation\model\Post.java
1
请完成以下Java代码
public void setNumberOfInsured (final @Nullable String NumberOfInsured) { set_Value (COLUMNNAME_NumberOfInsured, NumberOfInsured); } @Override public String getNumberOfInsured() { return get_ValueAsString(COLUMNNAME_NumberOfInsured); } /** * PayerType AD_Reference_ID=541319 * Reference name: PayerType_list */ public static final int PAYERTYPE_AD_Reference_ID=541319; /** Unbekannt = 0 */ public static final String PAYERTYPE_Unbekannt = "0"; /** Gesetzlich = 1 */ public static final String PAYERTYPE_Gesetzlich = "1"; /** Privat = 2 */ public static final String PAYERTYPE_Privat = "2"; /** Berufsgenossenschaft = 3 */ public static final String PAYERTYPE_Berufsgenossenschaft = "3"; /** Selbstzahler = 4 */ public static final String PAYERTYPE_Selbstzahler = "4"; /** Andere = 5 */ public static final String PAYERTYPE_Andere = "5"; @Override public void setPayerType (final @Nullable String PayerType)
{ set_Value (COLUMNNAME_PayerType, PayerType); } @Override public String getPayerType() { return get_ValueAsString(COLUMNNAME_PayerType); } @Override public void setUpdatedAt (final @Nullable java.sql.Timestamp UpdatedAt) { set_Value (COLUMNNAME_UpdatedAt, UpdatedAt); } @Override public java.sql.Timestamp getUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_UpdatedAt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_AlbertaPatient.java
1
请完成以下Java代码
public int getC_Withholding_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Withholding_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Exempt reason. @param ExemptReason Reason for not withholding */ public void setExemptReason (String ExemptReason) { set_Value (COLUMNNAME_ExemptReason, ExemptReason); } /** Get Exempt reason. @return Reason for not withholding */ public String getExemptReason () { return (String)get_Value(COLUMNNAME_ExemptReason); } /** Set Mandatory Withholding. @param IsMandatoryWithholding Monies must be withheld */ public void setIsMandatoryWithholding (boolean IsMandatoryWithholding) { set_Value (COLUMNNAME_IsMandatoryWithholding, Boolean.valueOf(IsMandatoryWithholding)); } /** Get Mandatory Withholding. @return Monies must be withheld */ public boolean isMandatoryWithholding () { Object oo = get_Value(COLUMNNAME_IsMandatoryWithholding); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Temporary exempt. @param IsTemporaryExempt Temporarily do not withhold taxes */ public void setIsTemporaryExempt (boolean IsTemporaryExempt) { set_Value (COLUMNNAME_IsTemporaryExempt, Boolean.valueOf(IsTemporaryExempt)); } /** Get Temporary exempt. @return Temporarily do not withhold taxes */ public boolean isTemporaryExempt () { Object oo = get_Value(COLUMNNAME_IsTemporaryExempt); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Withholding.java
1
请完成以下Java代码
public Builder appendIfNotEmpty(@Nullable final String string) { if (isEmpty()) { return this; } return append(string); } public Builder append(final StringBuilder constant) { if (constant == null || constant.length() <= 0) { return this; } append(constant.toString()); return this; } public Builder append(final Builder otherBuilder) { for (final IStringExpression expr : otherBuilder.expressions) { append(expr); } if (otherBuilder._lastConstantBuffer != null && otherBuilder._lastConstantBuffer.length() > 0) { appendToLastConstantBuffer(otherBuilder._lastConstantBuffer.toString()); } return this; } public Builder append(final CtxName name) { append(new SingleParameterStringExpression(name.toStringWithMarkers(), name)); return this; } /** * Wraps the entire content of this builder using given wrapper. * After this method invocation the builder will contain only the wrapped expression. */
public Builder wrap(final IStringExpressionWrapper wrapper) { Check.assumeNotNull(wrapper, "Parameter wrapper is not null"); final IStringExpression expression = build(); final IStringExpression expressionWrapped = wrapper.wrap(expression); expressions.clear(); append(expressionWrapped); return this; } /** * If the {@link Condition} is <code>true</code> then it wraps the entire content of this builder using given wrapper. * After this method invocation the builder will contain only the wrapped expression. */ public Builder wrapIfTrue(final boolean condition, final IStringExpressionWrapper wrapper) { if (!condition) { return this; } return wrap(wrapper); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CompositeStringExpression.java
1
请完成以下Java代码
public StartupStep tag(String key, Supplier<String> value) { return tag(key, value.get()); } @Override public StartupStep tag(String key, String value) { Assert.state(!this.ended.get(), "StartupStep has already ended."); this.tags.add(new DefaultTag(key, value)); return this; } @Override public void end() { this.ended.set(true); this.recorder.accept(this); } boolean isEnded() { return this.ended.get(); } static class DefaultTag implements Tag { private final String key; private final String value;
DefaultTag(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return this.key; } @Override public String getValue() { return this.value; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\BufferedStartupStep.java
1
请完成以下Java代码
public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * Status AD_Reference_ID=541993 * Reference name: C_OrderPaySchedule_Status */ public static final int STATUS_AD_Reference_ID=541993; /** Pending_Ref = PR */ public static final String STATUS_Pending_Ref = "PR";
/** Awaiting_Pay = WP */ public static final String STATUS_Awaiting_Pay = "WP"; /** Paid = P */ public static final String STATUS_Paid = "P"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderPaySchedule.java
1
请完成以下Java代码
public void onError(Observation observation, Registration registration, Exception error) { if (error != null) { var path = observation instanceof SingleObservation ? "Single Observation Cancel: " + ((SingleObservation) observation).getPath() : "Composite Observation Cancel: " + ((CompositeObservation) observation).getPaths(); var msgError = path + ": " + error.getMessage(); log.trace("Unable to handle notification [RegistrationId:{}]: [{}].", observation.getRegistrationId(), msgError); service.onErrorObservation(registration, msgError); } } @Override public void newObservation(Observation observation, Registration registration) { log.trace("Successful start newObservation [RegistrationId:{}: {}].", observation.getRegistrationId(), observation instanceof SingleObservation ? "Single: " + ((SingleObservation) observation).getPath() : "Composite: " + ((CompositeObservation) observation).getPaths()); } };
public final SendListener sendListener = new SendListener() { @Override public void dataReceived(Registration registration, TimestampedLwM2mNodes data, SendRequest request) { log.trace("Received Send request from [{}] containing value: [{}], coapRequest: [{}]", registration.getEndpoint(), data.toString(), request.getCoapRequest().toString()); if (registration != null) { service.onUpdateValueWithSendRequest(registration, data); } } @Override public void onError(Registration registration, String errorMessage, Exception error) { } }; }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mServerListener.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI getM_TU_HU_PI() { return get_ValueAsPO(COLUMNNAME_M_TU_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class); } @Override public void setM_TU_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_TU_HU_PI) { set_ValueFromPO(COLUMNNAME_M_TU_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_TU_HU_PI); } @Override public void setM_TU_HU_PI_ID (final int M_TU_HU_PI_ID) { if (M_TU_HU_PI_ID < 1) set_Value (COLUMNNAME_M_TU_HU_PI_ID, null); else set_Value (COLUMNNAME_M_TU_HU_PI_ID, M_TU_HU_PI_ID); } @Override public int getM_TU_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_TU_HU_PI_ID); }
@Override public void setQtyCUsPerTU (final BigDecimal QtyCUsPerTU) { set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU); } @Override public BigDecimal getQtyCUsPerTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyLU (final BigDecimal QtyLU) { set_Value (COLUMNNAME_QtyLU, QtyLU); } @Override public BigDecimal getQtyLU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final BigDecimal QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public BigDecimal getQtyTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_LUTU_Configuration.java
1
请完成以下Java代码
private Component getComponent(final VEditor editor) { return swingEditorFactory.getEditorComponent(editor); } private VEditor getEditor(final GridField gridField) { if (gridField == null) { return null; } for (final VEditor editor : fieldEditorsAll) { if (editor.getField() == gridField) { return editor; } } return null; } /** * Update fields UI properties * * @see #dynamicDisplay(int) */ private void dynamicDisplay() { final int fieldCount = model.getFieldCount(); for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++) { dynamicDisplay(fieldIndex); } } /** * Update field's UI properties: Displayed, Read-Write * * @param fieldIndex */ private void dynamicDisplay(final int fieldIndex) { final Properties ctx = model.getCtx(); final GridField gridField = model.getField(fieldIndex); // allways not null final VEditor editor = fieldEditors.get(fieldIndex); final VEditor editorTo = fieldEditorsTo.get(fieldIndex); final JLabel separator = fieldSeparators.get(fieldIndex); final JLabel label = fieldLabels.get(fieldIndex); // Visibility final boolean editorVisible = (editor != null) && gridField.isDisplayed(ctx); final boolean editorToVisible = (editorTo != null) && editorVisible; final boolean labelVisible = editorVisible || editorToVisible; final boolean separatorVisible = editorVisible || editorToVisible; // Read-Only/Read-Write final boolean editorRW = editorVisible && gridField.isEditablePara(ctx); final boolean editorToRW = editorToVisible && editorRW; // Update fields if (label != null) { label.setVisible(labelVisible); } if (editor != null) { editor.setVisible(editorVisible); editor.setReadWrite(editorRW); }
if (separator != null) { separator.setVisible(separatorVisible); } if (editorTo != null) { editorTo.setVisible(editorToVisible); editorTo.setReadWrite(editorToRW); } } public List<ProcessInfoParameter> createParameters() { // // Make sure all editor values are pushed back to model (GridFields) for (final VEditor editor : fieldEditorsAll) { final GridField gridField = editor.getField(); if (gridField == null) { // guard agaist null, shall not happen continue; } final Object value = editor.getValue(); model.setFieldValue(gridField, value); } // // Ask the model to create the parameters return model.createProcessInfoParameters(); } /** * #782 Request focus on the first process parameter (if possible) */ public void focusFirstParameter() { if (fieldEditors.isEmpty()) { // there are no parameters in this process. Nothing to focus return; } for (final VEditor fieldEditor : fieldEditors) { final boolean focusGained = getComponent(fieldEditor).requestFocusInWindow(); if (focusGained) { return; } } } } // ProcessParameterPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessParametersPanel.java
1
请完成以下Java代码
public long skip(long n) throws IOException { return wrappedReader.skip(n); } /** * Rewinds the reader such that the initial characters are returned when invoking read(). * * Throws an exception if more than the buffering limit has already been read. * @throws IOException */ public void rewind() throws IOException { if (!rewindable) { throw LOG.unableToRewindReader(); } wrappedReader.unread(buffer, 0, pos); pos = 0;
} public int getRewindBufferSize() { return buffer.length; } /** * * @return the number of characters that can still be read and rewound. */ public int getCurrentRewindableCapacity() { return buffer.length - pos; } }
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\RewindableReader.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getFeeRate() { return feeRate; } public void setFeeRate(BigDecimal feeRate) { this.feeRate = feeRate; } public BigDecimal getPlatCost() { return platCost; } public void setPlatCost(BigDecimal platCost) { this.platCost = platCost; } public BigDecimal getPlatProfit() { return platProfit; } public void setPlatProfit(BigDecimal platProfit) { this.platProfit = platProfit; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime; } public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; }
public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); } public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public SqlAndParams evaluate(@NonNull final Evaluatee evalCtx) { return SqlAndParams.of( this.sql.evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Fail), this.sqlParams); } // // // ------------------------------------------------------- // // @SuppressWarnings("UnusedReturnValue") public static class Builder { private final CompositeStringExpression.Builder sql = IStringExpression.composer(); private final ArrayList<Object> sqlParams = new ArrayList<>(); private Builder() {} public SqlAndParamsExpression build() { return new SqlAndParamsExpression(this); } public Builder appendIfNotEmpty(@Nullable final String sqlToAppend) { if (sqlToAppend != null) { sql.appendIfNotEmpty(sqlToAppend); } return this; } public Builder append(@NonNull final String sqlToAppend, final Object... sqlParamsToAppend) { sql.append(sqlToAppend); sqlParams.addAll(Arrays.asList(sqlParamsToAppend)); return this; } public Builder append(@Nullable final SqlAndParams sqlAndParams) { if (sqlAndParams != null) { sql.append(sqlAndParams.getSql()); sqlParams.addAll(sqlAndParams.getSqlParams()); } return this; } public Builder append(@NonNull final SqlAndParamsExpression sqlToAppend) { sql.append(sqlToAppend.getSql()); sqlParams.addAll(sqlToAppend.getSqlParams()); return this; } public Builder append(@NonNull final SqlAndParamsExpression.Builder sqlToAppend) { sql.append(sqlToAppend.sql);
sqlParams.addAll(sqlToAppend.sqlParams); return this; } public Builder append(@NonNull final IStringExpression sqlToAppend) { sql.append(sqlToAppend); return this; } public Builder append(@Nullable final String sqlToAppend) { if (sqlToAppend != null) { sql.append(sqlToAppend); } return this; } public Builder appendSqlList(@NonNull final String sqlColumnName, @NonNull final Collection<?> values) { final String sqlToAppend = DB.buildSqlList(sqlColumnName, values, sqlParams); sql.append(sqlToAppend); return this; } public boolean isEmpty() { return sql.isEmpty() && sqlParams.isEmpty(); } public Builder wrap(@NonNull final IStringExpressionWrapper wrapper) { sql.wrap(wrapper); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParamsExpression.java
1
请完成以下Java代码
static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestHostHeader(String host) { return ofRequestProcessor(BeforeFilterFunctions.setRequestHostHeader(host)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setResponseHeader(String name, String value) { return ofResponseProcessor(AfterFilterFunctions.setResponseHeader(name, value)); } static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix() { return stripPrefix(1); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix(int parts) { return ofRequestProcessor(BeforeFilterFunctions.stripPrefix(parts)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(int statusCode) { return setStatus(new HttpStatusHolder(null, statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusCode statusCode) { return setStatus(new HttpStatusHolder(statusCode, null)); } @Shortcut
static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusHolder statusCode) { return ofResponseProcessor(AfterFilterFunctions.setStatus(statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> uri(String uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> uri(URI uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(FilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\FilterFunctions.java
1
请完成以下Java代码
public void setRemote_Host (String Remote_Host) { set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Serial No. @param SerNo Product Serial Number */ public void setSerNo (String SerNo) { set_ValueNoCheck (COLUMNNAME_SerNo, SerNo); } /** Get Serial No. @return Product Serial Number */ public String getSerNo () { return (String)get_Value(COLUMNNAME_SerNo); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_ValueNoCheck (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL ()
{ return (String)get_Value(COLUMNNAME_URL); } /** Set Version No. @param VersionNo Version Number */ public void setVersionNo (String VersionNo) { set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo); } /** Get Version No. @return Version Number */ public String getVersionNo () { return (String)get_Value(COLUMNNAME_VersionNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Delivery.java
1
请完成以下Java代码
public class ListDuplicate { public List<Integer> listDuplicateUsingSet(List<Integer> list) { List<Integer> duplicates = new ArrayList<>(); Set<Integer> set = new HashSet<>(); for (Integer i : list) { if (set.contains(i)) { duplicates.add(i); } else { set.add(i); } } return duplicates; } public List<Integer> listDuplicateUsingMap(List<Integer> list) { List<Integer> duplicates = new ArrayList<>(); Map<Integer, Integer> frequencyMap = new HashMap<>(); for (Integer number : list) { frequencyMap.put(number, frequencyMap.getOrDefault(number, 0) + 1); } for (int number : frequencyMap.keySet()) { if (frequencyMap.get(number) != 1) { duplicates.add(number); } } return duplicates; } public List<Integer> listDuplicateUsingFilterAndSetAdd(List<Integer> list) { Set<Integer> elements = new HashSet<Integer>(); return list.stream() .filter(n -> !elements.add(n)) .collect(Collectors.toList()); } public List<Integer> listDuplicateUsingCollectionsFrequency(List<Integer> list) { List<Integer> duplicates = new ArrayList<>(); Set<Integer> set = list.stream() .filter(i -> Collections.frequency(list, i) > 1) .collect(Collectors.toSet()); duplicates.addAll(set); return duplicates; }
public List<Integer> listDuplicateUsingMapAndCollectorsGroupingBy(List<Integer> list) { List<Integer> duplicates = new ArrayList<>(); Set<Integer> set = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(m -> m.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toSet()); duplicates.addAll(set); return duplicates; } public static <T> Set<T> findDuplicateInArrayWithForLoop(T[] array) { Set<T> duplicates = new HashSet<>(); Set<T> seen = new HashSet<>(); for (T val : array) { if (!seen.add(val)) { duplicates.add(val); } } return duplicates; } public static <T> Set<T> findDuplicateInArrayWithStream(T[] array) { Set<T> seen = new HashSet<>(); return Arrays.stream(array) .filter(val -> !seen.add(val)) .collect(Collectors.toSet()); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-5\src\main\java\com\baeldung\listduplicate\ListDuplicate.java
1
请完成以下Java代码
public boolean isAutomatischerAbruf() { return automatischerAbruf; } /** * Sets the value of the automatischerAbruf property. * */ public void setAutomatischerAbruf(boolean value) { this.automatischerAbruf = value; } /** * Gets the value of the kundenKennung property. * * @return * possible object is * {@link String } *
*/ public String getKundenKennung() { return kundenKennung; } /** * Sets the value of the kundenKennung property. * * @param value * allowed object is * {@link String } * */ public void setKundenKennung(String value) { this.kundenKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VertragsdatenAntwort.java
1
请完成以下Java代码
public CompensateEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new CompensateEventDefinitionImpl(instanceContext); } }); waitForCompletionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_WAIT_FOR_COMPLETION) .build(); activityRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ACTIVITY_REF) .qNameAttributeReference(Activity.class) .build(); typeBuilder.build(); } public CompensateEventDefinitionImpl(ModelTypeInstanceContext context) { super(context); } public boolean isWaitForCompletion() {
return waitForCompletionAttribute.getValue(this); } public void setWaitForCompletion(boolean isWaitForCompletion) { waitForCompletionAttribute.setValue(this, isWaitForCompletion); } public Activity getActivity() { return activityRefAttribute.getReferenceTargetElement(this); } public void setActivity(Activity activity) { activityRefAttribute.setReferenceTargetElement(this, activity); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CompensateEventDefinitionImpl.java
1
请完成以下Java代码
public void setHeader(final List<String> header) { Check.assumeNotNull(header, "header not null"); Check.assume(!header.isEmpty(), "header not empty"); Check.assume(!headerAppended, "header was not already appended"); this.header = header; } private void appendHeader() throws IOException { if (headerAppended) { return; } Check.assumeNotNull(header, "header not null"); final StringBuilder headerLine = new StringBuilder(); for (final String headerCol : header) { if (headerLine.length() > 0) { headerLine.append(fieldDelimiter); } final String headerColQuoted = quoteCsvValue(headerCol); headerLine.append(headerColQuoted); } writer.append(headerLine.toString()); writer.append(lineEnding); headerAppended = true; } @Override public void appendLine(List<Object> values) throws IOException { appendHeader(); final StringBuilder line = new StringBuilder(); final int cols = header.size(); final int valuesCount = values.size(); for (int i = 0; i < cols; i++) { final Object csvValue; if (i < valuesCount) { csvValue = values.get(i); } else { csvValue = null; } final String csvValueQuoted = toCsvValue(csvValue); if (line.length() > 0) { line.append(fieldDelimiter); }
line.append(csvValueQuoted); } writer.append(line.toString()); writer.append(lineEnding); } private String toCsvValue(Object value) { final String valueStr; if (value == null) { valueStr = ""; } else if (value instanceof java.util.Date) { valueStr = dateFormat.format(value); } else { valueStr = value.toString(); } return quoteCsvValue(valueStr); } private String quoteCsvValue(String valueStr) { return fieldQuote + valueStr.replace(fieldQuote, fieldQuote + fieldQuote) + fieldQuote; } @Override public void close() throws IOException { if (writer == null) { return; } try { writer.flush(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // shall not happen e.printStackTrace(); // NOPMD by tsa on 3/13/13 1:46 PM } writer = null; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\CSVWriter.java
1
请完成以下Java代码
public String getUserId() { return userId; } public Date getTimestamp() { return timestamp; } public String getOperationId() { return operationId; } public String getExternalTaskId() { return externalTaskId; } public String getOperationType() { return operationType; } public String getEntityType() { return entityType; } public String getProperty() { return property; } public String getOrgValue() { return orgValue; }
public String getNewValue() { return newValue; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getCategory() { return category; } public String getAnnotation() { return annotation; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogEntryDto.java
1
请完成以下Java代码
public JsonExternalSystemInfo retrieveExternalSystemInfo(@NonNull final ExternalSystemParentConfig parentConfig) { final IExternalSystemChildConfig childConfig = parentConfig.getChildConfig(); final String orgCode = orgDAO.retrieveOrgValue(parentConfig.getOrgId()); return JsonExternalSystemInfo.builder() .externalSystemConfigId(JsonMetasfreshId.of(parentConfig.getId().getRepoId())) .externalSystemName(JsonExternalSystemName.of(parentConfig.getType().getValue())) .externalSystemChildConfigValue(childConfig.getValue()) .orgCode(orgCode) .parameters(getParameters(parentConfig)) .build(); } @NonNull private static Map<String, String> getParameters(@NonNull final ExternalSystemParentConfig config) { if (config.getType().isGRSSignum()) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(config.getChildConfig()); return getGRSSignumParameters(grsConfig);
} throw new AdempiereException("Unsupported externalSystemConfigType=" + config.getType()); } @NonNull private static Map<String, String> getGRSSignumParameters(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig) { final Map<String, String> parameters = new HashMap<>(); if (grsSignumConfig.isCreateBPartnerFolders()) { parameters.put(PARAM_BasePathForExportDirectories, grsSignumConfig.getBasePathForExportDirectories()); } return ImmutableMap.copyOf(parameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\externlasystem\JsonExternalSystemRetriever.java
1
请完成以下Java代码
public boolean isNotLockedBy(@NonNull final UserId userId) { if (isEmpty()) { return true; } return !isLockedBy(userId); } public boolean isLockedBy(@NonNull final UserId userId) { if (isEmpty()) { return false; } return locks.values() .stream() .anyMatch(lock -> lock.isLockedBy(userId)); } public void assertLockedBy(@NonNull final UserId expectedLockedBy) { if (isEmpty()) { return; } final List<ShipmentScheduleLock> locksByOtherUser = locks.values() .stream() .filter(lock -> lock.isNotLockedBy(expectedLockedBy)) .collect(ImmutableList.toImmutableList()); if (!locksByOtherUser.isEmpty()) { throw new AdempiereException("Following locks are not owned by " + expectedLockedBy + ": " + locksByOtherUser); } } public void assertLockType(@NonNull final ShipmentScheduleLockType expectedLockType) { if (isEmpty()) { return; }
final List<ShipmentScheduleLock> locksWithDifferentLockType = locks.values() .stream() .filter(lock -> !lock.isLockType(expectedLockType)) .collect(ImmutableList.toImmutableList()); if (!locksWithDifferentLockType.isEmpty()) { throw new AdempiereException("Following locks are not for " + expectedLockType + ": " + locksWithDifferentLockType); } } public Set<ShipmentScheduleId> getShipmentScheduleIdsNotLocked(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIdsToCheck) { if (isEmpty()) { return shipmentScheduleIdsToCheck; } return shipmentScheduleIdsToCheck.stream() .filter(this::isNotLocked) .collect(ImmutableSet.toImmutableSet()); } public Set<ShipmentScheduleId> getShipmentScheduleIdsLocked() { return locks.keySet(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\lock\ShipmentScheduleLocksMap.java
1
请完成以下Java代码
public void on(ProductRemovedEvent event) { orders.computeIfPresent(event.getOrderId(), (orderId, order) -> { order.removeProduct(event.getProductId()); emitUpdate(order); return order; }); } @EventHandler public void on(OrderConfirmedEvent event) { orders.computeIfPresent(event.getOrderId(), (orderId, order) -> { order.setOrderConfirmed(); emitUpdate(order); return order; }); } @EventHandler public void on(OrderShippedEvent event) { orders.computeIfPresent(event.getOrderId(), (orderId, order) -> { order.setOrderShipped(); emitUpdate(order); return order; }); } @QueryHandler public List<Order> handle(FindAllOrderedProductsQuery query) { return new ArrayList<>(orders.values()); } @QueryHandler public Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query) { return Mono.fromCallable(orders::values)
.flatMapMany(Flux::fromIterable); } @QueryHandler public Integer handle(TotalProductsShippedQuery query) { return orders.values() .stream() .filter(o -> o.getOrderStatus() == OrderStatus.SHIPPED) .map(o -> Optional.ofNullable(o.getProducts() .get(query.getProductId())) .orElse(0)) .reduce(0, Integer::sum); } @QueryHandler public Order handle(OrderUpdatesQuery query) { return orders.get(query.getOrderId()); } private void emitUpdate(Order order) { emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId() .equals(q.getOrderId()), order); } @Override public void reset(List<Order> orderList) { orders.clear(); orderList.forEach(o -> orders.put(o.getOrderId(), o)); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\InMemoryOrdersEventHandler.java
1
请完成以下Java代码
public class InOutCostRow implements IViewRow { @ViewColumn(seqNo = 10, widgetType = DocumentFieldWidgetType.Lookup, captionKey = "C_BPartner_ID") private final LookupValue bpartner; @ViewColumn(seqNo = 20, widgetType = DocumentFieldWidgetType.Lookup, captionKey = "C_OrderPO_ID") private final LookupValue purchaseOrder; @ViewColumn(seqNo = 30, widgetType = DocumentFieldWidgetType.Lookup, captionKey = "M_InOut_ID") private final LookupValue inout; @ViewColumn(seqNo = 40, widgetType = DocumentFieldWidgetType.Lookup, captionKey = "C_Cost_Type_ID") private final LookupValue costType; @ViewColumn(seqNo = 50, widgetType = DocumentFieldWidgetType.Text, captionKey = "C_Currency_ID") private final String currency; @ViewColumn(seqNo = 60, widgetType = DocumentFieldWidgetType.Amount, captionKey = "CostAmount") private final BigDecimal costAmountToInvoice; private final ViewRowFieldNameAndJsonValuesHolder<InOutCostRow> values; private final DocumentId rowId; @Getter private final InOutCostId inoutCostId; @Builder private InOutCostRow( final InOutCostId inoutCostId, final LookupValue bpartner, final LookupValue purchaseOrder, final LookupValue inout, final LookupValue costType, final String currency, final BigDecimal costAmountToInvoice)
{ this.bpartner = bpartner; this.purchaseOrder = purchaseOrder; this.inout = inout; this.costType = costType; this.currency = currency; this.costAmountToInvoice = costAmountToInvoice; values = ViewRowFieldNameAndJsonValuesHolder.newInstance(InOutCostRow.class); this.rowId = DocumentId.of(inoutCostId); this.inoutCostId = inoutCostId; } @Override public DocumentId getId() {return rowId;} @Override public boolean isProcessed() {return true;} @Nullable @Override public DocumentPath getDocumentPath() {return null;} @Override public Set<String> getFieldNames() {return values.getFieldNames();} @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() {return values.get(this);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostRow.java
1
请完成以下Java代码
public void setUsersByUsernameQuery(String usersByUsernameQueryString) { this.usersByUsernameQuery = usersByUsernameQueryString; } protected boolean getEnableAuthorities() { return this.enableAuthorities; } /** * Enables loading of authorities (roles) from the authorities table. Defaults to true */ public void setEnableAuthorities(boolean enableAuthorities) { this.enableAuthorities = enableAuthorities; } protected boolean getEnableGroups() { return this.enableGroups; } /** * Enables support for group authorities. Defaults to false * @param enableGroups
*/ public void setEnableGroups(boolean enableGroups) { this.enableGroups = enableGroups; } @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } private JdbcTemplate getJdbc() { JdbcTemplate template = getJdbcTemplate(); Assert.notNull(template, "JdbcTemplate cannot be null"); return template; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\jdbc\JdbcDaoImpl.java
1
请完成以下Java代码
public boolean remove(E element) { Integer index = elementToIndex.get(element); if (index == null) { return false; } elementToIndex.remove(element); indexToElement.remove(index); for (int i = index + 1; i < nextIndex; i++) { E elementAtI = indexToElement.get(i); if (elementAtI != null) { indexToElement.remove(i); elementToIndex.put(elementAtI, i - 1); indexToElement.put(i - 1, elementAtI); } }
nextIndex--; return true; } public int indexOf(E element) { return elementToIndex.getOrDefault(element, -1); } public E get(int index) { if (index < 0 || index >= nextIndex) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + nextIndex); } return indexToElement.get(index); } }
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\IndexAwareSetWithTwoMaps.java
1
请完成以下Java代码
public class C_PurchaseCandiate_Mark_Processed extends JavaProcess implements IProcessPrecondition { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable( @NonNull final IProcessPreconditionsContext context) { if (!I_C_PurchaseCandidate.Table_Name.equals(context.getTableName())) { return ProcessPreconditionsResolution.reject(); } final boolean containsEligibleRecords = context .streamSelectedModels(I_C_PurchaseCandidate.class) .anyMatch(not(I_C_PurchaseCandidate::isProcessed)); return ProcessPreconditionsResolution.acceptIf(containsEligibleRecords); } @Override protected String doIt() throws Exception { final IQueryBL queryBL = Services.get(IQueryBL.class); final PurchaseCandidateRepository purchaseCandidateRepository = Adempiere.getBean(PurchaseCandidateRepository.class); final ImmutableSet<PurchaseCandidateId> purchaseCandidateIds = queryBL .createQueryBuilder(I_C_PurchaseCandidate.class) .filter(getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)))
.create() .stream() .filter(not(I_C_PurchaseCandidate::isProcessed)) .map(I_C_PurchaseCandidate::getC_PurchaseCandidate_ID) .map(PurchaseCandidateId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); final ImmutableList<PurchaseCandidate> purchaseCandidates = purchaseCandidateRepository .streamAllByIds(purchaseCandidateIds) .peek(PurchaseCandidate::markProcessed) .collect(ImmutableList.toImmutableList()); purchaseCandidateRepository.saveAll(purchaseCandidates); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\process\C_PurchaseCandiate_Mark_Processed.java
1
请在Spring Boot框架中完成以下Java代码
private @Nullable SecurityService getCloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, Environment environment) { String cloudControllerUrl = environment.getProperty("vcap.application.cf_api"); boolean skipSslValidation = environment.getProperty("management.cloudfoundry.skip-ssl-validation", Boolean.class, false); return (cloudControllerUrl != null) ? new SecurityService(restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null; } private CorsConfiguration getCorsConfiguration() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); corsConfiguration .setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); return corsConfiguration; } /** * {@link WebSecurityConfigurer} to tell Spring Security to permit cloudfoundry * specific paths. The Cloud foundry endpoints are protected by their own security * interceptor. */ @ConditionalOnClass({ WebSecurityCustomizer.class, WebSecurity.class }) @Configuration(proxyBeanMethods = false) static class IgnoredCloudFoundryPathsWebSecurityConfiguration { private static final int FILTER_CHAIN_ORDER = -1; @Bean @Order(FILTER_CHAIN_ORDER) SecurityFilterChain cloudFoundrySecurityFilterChain(HttpSecurity http, CloudFoundryWebEndpointServletHandlerMapping handlerMapping) { RequestMatcher cloudFoundryRequest = getRequestMatcher(handlerMapping); http.csrf((csrf) -> csrf.ignoringRequestMatchers(cloudFoundryRequest)); http.securityMatchers((matches) -> matches.requestMatchers(cloudFoundryRequest)) .authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll());
return http.build(); } private RequestMatcher getRequestMatcher(CloudFoundryWebEndpointServletHandlerMapping handlerMapping) { PathMappedEndpoints endpoints = new PathMappedEndpoints(BASE_PATH, handlerMapping::getAllEndpoints); List<RequestMatcher> matchers = new ArrayList<>(); endpoints.getAllPaths().forEach((path) -> matchers.add(pathMatcher(path + "/**"))); matchers.add(pathMatcher(BASE_PATH)); matchers.add(pathMatcher(BASE_PATH + "/")); return new OrRequestMatcher(matchers); } private PathPatternRequestMatcher pathMatcher(String path) { return PathPatternRequestMatcher.withDefaults().matcher(path); } } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\CloudFoundryActuatorAutoConfiguration.java
2
请完成以下Java代码
public ShortCustomerInfo toShortCustomerInfo() { return new ShortCustomerInfo(id, title, isPublic()); } @Override @JsonProperty(access = Access.READ_ONLY) @Schema(description = "Name of the customer. Read-only, duplicated from title for backward compatibility", example = "Company A", accessMode = Schema.AccessMode.READ_ONLY) public String getName() { return title; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [title="); builder.append(title); builder.append(", tenantId="); builder.append(tenantId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", country="); builder.append(country); builder.append(", state="); builder.append(state); builder.append(", city="); builder.append(city);
builder.append(", address="); builder.append(address); builder.append(", address2="); builder.append(address2); builder.append(", zip="); builder.append(zip); builder.append(", phone="); builder.append(phone); builder.append(", email="); builder.append(email); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Customer.java
1
请完成以下Java代码
public static boolean isPalindromeRecursive(int number) { return isPalindromeHelper(number, 0) == number; } private static int isPalindromeHelper(int number, int reversedNumber) { if (number == 0) { return reversedNumber; } reversedNumber = reversedNumber * 10 + number % 10; return isPalindromeHelper(number / 10, reversedNumber); } public static boolean isPalindromeHalfReversal(int number) { if (number < 0 || (number % 10 == 0 && number != 0)) { return false; } int reversedNumber = 0; while (number > reversedNumber) { reversedNumber = reversedNumber * 10 + number % 10; number /= 10; } return number == reversedNumber || number == reversedNumber / 10; } public static boolean isPalindromeDigitByDigit(int number) { if (number < 0) {
return false; } int divisor = 1; while (number / divisor >= 10) { divisor *= 10; } while (number != 0) { int leading = number / divisor; int trailing = number % 10; if (leading != trailing) { return false; } number = (number % divisor) / 10; divisor /= 100; } return true; } }
repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\palindrome\PalindromeNumber.java
1
请完成以下Java代码
public ProcessInstanceStartEventSubscriptionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) { correlationParameterValues.put(parameterName, parameterValue); return this; } @Override public ProcessInstanceStartEventSubscriptionBuilder addCorrelationParameterValues(Map<String, Object> parameters) { correlationParameterValues.putAll(parameters); return this; } @Override public ProcessInstanceStartEventSubscriptionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } public String getProcessDefinitionKey() { return processDefinitionKey; } public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } public boolean isDoNotUpdateToLatestVersionAutomatically() { return doNotUpdateToLatestVersionAutomatically; }
public String getTenantId() { return tenantId; } @Override public EventSubscription subscribe() { checkValidInformation(); return runtimeService.registerProcessInstanceStartEventSubscription(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(processDefinitionKey)) { throw new FlowableIllegalArgumentException("The process definition must be provided using the key for the subscription to be registered."); } if (correlationParameterValues.isEmpty()) { throw new FlowableIllegalArgumentException( "At least one correlation parameter value must be provided for a dynamic process start event subscription, " + "otherwise the process would get started on all events, regardless their correlation parameter values."); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionBuilderImpl.java
1
请完成以下Java代码
public static class UiTheme { private Boolean backgroundEnabled = true; private Palette palette = new Palette(); private String color = "#14615A"; } /** * Color shades are based on Tailwind's color palettes: * <a href="https://tailwindcss.com/docs/customizing-colors">tailwindcss.com</a> * <p> * name shade number mainColorLighter 50 mainColorLight 300 mainColor 500 * mainColorDark 700 mainColorDarker 800 */ @Getter public static class Palette { private String shade50 = "#EEFCFA"; private String shade100 = "#D9F7F4"; private String shade200 = "#B7F0EA"; private String shade300 = "#91E8E0"; private String shade400 = "#6BE0D5"; private String shade500 = "#47D9CB"; private String shade600 = "#27BEAF"; private String shade700 = "#1E9084"; private String shade800 = "#14615A"; private String shade900 = "#0A2F2B"; public void set50(String shade50) { this.shade50 = shade50; } public void set100(String shade100) { this.shade100 = shade100; } public void set200(String shade200) { this.shade200 = shade200; } public void set300(String shade300) {
this.shade300 = shade300; } public void set400(String shade400) { this.shade400 = shade400; } public void set500(String shade500) { this.shade500 = shade500; } public void set600(String shade600) { this.shade600 = shade600; } public void set700(String shade700) { this.shade700 = shade700; } public void set800(String shade800) { this.shade800 = shade800; } public void set900(String shade900) { this.shade900 = shade900; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiProperties.java
1
请在Spring Boot框架中完成以下Java代码
private ResponseEntity<ByteArrayResource> downloadResourceIfChanged(ThrowingSupplier<TbResourceInfo> resourceInfoProvider, String etag) throws ThingsboardException { TbResourceInfo resourceInfo = resourceInfoProvider.get(); if (etag != null) { etag = StringUtils.remove(etag, '\"'); // etag is wrapped in double quotes due to HTTP specification if (etag.equals(resourceInfo.getEtag())) { return ResponseEntity.status(HttpStatus.NOT_MODIFIED) .eTag(resourceInfo.getEtag()) .build(); } } byte[] data = resourceService.getResourceData(resourceInfo.getTenantId(), resourceInfo.getId()); ByteArrayResource resource = new ByteArrayResource(data); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + resourceInfo.getFileName()) .header("x-filename", resourceInfo.getFileName()) .contentLength(resource.contentLength()) .header("Content-Type", resourceInfo.getResourceType().getMediaType()) .cacheControl(CacheControl.noCache())
.eTag(resourceInfo.getEtag()) .body(resource); } private TbResourceInfo checkResourceInfo(String scope, ResourceType resourceType, String key, Operation operation) throws ThingsboardException { TenantId tenantId; if (scope.equals("tenant")) { tenantId = getTenantId(); } else if (scope.equals("system")) { tenantId = TenantId.SYS_TENANT_ID; } else { throw new IllegalArgumentException("Invalid scope"); } TbResourceInfo resourceInfo = resourceService.findResourceInfoByTenantIdAndKey(tenantId, resourceType, key); checkEntity(getCurrentUser(), checkNotNull(resourceInfo), operation); return resourceInfo; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\TbResourceController.java
2
请完成以下Java代码
public Integer getPort() { return port; } public AppClusterServerStateWrapVO setPort(Integer port) { this.port = port; return this; } public Boolean getBelongToApp() { return belongToApp; } public AppClusterServerStateWrapVO setBelongToApp(Boolean belongToApp) { this.belongToApp = belongToApp; return this; } public Integer getConnectedCount() { return connectedCount; } public AppClusterServerStateWrapVO setConnectedCount(Integer connectedCount) { this.connectedCount = connectedCount; return this;
} public ClusterServerStateVO getState() { return state; } public AppClusterServerStateWrapVO setState(ClusterServerStateVO state) { this.state = state; return this; } @Override public String toString() { return "AppClusterServerStateWrapVO{" + "id='" + id + '\'' + ", ip='" + ip + '\'' + ", port='" + port + '\'' + ", belongToApp=" + belongToApp + ", state=" + state + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\AppClusterServerStateWrapVO.java
1
请完成以下Java代码
public class Person implements Serializable { private static final long serialVersionUID = 8510634155374943623L; /** * 主键 */ private Long id; /** * 名字 */ private String name; /** * 国家 */ private String country;
/** * 年龄 */ private Integer age; /** * 生日 */ private Date birthday; /** * 介绍 */ private String remark; }
repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\model\Person.java
1
请在Spring Boot框架中完成以下Java代码
public String getEntryCriterionId() { return entryCriterionId; } public void setEntryCriterionId(String entryCriterionId) { this.entryCriterionId = entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public String getExtraValue() { return extraValue; } public void setExtraValue(String extraValue) { this.extraValue = extraValue; } public boolean isShowInOverview() { return showInOverview; } public void setShowInOverview(boolean showInOverview) { this.showInOverview = showInOverview; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-planitem-instances/5") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } public String getDerivedCaseDefinitionUrl() { return derivedCaseDefinitionUrl; } public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) { this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl; } public String getStageInstanceUrl() { return stageInstanceUrl; } public void setStageInstanceUrl(String stageInstanceUrl) { this.stageInstanceUrl = stageInstanceUrl; } public void setLocalVariables(List<RestVariable> localVariables){ this.localVariables = localVariables; } public List<RestVariable> getLocalVariables() { return localVariables; } public void addLocalVariable(RestVariable restVariable) { localVariables.add(restVariable); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java
2
请完成以下Java代码
public boolean isOpen() { return !this.closed; } @Override public boolean isReadOnly() { return true; } @Override public String getSeparator() { return "/!"; } @Override public Iterable<Path> getRootDirectories() { assertNotClosed(); return Collections.emptySet(); } @Override public Iterable<FileStore> getFileStores() { assertNotClosed(); return Collections.emptySet(); } @Override public Set<String> supportedFileAttributeViews() { assertNotClosed(); return SUPPORTED_FILE_ATTRIBUTE_VIEWS; } @Override public Path getPath(String first, String... more) { assertNotClosed(); if (more.length != 0) { throw new IllegalArgumentException("Nested paths must contain a single element"); } return new NestedPath(this, first); } @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { throw new UnsupportedOperationException("Nested paths do not support path matchers"); }
@Override public UserPrincipalLookupService getUserPrincipalLookupService() { throw new UnsupportedOperationException("Nested paths do not have a user principal lookup service"); } @Override public WatchService newWatchService() throws IOException { throw new UnsupportedOperationException("Nested paths do not support the WatchService"); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } NestedFileSystem other = (NestedFileSystem) obj; return this.jarPath.equals(other.jarPath); } @Override public int hashCode() { return this.jarPath.hashCode(); } @Override public String toString() { return this.jarPath.toAbsolutePath().toString(); } private void assertNotClosed() { if (this.closed) { throw new ClosedFileSystemException(); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystem.java
1
请完成以下Java代码
public List<ProcessInfoParameter> createParameters() { // // Make sure all editor values are pushed back to model (GridFields) for (final VEditor editor : fieldEditorsAll) { final GridField gridField = editor.getField(); if (gridField == null) { // guard agaist null, shall not happen continue; } final Object value = editor.getValue(); model.setFieldValue(gridField, value); } // // Ask the model to create the parameters return model.createProcessInfoParameters(); }
/** * #782 Request focus on the first process parameter (if possible) */ public void focusFirstParameter() { if (fieldEditors.isEmpty()) { // there are no parameters in this process. Nothing to focus return; } for (final VEditor fieldEditor : fieldEditors) { final boolean focusGained = getComponent(fieldEditor).requestFocusInWindow(); if (focusGained) { return; } } } } // ProcessParameterPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessParametersPanel.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("sessionId", sessionId) .add("loggedIn", loggedIn) .add("locale", locale) .add("userPreferences", userPreference) .add("defaultUseHttpAcceptLanguage", defaultUseHttpAcceptLanguage) .toString(); } private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); UserSession.logger.trace("User session serialized: {}", this); } private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); UserSession.logger.trace("User session deserialized: {}", this); } Properties getCtx() { return ctx; } public ClientId getClientId() { return Env.getClientId(getCtx()); } public OrgId getOrgId() { return Env.getOrgId(getCtx()); } public String getOrgName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Org_Name); } public UserId getLoggedUserId() { return Env.getLoggedUserId(getCtx()); } public Optional<UserId> getLoggedUserIdIfExists() { return Env.getLoggedUserIdIfExists(getCtx()); } public RoleId getLoggedRoleId() { return Env.getLoggedRoleId(getCtx()); } public String getUserName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_User_Name); }
public String getRoleName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Role_Name); } String getAdLanguage() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Language); } Language getLanguage() { return Env.getLanguage(getCtx()); } /** * @return previous language */ String verifyLanguageAndSet(final Language lang) { final Properties ctx = getCtx(); final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language); // // Check the language (and update it if needed) final Language validLang = Env.verifyLanguageFallbackToBase(lang); // // Actual update final String adLanguageNew = validLang.getAD_Language(); Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew); this.locale = validLang.getLocale(); UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang); return adLanguageOld; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\InternalUserSessionData.java
1
请完成以下Java代码
public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public boolean isCreationLog() { return state == JobState.CREATED.getStateCode(); } public boolean isFailureLog() { return state == JobState.FAILED.getStateCode(); } public boolean isSuccessLog() { return state == JobState.SUCCESSFUL.getStateCode(); } public boolean isDeletionLog() { return state == JobState.DELETED.getStateCode(); } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId;
} public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricJobLogEvent.java
1
请完成以下Java代码
private void updateFlatrateTermProductAndPrice() { final I_C_Flatrate_Term term = flatrateBL.getById(retrieveSelectedFlatrateTermId()); C_Flatrate_Term_Change_ProcessHelper.throwExceptionIfTermHasInvoices(term); updateFlatrateTermProductAndPrice(term); updateNextFlatrateTermProductAndPrice(term); } private void updateFlatrateTermProductAndPrice(@NonNull final I_C_Flatrate_Term term) { final LocalDate date = TimeUtil.asLocalDate(term.getStartDate(), orgDAO.getTimeZone(OrgId.ofRepoId(term.getAD_Org_ID()))); final FlatrateTermPriceRequest request = FlatrateTermPriceRequest.builder() .flatrateTerm(term) .productId(retrieveSelectedProductId()) .priceDate(date) .build(); flatrateBL.updateFlatrateTermProductAndPrice(request); }
private void updateNextFlatrateTermProductAndPrice(@NonNull final I_C_Flatrate_Term term) { final ImmutableList<I_C_Flatrate_Term> termstoUpdate = flatrateBL.retrieveNextFlatrateTerms(term); termstoUpdate.forEach(this::updateFlatrateTermProductAndPrice); } final FlatrateTermId retrieveSelectedFlatrateTermId() { return FlatrateTermId.ofRepoId(getRecord_ID()); } final ProductId retrieveSelectedProductId() { return ProductId.ofRepoId(p_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change_Product.java
1
请完成以下Java代码
public void setIsStaled (boolean IsStaled) { set_Value (COLUMNNAME_IsStaled, Boolean.valueOf(IsStaled)); } /** Get Staled. @return Staled */ public boolean isStaled () { Object oo = get_Value(COLUMNNAME_IsStaled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Gueltig. @param IsValid Element ist gueltig */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Gueltig. @return Element ist gueltig */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Refresh Date. @param LastRefreshDate Last Refresh Date */
public void setLastRefreshDate (Timestamp LastRefreshDate) { set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate); } /** Get Last Refresh Date. @return Last Refresh Date */ public Timestamp getLastRefreshDate () { return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate); } /** Set Staled Since. @param StaledSinceDate Staled Since */ public void setStaledSinceDate (Timestamp StaledSinceDate) { set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate); } /** Get Staled Since. @return Staled Since */ public Timestamp getStaledSinceDate () { return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java
1
请完成以下Java代码
public static String generateMissingAuthorizationsList(List<MissingAuthorization> missingAuthorizations) { StringBuilder sBuilder = new StringBuilder(); boolean first = true; for(MissingAuthorization missingAuthorization: missingAuthorizations) { if (!first) { sBuilder.append(" or "); } else { first = false; } sBuilder.append(generateMissingAuthorizationMessage(missingAuthorization)); } return sBuilder.toString(); } /** * Generated exception message for the missing authorization. * * @param exceptionInfo to use */
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) { StringBuilder builder = new StringBuilder(); String permissionName = exceptionInfo.getViolatedPermissionName(); String resourceType = exceptionInfo.getResourceType(); String resourceId = exceptionInfo.getResourceId(); builder.append("'"); builder.append(permissionName); builder.append("' permission on resource '"); builder.append((resourceId != null ? (resourceId+"' of type '") : "" )); builder.append(resourceType); builder.append("'"); return builder.toString(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\AuthorizationException.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; } public int getMaxSessions() { return this.maxSessions; } public void setMaxSessions(int maxSessions) { this.maxSessions = maxSessions; } public Cookie getCookie() { return this.cookie; } } } /** * Strategies for supporting forward headers. */ public enum ForwardHeadersStrategy { /** * Use the underlying container's native support for forwarded headers. */ NATIVE, /** * Use Spring's support for handling forwarded headers. */ FRAMEWORK,
/** * Ignore X-Forwarded-* headers. */ NONE } public static class Encoding { /** * Mapping of locale to charset for response encoding. */ private @Nullable Map<Locale, Charset> mapping; public @Nullable Map<Locale, Charset> getMapping() { return this.mapping; } public void setMapping(@Nullable Map<Locale, Charset> mapping) { this.mapping = mapping; } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class CustomerExtensionType { @XmlElement(name = "CustomerExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact") protected at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType customerExtension; @XmlElement(name = "ErpelCustomerExtension") protected CustomType erpelCustomerExtension; /** * Gets the value of the customerExtension property. * * @return * possible object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType } * */ public at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType getCustomerExtension() { return customerExtension; } /** * Sets the value of the customerExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType } * */ public void setCustomerExtension(at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType value) { this.customerExtension = value;
} /** * Gets the value of the erpelCustomerExtension property. * * @return * possible object is * {@link CustomType } * */ public CustomType getErpelCustomerExtension() { return erpelCustomerExtension; } /** * Sets the value of the erpelCustomerExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelCustomerExtension(CustomType value) { this.erpelCustomerExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\CustomerExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
public float getSum(float number1, float number2) { return arithmeticService.add(number1, number2); } @Get("/subtract/{number1}/{number2}") public float getDifference(float number1, float number2) { return arithmeticService.subtract(number1, number2); } @Get("/multiply/{number1}/{number2}") public float getMultiplication(float number1, float number2) { return arithmeticService.multiply(number1, number2); } @Get("/divide/{number1}/{number2}") public float getDivision(float number1, float number2) { return arithmeticService.divide(number1, number2); } @Get("/memory") public String getMemoryStatus() { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); String memoryStats = ""; String init = String.format("Initial: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getInit() / 1073741824); String usedHeap = String.format("Used: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() .getUsed() / 1073741824); String maxHeap = String.format("Max: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() .getMax() / 1073741824); String committed = String.format("Committed: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() .getCommitted() / 1073741824); memoryStats += init; memoryStats += usedHeap; memoryStats += maxHeap; memoryStats += committed; return memoryStats; } }
repos\tutorials-master\microservices-modules\micronaut\src\main\java\com\baeldung\micronaut\vs\springboot\controller\ArithmeticController.java
2