instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public MProduct getProduct() { if (m_product == null) m_product = MProduct.get(getCtx(), getM_Product_ID()); return m_product; } // getProduct /** * Get Product Standard Precision * @return standard precision */ public int getUOMPrecision() { return getProduct().getUOMPrecision(); } // getUOMPrecision /************************************************************************** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MDistributionRunLine[") .append(get_ID()).append("-") .append(getInfo()) .append ("]"); return sb.toString (); } // toString /**
* Get Info * @return info */ public String getInfo() { StringBuffer sb = new StringBuffer (); sb.append("Line=").append(getLine()) .append (",TotalQty=").append(getTotalQty()) .append(",SumMin=").append(getActualMin()) .append(",SumQty=").append(getActualQty()) .append(",SumAllocation=").append(getActualAllocation()) .append(",MaxAllocation=").append(getMaxAllocation()) .append(",LastDiff=").append(getLastDifference()); return sb.toString (); } // getInfo } // MDistributionRunLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDistributionRunLine.java
1
请完成以下Java代码
public String getType() { return Batch.TYPE_HISTORIC_PROCESS_INSTANCE_DELETION; } protected DeleteHistoricProcessInstanceBatchConfigurationJsonConverter getJsonConverterInstance() { return DeleteHistoricProcessInstanceBatchConfigurationJsonConverter.INSTANCE; } @Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected BatchConfiguration createJobConfiguration(BatchConfiguration configuration, List<String> processIdsForJob) {
return new BatchConfiguration(processIdsForJob, configuration.isFailIfNotExists()); } @Override public void executeHandler(BatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { commandContext.executeWithOperationLogPrevented( new DeleteHistoricProcessInstancesCmd( batchConfiguration.getIds(), batchConfiguration.isFailIfNotExists())); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\deletion\DeleteHistoricProcessInstancesJobHandler.java
1
请完成以下Java代码
public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** * Type AD_Reference_ID=540987 * Reference name: AD_Role_Record_Access_Config_Type */ public static final int TYPE_AD_Reference_ID=540987; /** Table = T */
public static final String TYPE_Table = "T"; /** Business Partner Hierarchy = BPH */ public static final String TYPE_BusinessPartnerHierarchy = "BPH"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Record_Access_Config.java
1
请在Spring Boot框架中完成以下Java代码
public <T extends MobileApplication> Stream<T> streamMobileApplicationsOfType( @NonNull final Class<T> type, @NonNull final UserId userId, @NonNull final MobileApplicationPermissions permissions) { return streamMobileApplicationInfos(userId, permissions) .map(applicationInfo -> { final MobileApplication application = applications.getById(applicationInfo.getId()); return type.isInstance(application) ? type.cast(application) : null; }) .filter(Objects::nonNull); } public MobileApplication getById(@NonNull final MobileApplicationId id) { return applications.getById(id); } public void logout(@NonNull final IUserRolePermissions permissions) { final UserId userId = permissions.getUserId(); final MobileApplicationPermissions mobileApplicationPermissions = permissions.getMobileApplicationPermissions(); applications.stream() .filter(application -> hasAccess(application.getApplicationId(), mobileApplicationPermissions)) .forEach(application -> { try { application.logout(userId); } catch (Exception ex) { logger.warn("Application {} failed to logout. Skipped", application, ex); } }); }
private boolean hasAccess(@NonNull final MobileApplicationId applicationId, @NonNull final MobileApplicationPermissions permissions) { final MobileApplicationRepoId repoId = applicationInfoRepository.getById(applicationId).getRepoId(); return permissions.isAllowAccess(repoId); } private boolean hasActionAccess(@NonNull final MobileApplicationId applicationId, @NonNull String actionInternalName, final MobileApplicationPermissions permissions) { final MobileApplicationInfo applicationInfo = applicationInfoRepository.getById(applicationId); final MobileApplicationActionId actionId = applicationInfo.getActionIdByInternalName(actionInternalName).orElse(null); if (actionId == null) { return false; } return permissions.isAllowAction(applicationInfo.getRepoId(), actionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\application\service\MobileApplicationService.java
2
请完成以下Java代码
public T orElseThrow() { return orElseThrow(AdempiereException::new); } public T orElseThrow(@NonNull final AdMessageKey adMessageKey) { return orElseThrow(message -> new AdempiereException(adMessageKey).setParameter("detail", message)); } public T orElseThrow(@NonNull final Function<ITranslatableString, RuntimeException> exceptionFactory) { if (value != null) { return value; } else { throw exceptionFactory.apply(explanation); } } public T get() { return orElseThrow(); } public boolean isPresent() { return value != null; } public <U> ExplainedOptional<U> map(@NonNull final Function<? super T, ? extends U> mapper) { if (!isPresent()) { return emptyBecause(explanation); } else { final U newValue = mapper.apply(value); if (newValue == null) { return emptyBecause(explanation); } else { return of(newValue); } } } public ExplainedOptional<T> ifPresent(@NonNull final Consumer<T> consumer) { if (isPresent()) { consumer.accept(value); } return this; } @SuppressWarnings("UnusedReturnValue") public ExplainedOptional<T> ifAbsent(@NonNull final Consumer<ITranslatableString> consumer)
{ if (!isPresent()) { consumer.accept(explanation); } return this; } /** * @see #resolve(Function, Function) */ public <R> Optional<R> mapIfAbsent(@NonNull final Function<ITranslatableString, R> mapper) { return isPresent() ? Optional.empty() : Optional.ofNullable(mapper.apply(getExplanation())); } /** * @see #mapIfAbsent(Function) */ public <R> R resolve( @NonNull final Function<T, R> mapPresent, @NonNull final Function<ITranslatableString, R> mapAbsent) { return isPresent() ? mapPresent.apply(value) : mapAbsent.apply(explanation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ExplainedOptional.java
1
请完成以下Java代码
public void JsonLib() { for (int i = 0; i < count; i++) { JsonLibUtil.json2Bean(jsonStr, Person.class); } } @Benchmark public void Gson() { for (int i = 0; i < count; i++) { GsonUtil.json2Bean(jsonStr, Person.class); } } @Benchmark public void FastJson() { for (int i = 0; i < count; i++) { FastJsonUtil.json2Bean(jsonStr, Person.class); }
} @Benchmark public void Jackson() { for (int i = 0; i < count; i++) { JacksonUtil.json2Bean(jsonStr, Person.class); } } @Setup public void prepare() { jsonStr="{\"name\":\"邵同学\",\"fullName\":{\"firstName\":\"zjj_first\",\"middleName\":\"zjj_middle\",\"lastName\":\"zjj_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":[{\"name\":\"小明\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"Tony\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"陈小二\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"篮球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null}]}"; } @TearDown public void shutdown() { } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\JsonDeserializeBenchmark.java
1
请完成以下Java代码
public TechnicalInputChannel1Choice createTechnicalInputChannel1Choice() { return new TechnicalInputChannel1Choice(); } /** * Create an instance of {@link TotalTransactions2 } * */ public TotalTransactions2 createTotalTransactions2() { return new TotalTransactions2(); } /** * Create an instance of {@link TotalsPerBankTransactionCode2 } * */ public TotalsPerBankTransactionCode2 createTotalsPerBankTransactionCode2() { return new TotalsPerBankTransactionCode2(); } /** * Create an instance of {@link TransactionAgents2 } * */ public TransactionAgents2 createTransactionAgents2() { return new TransactionAgents2(); } /** * Create an instance of {@link TransactionDates2 } * */ public TransactionDates2 createTransactionDates2() { return new TransactionDates2(); } /** * Create an instance of {@link TransactionInterest2 } * */ public TransactionInterest2 createTransactionInterest2() { return new TransactionInterest2(); } /** * Create an instance of {@link TransactionParty2 } * */ public TransactionParty2 createTransactionParty2() { return new TransactionParty2(); } /** * Create an instance of {@link TransactionPrice2Choice } * */ public TransactionPrice2Choice createTransactionPrice2Choice() { return new TransactionPrice2Choice(); }
/** * Create an instance of {@link TransactionQuantities1Choice } * */ public TransactionQuantities1Choice createTransactionQuantities1Choice() { return new TransactionQuantities1Choice(); } /** * Create an instance of {@link TransactionReferences2 } * */ public TransactionReferences2 createTransactionReferences2() { return new TransactionReferences2(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.02", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ObjectFactory.java
1
请完成以下Java代码
public ExplainedOptional<ParsedScannedCode> parse(@NonNull final ScannedCode scannedCode) { if (formats.isEmpty()) { return ExplainedOptional.emptyBecause("No formats configured"); } final TranslatableStringBuilder notMatchingExplanation = TranslatableStrings.builder(); for (final ScannableCodeFormat format : formats) { final ExplainedOptional<ParsedScannedCode> result = format.parse(scannedCode); if (result.isPresent()) { return result; }
if (!notMatchingExplanation.isEmpty()) { notMatchingExplanation.append(" | "); } notMatchingExplanation.append(format.getName()).append(" ").append(result.getExplanation()); } return ExplainedOptional.emptyBecause(notMatchingExplanation.build()); } public boolean isEmpty() {return formats.isEmpty();} public ImmutableList<ScannableCodeFormat> toList() {return formats;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\ScannableCodeFormatsCollection.java
1
请完成以下Java代码
public java.lang.String getReceivedInfo() { return get_ValueAsString(COLUMNNAME_ReceivedInfo); } @Override public void setShipDate (final @Nullable java.sql.Timestamp ShipDate) { set_Value (COLUMNNAME_ShipDate, ShipDate); } @Override public java.sql.Timestamp getShipDate() { return get_ValueAsTimestamp(COLUMNNAME_ShipDate); } @Override public void setTrackingInfo (final @Nullable java.lang.String TrackingInfo) { set_Value (COLUMNNAME_TrackingInfo, TrackingInfo); } @Override public java.lang.String getTrackingInfo() { return get_ValueAsString(COLUMNNAME_TrackingInfo); }
@Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Package.java
1
请完成以下Java代码
protected void onExpiration(Session s, ExpiredSessionException ese, SessionKey key) { super.onExpiration(s, ese, key); onInvalidation(key); } @Override protected void onInvalidation(Session session, InvalidSessionException ise, SessionKey key) { super.onInvalidation(session, ise, key); onInvalidation(key); } private void onInvalidation(SessionKey key) { ServletRequest request = WebUtils.getRequest(key); if (request != null) { request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID); } if (WebUtils.isHttp(key)) { log.debug("Referenced session was invalid. Removing session ID cookie."); removeSessionIdCookie(WebUtils.getHttpRequest(key), WebUtils.getHttpResponse(key)); } else { log.debug("SessionKey argument is not HTTP compatible or does not have an HTTP request/response " + "pair. Session ID cookie will not be removed due to invalidated session."); } } /**
* 会话销毁 * * @param session Session * @param key SessionKey */ @Override protected void onStop(Session session, SessionKey key) { super.onStop(session, key); if (WebUtils.isHttp(key)) { HttpServletRequest request = WebUtils.getHttpRequest(key); HttpServletResponse response = WebUtils.getHttpResponse(key); log.debug("Session has been stopped (subject logout or explicit stop). Removing session ID cookie."); removeSessionIdCookie(request, response); } else { log.debug("SessionKey argument is not HTTP compatible or does not have an HTTP request/response " + "pair. Session ID cookie will not be removed due to stopped session."); } } }
repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\shiro\CustomSessionManager.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=12345678 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop spring.redis.host=localhost spring.redis.port=6379 spring.redis.lettuce.poo
l.max-idle=8 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1ms spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.shutdown-timeout=100ms
repos\SpringBoot-Learning-master\2.x\chapter5-4\src\main\resources\application.properties
2
请完成以下Java代码
public void setPath (final @Nullable java.lang.String Path) { set_Value (COLUMNNAME_Path, Path); } @Override public java.lang.String getPath() { return get_ValueAsString(COLUMNNAME_Path); } @Override public void setRemoteAddr (final @Nullable java.lang.String RemoteAddr) { set_Value (COLUMNNAME_RemoteAddr, RemoteAddr); } @Override public java.lang.String getRemoteAddr() { return get_ValueAsString(COLUMNNAME_RemoteAddr); } @Override public void setRemoteHost (final @Nullable java.lang.String RemoteHost) { set_Value (COLUMNNAME_RemoteHost, RemoteHost); } @Override public java.lang.String getRemoteHost() { return get_ValueAsString(COLUMNNAME_RemoteHost); } @Override public void setRequestURI (final @Nullable java.lang.String RequestURI) { set_Value (COLUMNNAME_RequestURI, RequestURI); } @Override public java.lang.String getRequestURI() { return get_ValueAsString(COLUMNNAME_RequestURI); } /** * Status AD_Reference_ID=541316 * Reference name: StatusList */ public static final int STATUS_AD_Reference_ID=541316; /** Empfangen = Empfangen */ public static final String STATUS_Empfangen = "Empfangen";
/** Verarbeitet = Verarbeitet */ public static final String STATUS_Verarbeitet = "Verarbeitet"; /** Fehler = Fehler */ public static final String STATUS_Fehler = "Fehler"; @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); } @Override public void setTime (final java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } @Override public void setUI_Trace_ExternalId (final @Nullable java.lang.String UI_Trace_ExternalId) { set_Value (COLUMNNAME_UI_Trace_ExternalId, UI_Trace_ExternalId); } @Override public java.lang.String getUI_Trace_ExternalId() { return get_ValueAsString(COLUMNNAME_UI_Trace_ExternalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit.java
1
请完成以下Java代码
public class SetUserPictureCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String userId; protected Picture picture; public SetUserPictureCmd(String userId, Picture picture) { this.userId = userId; this.picture = picture; } @Override public Object execute(CommandContext commandContext) { if (userId == null) { throw new FlowableIllegalArgumentException("userId is null");
} User user = CommandContextUtil.getIdmEngineConfiguration().getIdmIdentityService() .createUserQuery().userId(userId) .singleResult(); if (user == null) { throw new FlowableObjectNotFoundException("user " + userId + " doesn't exist", User.class); } CommandContextUtil.getUserEntityManager(commandContext).setUserPicture(user, picture); return null; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\cmd\SetUserPictureCmd.java
1
请完成以下Java代码
public class CompositeFacetsPoolListener implements IFacetsPoolListener { private final CopyOnWriteArrayList<IFacetsPoolListener> listeners = new CopyOnWriteArrayList<>(); public void addListener(final IFacetsPoolListener listener) { Check.assumeNotNull(listener, "listener not null"); listeners.addIfAbsent(listener); } public void removeListener(final IFacetsPoolListener listener) { listeners.remove(listener); } @Override public void onFacetsInit() {
for (final IFacetsPoolListener listener : listeners) { listener.onFacetsInit(); } } @Override public void onFacetExecute(final IFacet<?> facet) { for (final IFacetsPoolListener listener : listeners) { listener.onFacetExecute(facet); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\CompositeFacetsPoolListener.java
1
请完成以下Java代码
private Optional<ProductPrice> getManualPrice(@NonNull final I_C_OrderLine orderLine) { if (!orderLine.isManualPrice() || orderLine.getPrice_UOM_ID() <= 0) { logger.trace("Missing manual product price information on C_OrderLine: {}!", orderLine.getC_OrderLine_ID()); return Optional.empty(); } final ProductPrice productPrice = ProductPrice.builder() .productId(ProductId.ofRepoId(orderLine.getM_Product_ID())) .uomId(UomId.ofRepoId(orderLine.getPrice_UOM_ID())) .money(Money.of(orderLine.getPriceEntered(), CurrencyId.ofRepoId(orderLine.getC_Currency_ID()))) .build(); return Optional.of(productPrice); } @NonNull private Optional<ProductPrice> getManualPrice(@NonNull final I_C_InvoiceLine invoiceLine) { if (!invoiceLine.isManualPrice() || invoiceLine.getPrice_UOM_ID() <= 0 || invoiceLine.getM_Product_ID() <= 0) { logger.trace("Missing manual product price information on C_InvoiceLine: {}!", invoiceLine.getC_InvoiceLine_ID()); return Optional.empty(); } final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID())); final ProductPrice productPrice = ProductPrice.builder() .productId(ProductId.ofRepoId(invoiceLine.getM_Product_ID())) .uomId(UomId.ofRepoId(invoiceLine.getPrice_UOM_ID()))
.money(Money.of(invoiceLine.getPriceEntered(), CurrencyId.ofRepoId(invoice.getC_Currency_ID()))) .build(); return Optional.of(productPrice); } @NonNull private Optional<ProductPrice> getManualPrice(@NonNull final IPricingContext pricingContext) { if (pricingContext.getManualPriceEnabled() == null || !pricingContext.getManualPriceEnabled().isTrue() || pricingContext.getUomId() == null || pricingContext.getProductId() == null || pricingContext.getCurrencyId() == null || pricingContext.getManualPrice() == null) { logger.trace("Missing manual product price information on PricingContext: {}", pricingContext); return Optional.empty(); } final ProductPrice productPrice = ProductPrice.builder() .productId(pricingContext.getProductId()) .uomId(pricingContext.getUomId()) .money(Money.of(pricingContext.getManualPrice(), pricingContext.getCurrencyId())) .build(); return Optional.of(productPrice); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\pricing\rules\ManualPricePricingRule.java
1
请完成以下Java代码
public boolean isReady() { return true; } }; } public ServletInputStream getInputStream() { ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes()); return new ServletInputStream() { @Override public int read() throws IOException { return body.read(); } @Override public void setReadListener(ReadListener listener) {
} @Override public boolean isReady() { return true; } @Override public boolean isFinished() { return body.available() <= 0; } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
1
请完成以下Java代码
public class BasicTokenizer { /** * 预置分词器 */ public static final Segment SEGMENT = HanLP.newSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false); /** * 分词 * @param text 文本 * @return 分词结果 */ public static List<Term> segment(String text) { return SEGMENT.seg(text.toCharArray()); } /** * 分词 * @param text 文本 * @return 分词结果 */ public static List<Term> segment(char[] text) { return SEGMENT.seg(text); }
/** * 切分为句子形式 * @param text 文本 * @return 句子列表 */ public static List<List<Term>> seg2sentence(String text) { return SEGMENT.seg2sentence(text); } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) { return SEGMENT.seg2sentence(text, shortest); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\BasicTokenizer.java
1
请在Spring Boot框架中完成以下Java代码
public class ClientConfiguration { @Bean public Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } @Bean public OkHttpClient client() { return new OkHttpClient(); }
@Bean public RequestInterceptor requestInterceptor() { return requestTemplate -> { requestTemplate.header("user", "ajeje"); requestTemplate.header("password", "brazof"); requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType()); }; } // @Bean - uncomment to use this interceptor and remove @Bean from the requestInterceptor() public BasicAuthRequestInterceptor basicAuthRequestInterceptor() { return new BasicAuthRequestInterceptor("ajeje", "brazof"); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign\src\main\java\com\baeldung\cloud\openfeign\config\ClientConfiguration.java
2
请完成以下Java代码
public String getGroupIdAttribute() { return groupIdAttribute; } public void setGroupIdAttribute(String groupIdAttribute) { this.groupIdAttribute = groupIdAttribute; } public String getGroupMemberAttribute() { return groupMemberAttribute; } public void setGroupMemberAttribute(String groupMemberAttribute) { this.groupMemberAttribute = groupMemberAttribute; } public boolean isUseSsl() { return useSsl; } public void setUseSsl(boolean useSsl) { this.useSsl = useSsl; } public boolean isUsePosixGroups() { return usePosixGroups; } public void setUsePosixGroups(boolean usePosixGroups) { this.usePosixGroups = usePosixGroups; } public SearchControls getSearchControls() { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setTimeLimit(30000); return searchControls; } public String getGroupTypeAttribute() { return groupTypeAttribute;
} public void setGroupTypeAttribute(String groupTypeAttribute) { this.groupTypeAttribute = groupTypeAttribute; } public boolean isAllowAnonymousLogin() { return allowAnonymousLogin; } public void setAllowAnonymousLogin(boolean allowAnonymousLogin) { this.allowAnonymousLogin = allowAnonymousLogin; } public boolean isAuthorizationCheckEnabled() { return authorizationCheckEnabled; } public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) { this.authorizationCheckEnabled = authorizationCheckEnabled; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public boolean isPasswordCheckCatchAuthenticationException() { return passwordCheckCatchAuthenticationException; } public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) { this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java
1
请完成以下Java代码
public de.metas.async.model.I_C_Queue_PackageProcessor getC_Queue_PackageProcessor() { return get_ValueAsPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class); } @Override public void setC_Queue_PackageProcessor(de.metas.async.model.I_C_Queue_PackageProcessor C_Queue_PackageProcessor) { set_ValueFromPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class, C_Queue_PackageProcessor); } /** Set WorkPackage Processor. @param C_Queue_PackageProcessor_ID WorkPackage Processor */ @Override public void setC_Queue_PackageProcessor_ID (int C_Queue_PackageProcessor_ID) { if (C_Queue_PackageProcessor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, Integer.valueOf(C_Queue_PackageProcessor_ID)); } /** Get WorkPackage Processor. @return WorkPackage Processor */ @Override public int getC_Queue_PackageProcessor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_PackageProcessor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Assigned Workpackage Processors. @param C_Queue_Processor_Assign_ID Assigned Workpackage Processors */ @Override public void setC_Queue_Processor_Assign_ID (int C_Queue_Processor_Assign_ID) { if (C_Queue_Processor_Assign_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_Assign_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_Assign_ID, Integer.valueOf(C_Queue_Processor_Assign_ID)); } /** Get Assigned Workpackage Processors. @return Assigned Workpackage Processors */ @Override public int getC_Queue_Processor_Assign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_Assign_ID); if (ii == null)
return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_Processor getC_Queue_Processor() { return get_ValueAsPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class); } @Override public void setC_Queue_Processor(de.metas.async.model.I_C_Queue_Processor C_Queue_Processor) { set_ValueFromPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class, C_Queue_Processor); } /** Set Queue Processor Definition. @param C_Queue_Processor_ID Queue Processor Definition */ @Override public void setC_Queue_Processor_ID (int C_Queue_Processor_ID) { if (C_Queue_Processor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, Integer.valueOf(C_Queue_Processor_ID)); } /** Get Queue Processor Definition. @return Queue Processor Definition */ @Override public int getC_Queue_Processor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor_Assign.java
1
请完成以下Java代码
public class ServiceLevel8Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; }
/** * Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ServiceLevel8Choice.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) {
return false; } BPMNElementImpl that = (BPMNElementImpl) o; return ( Objects.equals(processInstanceId, that.processInstanceId) && Objects.equals(processDefinitionId, that.processDefinitionId) && Objects.equals(elementId, that.elementId) ); } @Override public int hashCode() { return Objects.hash(elementId, processInstanceId, processDefinitionId); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNElementImpl.java
1
请完成以下Java代码
public static final boolean le(TypeConverter converter, Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return !gt0(converter, o1, o2); } public static final boolean eq(TypeConverter converter, Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } Class<?> t1 = o1.getClass(); Class<?> t2 = o2.getClass(); if (BigDecimal.class.isAssignableFrom(t1) || BigDecimal.class.isAssignableFrom(t2)) { return (converter.convert(o1, BigDecimal.class).compareTo(converter.convert(o2, BigDecimal.class)) == 0); } if (SIMPLE_FLOAT_TYPES.contains(t1) || SIMPLE_FLOAT_TYPES.contains(t2)) { return converter.convert(o1, Double.class).equals(converter.convert(o2, Double.class)); } if (BigInteger.class.isAssignableFrom(t1) || BigInteger.class.isAssignableFrom(t2)) { return (converter.convert(o1, BigInteger.class).compareTo(converter.convert(o2, BigInteger.class)) == 0); } if (SIMPLE_INTEGER_TYPES.contains(t1) || SIMPLE_INTEGER_TYPES.contains(t2)) { return converter.convert(o1, Long.class).equals(converter.convert(o2, Long.class)); } if (t1 == Boolean.class || t2 == Boolean.class) { return converter.convert(o1, Boolean.class).equals(converter.convert(o2, Boolean.class)); } if (o1 instanceof Enum<?>) { return o1 == converter.convert(o2, o1.getClass()); } if (o2 instanceof Enum<?>) { return converter.convert(o1, o2.getClass()) == o2; } if (t1 == String.class || t2 == String.class) { return converter.convert(o1, String.class).equals(converter.convert(o2, String.class)); } return o1.equals(o2); }
public static final boolean ne(TypeConverter converter, Object o1, Object o2) { return !eq(converter, o1, o2); } public static final boolean empty(TypeConverter converter, Object o) { if (o == null || "".equals(o)) { return true; } if (o instanceof Object[]) { return ((Object[]) o).length == 0; } if (o instanceof Map<?, ?>) { return ((Map<?, ?>) o).isEmpty(); } if (o instanceof Collection<?>) { return ((Collection<?>) o).isEmpty(); } return false; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\misc\BooleanOperations.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_M_FreightCostShipper[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } public I_M_FreightCost getM_FreightCost() throws RuntimeException { return (I_M_FreightCost)MTable.get(getCtx(), I_M_FreightCost.Table_Name) .getPO(getM_FreightCost_ID(), get_TrxName()); } /** Set Frachtkostenpauschale. @param M_FreightCost_ID Frachtkostenpauschale */ public void setM_FreightCost_ID (int M_FreightCost_ID) { if (M_FreightCost_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCost_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCost_ID, Integer.valueOf(M_FreightCost_ID)); } /** Get Frachtkostenpauschale. @return Frachtkostenpauschale */ public int getM_FreightCost_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCost_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lieferweg-Versandkosten. @param M_FreightCostShipper_ID Lieferweg-Versandkosten */ public void setM_FreightCostShipper_ID (int M_FreightCostShipper_ID) { if (M_FreightCostShipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, Integer.valueOf(M_FreightCostShipper_ID)); } /** Get Lieferweg-Versandkosten. @return Lieferweg-Versandkosten */ public int getM_FreightCostShipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCostShipper_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Shipper getM_Shipper() throws RuntimeException { return (I_M_Shipper)MTable.get(getCtx(), I_M_Shipper.Table_Name) .getPO(getM_Shipper_ID(), get_TrxName()); } /** Set Lieferweg.
@param M_Shipper_ID Methode oder Art der Warenlieferung */ public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gueltig ab. @param ValidFrom Gueltig ab inklusiv (erster Tag) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gueltig ab. @return Gueltig ab inklusiv (erster Tag) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostShipper.java
1
请完成以下Java代码
public void moveHU(@RequestBody @NonNull final JsonMoveHURequest request) { assertActionAccess(HUManagerAction.Move); handlingUnitsService.move(MoveHURequest.builder() .huId(request.getHuId()) .huQRCode(HUQRCode.fromNullable(request.getHuQRCode())) .numberOfTUs(request.getNumberOfTUs()) .targetQRCode(request.getTargetQRCode()) .build()); } @PostMapping("/bulk/move") public void bulkMove(@RequestBody @NonNull final JsonBulkMoveHURequest request) { assertActionAccess(HUManagerAction.BulkActions); handlingUnitsService.bulkMove( BulkMoveHURequest.builder() .huQrCodes(request.getHuQRCodes().stream() .map(HUQRCode::fromGlobalQRCodeJsonString) .collect(ImmutableList.toImmutableList())) .targetQRCode(ScannedCode.ofString(request.getTargetQRCode())) .build() ); }
@PostMapping("/huLabels/print") public JsonPrintHULabelResponse printHULabels(@RequestBody @NonNull final JsonPrintHULabelRequest request) { assertActionAccess(HUManagerAction.PrintLabels); try (final FrontendPrinter frontendPrinter = FrontendPrinter.start()) { handlingUnitsService.printHULabels(request); final FrontendPrinterData printData = frontendPrinter.getDataAndClear(); return JsonPrintHULabelResponse.builder() .printData(JsonPrintHULabelResponse.JsonPrintDataItem.of(printData)) .build(); } } @GetMapping("/huLabels/printingOptions") public List<JsonHULabelPrintingOption> getPrintingOptions() { final String adLanguage = Env.getADLanguageOrBaseLanguage(); return handlingUnitsService.getLabelPrintingOptions(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\mobileui\HUManagerRestController.java
1
请完成以下Java代码
public OptionalInt getMinPrecision(@NonNull DocumentFieldWidgetType widgetType) { switch (widgetType) { case Integer: return ZERO; case CostPrice: return costPricePrecision; case Amount: return amountPrecision; case Quantity: return quantityPrecision; default: return OptionalInt.empty(); } } public WidgetTypeStandardNumberPrecision fallbackTo(@NonNull WidgetTypeStandardNumberPrecision other) { return builder() .amountPrecision(firstPresent(this.amountPrecision, other.amountPrecision)) .costPricePrecision(firstPresent(this.costPricePrecision, other.costPricePrecision)) .quantityPrecision(firstPresent(this.quantityPrecision, other.quantityPrecision)) .build();
} private static OptionalInt firstPresent(final OptionalInt optionalInt1, final OptionalInt optionalInt2) { if (optionalInt1 != null && optionalInt1.isPresent()) { return optionalInt1; } else if (optionalInt2 != null && optionalInt2.isPresent()) { return optionalInt2; } else { return OptionalInt.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\WidgetTypeStandardNumberPrecision.java
1
请完成以下Java代码
public class Activiti { /** * This is the component that you'll use in your Spring Integration * {@link org.springframework.integration.dsl.IntegrationFlow}. */ public static ActivitiInboundGateway inboundGateway(ProcessEngine processEngine, String... varsToPreserve) { return new ActivitiInboundGateway(processEngine, varsToPreserve); } /** * This is the bean to expose and then reference * from your Activiti BPMN flow in an expression. */ public static IntegrationActivityBehavior inboundGatewayActivityBehavior(ActivitiInboundGateway gateway) { return new IntegrationActivityBehavior(gateway); } /** * Any message that enters this {@link org.springframework.messaging.MessageHandler} * containing a {@code executionId} parameter will trigger a
* {@link org.activiti.engine.RuntimeService#signalEventReceived(String)}. */ public static MessageHandler signallingMessageHandler(final ProcessEngine processEngine) { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { String executionId = message.getHeaders().containsKey("executionId") ? (String) message.getHeaders().get("executionId") : (String) null; if (null != executionId) processEngine.getRuntimeService().trigger(executionId); } }; } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\integration\Activiti.java
1
请完成以下Java代码
public Class<?> getCommonPropertyType(ELContext context, Object base) { return isResolvable(base) ? Integer.class : null; } /** * Test whether the given base should be resolved by this ELResolver. * * @param base * The bean to analyze. * @return base != null && base.getClass().isArray() */ private final boolean isResolvable(Object base) { return base != null && base.getClass().isArray(); } private static void checkBounds(Object base, int idx) { if (idx < 0 || idx >= Array.getLength(base)) { throw new PropertyNotFoundException(new ArrayIndexOutOfBoundsException(idx).getMessage()); } } private static int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); }
if (property instanceof Character) { return (Character) property; } if (property instanceof Boolean) { return (Boolean) property ? 1 : 0; } if (property instanceof String) { try { return Integer.parseInt((String) property); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse array index: " + property, e); } } throw new IllegalArgumentException("Cannot coerce property to array index: " + property); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ArrayELResolver.java
1
请完成以下Java代码
private static class QtyReportedAndQtyActual { final BigDecimal qtyReported; final BigDecimal qtyActual; public QtyReportedAndQtyActual(BigDecimal qtyReported, BigDecimal qtyActual) { this.qtyReported = qtyReported; this.qtyActual = qtyActual; } } @Override protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray())
{ final String name = para.getParameterName(); if (para.getParameter() == null) { ; } else if (name.equals(I_C_Period.COLUMNNAME_C_Period_ID)) { final int periodId = para.getParameterAsInt(); p_periodTo = InterfaceWrapperHelper.create(getCtx(), periodId, I_C_Period.class, get_TrxName()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Prepare_Closing.java
1
请完成以下Java代码
public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication; OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange() .getAuthorizationResponse(); if (authorizationResponse.statusError()) { throw new OAuth2AuthorizationException(authorizationResponse.getError()); } OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange() .getAuthorizationRequest(); if (!authorizationResponse.getState().equals(authorizationRequest.getState())) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE); throw new OAuth2AuthorizationException(oauth2Error); } OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse( new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange())); OAuth2AuthorizationCodeAuthenticationToken authenticationResult = new OAuth2AuthorizationCodeAuthenticationToken( authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken(), accessTokenResponse.getAdditionalParameters()); authenticationResult.setDetails(authorizationCodeAuthentication.getDetails()); return authenticationResult; } @Override public boolean supports(Class<?> authentication) { return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeAuthenticationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeploymentName() { return deploymentName; } public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } public String getResourceLocation() { return resourceLocation; } public void setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; } public List<String> getResourceSuffixes() { return resourceSuffixes; } public void setResourceSuffixes(List<String> resourceSuffixes) { this.resourceSuffixes = resourceSuffixes; } public boolean isDeployResources() { return deployResources; } public void setDeployResources(boolean deployResources) { this.deployResources = deployResources; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isHistoryEnabled() { return historyEnabled; } public void setHistoryEnabled(boolean historyEnabled) { this.historyEnabled = historyEnabled;
} public boolean isEnableSafeXml() { return enableSafeXml; } public void setEnableSafeXml(boolean enableSafeXml) { this.enableSafeXml = enableSafeXml; } public boolean isStrictMode() { return strictMode; } public void setStrictMode(boolean strictMode) { this.strictMode = strictMode; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\dmn\FlowableDmnProperties.java
2
请完成以下Java代码
public void setC_Region_ID (int C_Region_ID) { if (C_Region_ID < 1) set_Value (COLUMNNAME_C_Region_ID, null); else set_Value (COLUMNNAME_C_Region_ID, Integer.valueOf(C_Region_ID)); } /** Get Region. @return Identifies a geographical Region */ @Override public int getC_Region_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Coordinates. @param Coordinates Location coordinate */ @Override public void setCoordinates (java.lang.String Coordinates) { set_Value (COLUMNNAME_Coordinates, Coordinates); } /** Get Coordinates. @return Location coordinate */ @Override public java.lang.String getCoordinates () { return (java.lang.String)get_Value(COLUMNNAME_Coordinates); } /** Set Locode. @param Locode Location code - UN/LOCODE */ @Override public void setLocode (java.lang.String Locode) { set_Value (COLUMNNAME_Locode, Locode); } /** Get Locode. @return Location code - UN/LOCODE */ @Override public java.lang.String getLocode () { return (java.lang.String)get_Value(COLUMNNAME_Locode); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set PLZ. @param Postal Postal code */ @Override public void setPostal (java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } /** Get PLZ. @return Postal code */ @Override public java.lang.String getPostal () { return (java.lang.String)get_Value(COLUMNNAME_Postal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_City.java
1
请在Spring Boot框架中完成以下Java代码
public class ScanScaleDeviceActivityHandler implements WFActivityHandler, SetScannedBarcodeSupport { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("manufacturing.scanScaleDevice"); private final ManufacturingJobService manufacturingJobService; public ScanScaleDeviceActivityHandler( final @NonNull ManufacturingJobService manufacturingJobService) { this.manufacturingJobService = manufacturingJobService; } @Override public WFActivityType getHandledActivityType() {return HANDLED_ACTIVITY_TYPE;} @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return SetScannedBarcodeSupportHelper.uiComponent() .alwaysAvailableToUser(wfActivity.getAlwaysAvailableToUser()) .currentValue(getCurrentScaleDevice(wfProcess) .map(scaleDevice -> toJsonQRCode(scaleDevice, jsonOpts.getAdLanguage())) .orElse(null)) .validOptions(streamAvailableScaleDevices(wfProcess) .map(scaleDevice1 -> toJsonQRCode(scaleDevice1, jsonOpts.getAdLanguage())) .collect(ImmutableList.toImmutableList())) .build(); } private Optional<ScaleDevice> getCurrentScaleDevice(final @NonNull WFProcess wfProcess) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); return manufacturingJobService.getCurrentScaleDevice(job); } private Stream<ScaleDevice> streamAvailableScaleDevices(final @NonNull WFProcess wfProcess) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess);
return manufacturingJobService.streamAvailableScaleDevices(job); } private static JsonQRCode toJsonQRCode(final ScaleDevice scaleDevice, final String adLanguage) { final DeviceQRCode qrCode = DeviceQRCode.builder() .deviceId(scaleDevice.getDeviceId()) .caption(scaleDevice.getCaption().translate(adLanguage)) .build(); return JsonQRCode.builder() .qrCode(qrCode.toGlobalQRCodeJsonString()) .caption(qrCode.getCaption()) .build(); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return getCurrentScaleDevice(wfProcess).isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(final @NonNull SetScannedBarcodeRequest request) { final DeviceId newScaleDeviceId = DeviceQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode()).getDeviceId(); return ManufacturingMobileApplication.mapDocument( request.getWfProcess(), job -> manufacturingJobService.withCurrentScaleDevice(job, newScaleDeviceId) ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\scanScaleDevice\ScanScaleDeviceActivityHandler.java
2
请完成以下Java代码
public static <T> ReactiveAuthorizationManager<T> hasScope(String scope) { assertScope(scope); return AuthorityReactiveAuthorizationManager.hasAuthority("SCOPE_" + scope); } /** * Create a {@link ReactiveAuthorizationManager} that requires an * {@link Authentication} to have at least one authority among {@code SCOPE_scope1}, * {@code SCOPE_scope2}, ... {@code SCOPE_scopeN}. * * <p> * For example, if you call {@code hasAnyScope("read", "write")}, then this will * require that each authentication have at least a * {@link org.springframework.security.core.GrantedAuthority} whose value is either * {@code SCOPE_read} or {@code SCOPE_write}. * * <p> * This would equivalent to calling * {@code AuthorityReactiveAuthorizationManager#hasAnyAuthority("SCOPE_read", "SCOPE_write")}. * @param scopes the scope values to allow * @param <T> the secure object * @return an {@link ReactiveAuthorizationManager} that requires at least one * authority among {@code "SCOPE_scope1"}, {@code SCOPE_scope2}, ... * {@code SCOPE_scopeN}. */
public static <T> ReactiveAuthorizationManager<T> hasAnyScope(String... scopes) { String[] mappedScopes = new String[scopes.length]; for (int i = 0; i < scopes.length; i++) { assertScope(scopes[i]); mappedScopes[i] = "SCOPE_" + scopes[i]; } return AuthorityReactiveAuthorizationManager.hasAnyAuthority(mappedScopes); } private static void assertScope(String scope) { Assert.isTrue(!scope.startsWith("SCOPE_"), () -> scope + " should not start with SCOPE_ since SCOPE_" + " is automatically prepended when using hasScope and hasAnyScope. Consider using " + " AuthorityReactiveAuthorizationManager#hasAuthority or #hasAnyAuthority instead."); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\authorization\OAuth2ReactiveAuthorizationManagers.java
1
请完成以下Java代码
private Settings settings() { if (properties != null) { Settings.Builder builder = Settings.builder(); properties.forEach((key, value) -> { builder.put(key.toString(), value.toString()); }); return builder.build(); } return Settings.builder() .put("cluster.name", clusterName) .put("client.transport.sniff", clientTransportSniff) .put("client.transport.ignore_cluster_name", clientIgnoreClusterName) .put("client.transport.ping_timeout", clientPingTimeout) .put("client.transport.nodes_sampler_interval", clientNodesSamplerInterval) .build(); } public void setClusterNodes(String clusterNodes) { this.clusterNodes = ClusterNodes.of(clusterNodes); } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setClientTransportSniff(Boolean clientTransportSniff) { this.clientTransportSniff = clientTransportSniff; } public String getClientNodesSamplerInterval() { return clientNodesSamplerInterval;
} public void setClientNodesSamplerInterval(String clientNodesSamplerInterval) { this.clientNodesSamplerInterval = clientNodesSamplerInterval; } public String getClientPingTimeout() { return clientPingTimeout; } public void setClientPingTimeout(String clientPingTimeout) { this.clientPingTimeout = clientPingTimeout; } public Boolean getClientIgnoreClusterName() { return clientIgnoreClusterName; } public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) { this.clientIgnoreClusterName = clientIgnoreClusterName; } public void setProperties(Properties properties) { this.properties = properties; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-elasticsearch\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\spring\TracingTransportClientFactoryBean.java
1
请在Spring Boot框架中完成以下Java代码
public void setEstimatedEffortIfNotSet(@Nullable final BigDecimal estimatedEffort) { if (this.estimatedEffort == null || this.estimatedEffort.signum() == 0) { this.estimatedEffort = estimatedEffort; } } public void addAggregatedEffort(@Nullable final Effort effort) { this.aggregatedEffort = aggregatedEffort.addNullSafe(effort); } public void addIssueEffort(@Nullable final Effort effort) { this.issueEffort = issueEffort.addNullSafe(effort); } public void addInvoiceableChildEffort(@Nullable final Quantity augent)
{ this.invoicableChildEffort = Quantitys.addNullSafe( UOMConversionContext.of((ProductId)null), invoicableChildEffort, augent); } @Nullable public Instant getLatestActivity() { return Stream.of(latestActivityOnIssue, latestActivityOnSubIssues) .filter(Objects::nonNull) .max(Instant::compareTo) .orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\IssueEntity.java
2
请完成以下Java代码
private void readEscaped() throws IOException { this.character = this.reader.read(); int escapeIndex = ESCAPES[0].indexOf(this.character); if (escapeIndex != -1) { this.character = ESCAPES[1].charAt(escapeIndex); } else if (this.character == '\n') { this.columnNumber = -1; read(); } else if (this.character == 'u') { readUnicode(); } } private void readUnicode() throws IOException { this.character = 0; for (int i = 0; i < 4; i++) { int digit = this.reader.read(); if (digit >= '0' && digit <= '9') { this.character = (this.character << 4) + digit - '0'; } else if (digit >= 'a' && digit <= 'f') { this.character = (this.character << 4) + digit - 'a' + 10; } else if (digit >= 'A' && digit <= 'F') { this.character = (this.character << 4) + digit - 'A' + 10; } else { throw new IllegalStateException("Malformed \\uxxxx encoding."); } } } boolean isWhiteSpace() { return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f'); } boolean isEndOfFile() { return this.character == -1; } boolean isEndOfLine() { return this.character == -1 || (!this.escaped && this.character == '\n'); } boolean isListDelimiter() { return !this.escaped && this.character == ','; } boolean isPropertyDelimiter() { return !this.escaped && (this.character == '=' || this.character == ':');
} char getCharacter() { return (char) this.character; } Location getLocation() { return new Location(this.reader.getLineNumber(), this.columnNumber); } boolean isSameLastLineCommentPrefix() { return this.lastLineCommentPrefixCharacter == this.character; } boolean isCommentPrefixCharacter() { return this.character == '#' || this.character == '!'; } boolean isHyphenCharacter() { return this.character == '-'; } } /** * A single document within the properties file. */ static class Document { private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>(); void put(String key, OriginTrackedValue value) { if (!key.isEmpty()) { this.values.put(key, value); } } boolean isEmpty() { return this.values.isEmpty(); } Map<String, OriginTrackedValue> asMap() { return this.values; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
1
请完成以下Java代码
class WBWindow { /** * WBWindow * @param type * @param id */ public WBWindow (int type, int id) { Type = type; ID = id; } /** Type */ public int Type = 0; /** ID */ public int ID = 0; /** Window No */ public int WindowNo = -1; /** Window Model */ public GridWindow mWindow = null; // public MFrame mFrame = null; // public MProcess mProcess = null; } // WBWindow // metas: begin public GridWindow getMWindowById(AdWindowId adWindowId)
{ if (adWindowId == null) { return null; } for (WBWindow win : m_windows) { if (win.Type == TYPE_WINDOW && AdWindowId.equals(adWindowId, win.mWindow.getAdWindowId())) { return win.mWindow; } } return null; } // metas: end } // Workbench
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWorkbench.java
1
请完成以下Java代码
private Optional<RequestTypeId> retrieveDefaultRequestTypeId() { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_R_RequestType.COLUMNNAME_IsDefault, true) .create() .firstIdOnly(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } private Optional<RequestTypeId> retrieveFirstActiveRequestTypeId() { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .orderBy(I_R_RequestType.COLUMNNAME_R_RequestType_ID)
.create() .firstId(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } @Override public I_R_RequestType getById(@NonNull final RequestTypeId requestTypeId) { return queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addEqualsFilter(I_R_RequestType.COLUMNNAME_R_RequestType_ID, requestTypeId) .create() .firstOnlyNotNull(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\api\impl\RequestTypeDAO.java
1
请完成以下Java代码
public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); } @Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsArchiveFile (final boolean IsArchiveFile) { set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile); } @Override public boolean isArchiveFile() { return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsReconciled (final boolean IsReconciled) { set_Value (COLUMNNAME_IsReconciled, IsReconciled); } @Override public boolean isReconciled() { return get_ValueAsBoolean(COLUMNNAME_IsReconciled); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); }
@Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { throw new IllegalArgumentException ("Processing is virtual column"); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
1
请完成以下Java代码
private HULabelConfig getLabelConfigOrNull(final HUToReport hu) { final ExplainedOptional<HULabelConfig> optionalLabelConfig = labelConfigProvider.getLabelConfig(hu); if (optionalLabelConfig.isPresent()) { HULabelConfig huLabelConfig = optionalLabelConfig.get(); if (onlyIfAutoPrint && !huLabelConfig.isAutoPrint()) { return null; } if (printCopiesOverride != null) { huLabelConfig = huLabelConfig.withAutoPrintCopies(printCopiesOverride); } return huLabelConfig; } else { if (failOnMissingLabelConfig) { throw new AdempiereException(optionalLabelConfig.getExplanation()); } else { return null; } } } private void add(@NonNull final HUToReport hu, @NonNull final PrintInstructions printInstructions) { // Don't add it if we already considered it if (!huIdsCollected.add(hu.getHUId())) { return; } final BatchToPrint lastBatch = !batches.isEmpty() ? batches.get(batches.size() - 1) : null; final BatchToPrint batch; if (lastBatch == null || !lastBatch.isMatching(printInstructions)) { batch = new BatchToPrint(printInstructions); batches.add(batch); } else { batch = lastBatch; } batch.addHU(hu); } public boolean isEmpty() {return huIdsCollected.isEmpty();} public ImmutableSet<HuId> getHuIds() {return ImmutableSet.copyOf(huIdsCollected);} public void forEach(@NonNull final Consumer<BatchToPrint> action)
{ batches.forEach(action); } } @Getter private static class BatchToPrint { @NonNull private final PrintInstructions printInstructions; @NonNull private final ArrayList<HUToReport> hus = new ArrayList<>(); private BatchToPrint(final @NonNull PrintInstructions printInstructions) {this.printInstructions = printInstructions;} public boolean isMatching(@NonNull final PrintInstructions printInstructions) { return Objects.equals(this.printInstructions, printInstructions); } public void addHU(@NonNull final HUToReport hu) {this.hus.add(hu);} } @Value @Builder private static class PrintInstructions { @NonNull AdProcessId printFormatProcessId; @Builder.Default PrintCopies copies = PrintCopies.ONE; @Builder.Default boolean onlyOneHUPerPrint = true; public static PrintInstructions of(HULabelConfig huLabelConfig) { return builder() .printFormatProcessId(huLabelConfig.getPrintFormatProcessId()) .copies(huLabelConfig.getAutoPrintCopies()) // IMPORTANT: call the report with one HU only because label reports are working only if we provide M_HU_ID parameter. // We changed HUReportExecutor to provide the M_HU_ID parameter and as AD_Table_ID/Record_ID in case only one HU is provided. .onlyOneHUPerPrint(true) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\labels\HULabelPrintCommand.java
1
请完成以下Java代码
public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection) { if (this.isEmpty()) { return documentIdsSelection; } else if (documentIdsSelection.isEmpty()) { return this; } if (this.all) { return this; } else if (documentIdsSelection.all) { return documentIdsSelection; }
final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet()); final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds); if (this.equals(result)) { return this; } else if (documentIdsSelection.equals(result)) { return documentIdsSelection; } else { return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getMaxInactiveInterval() { return this.maxInactiveInterval; } public String getRedisNamespace() { return this.redisNamespace; } public SaveMode getSaveMode() { return this.saveMode; } public SessionIdGenerator getSessionIdGenerator() { return this.sessionIdGenerator; } public RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer; } @Autowired public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider<ReactiveRedisConnectionFactory> springSessionRedisConnectionFactory, ObjectProvider<ReactiveRedisConnectionFactory> redisConnectionFactory) { ReactiveRedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory .getIfAvailable(); if (redisConnectionFactoryToUse == null) { redisConnectionFactoryToUse = redisConnectionFactory.getObject(); } this.redisConnectionFactory = redisConnectionFactoryToUse; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } @Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<ReactiveSessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<ReactiveSessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() { return this.sessionRepositoryCustomizers; }
protected ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() { RedisSerializer<String> keySerializer = RedisSerializer.string(); RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer : new JdkSerializationRedisSerializer(); RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext .<String, Object>newSerializationContext(defaultSerializer) .key(keySerializer) .hashKey(keySerializer) .build(); return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext); } public ReactiveRedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\AbstractRedisWebSessionConfiguration.java
2
请完成以下Java代码
public SetRemovalTimeToHistoricProcessInstancesBuilder updateInChunks() { updateInChunks = true; return this; } @Override public SetRemovalTimeToHistoricProcessInstancesBuilder chunkSize(int chunkSize) { if (chunkSize > ProcessSetRemovalTimeJobHandler.MAX_CHUNK_SIZE || chunkSize <= 0) { throw new BadUserRequestException(String.format("The value for chunk size should be between 1 and %s", ProcessSetRemovalTimeJobHandler.MAX_CHUNK_SIZE)); } this.chunkSize = chunkSize; return this; } @Override public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricProcessInstancesCmd(this)); } public HistoricProcessInstanceQuery getQuery() { return query; } public List<String> getIds() { return ids; } public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public boolean isHierarchical() { return isHierarchical;
} public boolean isUpdateInChunks() { return updateInChunks; } public Integer getChunkSize() { return chunkSize; } public static enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricProcessInstancesBuilderImpl.java
1
请完成以下Java代码
public class FinancialInstitutionIdentification7 { @XmlElement(name = "BIC") protected String bic; @XmlElement(name = "ClrSysMmbId") protected ClearingSystemMemberIdentification2 clrSysMmbId; @XmlElement(name = "Nm") protected String nm; @XmlElement(name = "PstlAdr") protected PostalAddress6 pstlAdr; @XmlElement(name = "Othr") protected GenericFinancialIdentification1 othr; /** * Gets the value of the bic property. * * @return * possible object is * {@link String } * */ public String getBIC() { return bic; } /** * Sets the value of the bic property. * * @param value * allowed object is * {@link String } * */ public void setBIC(String value) { this.bic = value; } /** * Gets the value of the clrSysMmbId property. * * @return * possible object is * {@link ClearingSystemMemberIdentification2 } * */ public ClearingSystemMemberIdentification2 getClrSysMmbId() { return clrSysMmbId; } /** * Sets the value of the clrSysMmbId property. * * @param value * allowed object is * {@link ClearingSystemMemberIdentification2 } * */ public void setClrSysMmbId(ClearingSystemMemberIdentification2 value) { this.clrSysMmbId = value; } /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; }
/** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } /** * Gets the value of the pstlAdr property. * * @return * possible object is * {@link PostalAddress6 } * */ public PostalAddress6 getPstlAdr() { return pstlAdr; } /** * Sets the value of the pstlAdr property. * * @param value * allowed object is * {@link PostalAddress6 } * */ public void setPstlAdr(PostalAddress6 value) { this.pstlAdr = value; } /** * Gets the value of the othr property. * * @return * possible object is * {@link GenericFinancialIdentification1 } * */ public GenericFinancialIdentification1 getOthr() { return othr; } /** * Sets the value of the othr property. * * @param value * allowed object is * {@link GenericFinancialIdentification1 } * */ public void setOthr(GenericFinancialIdentification1 value) { this.othr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\FinancialInstitutionIdentification7.java
1
请完成以下Java代码
public class ReturnCodeResolver { public static MqttConnectReturnCode getConnectionReturnCode(MqttVersion mqttVersion, MqttConnectReturnCode returnCode) { if (!MqttVersion.MQTT_5.equals(mqttVersion) && !MqttConnectReturnCode.CONNECTION_ACCEPTED.equals(returnCode)) { switch (returnCode) { case CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD: case CONNECTION_REFUSED_NOT_AUTHORIZED_5: return MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED; case CONNECTION_REFUSED_CLIENT_IDENTIFIER_NOT_VALID: return MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED; case CONNECTION_REFUSED_SERVER_UNAVAILABLE_5: case CONNECTION_REFUSED_CONNECTION_RATE_EXCEEDED: return MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE; default: log.warn("Unknown return code for conversion: {}", returnCode.name()); } } return MqttConnectReturnCode.valueOf(returnCode.byteValue()); } public static int getSubscriptionReturnCode(MqttVersion mqttVersion, MqttReasonCodes.SubAck returnCode) { if (!MqttVersion.MQTT_5.equals(mqttVersion) && !(MqttReasonCodes.SubAck.GRANTED_QOS_0.equals(returnCode) || MqttReasonCodes.SubAck.GRANTED_QOS_1.equals(returnCode) || MqttReasonCodes.SubAck.GRANTED_QOS_2.equals(returnCode))) { switch (returnCode) {
case UNSPECIFIED_ERROR: case TOPIC_FILTER_INVALID: case IMPLEMENTATION_SPECIFIC_ERROR: case NOT_AUTHORIZED: case PACKET_IDENTIFIER_IN_USE: case QUOTA_EXCEEDED: case SHARED_SUBSCRIPTIONS_NOT_SUPPORTED: case SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED: case WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED: return MqttQoS.FAILURE.value(); } } return returnCode.byteValue(); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\ReturnCodeResolver.java
1
请完成以下Java代码
public void add(final PurchaseCandidate candidate) { if (candidate.isZeroQty()) { return; } if (order == null) { order = createOrder(candidate); orderLinesAggregator = new OrderLinesAggregator(order); } orderLinesAggregator.add(candidate); } private I_C_Order createOrder(final PurchaseCandidate candidate) { final int adOrgId = candidate.getAD_Org_ID(); final int warehouseId = candidate.getM_Warehouse_ID(); final I_C_BPartner bpartner = bpartnersRepo.getById(candidate.getC_BPartner_ID()); final int pricingSystemId = candidate.getM_PricingSystem_ID(); // the price is taken from the candidates and C_OrderLine.IsManualPrice is set to 'Y' // gh #1088 I have no clue wtf the comment above "the price is taken from..." is supposed to mean. // So instead of using M_PriceList_ID_None here, we use the candidate's PL. // Because otherwise, de.metas.order.model.interceptor.C_Order#onPriceListChangeInterceptor(...) will update the order pricing system to M_PricingSystem_ID_None // and then the system won't be able to get the new order lines' C_TaxCategories and MOrderLine.beforeSave() will fail // final int priceListId = MPriceList.M_PriceList_ID_None; final int priceListId = candidate.getM_PriceList_ID(); final int currencyId = candidate.getC_Currency_ID(); final Timestamp datePromised = candidate.getDatePromised(); final Timestamp dateOrdered = TimeUtil.min(SystemTime.asDayTimestamp(), datePromised); final I_C_Order order = InterfaceWrapperHelper.newInstance(I_C_Order.class); // // Doc type order.setAD_Org_ID(adOrgId); order.setIsSOTrx(false); orderBL.setDefaultDocTypeTargetId(order); // // Warehouse order.setM_Warehouse_ID(warehouseId); // // BPartner orderBL.setBPartner(order, bpartner); orderBL.setBill_User_ID(order); // // Dates order.setDateOrdered(dateOrdered); order.setDateAcct(dateOrdered); order.setDatePromised(datePromised); // // Price list if (pricingSystemId > 0) { order.setM_PricingSystem_ID(pricingSystemId); }
if (priceListId > 0) { order.setM_PriceList_ID(priceListId); } order.setC_Currency_ID(currencyId); // // SalesRep: // * let it to be set from BPartner (this was done above, by orderBL.setBPartner method) // * if not set use it from context final Properties ctx = InterfaceWrapperHelper.getCtx(order); if (order.getSalesRep_ID() <= 0) { order.setSalesRep_ID(Env.getContextAsInt(ctx, Env.CTXNAME_SalesRep_ID)); } if (order.getSalesRep_ID() <= 0) { order.setSalesRep_ID(Env.getAD_User_ID(ctx)); } order.setDocStatus(DocStatus.Drafted.getCode()); order.setDocAction(IDocument.ACTION_Complete); // // Save & return InterfaceWrapperHelper.save(order); return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrderHeaderAggregation.java
1
请完成以下Java代码
public List<String> map(ConfigurationPropertyName configurationPropertyName) { List<String> mapped = new ArrayList<>(4); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.SYSTEM_ENVIRONMENT, true)); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.LEGACY_SYSTEM_ENVIRONMENT, true)); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.SYSTEM_ENVIRONMENT, false)); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.LEGACY_SYSTEM_ENVIRONMENT, false)); return mapped; } private void addIfMissing(List<String> list, String value) { if (!list.contains(value)) { list.add(value); } } @Override public ConfigurationPropertyName map(String propertySourceName) { ConfigurationPropertyName configurationPropertyName = this.propertySourceNameCache.get(propertySourceName); if (configurationPropertyName == null) { configurationPropertyName = convertName(propertySourceName); this.propertySourceNameCache.put(propertySourceName, configurationPropertyName); } return configurationPropertyName; } private ConfigurationPropertyName convertName(String propertySourceName) { try { return ConfigurationPropertyName.adapt(propertySourceName, '_', this::processElementValue); } catch (Exception ex) { return ConfigurationPropertyName.EMPTY; } } private CharSequence processElementValue(CharSequence value) { String result = value.toString().toLowerCase(Locale.ENGLISH); return isNumber(result) ? "[" + result + "]" : result; }
private static boolean isNumber(String string) { return string.chars().allMatch(Character::isDigit); } @Override public BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> getAncestorOfCheck() { return this::isAncestorOf; } private boolean isAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { return name.isAncestorOf(candidate) || isLegacyAncestorOf(name, candidate); } private boolean isLegacyAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { if (!name.hasDashedElement()) { return false; } ConfigurationPropertyName legacyCompatibleName = name.asSystemEnvironmentLegacyName(); return legacyCompatibleName != null && legacyCompatibleName.isAncestorOf(candidate); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\SystemEnvironmentPropertyMapper.java
1
请在Spring Boot框架中完成以下Java代码
public List<TaskResponse> searchTasks(@RequestParam("status") Optional<String> status, @RequestParam("createdBy") Optional<String> createdBy) { var tasks = tasksService.search(status, createdBy); return tasks.stream() .map(this::buildResponse) .collect(Collectors.toList()); } @GetMapping("/{id}") public TaskResponse getTask(@PathVariable("id") String id) { var task = tasksService.getTaskById(id); return buildResponse(task); } @DeleteMapping("/{id}") public void deleteTask(@PathVariable("id") String id) { tasksService.deleteTaskById(id); }
@PatchMapping("/{id}") public TaskResponse patchTask(@PathVariable("id") String id, @RequestBody PatchTaskRequest body) { var task = tasksService.updateTask(id, body.status(), body.assignedTo()); return buildResponse(task); } private TaskResponse buildResponse(final TaskRecord task) { return new TaskResponse(task.getId(), task.getTitle(), task.getCreated(), task.getCreatedBy(), task.getAssignedTo(), task.getStatus()); } @ExceptionHandler(UnknownTaskException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public void handleUnknownTask() { } }
repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\java\com\baeldung\tasksservice\adapters\http\TasksController.java
2
请在Spring Boot框架中完成以下Java代码
public String getExpressNo() { return expressNo; } public void setExpressNo(String expressNo) { this.expressNo = expressNo; } public Integer getPayModeCode() { return payModeCode; } public void setPayModeCode(Integer payModeCode) { this.payModeCode = payModeCode; } public String getTotalPrice() {
return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } @Override public String toString() { return "OrderUpdateReq{" + "id='" + id + '\'' + ", orderStateCode=" + orderStateCode + ", expressNo='" + expressNo + '\'' + ", payModeCode=" + payModeCode + ", totalPrice='" + totalPrice + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderUpdateReq.java
2
请完成以下Java代码
public java.sql.Timestamp getRequestEndTime () { return (java.sql.Timestamp)get_Value(COLUMNNAME_RequestEndTime); } /** Set Request Method. @param RequestMethod Request Method */ @Override public void setRequestMethod (java.lang.String RequestMethod) { set_Value (COLUMNNAME_RequestMethod, RequestMethod); } /** Get Request Method. @return Request Method */ @Override public java.lang.String getRequestMethod () { return (java.lang.String)get_Value(COLUMNNAME_RequestMethod); } /** Set Anfrage Start . @param RequestStartTime Anfrage Start */ @Override public void setRequestStartTime (java.sql.Timestamp RequestStartTime) { set_ValueNoCheck (COLUMNNAME_RequestStartTime, RequestStartTime); } /** Get Anfrage Start . @return Anfrage Start */ @Override public java.sql.Timestamp getRequestStartTime () { return (java.sql.Timestamp)get_Value(COLUMNNAME_RequestStartTime); } /** Set Abfrage. @param RequestUrl Abfrage */ @Override public void setRequestUrl (java.lang.String RequestUrl) { set_ValueNoCheck (COLUMNNAME_RequestUrl, RequestUrl); } /** Get Abfrage. @return Abfrage */ @Override public java.lang.String getRequestUrl () { return (java.lang.String)get_Value(COLUMNNAME_RequestUrl); } /** Set Antwort . @param ResponseCode Antwort */ @Override public void setResponseCode (int ResponseCode) { set_Value (COLUMNNAME_ResponseCode, Integer.valueOf(ResponseCode)); } /** Get Antwort . @return Antwort */ @Override public int getResponseCode () { Integer ii = (Integer)get_Value(COLUMNNAME_ResponseCode); if (ii == null) return 0; return ii.intValue(); } /** Set Antwort-Text. @param ResponseText Anfrage-Antworttext */ @Override
public void setResponseText (java.lang.String ResponseText) { set_Value (COLUMNNAME_ResponseText, ResponseText); } /** Get Antwort-Text. @return Anfrage-Antworttext */ @Override public java.lang.String getResponseText () { return (java.lang.String)get_Value(COLUMNNAME_ResponseText); } /** Set TransaktionsID Client. @param TransactionIDClient TransaktionsID Client */ @Override public void setTransactionIDClient (java.lang.String TransactionIDClient) { set_ValueNoCheck (COLUMNNAME_TransactionIDClient, TransactionIDClient); } /** Get TransaktionsID Client. @return TransaktionsID Client */ @Override public java.lang.String getTransactionIDClient () { return (java.lang.String)get_Value(COLUMNNAME_TransactionIDClient); } /** Set TransaktionsID Server. @param TransactionIDServer TransaktionsID Server */ @Override public void setTransactionIDServer (java.lang.String TransactionIDServer) { set_ValueNoCheck (COLUMNNAME_TransactionIDServer, TransactionIDServer); } /** Get TransaktionsID Server. @return TransaktionsID Server */ @Override public java.lang.String getTransactionIDServer () { return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Log.java
1
请完成以下Java代码
public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SalesRegion.java
1
请完成以下Java代码
public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false; // After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; return false; } // reverseCorrectionIt /** * Reverse Accrual - none * @return false */ @Override public boolean reverseAccrualIt() { log.info(toString()); // Before reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; // After reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return false; } // reverseAccrualIt /** * Re-activate * @return false */ @Override public boolean reActivateIt() { log.info(toString()); // Before reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REACTIVATE); if (m_processMsg != null) return false; // After reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REACTIVATE); if (m_processMsg != null) return false; return false; } // reActivateIt /************************************************************************* * Get Summary * @return Summary of Document */ @Override public String getSummary() {
StringBuffer sb = new StringBuffer(); sb.append(getDocumentNo()); // : Total Lines = 123.00 (#1) sb.append(": ") .append(Msg.translate(getCtx(),"ApprovalAmt")).append("=").append(getApprovalAmt()) .append(" (#").append(getLines(false).length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) sb.append(" - ").append(getDescription()); return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getCreated()); } /** * Get Process Message * @return clear text error message */ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * @return AD_User_ID */ @Override public int getDoc_User_ID() { return getUpdatedBy(); } // getDoc_User_ID /** * Get Document Currency * @return C_Currency_ID */ @Override public int getC_Currency_ID() { // MPriceList pl = MPriceList.get(getCtx(), getM_PriceList_ID()); // return pl.getC_Currency_ID(); return 0; } // getC_Currency_ID } // MInOutConfirm
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInOutConfirm.java
1
请完成以下Java代码
public void onDeviceDeleted(DeviceId deviceId) { snmpTransportContext.onDeviceDeleted(this); } @Override public void onResponse(ResponseEvent event) { if (isActive) { snmpTransportContext.getSnmpTransportService().processResponseEvent(this, event); } } public void initializeTarget(SnmpDeviceProfileTransportConfiguration profileTransportConfig, SnmpDeviceTransportConfiguration deviceTransportConfig) throws Exception { log.trace("Initializing target for SNMP session of device {}", device); this.target = snmpTransportContext.getSnmpAuthService().setUpSnmpTarget(profileTransportConfig, deviceTransportConfig); log.debug("SNMP target initialized: {}", target); } public void close() { isActive = false; } public String getToken() { return token; } @Override public int nextMsgId() { return msgIdSeq.incrementAndGet(); } @Override public void onGetAttributesResponse(GetAttributeResponseMsg getAttributesResponse) { } @Override public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg attributeUpdateNotification) { log.trace("[{}] Received attributes update notification to device", sessionId); try { snmpTransportContext.getSnmpTransportService().onAttributeUpdate(this, attributeUpdateNotification); } catch (Exception e) { snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.SHARED_ATTRIBUTES_SETTING.getLabel(), e); }
} @Override public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) { log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage()); if (sessionCloseNotification.getMessage().equals(DefaultTransportService.SESSION_EXPIRED_MESSAGE)) { if (sessionTimeoutHandler != null) { sessionTimeoutHandler.run(); } } } @Override public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) { log.trace("[{}] Received RPC command to device", sessionId); try { snmpTransportContext.getSnmpTransportService().onToDeviceRpcRequest(this, toDeviceRequest); snmpTransportContext.getTransportService().process(getSessionInfo(), toDeviceRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); } catch (Exception e) { snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.TO_DEVICE_RPC_REQUEST.getLabel(), e); } } @Override public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) { } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\session\DeviceSessionContext.java
1
请完成以下Java代码
public abstract class DbOperation implements Recyclable { /** * The type of the operation. */ protected DbOperationType operationType; protected int rowsAffected; protected Exception failure; protected State state; /** * The type of the DbEntity this operation is executed on. */ protected Class<? extends DbEntity> entityType; @Override public void recycle() { // clean out the object state operationType = null; entityType = null; } // getters / setters ////////////////////////////////////////// public Class<? extends DbEntity> getEntityType() { return entityType; } public void setEntityType(Class<? extends DbEntity> entityType) { this.entityType = entityType; } public DbOperationType getOperationType() { return operationType; } public void setOperationType(DbOperationType operationType) { this.operationType = operationType; } public int getRowsAffected() { return rowsAffected; } public void setRowsAffected(int rowsAffected) { this.rowsAffected = rowsAffected; } public boolean isFailed() { return state == State.FAILED_CONCURRENT_MODIFICATION || state == State.FAILED_CONCURRENT_MODIFICATION_EXCEPTION || state == State.FAILED_ERROR; }
public State getState() { return state; } public void setState(State state) { this.state = state; } public Exception getFailure() { return failure; } public void setFailure(Exception failure) { this.failure = failure; } public enum State { NOT_APPLIED, APPLIED, /** * Indicates that the operation was not performed for any reason except * concurrent modifications. */ FAILED_ERROR, /** * Indicates that the operation was not performed and that the reason * was a concurrent modification to the data to be updated. * Applies to databases with isolation level READ_COMMITTED. */ FAILED_CONCURRENT_MODIFICATION, /** * Indicates that the operation was not performed and was a concurrency * conflict with a SQL exception. Applies to PostgreSQL. */ FAILED_CONCURRENT_MODIFICATION_EXCEPTION } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbOperation.java
1
请完成以下Java代码
public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Commission_Share commissionShareRecord = getCommissionShareRecord(ic); // Right now, only invoiced sales transactions are commission-worthy. // We can later add a tick-box in the commission settings to make this configurable. final BigDecimal delivered = commissionShareRecord.getPointsSum_Invoiced() // .add(commissionShareRecord.getPointsSum_Invoiceable()) ; ic.setQtyDelivered(delivered); ic.setQtyDeliveredInUOM(delivered); // we use the commission product's stock uom, so no uom conversion is needed ic.setDeliveryDate(ic.getDateOrdered()); ic.setM_InOut_ID(-1); } private I_C_Commission_Share getCommissionShareRecord(@NonNull final I_C_Invoice_Candidate ic) { return TableRecordReference .ofReferenced(ic) .getModel(I_C_Commission_Share.class); } @Override public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Commission_Share commissionShareRecord = getCommissionShareRecord(ic); final SOTrx soTrx = SOTrx.ofBoolean(commissionShareRecord.isSOTrx()); ic.setBill_BPartner_ID(soTrx.isSales() ? commissionShareRecord.getC_BPartner_Payer_ID() : commissionShareRecord.getC_BPartner_SalesRep_ID()); } @Override public String toString() { return "CommissionShareHandler"; }
@NonNull private DocTypeId getDoctypeId(@NonNull final I_C_Commission_Share shareRecord) { final CommissionConstants.CommissionDocType commissionDocType = getCommissionDocType(shareRecord); return docTypeDAO.getDocTypeId( DocTypeQuery.builder() .docBaseType(commissionDocType.getDocBaseType()) .docSubType(DocSubType.ofCode(commissionDocType.getDocSubType())) .adClientId(shareRecord.getAD_Client_ID()) .adOrgId(shareRecord.getAD_Org_ID()) .build()); } @NonNull private CommissionConstants.CommissionDocType getCommissionDocType(@NonNull final I_C_Commission_Share shareRecord) { if (!shareRecord.isSOTrx()) { // note that SOTrx is about the share record's settlement. // I.e. if the sales-rep receives money from the commission, then it's a purchase order trx return CommissionConstants.CommissionDocType.COMMISSION; } else if (shareRecord.getC_LicenseFeeSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.LICENSE_COMMISSION; } else if (shareRecord.getC_MediatedCommissionSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.MEDIATED_COMMISSION; } throw new AdempiereException("Unhandled commission type! ") .appendParametersToMessage() .setParameter("C_CommissionShare_ID", shareRecord.getC_Commission_Share_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\invoicecandidate\CommissionShareHandler.java
1
请完成以下Java代码
public void onScriptApplied(final IScript script) { // nothing } @Override public ScriptFailedResolution onScriptFailed(final IScript script, final ScriptExecutionException e) throws RuntimeException { final File file = script.getLocalFile(); final String exceptionMessage = e.toStringX(false); // printStackTrace=false final PrintStream out = System.out; final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); out.println("--------------------------------------------------------------------------------------------------"); out.println("Script failed to run: " + file.toString()); out.println(); out.println(exceptionMessage); out.println("--------------------------------------------------------------------------------------------------"); do { out.println("What shall we do?"); out.println("F - fail, I - Ignore, R - Retry"); out.flush(); String answer; try { answer = in.readLine(); } catch (final IOException ioex) { out.println("Failed reading from console. Throwing inital error."); out.flush(); e.addSuppressed(ioex); throw e;
} if ("F".equalsIgnoreCase(answer)) { return ScriptFailedResolution.Fail; } else if ("I".equalsIgnoreCase(answer)) { return ScriptFailedResolution.Ignore; } else if ("R".equalsIgnoreCase(answer)) { return ScriptFailedResolution.Retry; } else { out.println("Unknown option: " + answer); } } while (true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\applier\impl\ConsoleScriptsApplierListener.java
1
请完成以下Java代码
public void setPolicyDirectives(String policyDirectives) { Assert.hasLength(policyDirectives, "policyDirectives must not be null or empty"); this.policyDirectives = policyDirectives; this.delegate = createDelegate(); } /** * Set whether to include the {@code Content-Security-Policy-Report-Only} header in * the response. Otherwise, defaults to the {@code Content-Security-Policy} header. * @param reportOnly whether to only report policy violations */ public void setReportOnly(boolean reportOnly) { this.reportOnly = reportOnly; this.delegate = createDelegate(); }
private @Nullable ServerHttpHeadersWriter createDelegate() { if (this.policyDirectives == null) { return null; } Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(resolveHeader(this.reportOnly), this.policyDirectives); return builder.build(); } private static String resolveHeader(boolean reportOnly) { return reportOnly ? CONTENT_SECURITY_POLICY_REPORT_ONLY : CONTENT_SECURITY_POLICY; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\ContentSecurityPolicyServerHttpHeadersWriter.java
1
请完成以下Java代码
Mono<Void> add(String sessionId, Instant expiration) { long expirationInMillis = expiration.toEpochMilli(); return this.sessionRedisOperations.opsForZSet().add(getExpirationsKey(), sessionId, expirationInMillis).then(); } /** * Remove the session id from the sorted set. * @param sessionId the session id * @return a {@link Mono} that completes when the operation completes */ Mono<Void> remove(String sessionId) { return this.sessionRedisOperations.opsForZSet().remove(getExpirationsKey(), sessionId).then(); } /** * Retrieve the session ids that have the expiration time less than the value passed * in {@code expiredBefore}. * @param expiredBefore the expiration time * @return a {@link Flux} that emits the session ids */ Flux<String> retrieveExpiredSessions(Instant expiredBefore) { Range<Double> range = Range.closed(0D, (double) expiredBefore.toEpochMilli()); Limit limit = Limit.limit().count(this.retrieveCount); return this.sessionRedisOperations.opsForZSet()
.reverseRangeByScore(getExpirationsKey(), range, limit) .cast(String.class); } private String getExpirationsKey() { return this.namespace + "sessions:expirations"; } /** * Set the namespace for the keys used by this class. * @param namespace the namespace */ void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be null or empty"); this.namespace = namespace; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetReactiveRedisSessionExpirationStore.java
1
请完成以下Java代码
protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (name.equals("AD_Table_ID")) p_AD_Table_ID = ((BigDecimal)para[i].getParameter()).intValue(); else log.error("Unknown Parameter: " + name); } } // prepare /** * Perform process. * @return clear Message * @throws Exception */ protected String doIt() throws Exception { log.info("AD_Table_ID=" + p_AD_Table_ID); // get Table Info
MTable table = new MTable (getCtx(), p_AD_Table_ID, get_TrxName()); if (table.get_ID() == 0) throw new IllegalArgumentException ("No AD_Table_ID=" + p_AD_Table_ID); String tableName = table.getTableName(); if (!tableName.startsWith("I")) throw new IllegalArgumentException ("Not an import table = " + tableName); // Delete String sql = "DELETE FROM " + tableName + " WHERE AD_Client_ID=" + getAD_Client_ID(); int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); String msg = Msg.translate(getCtx(), tableName + "_ID") + " #" + no; return msg; } // ImportDelete } // ImportDelete
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\ImportDelete.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; AdminSettings other = (AdminSettings) obj; if (jsonValue == null) { if (other.jsonValue != null) return false; } else if (!jsonValue.equals(other.jsonValue)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } @Override
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AdminSettings [key="); builder.append(key); builder.append(", jsonValue="); builder.append(jsonValue); 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\AdminSettings.java
1
请完成以下Java代码
public OAuth2AuthorizationRequest getAuthorizationRequest() { return get(OAuth2AuthorizationRequest.class); } /** * Returns the {@link OAuth2AuthorizationConsent authorization consent}. * @return the {@link OAuth2AuthorizationConsent} */ @Nullable public OAuth2AuthorizationConsent getAuthorizationConsent() { return get(OAuth2AuthorizationConsent.class); } /** * Constructs a new {@link Builder} with the provided * {@link OAuth2AuthorizationCodeRequestAuthenticationToken}. * @param authentication the {@link OAuth2AuthorizationCodeRequestAuthenticationToken} * @return the {@link Builder} */ public static Builder with(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2AuthorizationCodeRequestAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OAuth2AuthorizationCodeRequestAuthenticationContext, Builder> { private Builder(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link RegisteredClient registered client}. * @param registeredClient the {@link RegisteredClient} * @return the {@link Builder} for further configuration
*/ public Builder registeredClient(RegisteredClient registeredClient) { return put(RegisteredClient.class, registeredClient); } /** * Sets the {@link OAuth2AuthorizationRequest authorization request}. * @param authorizationRequest the {@link OAuth2AuthorizationRequest} * @return the {@link Builder} for further configuration */ public Builder authorizationRequest(OAuth2AuthorizationRequest authorizationRequest) { return put(OAuth2AuthorizationRequest.class, authorizationRequest); } /** * Sets the {@link OAuth2AuthorizationConsent authorization consent}. * @param authorizationConsent the {@link OAuth2AuthorizationConsent} * @return the {@link Builder} for further configuration */ public Builder authorizationConsent(OAuth2AuthorizationConsent authorizationConsent) { return put(OAuth2AuthorizationConsent.class, authorizationConsent); } /** * Builds a new {@link OAuth2AuthorizationCodeRequestAuthenticationContext}. * @return the {@link OAuth2AuthorizationCodeRequestAuthenticationContext} */ @Override public OAuth2AuthorizationCodeRequestAuthenticationContext build() { Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null"); return new OAuth2AuthorizationCodeRequestAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeRequestAuthenticationContext.java
1
请完成以下Java代码
private void writeResponse( @NonNull final HttpServletResponse httpServletResponse, @NonNull final ApiResponse apiResponse) throws IOException { forwardSomeResponseHttpHeaders(httpServletResponse, apiResponse.getHttpHeaders()); httpServletResponse.setStatus(apiResponse.getStatusCode()); httpServletResponse.setContentType(apiResponse.getContentType() != null ? apiResponse.getContentType().toString() : null); httpServletResponse.setCharacterEncoding(apiResponse.getCharset().name()); final String body = apiResponse.getBodyAsString(); if (body != null) { httpServletResponse.getWriter().write(body); } httpServletResponse.flushBuffer(); } private void forwardSomeResponseHttpHeaders(@NonNull final HttpServletResponse servletResponse, @Nullable final HttpHeaders httpHeaders) { if (httpHeaders == null || httpHeaders.isEmpty()) { return; } httpHeaders.keySet() .stream() .filter(key -> !key.equals(HttpHeaders.CONNECTION)) .filter(key -> !key.equals(HttpHeaders.CONTENT_LENGTH)) .filter(key -> !key.equals(HttpHeaders.CONTENT_TYPE)) .filter(key -> !key.equals(HttpHeaders.TRANSFER_ENCODING)) // if we forwarded this without knowing what we do, we would annoy a possible nginx reverse proxy .forEach(key -> { final List<String> values = httpHeaders.get(key); if (values != null) { values.forEach(value -> servletResponse.addHeader(key, value)); } }); } @NonNull private ApiResponse wrapBodyIfNeeded( @Nullable final ApiAuditConfig apiAuditConfig, @Nullable final ApiRequestAudit apiRequestAudit, @NonNull final ApiResponse apiResponse) {
if (apiAuditConfig != null && apiRequestAudit != null && apiAuditConfig.isWrapApiResponse() && apiResponse.isJson()) { return apiResponse.toBuilder() .contentType(MediaType.APPLICATION_JSON) .charset(StandardCharsets.UTF_8) .body(JsonApiResponse.builder() .requestId(JsonMetasfreshId.of(apiRequestAudit.getIdNotNull().getRepoId())) .endpointResponse(apiResponse.getBody()) .build()) .build(); } else { final HttpHeaders httpHeaders = apiResponse.getHttpHeaders() != null ? new HttpHeaders(apiResponse.getHttpHeaders()) : new HttpHeaders(); if (apiRequestAudit != null) { httpHeaders.add(API_RESPONSE_HEADER_REQUEST_AUDIT_ID, String.valueOf(apiRequestAudit.getIdNotNull().getRepoId())); } return apiResponse.toBuilder().httpHeaders(httpHeaders).build(); } } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean isResetServletResponse(@NonNull final HttpServletResponse response) { if (!response.isCommitted()) { response.reset(); return true; } Loggables.addLog("HttpServletResponse has already been committed -> cannot be altered! response status = {}", response.getStatus()); return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ResponseHandler.java
1
请完成以下Java代码
public static LocalDateTime readEventsByDateWithTZ(LocalDateTime localDateTime) { try { Event event = collection .find(eq("dateTime", localDateTime)) .first(); OffsetDateTime offsetDateTime = OffsetDateTime.of(event.dateTime, ZoneOffset.of(pianoLessonsTZ.timeZoneOffset)); ZonedDateTime zoned = offsetDateTime.atZoneSameInstant(ZoneId.of("America/Toronto")); return zoned.toLocalDateTime(); } catch (MongoException me) { System.err.println("Failed to read with error: " + me); throw me; } } public static long updateDateField() { Document document = new Document().append("title", "Piano lessons"); Bson update = Updates.currentDate("updatedAt"); UpdateOptions options = new UpdateOptions().upsert(false); try { UpdateResult result = collection.updateOne(document, update, options); return result.getModifiedCount(); } catch (MongoException me) { System.err.println("Failed to update with error: " + me); throw me; } } public static long updateManyEventsWithDateCriteria(LocalDate updateManyFrom, LocalDate updateManyTo) { Bson query = and(gte("dateTime", updateManyFrom), lt("dateTime", updateManyTo)); Bson updates = Updates.currentDate("dateTime"); try { UpdateResult result = collection.updateMany(query, updates);
return result.getModifiedCount(); } catch(MongoException me) { System.err.println("Failed to replace/update with error: " + me); throw me; } } public static long deleteEventsByDate(LocalDate from, LocalDate to) { Bson query = and(gte("dateTime", from), lt("dateTime", to)); try { DeleteResult result = collection.deleteMany(query); return result.getDeletedCount(); } catch (MongoException me) { System.err.println("Failed to delete with error: " + me); throw me; } } public static void dropDb() { db.drop(); } public static void main(String[] args) { } }
repos\tutorials-master\persistence-modules\java-mongodb-queries\src\main\java\com\baeldung\mongo\crud\CrudClient.java
1
请完成以下Java代码
public class ExportProductSpecifications extends JavaProcess implements IProcessPrecondition { private final static String tableName = "\"de.metas.fresh\".product_specifications_v"; private final SpreadsheetExporterService spreadsheetExporterService = SpringContextHolder.instance.getBean(SpreadsheetExporterService.class); @Override protected String doIt() throws Exception { final JdbcExcelExporter jdbcExcelExporter = JdbcExcelExporter.builder() .ctx(getCtx()) .columnHeaders(getColumnHeaders()) .build(); jdbcExcelExporter.setFontCharset(Font.ANSI_CHARSET); spreadsheetExporterService.processDataFromSQL(getSql(), jdbcExcelExporter); final File tempFile = jdbcExcelExporter.getResultFile(); final boolean backEndOrSwing = Ini.getRunMode() == RunMode.BACKEND || Ini.isSwingClient(); if (backEndOrSwing) { Env.startBrowser(tempFile.toURI().toString()); } else { getResult().setReportData(tempFile); } return MSG_OK; } private String getSql() { final I_M_Product product = Services.get(IProductDAO.class).getById(getRecord_ID()); final StringBuffer sb = new StringBuffer(); sb.append("SELECT productName, CustomerLabelName, additional_produktinfos, productValue, UPC, weight, country, guaranteedaysmin, ") .append("warehouse_temperature, productDecription, componentName, IsPackagingMaterial,componentIngredients, qtybatch, ") .append("allergen, nutritionName, nutritionqty FROM ") .append(tableName) .append(" WHERE ") .append(tableName).append(".productValue = '").append(product.getValue()).append("'") .append(" ORDER BY productValue "); return sb.toString(); }
private List<String> getColumnHeaders() { final List<String> columnHeaders = new ArrayList<>(); columnHeaders.add("ProductName"); columnHeaders.add("CustomerLabelName"); columnHeaders.add("Additional_produktinfos"); columnHeaders.add("ProductValue"); columnHeaders.add("UPC"); columnHeaders.add("NetWeight"); columnHeaders.add("Country"); columnHeaders.add("ShelfLifeDays"); columnHeaders.add("Warehouse_temperature"); columnHeaders.add("ProductDescription"); columnHeaders.add("M_BOMProduct_ID"); columnHeaders.add("IsPackagingMaterial"); columnHeaders.add("Ingredients"); columnHeaders.add("QtyBatch"); columnHeaders.add("Allergen"); columnHeaders.add("M_Product_Nutrition_ID"); columnHeaders.add("NutritionQty"); return columnHeaders; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\product\process\ExportProductSpecifications.java
1
请完成以下Java代码
class DBVersionGetter { private static final transient Logger logger = LoggerFactory.getLogger(DBVersionGetter.class); @NonNull final DBConnectionMaker dbConnectionMaker; private static final String DB_VERSION_INITIAL_VALUE = "0.0.0-initial-value"; private static final String CREATE_DB_VERSION_COLUMN_DDL = "ALTER TABLE public.AD_System ADD COLUMN DBVersion VARCHAR(50) DEFAULT '" + DB_VERSION_INITIAL_VALUE + "'"; private static final String SELECT_DB_VERSION_SQL = "SELECT DBVersion FROM public.AD_System"; public String retrieveDBVersion( @NonNull final DBConnectionSettings settings, @NonNull final String dbName) { final IDatabase dbConnection = dbConnectionMaker.createDummyDatabase(settings, dbName); try (final Connection connection = dbConnection.getConnection(); final Statement stmt = connection.createStatement()) { return retrieveDBVersion0(stmt); } catch (final SQLException e) { logger.info("Could not retrieve the DB version"); if ("42703".equals(e.getSQLState())) // 42703 => undefined_column, see https://www.postgresql.org/docs/9.5/static/errcodes-appendix.html { // we are a migration tool, so it might well be that the column is not yet there logger.info("Trying to create the DBVersion column now"); try (final Connection connection = dbConnection.getConnection(); final Statement stmt = connection.createStatement()) {
stmt.execute(CREATE_DB_VERSION_COLUMN_DDL); logger.info("Created the column with the initial value {}", DB_VERSION_INITIAL_VALUE); return DB_VERSION_INITIAL_VALUE; } catch (final SQLException e1) { throw new CantRetrieveDBVersionException("Could not create the missing column AD_System.DBVersion; Sql=" + CREATE_DB_VERSION_COLUMN_DDL, e); } } // fail throw new CantRetrieveDBVersionException("Could not retrieve the DB version; selectSql=" + SELECT_DB_VERSION_SQL, e); } } private String retrieveDBVersion0(final Statement stmt) throws SQLException { final ResultSet resultSet = stmt.executeQuery(SELECT_DB_VERSION_SQL); resultSet.next(); final String dbVersion = resultSet.getString(1); return dbVersion; } public static final class CantRetrieveDBVersionException extends RuntimeException { private static final long serialVersionUID = -5089487300354591676L; private CantRetrieveDBVersionException(final String msg, final Exception e) { super(msg, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBVersionGetter.java
1
请完成以下Java代码
public void setType(String type) { this.type = type; } @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; } @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) public void setSuspended(Boolean suspended) { this.suspended = suspended; } @CamundaQueryParam(value="createdBy") public void setCreateUserId(String userId) { this.userId = userId; } @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } @CamundaQueryParam(value = "withFailures", converter = BooleanConverter.class) public void setWithFailures(final Boolean withFailures) { this.withFailures = withFailures; } @CamundaQueryParam(value = "withoutFailures", converter = BooleanConverter.class) public void setWithoutFailures(final Boolean withoutFailures) { this.withoutFailures = withoutFailures; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected BatchStatisticsQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createBatchStatisticsQuery(); } protected void applyFilters(BatchStatisticsQuery query) { if (batchId != null) { query.batchId(batchId); } if (type != null) { query.type(type); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(suspended)) { query.suspended(); } if (FALSE.equals(suspended)) { query.active();
} if (userId != null) { query.createdBy(userId); } if (startedBefore != null) { query.startedBefore(startedBefore); } if (startedAfter != null) { query.startedAfter(startedAfter); } if (TRUE.equals(withFailures)) { query.withFailures(); } if (TRUE.equals(withoutFailures)) { query.withoutFailures(); } } protected void applySortBy(BatchStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { query.orderById(); } else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { query.orderByTenantId(); } else if (sortBy.equals(SORT_BY_START_TIME_VALUE)) { query.orderByStartTime(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchStatisticsQueryDto.java
1
请完成以下Java代码
private TokenBucket getTokenBucket() { if (tokenBucket != null) { return tokenBucket; } synchronized (this) { if (tokenBucket == null) { tokenBucket = TokenBuckets.builder() .withCapacity(capacity) .withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit) .build(); } } return tokenBucket; } public int getCapacity() { return capacity; } public ThrottleGatewayFilter setCapacity(int capacity) { this.capacity = capacity; return this; } public int getRefillTokens() { return refillTokens; } public ThrottleGatewayFilter setRefillTokens(int refillTokens) { this.refillTokens = refillTokens; return this; } public int getRefillPeriod() { return refillPeriod; } public ThrottleGatewayFilter setRefillPeriod(int refillPeriod) { this.refillPeriod = refillPeriod; return this;
} public TimeUnit getRefillUnit() { return refillUnit; } public ThrottleGatewayFilter setRefillUnit(TimeUnit refillUnit) { this.refillUnit = refillUnit; return this; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { TokenBucket tokenBucket = getTokenBucket(); // TODO: get a token bucket for a key log.debug("TokenBucket capacity: " + tokenBucket.getCapacity()); boolean consumed = tokenBucket.tryConsume(); if (consumed) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-sample\src\main\java\org\springframework\cloud\gateway\sample\ThrottleGatewayFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class InventoryQuery { @NonNull @Default QueryLimit limit = QueryLimit.ONE_THOUSAND; @NonNull @Default InSetPredicate<UserId> onlyResponsibleIds = InSetPredicate.any(); @NonNull @Default InSetPredicate<WarehouseId> onlyWarehouseIds = InSetPredicate.any(); @NonNull @Default InSetPredicate<DocStatus> onlyDocStatuses = InSetPredicate.any(); @NonNull @Singular ImmutableSet<InventoryId> excludeInventoryIds; @SuppressWarnings("unused") public static class InventoryQueryBuilder { public InventoryQueryBuilder noResponsibleId() { return onlyResponsibleIds(InSetPredicate.onlyNull()); } public InventoryQueryBuilder onlyResponsibleId(@NonNull final UserId responsibleId) { return onlyResponsibleIds(InSetPredicate.only(responsibleId)); } public InventoryQueryBuilder onlyWarehouseIdOrAny(@Nullable final WarehouseId warehouseId) { return onlyWarehouseIds(InSetPredicate.onlyOrAny(warehouseId));
} public InventoryQueryBuilder onlyDraftOrInProgress() { return onlyDocStatuses(InSetPredicate.only(DocStatus.Drafted, DocStatus.InProgress)); } public <T> InventoryQueryBuilder excludeInventoryIdsOf(@Nullable Collection<T> collection, @NonNull final Function<T, InventoryId> inventoryIdFunction) { if (collection == null || collection.isEmpty()) {return this;} final ImmutableSet<InventoryId> inventoryIds = collection.stream() .filter(Objects::nonNull) .map(inventoryIdFunction) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); return excludeInventoryIds(inventoryIds); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\InventoryQuery.java
2
请完成以下Java代码
public static String parseRootDnFromUrl(String url) { Assert.hasLength(url, "url must have length"); String urlRootDn; if (url.startsWith("ldap:") || url.startsWith("ldaps:")) { URI uri = parseLdapUrl(url); urlRootDn = uri.getRawPath(); } else { // Assume it's an embedded server urlRootDn = url; } if (urlRootDn.startsWith("/")) { urlRootDn = urlRootDn.substring(1); } return urlRootDn; } /** * Parses the supplied LDAP URL. * @param url the URL (e.g. * <tt>ldap://monkeymachine:11389/dc=springframework,dc=org</tt>). * @return the URI object created from the URL
* @throws IllegalArgumentException if the URL is null, empty or the URI syntax is * invalid. */ private static URI parseLdapUrl(String url) { Assert.hasLength(url, "url must have length"); try { return new URI(url); } catch (URISyntaxException ex) { throw new IllegalArgumentException("Unable to parse url: " + url, ex); } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\LdapUtils.java
1
请完成以下Java代码
public void setProjectValue (final @Nullable java.lang.String ProjectValue) { set_Value (COLUMNNAME_ProjectValue, ProjectValue); } @Override public java.lang.String getProjectValue() { return get_ValueAsString(COLUMNNAME_ProjectValue); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated) { set_Value (COLUMNNAME_QtyCalculated, QtyCalculated); } @Override public BigDecimal getQtyCalculated() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUOM (final java.lang.String UOM) {
set_Value (COLUMNNAME_UOM, UOM); } @Override public java.lang.String getUOM() { return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setWarehouseValue (final java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java
1
请完成以下Java代码
public class ProductInfo implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private Date publicationDate; private double price; private int availableQuantity; private int deliveryTime; private float ratings; private boolean verificationStatus; private String imageLocalPath; private String imageUrl; /*** * Mapping and DB integration. * Apparel Category * **/ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "apparel_id") private ApparelCategory apparelCategory; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "brand_id") private ProductBrandCategory productBrandCategory; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "gender_id") @JsonIgnore private GenderCategory genderCategory; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "price_id") @JsonIgnore private PriceRangeCategory priceRangeCategory;
@OneToMany(mappedBy = "productInfo") @JsonIgnore private List<OrderInfo> orderInfo; // public ProductInfo(int id, String productName, Date generateRandomDate, ProductBrandCategory productBrandCategory, GenderCategory genderCategory, ApparelCategory apparelCategory, PriceRangeCategory priceRangeCategory, int availableQuantity, int deliveryTime, double price, float generateRandomFloat, boolean verificationStatus, String imageLocalPath, String imageURL) { this.id = id; this.name = productName; this.publicationDate = generateRandomDate; this.productBrandCategory = productBrandCategory; this.genderCategory = genderCategory; this.apparelCategory = apparelCategory; this.priceRangeCategory = priceRangeCategory; this.availableQuantity = availableQuantity; this.imageUrl = imageURL; this.imageLocalPath = imageLocalPath; this.ratings = generateRandomFloat; this.verificationStatus = verificationStatus; this.deliveryTime = deliveryTime; this.price = price; } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-5.Spring-ReactJS-Ecommerce-Shopping\fullstack\backend\model\src\main\java\com\urunov\entity\info\ProductInfo.java
1
请完成以下Java代码
public boolean isMembershipBadgeToPrint () { Object oo = get_Value(COLUMNNAME_IsMembershipBadgeToPrint); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Body. @param LetterBody Body */ @Override public void setLetterBody (java.lang.String LetterBody) { set_Value (COLUMNNAME_LetterBody, LetterBody); } /** Get Body. @return Body */ @Override public java.lang.String getLetterBody () { return (java.lang.String)get_Value(COLUMNNAME_LetterBody); } /** Set Body (parsed). @param LetterBodyParsed Body (parsed) */ @Override public void setLetterBodyParsed (java.lang.String LetterBodyParsed) { set_Value (COLUMNNAME_LetterBodyParsed, LetterBodyParsed); } /** Get Body (parsed). @return Body (parsed) */ @Override public java.lang.String getLetterBodyParsed () { return (java.lang.String)get_Value(COLUMNNAME_LetterBodyParsed); } /** Set Subject. @param LetterSubject Subject */ @Override public void setLetterSubject (java.lang.String LetterSubject) { set_Value (COLUMNNAME_LetterSubject, LetterSubject); } /** Get Subject. @return Subject */ @Override public java.lang.String getLetterSubject () {
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override 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.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_C_Letter.java
1
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatus() {
return status; } public void setStatus(String status) { this.status = status; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } }
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\firestore\Task.java
1
请完成以下Java代码
public java.lang.String getPaySelectionTrxType () { return (java.lang.String)get_Value(COLUMNNAME_PaySelectionTrxType); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override 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 Gesamtbetrag. @param TotalAmt Gesamtbetrag */ @Override public void setTotalAmt (java.math.BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Gesamtbetrag. @return Gesamtbetrag */ @Override public java.math.BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelection.java
1
请完成以下Java代码
protected @NonNull ObjectToJsonConverter getObjectToJsonConverter() { return this.converter; } /** * Converts the given {@link Iterable} of {@link Object Objects} into a {@link String JSON} array. * * @param iterable {@link Iterable} containing the {@link Object Objects} to convert into {@link String JSON}; * must not be {@literal null}. * @return the {@link String JSON} generated from the given {@link Iterable} of {@link Object Objects}; * never {@literal null}. * @throws IllegalArgumentException if {@link Iterable} is {@literal null}. * @see #getObjectToJsonConverter() * @see java.lang.Iterable */ @Override public @NonNull String convert(@NonNull Iterable<?> iterable) { Assert.notNull(iterable, "Iterable must not be null"); StringBuilder json = new StringBuilder(BEGIN_ARRAY); ObjectToJsonConverter converter = getObjectToJsonConverter(); boolean addComma = false; for (Object value : CollectionUtils.nullSafeIterable(iterable)) { json.append(addComma ? JSON_OBJECT_SEPARATOR : EMPTY_STRING); json.append(converter.convert(value)); addComma = true; } json.append(END_ARRAY);
return json.toString(); } /** * Converts the {@link Map#values() values} from the given {@link Map} into {@link String JSON}. * * @param <K> {@link Class} type of the {@link Map#keySet() keys}. * @param <V> {@link Class} type of the {@link Map#values() values}. * @param map {@link Map} containing the {@link Map#values() values} to convert into {@link String JSON}. * @return {@link String JSON} generated from the {@link Map#values() values} in the given {@link Map}. * @see #convert(Iterable) * @see java.util.Map */ public @NonNull <K, V> String convert(@Nullable Map<K, V> map) { return convert(CollectionUtils.nullSafeMap(map).values()); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\AbstractObjectArrayToJsonConverter.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public org.compiere.model.I_S_Resource getPP_Plant() { return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class); } @Override public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant) { set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant); } @Override public void setPP_Plant_ID (final int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID); } @Override public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public void setProductGroup (final @Nullable java.lang.String ProductGroup) { throw new IllegalArgumentException ("ProductGroup is virtual column"); } @Override public java.lang.String getProductGroup() { return get_ValueAsString(COLUMNNAME_ProductGroup); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); }
@Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyCount (final BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java
1
请完成以下Java代码
public static void main(String[] args) { JacksonModule module = new JacksonModule(RESPECT_JSONPROPERTY_REQUIRED); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(DRAFT_2020_12, PLAIN_JSON).with(module).with(EXTRA_OPEN_API_FORMAT_VALUES); SchemaGenerator generator = new SchemaGenerator(configBuilder.build()); JsonNode jsonSchema = generator.generateSchema(Person.class); System.out.println(jsonSchema.toPrettyString()); } static class Person { @JsonProperty(access = JsonProperty.Access.READ_ONLY) UUID id; @JsonProperty(access = JsonProperty.Access.READ_WRITE, required = true) String name; @JsonProperty(access = JsonProperty.Access.READ_WRITE, required = true) String surname; @JsonProperty(access = JsonProperty.Access.READ_WRITE, required = true) Address address; @JsonIgnore String fullName; @JsonProperty(access = JsonProperty.Access.READ_ONLY) Date createdAt;
@JsonProperty(access = JsonProperty.Access.READ_WRITE) List<Person> friends; } static class Address { @JsonProperty() String street; @JsonProperty(required = true) String city; @JsonProperty(required = true) String country; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\modules\JacksonModuleSchemaGenerator.java
1
请完成以下Java代码
public static void setSearchPathForDLM(final Connection c) throws SQLException { changeSetting(c, "search_path", "\"$user\", dlm, public"); } public static void changeDLMCoalesceLevel(final Connection c, final int dlmCoalesceLevel) throws SQLException { changeSetting(c, SETTING_DLM_COALESCE_LEVEL, dlmCoalesceLevel); } public static void changeDLMLevel(final Connection c, final int dlmLevel) throws SQLException { changeSetting(c, SETTING_DLM_LEVEL, dlmLevel); } public static int retrieveCurrentDLMLevel(final Connection c) throws SQLException { return restrieveSetting(c, FUNCTION_DLM_LEVEL); } public static int retrieveCurrentDLMCoalesceLevel(final Connection c) throws SQLException { return restrieveSetting(c, FUNCTION_DLM_COALESCE_LEVEL); } private static int restrieveSetting(final Connection c, final String functionName) throws SQLException { final ResultSet rs = c.prepareStatement("SELECT " + functionName).executeQuery();
final Integer dlmLevel = rs.next() ? rs.getInt(1) : null; Check.errorIf(dlmLevel == null, "Unable to retrieve the current setting for {} from the DB", SETTING_DLM_COALESCE_LEVEL); return dlmLevel; } private static void changeSetting(final Connection c, final String setting, final int value) throws SQLException { final String valueStr = Integer.toString(value); changeSetting(c, setting, valueStr); } private static void changeSetting(final Connection c, final String setting, final String valueStr) throws SQLException { final PreparedStatement ps = c.prepareStatement("select set_config('" + setting + "'::text, ?::text, ?::boolean)"); ps.setString(1, valueStr); ps.setBoolean(2, false); ps.execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMConnectionUtils.java
1
请完成以下Java代码
public IProductionMaterialQuery createInitialQuery() { return new ProductionMaterialQuery(); } @Override public List<IProductionMaterial> retriveProductionMaterials(final IProductionMaterialQuery query) { final ProductionMaterialQueryExecutor queryExecutor = new ProductionMaterialQueryExecutor(query); return queryExecutor.retriveProductionMaterials(); } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocuments(final I_M_Material_Tracking materialTracking) { return new MaterialTrackingDocuments(materialTracking); } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocumentsFor(@NonNull final I_PP_Order model) { final IMaterialTrackingDocuments materialTrackingDocuments = retrieveMaterialTrackingDocumentsOrNullFor(model); if (materialTrackingDocuments == null) { throw new AdempiereException("@NotFound@ @M_Material_Tracking_ID@"
+ "\n model: " + model); } return materialTrackingDocuments; } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocumentsOrNullFor(@NonNull final I_PP_Order model) { // Retrieve Material Tracking via material_tracklin final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final I_M_Material_Tracking materialTracking = materialTrackingDAO.retrieveSingleMaterialTrackingForModel(model); if (materialTracking == null) { return null; } return retrieveMaterialTrackingDocuments(materialTracking); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityBasedInvoicingDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue private Long id; private String title; @CreationTimestamp private Instant createdOn; @UpdateTimestamp private Instant lastUpdatedOn; public Book() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public Instant getCreatedOn() { return createdOn; } public void setCreatedOn(Instant createdOn) { this.createdOn = createdOn; } public Instant getLastUpdatedOn() { return lastUpdatedOn; } public void setLastUpdatedOn(Instant lastUpdatedOn) { this.lastUpdatedOn = lastUpdatedOn; } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\creationupdatetimestamp\model\Book.java
2
请完成以下Java代码
public Object getValue(VariableScope variableScope) { ScriptInvocation invocation = new ScriptInvocation(script, variableScope); try { Context .getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(invocation); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ProcessEngineException(e); } return invocation.getInvocationResult(); }
@Override public boolean isDynamic() { return true; } public ExecutableScript getScript() { return script; } public void setScript(ExecutableScript script) { this.script = script; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\ScriptValueProvider.java
1
请完成以下Java代码
public UserQuery userId(String id) { ensureNotNull("Provided id", id); this.id = id; return this; } public UserQuery userIdIn(String... ids) { ensureNotNull("Provided ids", ids); this.ids = ids; return this; } public UserQuery userFirstName(String firstName) { this.firstName = firstName; return this; } public UserQuery userFirstNameLike(String firstNameLike) { ensureNotNull("Provided firstNameLike", firstNameLike); this.firstNameLike = firstNameLike; return this; } public UserQuery userLastName(String lastName) { this.lastName = lastName; return this; } public UserQuery userLastNameLike(String lastNameLike) { ensureNotNull("Provided lastNameLike", lastNameLike); this.lastNameLike = lastNameLike; return this; } public UserQuery userEmail(String email) { this.email = email; return this; } public UserQuery userEmailLike(String emailLike) { ensureNotNull("Provided emailLike", emailLike); this.emailLike = emailLike; return this; } public UserQuery memberOfGroup(String groupId) { ensureNotNull("Provided groupId", groupId); this.groupId = groupId; return this; } public UserQuery potentialStarter(String procDefId) { ensureNotNull("Provided processDefinitionId", procDefId); this.procDefId = procDefId; return this; } public UserQuery memberOfTenant(String tenantId) { ensureNotNull("Provided tenantId", tenantId); this.tenantId = tenantId; return this; } //sorting ////////////////////////////////////////////////////////// public UserQuery orderByUserId() { return orderBy(UserQueryProperty.USER_ID); } public UserQuery orderByUserEmail() { return orderBy(UserQueryProperty.EMAIL); } public UserQuery orderByUserFirstName() {
return orderBy(UserQueryProperty.FIRST_NAME); } public UserQuery orderByUserLastName() { return orderBy(UserQueryProperty.LAST_NAME); } //getters ////////////////////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getFirstName() { return firstName; } public String getFirstNameLike() { return firstNameLike; } public String getLastName() { return lastName; } public String getLastNameLike() { return lastNameLike; } public String getEmail() { return email; } public String getEmailLike() { return emailLike; } public String getGroupId() { return groupId; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public Company getWorkplace() { return workplace; } public void setWorkplace(Company workplace) { this.workplace = workplace; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return Objects.equals(id, employee.id) && Objects.equals(workplace, employee.workplace) && Objects.equals(firstName, employee.firstName); } @Override public int hashCode() { return Objects.hash(id, workplace, firstName); } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\proxy\Employee.java
1
请完成以下Java代码
public void put(String propertyName, String value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, Boolean value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, Short value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, Integer value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, Long value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, Double value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, Float value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, BigDecimal value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, BigInteger value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, byte[] value) { jsonNode.put(propertyName, value); }
@Override public void putNull(String propertyName) { jsonNode.putNull(propertyName); } @Override public FlowableArrayNode putArray(String propertyName) { return new FlowableJackson2ArrayNode(jsonNode.putArray(propertyName)); } @Override public void set(String propertyName, FlowableJsonNode value) { jsonNode.set(propertyName, asJsonNode(value)); } @Override public FlowableObjectNode putObject(String propertyName) { return new FlowableJackson2ObjectNode(jsonNode.putObject(propertyName)); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ObjectNode.java
1
请完成以下Java代码
public void setEncoding (final java.lang.String Encoding) { set_Value (COLUMNNAME_Encoding, Encoding); } @Override public java.lang.String getEncoding() { return get_ValueAsString(COLUMNNAME_Encoding); } @Override public void setHeader_Line1 (final java.lang.String Header_Line1) { set_Value (COLUMNNAME_Header_Line1, Header_Line1); } @Override public java.lang.String getHeader_Line1() { return get_ValueAsString(COLUMNNAME_Header_Line1); } @Override public void setHeader_Line2 (final java.lang.String Header_Line2) { set_Value (COLUMNNAME_Header_Line2, Header_Line2); } @Override public java.lang.String getHeader_Line2() { return get_ValueAsString(COLUMNNAME_Header_Line2); } @Override public void setIsDefault (final boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, IsDefault);
} @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSQL_Select (final java.lang.String SQL_Select) { set_Value (COLUMNNAME_SQL_Select, SQL_Select); } @Override public java.lang.String getSQL_Select() { return get_ValueAsString(COLUMNNAME_SQL_Select); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Zebra_Config.java
1
请完成以下Java代码
private void performDestroyEmptyHUsIfNeeded(final IHUContext huContext) { if (!destroyEmptyHUs) { return; } for (final I_M_HU hu : sourceHUs) { // Skip it if already destroyed if (handlingUnitsBL.isDestroyed(hu)) { continue; } handlingUnitsBL.destroyIfEmptyStorage(huContext, hu); } } private void createHUSnapshotsIfRequired(final IHUContext huContext) { if (!createHUSnapshots) { return; } // Make sure no snapshots were already created
// shall not happen if (snapshotId != null) { throw new IllegalStateException("Snapshot was already created: " + snapshotId); } snapshotId = Services.get(IHUSnapshotDAO.class) .createSnapshot() .setContext(huContext) .addModels(sourceHUs) .createSnapshots() .getSnapshotId(); } public I_M_HU getSingleSourceHU() { return CollectionUtils.singleElement(sourceHUs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\HUListAllocationSourceDestination.java
1
请完成以下Java代码
public void changePlanItemState(ChangePlanItemStateBuilderImpl changePlanItemStateBuilder) { commandExecutor.execute(new ChangePlanItemStateCmd(changePlanItemStateBuilder, configuration)); } @Override public void addEventListener(FlowableEventListener listenerToAdd) { commandExecutor.execute(new AddEventListenerCommand(listenerToAdd)); } @Override public void addEventListener(FlowableEventListener listenerToAdd, FlowableEngineEventType... types) { commandExecutor.execute(new AddEventListenerCommand(listenerToAdd, types)); } @Override public void removeEventListener(FlowableEventListener listenerToRemove) { commandExecutor.execute(new RemoveEventListenerCommand(listenerToRemove)); } @Override public void dispatchEvent(FlowableEvent event) { commandExecutor.execute(new DispatchEventCommand(event)); } @Override public CaseInstanceStartEventSubscriptionBuilder createCaseInstanceStartEventSubscriptionBuilder() { return new CaseInstanceStartEventSubscriptionBuilderImpl(this); }
@Override public CaseInstanceStartEventSubscriptionModificationBuilder createCaseInstanceStartEventSubscriptionModificationBuilder() { return new CaseInstanceStartEventSubscriptionModificationBuilderImpl(this); } @Override public CaseInstanceStartEventSubscriptionDeletionBuilder createCaseInstanceStartEventSubscriptionDeletionBuilder() { return new CaseInstanceStartEventSubscriptionDeletionBuilderImpl(this); } public EventSubscription registerCaseInstanceStartEventSubscription(CaseInstanceStartEventSubscriptionBuilderImpl builder) { return commandExecutor.execute(new RegisterCaseInstanceStartEventSubscriptionCmd(builder)); } public void migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(CaseInstanceStartEventSubscriptionModificationBuilderImpl builder) { commandExecutor.execute(new ModifyCaseInstanceStartEventSubscriptionCmd(builder)); } public void deleteCaseInstanceStartEventSubscriptions(CaseInstanceStartEventSubscriptionDeletionBuilderImpl builder) { commandExecutor.execute(new DeleteCaseInstanceStartEventSubscriptionCmd(builder)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnRuntimeServiceImpl.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected void prepare() { final IQueryFilter<I_PP_Order> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBuilder<I_PP_Order> queryBuilderForShipmentSchedulesSelection = ppOrderDAO.createQueryForPPOrderSelection(userSelectionFilter); // Create selection and return how many items were added final int selectionCount = queryBuilderForShipmentSchedulesSelection .create() .createSelection(getPinstanceId()); if (selectionCount <= 0) { throw new AdempiereException(MSG_ONLY_CLOSED_LINES)
.markAsUserValidationError(); } } @Override protected String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); ppOrderBL.updateExportStatus(APIExportStatus.ofCode(exportStatus), pinstanceId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_ChangeExportStatus.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public List<String> getFailures() { return failures; } public void setFailures(List<String> failures) { this.failures = failures; } public List<MigratingActivityInstanceValidationReportDto> getActivityInstanceValidationReports() { return activityInstanceValidationReports; } public void setActivityInstanceValidationReports(List<MigratingActivityInstanceValidationReportDto> activityInstanceValidationReports) { this.activityInstanceValidationReports = activityInstanceValidationReports; }
public List<MigratingTransitionInstanceValidationReportDto> getTransitionInstanceValidationReports() { return transitionInstanceValidationReports; } public void setTransitionInstanceValidationReports(List<MigratingTransitionInstanceValidationReportDto> transitionInstanceValidationReports) { this.transitionInstanceValidationReports = transitionInstanceValidationReports; } public static MigratingProcessInstanceValidationReportDto from(MigratingProcessInstanceValidationReport validationReport) { MigratingProcessInstanceValidationReportDto dto = new MigratingProcessInstanceValidationReportDto(); dto.setProcessInstanceId(validationReport.getProcessInstanceId()); dto.setFailures(validationReport.getFailures()); dto.setActivityInstanceValidationReports(MigratingActivityInstanceValidationReportDto.from(validationReport.getActivityInstanceReports())); dto.setTransitionInstanceValidationReports(MigratingTransitionInstanceValidationReportDto.from(validationReport.getTransitionInstanceReports())); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigratingProcessInstanceValidationReportDto.java
1
请在Spring Boot框架中完成以下Java代码
public I_C_BP_Group getDefaultByClientOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { final BPGroupId bpGroupId = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_BP_Group.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_Group.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId()) .addInArrayFilter(I_C_BP_Group.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId(), OrgId.ANY) .addEqualsFilter(I_C_BP_Group.COLUMNNAME_IsDefault, true) .orderByDescending(I_C_BP_Group.COLUMNNAME_AD_Org_ID) .create() .firstId(BPGroupId::ofRepoIdOrNull); if (bpGroupId == null) { logger.warn("No default BP group found for {}", clientAndOrgId); return null; } return getById(bpGroupId);
} @Override public BPartnerNameAndGreetingStrategyId getBPartnerNameAndGreetingStrategyId(@NonNull final BPGroupId bpGroupId) { final I_C_BP_Group bpGroup = getById(bpGroupId); return StringUtils.trimBlankToOptional(bpGroup.getBPNameAndGreetingStrategy()) .map(BPartnerNameAndGreetingStrategyId::ofString) .orElse(DoNothingBPartnerNameAndGreetingStrategy.ID); } @Override public void save(@NonNull final I_C_BP_Group bpGroup) { InterfaceWrapperHelper.saveRecord(bpGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPGroupDAO.java
2
请完成以下Java代码
public class ResponseWrapper extends HttpServletResponseWrapper { private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); private final PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream)); public ResponseWrapper(HttpServletResponse response) { super(response); } @Override public ServletOutputStream getOutputStream() { return new ServletOutputStream() { @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener writeListener) { } @Override public void write(int b) { outputStream.write(b); } }; } @Override
public PrintWriter getWriter() { return writer; } @Override public void flushBuffer() throws IOException { super.flushBuffer(); writer.flush(); } public String getBodyAsString() { writer.flush(); return outputStream.toString(); } }
repos\tutorials-master\logging-modules\log-all-requests\src\main\java\com\baeldung\logallrequests\ResponseWrapper.java
1
请在Spring Boot框架中完成以下Java代码
protected void processRestoredState(CalculatedFieldStateProto stateMsg, TopicPartitionInfo partition, TbCallback callback) { var id = fromProto(stateMsg.getId()); if (partition == null) { try { partition = actorSystemContext.resolve(ServiceType.TB_RULE_ENGINE, DataConstants.CF_QUEUE_NAME, id.tenantId(), id.entityId()); } catch (TenantNotFoundException e) { log.debug("Skipping CF state msg for non-existing tenant {}", id.tenantId()); return; } } var state = fromProto(id, stateMsg); processRestoredState(id, state, partition, callback); } protected void processRestoredState(CalculatedFieldEntityCtxId id, CalculatedFieldState state, TopicPartitionInfo partition, TbCallback callback) { partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME); actorSystemContext.tellWithHighPriority(new CalculatedFieldStateRestoreMsg(id, state, partition, callback)); } @Override public void restore(QueueKey queueKey, Set<TopicPartitionInfo> partitions) { stateService.update(queueKey, partitions, new QueueStateService.RestoreCallback() { @Override public void onAllPartitionsRestored() { } @Override public void onPartitionRestored(TopicPartitionInfo partition) { partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME); actorSystemContext.tellWithHighPriority(new CalculatedFieldStatePartitionRestoreMsg(partition)); } }); }
@Override public void delete(Set<TopicPartitionInfo> partitions) { stateService.delete(partitions); } @Override public Set<TopicPartitionInfo> getPartitions() { return stateService.getPartitions().values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); } @Override public void stop() { stateService.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\AbstractCalculatedFieldStateService.java
2
请完成以下Java代码
protected void initObjectMapper(AbstractEngineConfiguration engineConfiguration, AbstractEngineConfiguration targetEngineConfiguration) { if (targetEngineConfiguration.getObjectMapper() == null) { targetEngineConfiguration.setObjectMapper(engineConfiguration.getObjectMapper()); } } protected void initVariableTypes(AbstractEngineConfiguration engineConfiguration, AbstractEngineConfiguration targetEngineConfiguration) { if (engineConfiguration instanceof HasVariableTypes && targetEngineConfiguration instanceof HasVariableTypes) { ((HasVariableTypes) targetEngineConfiguration).setVariableTypes(((HasVariableTypes) engineConfiguration).getVariableTypes()); ((HasVariableTypes) targetEngineConfiguration).setVariableJsonMapper(((HasVariableTypes) engineConfiguration).getVariableJsonMapper()); } } protected void initSchemaManager(AbstractEngineConfiguration engineConfiguration, AbstractEngineConfiguration targetEngineConfiguration) { // We are going to disable the Schema management in the target engine as the lead engine is the one that is going to handle the schema generation targetEngineConfiguration.setDatabaseSchemaUpdate(null);
engineConfiguration.addAdditionalSchemaManager(targetEngineConfiguration.createEngineSchemaManager()); } protected abstract List<Class<? extends Entity>> getEntityInsertionOrder(); protected abstract List<Class<? extends Entity>> getEntityDeletionOrder(); public boolean isEnableMybatisXmlMappingValidation() { return enableMybatisXmlMappingValidation; } public void setEnableMybatisXmlMappingValidation(boolean enableMybatisXmlMappingValidation) { this.enableMybatisXmlMappingValidation = enableMybatisXmlMappingValidation; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractEngineConfigurator.java
1
请完成以下Java代码
public class CustomerData extends BaseEntityData<CustomerFields> { private final ConcurrentMap<EntityType, ConcurrentMap<UUID, EntityData<?>>> entitiesById = new ConcurrentHashMap<>(); public CustomerData(UUID entityId) { super(entityId); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } public Collection<EntityData<?>> getEntities(EntityType entityType) { var map = entitiesById.get(entityType); if (map == null) { return Collections.emptyList(); } else {
return map.values(); } } public void addOrUpdate(EntityData<?> ed) { entitiesById.computeIfAbsent(ed.getEntityType(), et -> new ConcurrentHashMap<>()).put(ed.getId(), ed); } public boolean remove(EntityType entityType, UUID entityId) { var map = entitiesById.get(entityType); if (map != null) { return map.remove(entityId) != null; } else { return false; } } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\data\CustomerData.java
1
请在Spring Boot框架中完成以下Java代码
public class ExpenseTrackerApplication implements AppShellConfigurator { @Autowired private Environment environment; public static void main(String[] args) { SpringApplication.run(ExpenseTrackerApplication.class, args); } @Bean @Primary @ConfigurationProperties("main.datasource") DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); }
@Bean @Primary @ConfigurationProperties("main.datasource.hikari") DataSource dataSource(final DataSourceProperties dataSourceProperties) { return dataSourceProperties.initializeDataSourceBuilder().build(); } @EventListener public void printApplicationUrl(final ApplicationStartedEvent event) { LoggerFactory.getLogger(ExpenseTrackerApplication.class).info("Application started at " + "http://localhost:" + environment.getProperty("local.server.port") + Strings.nullToEmpty(environment.getProperty("server.servlet.context-path"))); } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\ExpenseTrackerApplication.java
2
请完成以下Java代码
public class PasswordHelper { private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); private static String algorithmName = "md5"; private static String hashIteration = "2"; private static int hashIterations = Integer.valueOf(hashIteration); public static void encryptPassword(PmsOperator pmsOperator) { pmsOperator.setsalt(randomNumberGenerator.nextBytes().toHex()); String newPassword = new SimpleHash(algorithmName, pmsOperator.getLoginPwd(), ByteSource.Util.bytes(pmsOperator.getCredentialsSalt()), hashIterations).toHex(); pmsOperator.setLoginPwd(newPassword); }
/** * 加密密码 * * @param loginPwd * 明文密码 * @param salt * @return */ public static String getPwd(String loginPwd, String salt) { String newPassword = new SimpleHash(algorithmName, loginPwd, ByteSource.Util.bytes(salt), hashIterations).toHex(); return newPassword; } public static void main(String[] args) { System.out.println(getPwd("roncoo.123","admin_roncoo8d78869f470951332959580424d4bf4f")); } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\utils\PasswordHelper.java
1
请完成以下Java代码
public class SynchronizedMethods { private int sum = 0; private int syncSum = 0; static int staticSum = 0; void calculate() { setSum(getSum() + 1); } synchronized void synchronisedCalculate() { setSyncSum(getSyncSum() + 1); } static synchronized void syncStaticCalculate() { staticSum = staticSum + 1; }
public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } int getSyncSum() { return syncSum; } private void setSyncSum(int syncSum) { this.syncSum = syncSum; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-4\src\main\java\com\baeldung\concurrent\synchronize\SynchronizedMethods.java
1
请完成以下Java代码
public String getEventSubscriptionId() { return eventSubscriptionId; } public void setEventSubscriptionId(String eventSubscriptionId) { this.eventSubscriptionId = eventSubscriptionId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType;
} public boolean isHasExistingInstancesForUniqueCorrelation() { return hasExistingInstancesForUniqueCorrelation; } public void setHasExistingInstancesForUniqueCorrelation(boolean hasExistingInstancesForUniqueCorrelation) { this.hasExistingInstancesForUniqueCorrelation = hasExistingInstancesForUniqueCorrelation; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("eventSubscriptionId='" + eventSubscriptionId + "'") .add("subScopeId='" + subScopeId + "'") .add("scopeType='" + scopeType + "'") .add("scopeDefinitionId='" + scopeDefinitionId + "'") .add("hasExistingInstancesForUniqueCorrelation=" + hasExistingInstancesForUniqueCorrelation) .toString(); } }
repos\flowable-engine-main\modules\flowable-event-registry-api\src\main\java\org\flowable\eventregistry\api\EventConsumerInfo.java
1
请完成以下Java代码
public class ExampleLayout extends SplitLayout { public ExampleLayout() { var grid = new Grid<>(Contact.class); grid.setColumns("name", "email", "phone"); grid.setItems(List.of( new Contact("John Doe", "john@doe.com", "123 456 789"), new Contact("Jane Doe", "jane@doe.com", "987 654 321") )); var form = new VerticalLayout(); var nameField = new TextField("Name"); var emailField = new TextField("Email"); var phoneField = new TextField("Phone");
var saveButton = new Button("Save"); var cancelButton = new Button("Cancel"); form.add( nameField, emailField, phoneField, new HorizontalLayout(saveButton, cancelButton) ); setSizeFull(); setSplitterPosition(70); addToPrimary(grid); addToSecondary(form); } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\introduction\basics\ExampleLayout.java
1