instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setAD_Modification_ID (int AD_Modification_ID) { if (AD_Modification_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Modification_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Modification_ID, Integer.valueOf(AD_Modification_ID)); } /** Get Modification. @return System Modification or Extension */ public int getAD_Modification_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Modification_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_ValueNoCheck (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name
Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Version. @param Version Version of the table definition */ public void setVersion (String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ public String getVersion () { return (String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Modification.java
1
请完成以下Java代码
private String getPriorityForNewWorkpackage(final IWorkpackagePrioStrategy defaultPrio) { // // Use the one from thread context (if any) final String priority = contextFactory.getThreadInheritedPriority(); if (!Check.isEmpty(priority, true)) { return priority; } // // No priority set => return automatic priority return defaultPrio.getPrioriy(this); } @Override public String getEnquingPackageProcessorInternalName() { Check.errorIf(Check.isEmpty(enquingPackageProcessorInternalName, true), UnsupportedOperationException.class, "Queue {} has no EnqueuingProcessorInternalName. It was problably not intended for enqueuing, but for queue processing", this); return enquingPackageProcessorInternalName; } @Override public IWorkPackageBuilder newWorkPackage() { return newWorkPackage(ctx); } @Override public IWorkPackageBuilder newWorkPackage(final Properties context) { if (enquingPackageProcessorId == null) { throw new IllegalStateException("Enquing not allowed");
} return new WorkPackageBuilder(context, this, enquingPackageProcessorId); } @NonNull public Set<QueuePackageProcessorId> getQueuePackageProcessorIds() { return packageProcessorIds; } @Override public QueueProcessorId getQueueProcessorId() { return queueProcessorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQueue.java
1
请完成以下Java代码
public class PageParam { private int beginLine; //起始行 private Integer pageSize = 3; private Integer currentPage=0; // 当前页 public int getBeginLine() { return pageSize*currentPage; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; }
public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第07课:Spring Boot 集成 MyBatis\spring-boot-mybatis-annotation\src\main\java\com\neo\param\PageParam.java
1
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; }
public Library getLibrary() { return library; } public void setLibrary(Library library) { this.library = library; } public List<Author> getAuthors() { return authors; } public void setAuthors(List<Author> authors) { this.authors = authors; } }
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\books\models\Book.java
1
请完成以下Java代码
private @Nullable String strip(String path) { if (path == null) { return null; } int semicolonIndex = path.indexOf(';'); if (semicolonIndex < 0) { int doubleSlashIndex = path.indexOf("//"); if (doubleSlashIndex < 0) { // Most likely case, no parameters in any segment and no '//', so no // stripping required return path; } } StringTokenizer tokenizer = new StringTokenizer(path, "/"); StringBuilder stripped = new StringBuilder(path.length()); if (path.charAt(0) == '/') { stripped.append('/'); } while (tokenizer.hasMoreTokens()) { String segment = tokenizer.nextToken(); semicolonIndex = segment.indexOf(';'); if (semicolonIndex >= 0) { segment = segment.substring(0, semicolonIndex); } stripped.append(segment).append('/'); } // Remove the trailing slash if the original path didn't have one if (path.charAt(path.length() - 1) != '/') { stripped.deleteCharAt(stripped.length() - 1); } return stripped.toString(); } @Override public @Nullable String getPathInfo() { return this.stripPaths ? this.strippedPathInfo : super.getPathInfo(); } @Override public @Nullable String getServletPath() { return this.stripPaths ? this.strippedServletPath : super.getServletPath(); } @Override public RequestDispatcher getRequestDispatcher(String path) { return this.stripPaths ? new FirewalledRequestAwareRequestDispatcher(path) : super.getRequestDispatcher(path); } @Override public void reset() { this.stripPaths = false; } /** * Ensures {@link FirewalledRequest#reset()} is called prior to performing a forward.
* It then delegates work to the {@link RequestDispatcher} from the original * {@link HttpServletRequest}. * * @author Rob Winch */ private class FirewalledRequestAwareRequestDispatcher implements RequestDispatcher { private final String path; /** * @param path the {@code path} that will be used to obtain the delegate * {@link RequestDispatcher} from the original {@link HttpServletRequest}. */ FirewalledRequestAwareRequestDispatcher(String path) { this.path = path; } @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { reset(); getDelegateDispatcher().forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { getDelegateDispatcher().include(request, response); } private RequestDispatcher getDelegateDispatcher() { return RequestWrapper.super.getRequestDispatcher(this.path); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\RequestWrapper.java
1
请完成以下Java代码
public class TraditionalChineseTokenizer { /** * 预置分词器 */ public static Segment SEGMENT = HanLP.newSegment(); private static List<Term> segSentence(String text) { String sText = CharTable.convert(text); List<Term> termList = SEGMENT.seg(sText); int offset = 0; for (Term term : termList) { term.offset = offset; term.word = text.substring(offset, offset + term.length()); offset += term.length(); } return termList; } public static List<Term> segment(String text) { List<Term> termList = new LinkedList<Term>(); for (String sentence : SentencesUtil.toSentenceList(text)) { termList.addAll(segSentence(sentence)); } return termList; } /** * 分词 * * @param text 文本 * @return 分词结果 */
public static List<Term> segment(char[] text) { return segment(CharTable.convert(text)); } /** * 切分为句子形式 * * @param text 文本 * @return 句子列表 */ public static List<List<Term>> seg2sentence(String text) { List<List<Term>> resultList = new LinkedList<List<Term>>(); { for (String sentence : SentencesUtil.toSentenceList(text)) { resultList.add(segment(sentence)); } } return resultList; } /** * 分词断句 输出句子形式 * * @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\TraditionalChineseTokenizer.java
1
请完成以下Java代码
public void setA_Salvage_Value (BigDecimal A_Salvage_Value) { set_Value (COLUMNNAME_A_Salvage_Value, A_Salvage_Value); } /** Get Salvage Value. @return Salvage Value */ public BigDecimal getA_Salvage_Value () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Salvage_Value); if (bd == null) return Env.ZERO; return bd; } /** Set Asset Depreciation Date. @param AssetDepreciationDate Date of last depreciation */ public void setAssetDepreciationDate (Timestamp AssetDepreciationDate) { set_Value (COLUMNNAME_AssetDepreciationDate, AssetDepreciationDate); } /** Get Asset Depreciation Date. @return Date of last depreciation */ public Timestamp getAssetDepreciationDate () { return (Timestamp)get_Value(COLUMNNAME_AssetDepreciationDate); } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date. @return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Depreciate. @param IsDepreciated The asset will be depreciated */ public void setIsDepreciated (boolean IsDepreciated) { set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated)); } /** Get Depreciate. @return The asset will be depreciated */ public boolean isDepreciated () { Object oo = get_Value(COLUMNNAME_IsDepreciated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Workfile.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringConfig { // @Bean // public DataSource dataSource(){ // return new EmbeddedDatabaseBuilder() // .setType(EmbeddedDatabaseType.H2) // .addScript("classpath:schema.sql") // .addScript("classpath:data.sql") // .build(); // } @Bean public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); } @Bean public JpaVendorAdapter jpaVendorAdapter(){ HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.H2); jpaVendorAdapter.setShowSql(true); jpaVendorAdapter.setGenerateDdl(false); return jpaVendorAdapter; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(){ LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); // localContainerEntityManagerFactoryBean.setDataSource(dataSource()); localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter()); localContainerEntityManagerFactoryBean.setPackagesToScan("spring.jersey.domain"); return localContainerEntityManagerFactoryBean; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringJerseySimple\src\main\java\spring\jersey\SpringConfig.java
2
请完成以下Java代码
private final void expungeStaleEntriesAssumeSync() { ListWeakReference r; while ((r = (ListWeakReference)queue.poll()) != null) { final ListEntry le = r.getListEntry(); final int i = list.indexOf(le); if (i != -1) { list.remove(i); } } } private class ListWeakReference extends WeakReference<T> { private final ListEntry parent; public ListWeakReference(final T value, final ListEntry parent) { super(value, queue); this.parent = parent; } public ListEntry getListEntry() { return this.parent; } } private class ListEntry { final T value; final ListWeakReference weakValue; final boolean isWeak; /** * String representation of "value" (only if isWeak). * * NOTE: this variable is filled only if {@link WeakList#DEBUG} flag is set. */ final String valueStr; public ListEntry(final T value, final boolean isWeak) { if (isWeak) { this.value = null; this.weakValue = new ListWeakReference(value, this); this.isWeak = true; this.valueStr = DEBUG ? String.valueOf(value) : null; } else { this.value = value; this.weakValue = null; this.isWeak = false; this.valueStr = null; } } private boolean isAvailable() { if (isWeak) { return weakValue.get() != null; }
else { return true; } } public T get() { if (isWeak) { return weakValue.get(); } else { return value; } } /** * Always compare by identity. * * @return true if it's the same instance. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } return false; } @Override public int hashCode() { // NOTE: we implemented this method only to get rid of "implemented equals() but not hashCode() warning" return super.hashCode(); } @Override public String toString() { if (!isAvailable()) { return DEBUG ? "<GARBAGED: " + valueStr + ">" : "<GARBAGED>"; } else { return String.valueOf(this.get()); } } } /** * Gets internal lock used by this weak list. * * NOTE: use it only if you know what are you doing. * * @return internal lock used by this weak list. */ public final ReentrantLock getReentrantLock() { return lock; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\WeakList.java
1
请在Spring Boot框架中完成以下Java代码
public class ItemDeprecation { private String reason; private String replacement; private String since; private String level; public ItemDeprecation() { this(null, null, null); } public ItemDeprecation(String reason, String replacement, String since) { this(reason, replacement, since, null); } public ItemDeprecation(String reason, String replacement, String since, String level) { this.reason = reason; this.replacement = replacement; this.since = since; this.level = level; } public String getReason() { return this.reason; } public void setReason(String reason) { this.reason = reason; } public String getReplacement() { return this.replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } public String getSince() { return this.since; } public void setSince(String since) { this.since = since; } public String getLevel() { return this.level; } public void setLevel(String level) { this.level = level; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemDeprecation other = (ItemDeprecation) o; return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement)
&& nullSafeEquals(this.level, other.level) && nullSafeEquals(this.since, other.since); } @Override public int hashCode() { int result = nullSafeHashCode(this.reason); result = 31 * result + nullSafeHashCode(this.replacement); result = 31 * result + nullSafeHashCode(this.level); result = 31 * result + nullSafeHashCode(this.since); return result; } @Override public String toString() { return "ItemDeprecation{reason='" + this.reason + '\'' + ", replacement='" + this.replacement + '\'' + ", level='" + this.level + '\'' + ", since='" + this.since + '\'' + '}'; } private boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return o1.equals(o2); } private int nullSafeHashCode(Object o) { return (o != null) ? o.hashCode() : 0; } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemDeprecation.java
2
请完成以下Spring Boot application配置
# =================================================================== # Spring Boot configuration for the "prod" profile. # # This configuration overrides the application.yml file. # # More information on profiles: https://www.jhipster.tech/profiles/ # More information on configuration properties: https://www.jhipster.tech/common-application-properties/ # =================================================================== # =================================================================== # Standard Spring Boot properties. # Full reference is available at: # http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html # =================================================================== logging: level: ROOT: INFO com.baeldung.jhipster6: INFO io.github.jhipster: INFO spring: devtools: restart: enabled: false livereload: enabled: false datasource: type: com.zaxxer.hikari.HikariDataSource url: jdbc:mysql://localhost:3306/Bookstore?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC username: root password: hikari: poolName: Hikari auto-commit: false data-source-properties: cachePrepStmts: true prepStmtCacheSize: 250 prepStmtCacheSqlLimit: 2048 useServerPrepStmts: true jpa: database-platform: org.hibernate.dialect.MySQL5InnoDBDialect database: MYSQL show-sql: false properties: hibernate.id.new_generator_mappings: true hibernate.connection.provider_disables_autocommit: true hibernate.cache.use_second_level_cache: false hibernate.cache.use_query_cache: false hibernate.generate_statistics: true liquibase: contexts: prod mail: host: localhost port: 25 username: password: thymeleaf: cache: true # =================================================================== # To enable TLS in production, generate a certificate using: # keytool -genkey -alias bookstore -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 # # You can also use Let's Encrypt: # https://maximilian-boehm.com/hp2121/Create-a-Java-Keystore-JKS-from-Let-s-Encrypt-Certificates.htm # # Then, modify the server.ssl properties so your "server" configuration looks like: # # server: # port: 443 # ssl: # key-store: classpath:config/tls/keystore.p12 # key-store-password: password # key-store-type: PKCS12 # key-alias: bookstore # # The ciphers suite enforce the security by deactivating some old and deprecated SSL cipher, this list was tested against SSL Labs (https://www.ssllabs.com/ssltest/) # ciphers: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ,TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA # =================================================================== server: port: 8080 compression: enabled: true mime-types: text/html,text/xml,text/plain,text/css, application/javascript, application/json min-response-size: 1024 # =================================================================== # JHipster specific properties # # Full reference is available at: https://www.jhipster.tech/common-application-properties/ # =================================================================== jhipster: http: version: V_1_1 # To use HTTP/2 you will need SSL support (see above the "server.ssl" configuration) cache: # Used by the CachingHttpHeadersFilter timeToLiveInDays: 1461 security: authentication: jwt:
# This token must be encoded using Base64 and be at least 256 bits long (you can type `openssl rand -base64 64` on your command line to generate a 512 bits one) # As this is the PRODUCTION configuration, you MUST change the default key, and store it securely: # - In the JHipster Registry (which includes a Spring Cloud Config server) # - In a separate `application-prod.yml` file, in the same folder as your executable WAR file # - In the `JHIPSTER_SECURITY_AUTHENTICATION_JWT_BASE64_SECRET` environment variable base64-secret: NDJmOTVlZjI2NzhlZDRjNmVkNTM1NDE2NjkyNDljZDJiNzBlMjI5YmZjMjY3MzdjZmZlMjI3NjE4OTRkNzc5MWYzNDNlYWMzYmJjOWRmMjc5ZWQyZTZmOWZkOTMxZWZhNWE1MTVmM2U2NjFmYjhlNDc2Y2Q3NzliMGY0YzFkNmI= # Token is valid 24 hours token-validity-in-seconds: 86400 token-validity-in-seconds-for-remember-me: 2592000 mail: # specific JHipster mail property, for standard properties see MailProperties from: Bookstore@localhost base-url: http://my-server-url-to-change # Modify according to your server's URL metrics: logs: # Reports metrics in the logs enabled: false report-frequency: 60 # in seconds logging: logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration enabled: false host: localhost port: 5000 queue-size: 512 # =================================================================== # Application specific properties # Add your own application properties here, see the ApplicationProperties class # to have type-safe configuration, like in the JHipsterProperties above # # More documentation is available at: # https://www.jhipster.tech/common-application-properties/ # =================================================================== # application:
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\resources\config\application-prod.yml
2
请在Spring Boot框架中完成以下Java代码
public class XmlRequest { @NonNull String language; /** expecting default = production */ @NonNull XmlMode modus; long validationStatus; @NonNull XmlProcessing processing; @NonNull XmlPayload payload; public XmlRequest withMod(@Nullable final RequestMod requestMod) { if (requestMod == null) { return this; } final XmlRequestBuilder builder = toBuilder(); if (requestMod.getModus() != null) {
builder.modus(requestMod.getModus()); } return builder .processing(processing.withMod(requestMod.getProcessingMod())) .payload(payload.withMod(requestMod.getPayloadMod())) .build(); } @Value @Builder public static class RequestMod { @Nullable XmlMode modus; @Nullable PayloadMod payloadMod; @Nullable ProcessingMod processingMod; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\XmlRequest.java
2
请完成以下Java代码
public String getTableName() { String modelTableName = _modelTableName; if (modelTableName == null) { modelTableName = _modelTableName = InterfaceWrapperHelper.getTableName(modelClass); } return modelTableName; } /** * @return function which gets the column value from model. */ public final <ValueType> Function<MT, ValueType> asValueFunction() { // NOTE: we are returning a new instance each time, because this method is not used so offen // and because storing an instace for each ModelColumn will consume way more memory. final Function<MT, Object> valueFunction = new ValueFunction(); @SuppressWarnings("unchecked") final Function<MT, ValueType> valueFunctionCasted = (Function<MT, ValueType>)valueFunction; return valueFunctionCasted; } /** * Function which gets the Value of this model column.
* * @author tsa */ private final class ValueFunction implements Function<MT, Object> { @Override public Object apply(final MT model) { final Object value = InterfaceWrapperHelper.getValue(model, columnName).orElse(null); return value; } @Override public String toString() { return "ValueFunction[" + modelClass + " -> " + columnName + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\ModelColumn.java
1
请完成以下Java代码
public @Nullable DataSize getSize() { return size; } public void setSize(DataSize size) { this.size = size; } public Duration getTimeToLive() { if (timeToLive == null) { LOGGER.debug(String.format( "No TTL configuration found. Default TTL will be applied for cache entries: %s minutes", DEFAULT_CACHE_TTL_MINUTES)); return DEFAULT_CACHE_TTL_MINUTES; } else { return timeToLive; } } public void setTimeToLive(Duration timeToLive) { this.timeToLive = timeToLive; } public RequestOptions getRequest() { return request; } public void setRequest(RequestOptions request) { this.request = request; } @Override public String toString() { return "LocalResponseCacheProperties{" + "size=" + size + ", timeToLive=" + timeToLive + ", request=" + request + '}'; } public static class RequestOptions { private NoCacheStrategy noCacheStrategy = NoCacheStrategy.SKIP_UPDATE_CACHE_ENTRY; public NoCacheStrategy getNoCacheStrategy() { return noCacheStrategy; }
public void setNoCacheStrategy(NoCacheStrategy noCacheStrategy) { this.noCacheStrategy = noCacheStrategy; } @Override public String toString() { return "RequestOptions{" + "noCacheStrategy=" + noCacheStrategy + '}'; } } /** * When client sends "no-cache" directive in "Cache-Control" header, the response * should be re-validated from upstream. There are several strategies that indicates * what to do with the new fresh response. */ public enum NoCacheStrategy { /** * Update the cache entry by the fresh response coming from upstream with a new * time to live. */ UPDATE_CACHE_ENTRY, /** * Skip the update. The client will receive the fresh response, other clients will * receive the old entry in cache. */ SKIP_UPDATE_CACHE_ENTRY } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheProperties.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isClosed(@NonNull final ProjectId projectId) { final I_C_Project projectRecord = getById(projectId); return projectRecord.isProcessed(); } public void closeProject(@NonNull final ProjectId projectId) { final I_C_Project projectRecord = getById(projectId); if (projectRecord.isProcessed()) { throw new AdempiereException("Project already closed: " + projectId); } projectStatusListeners.onBeforeClose(projectRecord); projectLineRepository.markLinesAsProcessed(projectId); projectRecord.setProcessed(true); InterfaceWrapperHelper.saveRecord(projectRecord); projectStatusListeners.onAfterClose(projectRecord); } public void uncloseProject(@NonNull final ProjectId projectId) { final I_C_Project projectRecord = getById(projectId);
if (!projectRecord.isProcessed()) { throw new AdempiereException("Project not closed: " + projectId); } projectStatusListeners.onBeforeUnClose(projectRecord); projectLineRepository.markLinesAsNotProcessed(projectId); projectRecord.setProcessed(false); InterfaceWrapperHelper.saveRecord(projectRecord); projectStatusListeners.onAfterUnClose(projectRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\ProjectService.java
2
请完成以下Java代码
public void setValue(final Object key, final Object value) { final String sysconfigName = createSysConfigName(key); try { final String sysconfigValue = serializer.toString(value); saveSysConfig(sysconfigName, sysconfigValue); } catch (Exception e) { logger.error("Failed saving " + sysconfigName + ": " + value, e); } } private void saveSysConfig(final String sysconfigName, final String sysconfigValue) { if (!DB.isConnected()) { logger.warn("DB not connected. Cannot write: " + sysconfigName + "=" + sysconfigValue); return; } developerModeBL.executeAsSystem(new ContextRunnable() { @Override public void run(Properties sysCtx) { sysConfigBL.setValue(sysconfigName, sysconfigValue, ClientId.SYSTEM, OrgId.ANY); } }); } private String createSysConfigName(Object key) { return createSysConfigPrefix() + "." + key.toString(); } private String createSysConfigPrefix() { return SYSCONFIG_PREFIX + lookAndFeelId; } public void loadAllFromSysConfigTo(final UIDefaults uiDefaults) { if (!DB.isConnected()) {
return; } final String prefix = createSysConfigPrefix() + "."; final boolean removePrefix = true; final Properties ctx = Env.getCtx(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx)); final Map<String, String> map = sysConfigBL.getValuesForPrefix(prefix, removePrefix, clientAndOrgId); for (final Map.Entry<String, String> mapEntry : map.entrySet()) { final String key = mapEntry.getKey(); final String valueStr = mapEntry.getValue(); try { final Object value = serializer.fromString(valueStr); uiDefaults.put(key, value); } catch (Exception ex) { logger.warn("Failed loading " + key + ": " + valueStr + ". Skipped.", ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SysConfigUIDefaultsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class MyUser { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; private int age; public MyUser() { super(); } public MyUser(final String firstName, final String lastName, final String email, final int age) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.age = age; } // public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) {
this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(final String username) { email = username; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MyUser user = (MyUser) obj; if (!email.equals(user.email)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("MyUser [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\model\MyUser.java
2
请完成以下Java代码
public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
public boolean isAllRolesContainingGroup() { return type == RecipientType.AllRolesContainingGroup; } public UserId getUserId() { if (type != RecipientType.User) { throw new AdempiereException("UserId not available: " + this); } return userId; } public UserGroupId getGroupId() { if (type != RecipientType.Group) { throw new AdempiereException("UserGroupId not available: " + this); } return groupId; } public boolean isRoleIdSet() {
return roleId != null; } @NonNull public RoleId getRoleId() { return Check.assumeNotNull(roleId, "roleId is set for {}", this); } public NotificationGroupName getNotificationGroupName() { if (type != RecipientType.AllRolesContainingGroup) { throw new AdempiereException("NotificationGroupName not available: " + this); } return notificationGroupName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\Recipient.java
1
请在Spring Boot框架中完成以下Java代码
public String getTunnelRestrictionCode() { return tunnelRestrictionCode; } /** * Sets the value of the tunnelRestrictionCode property. * * @param value * allowed object is * {@link String } * */ public void setTunnelRestrictionCode(String value) { this.tunnelRestrictionCode = value; } /** * Gets the value of the hazardousWeight property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getHazardousWeight() { return hazardousWeight; } /** * Sets the value of the hazardousWeight property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setHazardousWeight(BigDecimal value) { this.hazardousWeight = value; } /** * Gets the value of the netWeight property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getNetWeight() { return netWeight; } /** * Sets the value of the netWeight property. * * @param value * allowed object is
* {@link BigDecimal } * */ public void setNetWeight(BigDecimal value) { this.netWeight = value; } /** * Gets the value of the factor property. * */ public int getFactor() { return factor; } /** * Sets the value of the factor property. * */ public void setFactor(int value) { this.factor = value; } /** * Gets the value of the notOtherwiseSpecified property. * * @return * possible object is * {@link String } * */ public String getNotOtherwiseSpecified() { return notOtherwiseSpecified; } /** * Sets the value of the notOtherwiseSpecified property. * * @param value * allowed object is * {@link String } * */ public void setNotOtherwiseSpecified(String value) { this.notOtherwiseSpecified = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Hazardous.java
2
请完成以下Java代码
public String getType() { return Batch.TYPE_PROCESS_INSTANCE_RESTART; } @Override protected void postProcessJob(RestartProcessInstancesBatchConfiguration configuration, JobEntity job, RestartProcessInstancesBatchConfiguration jobConfiguration) { if (job.getDeploymentId() == null) { CommandContext commandContext = Context.getCommandContext(); ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessEngineConfiguration().getDeploymentCache() .findDeployedProcessDefinitionById(configuration.getProcessDefinitionId()); job.setDeploymentId(processDefinitionEntity.getDeploymentId()); } } @Override public void executeHandler(RestartProcessInstancesBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { String processDefinitionId = batchConfiguration.getProcessDefinitionId(); RestartProcessInstanceBuilderImpl builder = new RestartProcessInstanceBuilderImpl(processDefinitionId); builder.processInstanceIds(batchConfiguration.getIds()); builder.setInstructions(batchConfiguration.getInstructions()); if (batchConfiguration.isInitialVariables()) { builder.initialSetOfVariables(); } if (batchConfiguration.isSkipCustomListeners()) { builder.skipCustomListeners();
} if (batchConfiguration.isWithoutBusinessKey()) { builder.withoutBusinessKey(); } if (batchConfiguration.isSkipIoMappings()) { builder.skipIoMappings(); } CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration() .getCommandExecutorTxRequired(); commandContext.executeWithOperationLogPrevented( new RestartProcessInstancesCmd(commandExecutor, builder)); } @Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected RestartProcessInstancesBatchConfiguration createJobConfiguration(RestartProcessInstancesBatchConfiguration configuration, List<String> processIdsForJob) { return new RestartProcessInstancesBatchConfiguration(processIdsForJob, configuration.getInstructions(), configuration.getProcessDefinitionId(), configuration.isInitialVariables(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings(), configuration.isWithoutBusinessKey()); } @Override protected RestartProcessInstancesBatchConfigurationJsonConverter getJsonConverterInstance() { return RestartProcessInstancesBatchConfigurationJsonConverter.INSTANCE; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstancesJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public static class Livereload { /** * Whether to enable a livereload.com-compatible server. */ private boolean enabled; /** * Server port. */ private int port = 35729; public boolean isEnabled() { return this.enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
2
请完成以下Java代码
public String getMessageName() { return messageName; } public void setMessageName(String messageName) { this.messageName = messageName; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto runtimeQuery) { this.processInstanceQuery = runtimeQuery;
} public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historyQuery) { this.historicProcessInstanceQuery = historyQuery; } public Map<String, VariableValueDto> getVariables() { return variables; } public void setVariables(Map<String, VariableValueDto> variables) { this.variables = variables; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\batch\CorrelationMessageAsyncDto.java
1
请完成以下Java代码
public void setC_Currency_To(org.compiere.model.I_C_Currency C_Currency_To) { set_ValueFromPO(COLUMNNAME_C_Currency_ID_To, org.compiere.model.I_C_Currency.class, C_Currency_To); } /** Set Zielwährung. @param C_Currency_ID_To Target currency */ @Override public void setC_Currency_ID_To (int C_Currency_ID_To) { set_Value (COLUMNNAME_C_Currency_ID_To, Integer.valueOf(C_Currency_ID_To)); } /** Get Zielwährung. @return Target currency */ @Override public int getC_Currency_ID_To () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID_To); if (ii == null) return 0; return ii.intValue(); } /** Set Divisor. @param DivideRate To convert Source number to Target number, the Source is divided */ @Override public void setDivideRate (java.math.BigDecimal DivideRate) { set_Value (COLUMNNAME_DivideRate, DivideRate); } /** Get Divisor. @return To convert Source number to Target number, the Source is divided */ @Override public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return Env.ZERO; return bd; } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return Env.ZERO; return bd; } /** Set Gültig ab. @param ValidFrom Valid from including this date (first day) */ @Override
public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Valid from including this date (first day) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Valid to including this date (last day) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Valid to including this date (last day) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Conversion_Rate.java
1
请完成以下Java代码
public void setUp() { for (long i = 0; i < iterations; i++) { employeeList.add(new Employee(i, "John")); employeeVector.add(new Employee(i, "John")); } employeeList.add(employee); employeeVector.add(employee); employeeIndex = employeeList.indexOf(employee); } } @Benchmark public void testAddAt(ArrayListBenchmark.MyState state) { state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); } @Benchmark public boolean testContains(ArrayListBenchmark.MyState state) { return state.employeeList.contains(state.employee); } @Benchmark public boolean testContainsVector(ArrayListBenchmark.MyState state) { return state.employeeVector.contains(state.employee); } @Benchmark public int testIndexOf(ArrayListBenchmark.MyState state) { return state.employeeList.indexOf(state.employee); } @Benchmark public Employee testGet(ArrayListBenchmark.MyState state) { return state.employeeList.get(state.employeeIndex); } @Benchmark public Employee testVectorGet(ArrayListBenchmark.MyState state) { return state.employeeVector.get(state.employeeIndex);
} @Benchmark public boolean testRemove(ArrayListBenchmark.MyState state) { return state.employeeList.remove(state.employee); } @Benchmark public void testAdd(ArrayListBenchmark.MyState state) { state.employeeList.add(new Employee(state.iterations + 1, "John")); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(ArrayListBenchmark.class.getSimpleName()).threads(3) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-3\src\main\java\com\baeldung\collections\arraylistvsvector\ArrayListBenchmark.java
1
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getWords() {
return words; } public void setWords(String words) { this.words = words; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
repos\tutorials-master\web-modules\java-lite\src\main\java\app\models\Article.java
1
请完成以下Java代码
public void announcementAutoRelease(String dataId, String currentUserName) { } @Override public SysDepartModel queryCompByOrgCode(String orgCode) { return null; } @Override public SysDepartModel queryCompByOrgCodeAndLevel(String orgCode, Integer level) { return null; } @Override public Object runAiragFlow(AiragFlowDTO airagFlowDTO) { return null;
} @Override public void uniPushMsgToUser(PushMessageDTO pushMessageDTO) { } @Override public String getDepartPathNameByOrgCode(String orgCode, String depId) { return ""; } @Override public List<String> queryUserIdsByCascadeDeptIds(List<String> deptIds) { return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\system\api\fallback\SysBaseAPIFallback.java
1
请在Spring Boot框架中完成以下Java代码
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (null == configAttributes || 0 >= configAttributes.size()) { return; } else { String needRole; for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) { needRole = iter.next().getAttribute(); for(GrantedAuthority ga : authentication.getAuthorities()) { if(needRole.trim().equals(ga.getAuthority().trim())) { return; } } } throw new AccessDeniedException("当前访问没有权限"); } } /** * 表示此AccessDecisionManager是否能够处理传递的ConfigAttribute呈现的授权请求
*/ @Override public boolean supports(ConfigAttribute configAttribute) { return true; } /** * 表示当前AccessDecisionManager实现是否能够为指定的安全对象(方法调用或Web请求)提供访问控制决策 */ @Override public boolean supports(Class<?> aClass) { return true; } }
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyAccessDecisionManager.java
2
请完成以下Java代码
public final class GlobalQRCodeParseResult { @Nullable GlobalQRCode globalQRCode; @Nullable String error; public static GlobalQRCodeParseResult error(@NonNull final String error) { Check.assumeNotEmpty(error, "error is not empty"); return new GlobalQRCodeParseResult(null, error); } public static GlobalQRCodeParseResult ok(@NonNull final GlobalQRCode globalQRCode) { return new GlobalQRCodeParseResult(globalQRCode, null); } public GlobalQRCodeParseResult(@Nullable final GlobalQRCode globalQRCode, @Nullable final String error) { if (CoalesceUtil.countNotNulls(globalQRCode, error) != 1) { throw Check.mkEx("One and only one shall be specified: " + globalQRCode + ", " + error); }
this.globalQRCode = globalQRCode; this.error = error; } public GlobalQRCode orThrow() { if (globalQRCode == null) { throw Check.mkEx(error); } else { return globalQRCode; } } public GlobalQRCode orNullIfError() { return globalQRCode; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCodeParseResult.java
1
请完成以下Java代码
public UserInfo grant(TokenParameter tokenParameter) { String tenantId = tokenParameter.getArgs().getStr("tenantId"); String account = tokenParameter.getArgs().getStr("account"); String password = tokenParameter.getArgs().getStr("password"); // 判断账号和IP是否锁定 TokenUtil.checkAccountAndIpLock(bladeRedis, tenantId, account); UserInfo userInfo = null; if (Func.isNoneBlank(account, password)) { // 获取用户类型 String userType = tokenParameter.getArgs().getStr("userType"); // 解密密码 String decryptPassword = TokenUtil.decryptPassword(password, authProperties.getPublicKey(), authProperties.getPrivateKey()); // 定义返回结果 R<UserInfo> result; // 根据不同用户类型调用对应的接口返回数据,用户可自行拓展 if (userType.equals(BladeUserEnum.WEB.getName())) { result = userClient.userInfo(tenantId, account, DigestUtil.encrypt(decryptPassword)); } else if (userType.equals(BladeUserEnum.APP.getName())) { result = userClient.userInfo(tenantId, account, DigestUtil.encrypt(decryptPassword)); } else { result = userClient.userInfo(tenantId, account, DigestUtil.encrypt(decryptPassword)); } userInfo = result.isSuccess() ? result.getData() : null;
} if (userInfo == null || userInfo.getUser() == null) { // 处理登录失败 TokenUtil.handleLoginFailure(bladeRedis, tenantId, account); log.error("用户登录失败, 账号:{}, IP:{}", account, WebUtil.getIP()); throw new ServiceException(TokenUtil.USER_NOT_FOUND); } else { // 处理登录成功 TokenUtil.handleLoginSuccess(bladeRedis, tenantId, account); } return userInfo; } }
repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\granter\PasswordTokenGranter.java
1
请完成以下Java代码
public String toString() { return "Letter{" + "returningAddress='" + returningAddress + '\'' + ", insideAddress='" + insideAddress + '\'' + ", dateOfLetter=" + dateOfLetter + ", salutation='" + salutation + '\'' + ", body='" + body + '\'' + ", closing='" + closing + '\'' + '}'; } static Letter createLetter(String salutation, String body) { return new Letter(salutation, body); } static BiFunction<String, String, Letter> SIMPLE_LETTER_CREATOR = // (salutation, body) -> new Letter(salutation, body); static Function<String, Function<String, Letter>> SIMPLE_CURRIED_LETTER_CREATOR = // saluation -> body -> new Letter(saluation, body); static Function<String, Function<String, Function<LocalDate, Function<String, Function<String, Function<String, Letter>>>>>> LETTER_CREATOR = // returnAddress -> closing -> dateOfLetter -> insideAddress -> salutation -> body -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); static AddReturnAddress builder() { return returnAddress -> closing -> dateOfLetter
-> insideAddress -> salutation -> body -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); } interface AddReturnAddress { Letter.AddClosing withReturnAddress(String returnAddress); } interface AddClosing { Letter.AddDateOfLetter withClosing(String closing); } interface AddDateOfLetter { Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter); } interface AddInsideAddress { Letter.AddSalutation withInsideAddress(String insideAddress); } interface AddSalutation { Letter.AddBody withSalutation(String salutation); } interface AddBody { Letter withBody(String body); } }
repos\tutorials-master\patterns-modules\design-patterns-functional\src\main\java\com\baeldung\currying\Letter.java
1
请完成以下Java代码
public KerberosTicketValidation run() throws Exception { byte[] responseToken = new byte[0]; GSSName gssName = null; GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null); while (!context.isEstablished()) { responseToken = context.acceptSecContext(this.kerberosTicket, 0, this.kerberosTicket.length); gssName = context.getSrcName(); if (gssName == null) { throw new BadCredentialsException("GSSContext name of the context initiator is null"); } } GSSCredential delegationCredential = null; if (context.getCredDelegState()) { delegationCredential = context.getDelegCred(); } if (!SunJaasKerberosTicketValidator.this.holdOnToGSSContext) { context.dispose(); } return new KerberosTicketValidation(gssName.toString(), SunJaasKerberosTicketValidator.this.servicePrincipal, responseToken, context, delegationCredential); } } /** * Normally you need a JAAS config file in order to use the JAAS Kerberos Login * Module, with this class it is not needed and you can have different configurations * in one JVM. */ private static final class LoginConfig extends Configuration { private String keyTabLocation; private String servicePrincipalName; private String realmName; private boolean multiTier; private boolean debug; private boolean refreshKrb5Config; private LoginConfig(String keyTabLocation, String servicePrincipalName, String realmName, boolean multiTier,
boolean debug, boolean refreshKrb5Config) { this.keyTabLocation = keyTabLocation; this.servicePrincipalName = servicePrincipalName; this.realmName = realmName; this.multiTier = multiTier; this.debug = debug; this.refreshKrb5Config = refreshKrb5Config; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { HashMap<String, String> options = new HashMap<String, String>(); options.put("useKeyTab", "true"); options.put("keyTab", this.keyTabLocation); options.put("principal", this.servicePrincipalName); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); if (this.debug) { options.put("debug", "true"); } if (this.realmName != null) { options.put("realm", this.realmName); } if (this.refreshKrb5Config) { options.put("refreshKrb5Config", "true"); } if (!this.multiTier) { options.put("isInitiator", "false"); } return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), }; } } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\SunJaasKerberosTicketValidator.java
1
请完成以下Java代码
public boolean isReadable() { return isReadable; } public void setReadable(boolean isReadable) { this.isReadable = isReadable; } public boolean isRequired() { return isRequired; } public void setRequired(boolean isRequired) { this.isRequired = isRequired; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; }
public Expression getVariableExpression() { return variableExpression; } public void setVariableExpression(Expression variableExpression) { this.variableExpression = variableExpression; } public Expression getDefaultExpression() { return defaultExpression; } public void setDefaultExpression(Expression defaultExpression) { this.defaultExpression = defaultExpression; } public boolean isWritable() { return isWritable; } public void setWritable(boolean isWritable) { this.isWritable = isWritable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\FormPropertyHandler.java
1
请完成以下Java代码
public Object getModelValueAt(int rowIndexModel, int columnIndexModel) { return getModel().getValueAt(rowIndexModel, columnIndexModel); } private ITableColorProvider colorProvider = new DefaultTableColorProvider(); @Override public void setColorProvider(final ITableColorProvider colorProvider) { Check.assumeNotNull(colorProvider, "colorProvider not null"); this.colorProvider = colorProvider; } @Override public ITableColorProvider getColorProvider() { return colorProvider; } @Override public void setModel(final TableModel dataModel) { super.setModel(dataModel); if (modelRowSorter == null) { // i.e. we are in JTable constructor and modelRowSorter was not yet set // => do nothing
} else if (!modelRowSorter.isEnabled()) { setupViewRowSorter(); } } private final void setupViewRowSorter() { final TableModel model = getModel(); viewRowSorter.setModel(model); if (modelRowSorter != null) { viewRowSorter.setSortKeys(modelRowSorter.getSortKeys()); } setRowSorter(viewRowSorter); viewRowSorter.sort(); } } // CTable
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTable.java
1
请完成以下Java代码
public static void disconnect(Channel channel) { if (channel != null) { if (channel.isConnected()) { try { channel.disconnect(); log.info("channel is closed already"); } catch (Exception e) { log.error("JSch channel disconnect error:", e); } } } } public static int checkAck(InputStream in) throws IOException { int b = in.read(); // b may be 0 for success, // 1 for error, // 2 for fatal error, // -1 if (b == 0) { return b; } if (b == -1) { return b; } if (b == 1 || b == 2) { StringBuilder sb = new StringBuilder(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1) { // error log.debug(sb.toString()); } if (b == 2) { // fatal error log.debug(sb.toString()); }
} return b; } public static void closeInputStream(InputStream in) { if (in != null) { try { in.close(); } catch (IOException e) { log.error("Close input stream error." + e.getMessage()); } } } public static void closeOutputStream(OutputStream out) { if (out != null) { try { out.close(); } catch (IOException e) { log.error("Close output stream error." + e.getMessage()); } } } }
repos\springboot-demo-master\JSch\src\main\java\com\et\jsch\util\JSchUtil.java
1
请完成以下Java代码
public ModificationBuilder processInstanceQuery(ProcessInstanceQuery processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; return this; } @Override public ModificationBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; return this; } @Override public ModificationBuilder skipCustomListeners() { this.skipCustomListeners = true; return this; } @Override public ModificationBuilder skipIoMappings() { this.skipIoMappings = true; return this; } @Override public ModificationBuilder setAnnotation(String annotation) { this.annotation = annotation; return this; } public void execute(boolean writeUserOperationLog) { commandExecutor.execute(new ProcessInstanceModificationCmd(this, writeUserOperationLog)); } @Override public void execute() { execute(true); } @Override public Batch executeAsync() { return commandExecutor.execute(new ProcessInstanceModificationBatchCmd(this)); } public CommandExecutor getCommandExecutor() { return commandExecutor; } public ProcessInstanceQuery getProcessInstanceQuery() { return processInstanceQuery; } public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public String getProcessDefinitionId() { return processDefinitionId; }
public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public List<AbstractProcessInstanceModificationCommand> getInstructions() { return instructions; } public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) { this.instructions = instructions; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; } public String getAnnotation() { return annotation; } public void setAnnotationInternal(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBuilderImpl.java
1
请完成以下Java代码
public void beforeReverseCorrect(final I_M_Inventory inventoryRecord) { if (!inventoryService.isMaterialDisposal(inventoryRecord)) { // NOTE we check only for regular iventories because in case of internal use/material disposal this is not reliable // the problem shall be fixed for good in another task. assertLastHUTrxWasThisInventory(inventoryRecord); } } private void assertLastHUTrxWasThisInventory(final I_M_Inventory inventoryRecord) { final Inventory inventory = inventoryService.toInventory(inventoryRecord); inventory.getLines().forEach(this::assertLastHUTrxWasThisInventoryLine); } private void assertLastHUTrxWasThisInventoryLine(@NonNull final InventoryLine line) { line.getInventoryLineHUs().forEach(hu -> assertLastHUTrxWasThisInventoryLine(line, hu)); } private void assertLastHUTrxWasThisInventoryLine(@NonNull final InventoryLine line, @NonNull final InventoryLineHU lineHU) { final HuId huId = Objects.requireNonNull(lineHU.getHuId()); final InventoryLineId lineId = Objects.requireNonNull(line.getId()); if (!huTransactionBL.isLatestHUTrx(huId, TableRecordReference.of(I_M_InventoryLine.Table_Name, lineId))) { throw new HUException("@InventoryReverseError@") .setParameter("line", line) .setParameter("lineHU", lineHU); } } @DocValidate(timings = ModelValidator.TIMING_AFTER_REVERSECORRECT) public void afterReverseCorrect(final I_M_Inventory inventory) { if (inventoryService.isMaterialDisposal(inventory)) { restoreHUsFromSnapshots(inventory); reverseEmptiesMovements(inventory); }
} private void restoreHUsFromSnapshots(final I_M_Inventory inventory) { final String snapshotId = inventory.getSnapshot_UUID(); if (Check.isBlank(snapshotId)) { throw new HUException("@NotFound@ @Snapshot_UUID@ (" + inventory + ")"); } final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID()); final List<Integer> topLevelHUIds = inventoryDAO.retrieveLinesForInventoryId(inventoryId, I_M_InventoryLine.class) .stream() .map(I_M_InventoryLine::getM_HU_ID) .collect(ImmutableList.toImmutableList()); huSnapshotDAO.restoreHUs() .setContext(PlainContextAware.newWithThreadInheritedTrx()) .setSnapshotId(snapshotId) .setDateTrx(inventory.getMovementDate()) .addModelIds(topLevelHUIds) .setReferencedModel(inventory) .restoreFromSnapshot(); } private void reverseEmptiesMovements(final I_M_Inventory inventory) { final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID()); movementDAO.retrieveMovementsForInventoryQuery(inventoryId) .addEqualsFilter(I_M_Inventory.COLUMNNAME_DocStatus, X_M_Inventory.DOCSTATUS_Completed) .create() .stream() .forEach(emptiesMovement -> documentBL.processEx(emptiesMovement, X_M_Movement.DOCACTION_Reverse_Correct, X_M_Movement.DOCSTATUS_Reversed)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\interceptor\M_Inventory.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataObject.class, BPMN_ELEMENT_DATA_OBJECT) .namespaceUri(BPMN20_NS) .extendsType(FlowElement.class) .instanceProvider(new ModelTypeInstanceProvider<DataObject>() { public DataObject newInstance(ModelTypeInstanceContext instanceContext) { return new DataObjectImpl(instanceContext); } }); itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF) .qNameAttributeReference(ItemDefinition.class) .build(); isCollectionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_COLLECTION) .defaultValue(false) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); dataStateChild = sequenceBuilder.element(DataState.class) .build(); typeBuilder.build(); } public DataObjectImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } @Override public ItemDefinition getItemSubject() { return itemSubjectRefAttribute.getReferenceTargetElement(this); } @Override
public void setItemSubject(ItemDefinition itemSubject) { itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject); } @Override public DataState getDataState() { return dataStateChild.getChild(this); } @Override public void setDataState(DataState dataState) { dataStateChild.setChild(this, dataState); } @Override public boolean isCollection() { return isCollectionAttribute.getValue(this); } @Override public void setCollection(boolean isCollection) { isCollectionAttribute.setValue(this, isCollection); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataObjectImpl.java
1
请完成以下Java代码
public void invalidateAll() { cachesByTableName.values().forEach(IDCache::reset); cachesByTableName.clear(); if (logger.isTraceEnabled()) { logger.trace("Cleared all caches for trx={} ", trxName); } } public void invalidateByTableName(final String tableName) { final IDCache<PO> cache = getByTableNameIfExists(tableName); if (cache == null) { return; } // Invalidate the cache cache.reset(); // Logging if (logger.isTraceEnabled()) { logger.trace("Cleared cache {} for tableName={}, trx={} ", cache.getCacheName(), tableName, trxName); } } public void invalidateByRecord(final TableRecordReference recordRef) { final String tableName = recordRef.getTableName(); final int recordId = recordRef.getRecord_ID(); // // Get table's cache map. final IDCache<PO> cache = getByTableNameIfExists(tableName); if (cache == null) { return; } // Invalidate the cache final boolean invalidated = cache.remove(recordId) != null; // Logging if (invalidated && logger.isTraceEnabled()) {
logger.trace("Model removed from cache {}: record={}/{}, trx={} ", cache.getCacheName(), tableName, recordId, trxName); } } public void put(@NonNull final PO po, @NonNull final ITableCacheConfig cacheConfig) { // // Get table's cache map. // If does not exist, create one. final IDCache<PO> cache = getByTableNameOrCreate(cacheConfig); // // Add our PO to cache final int recordId = po.get_ID(); final PO poCopy = copyPO(po, trxName); if (poCopy == null) { logger.warn("Failed to add {} to cache because copy failed. Ignored.", po); return; } cache.put(recordId, poCopy); // Logging if (logger.isTraceEnabled()) { logger.trace("Model added to cache {}: {} ", cache.getCacheName(), poCopy); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\ModelCacheService.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<Long> publishArticle(Article article) { try { article = articleRepo.save(article); auditRepo.save(new Audit("SAVE_ARTICLE", "SUCCESS", "saved: " + article.getTitle())); return Optional.of(article.getId()); } catch (Exception e) { String errMsg = "failed to save: %s, err: %s".formatted(article.getTitle(), e.getMessage()); auditRepo.save(new Audit("SAVE_ARTICLE", "FAILURE", errMsg)); return Optional.empty(); } } @Transactional public Optional<Long> publishArticle_v2(Article article) { try { article = articleRepo.save(article); auditService.saveAudit("SAVE_ARTICLE", "SUCCESS", "saved: " + article.getTitle()); return Optional.of(article.getId()); } catch (Exception e) { auditService.saveAudit("SAVE_ARTICLE", "FAILURE", "failed to save: " + article.getTitle());
return Optional.empty(); } } public Optional<Long> publishArticle_v3(final Article article) { try { Article savedArticle = transactionTemplate.execute(txStatus -> { Article saved = articleRepo.save(article); auditRepo.save(new Audit("SAVE_ARTICLE", "SUCCESS", "saved: " + article.getTitle())); return saved; }); return Optional.of(savedArticle.getId()); } catch (Exception e) { auditRepo.save( new Audit("SAVE_ARTICLE", "FAILURE", "failed to save: " + article.getTitle())); return Optional.empty(); } } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\rollbackonly\Blog.java
2
请完成以下Java代码
public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement statement = (MappedStatement) args[0]; String sql = statement.getBoundSql(args[1]).getSql(); System.out.println("--------intercept method: " + statement.getId() + "\n-----sql: " + sql + "\n------args: " + JSON.toJSONString(args[1])); //执行目标方法 return invocation.proceed(); } /** * 包装目标对象:为目标对象创建一个代理对象 * * @param target * @return */
@Override public Object plugin(Object target) { return Plugin.wrap(target, this); } /** * 将插件注册时的properties属性设置进来 * * @param properties */ @Override public void setProperties(Properties properties) { System.out.println("插件配置的信息 = " + properties); } }
repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\mybatis\EditPlugin.java
1
请完成以下Java代码
public String getSummary() { StringBuilder sb = new StringBuilder(); sb.append(getDocumentNo()); if (m_lines != null) { sb.append(" (#").append(m_lines.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()); } @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg @Override public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID @Override public BigDecimal getApprovalAmt()
{ // TODO Auto-generated method stub return null; } @Override public int getC_Currency_ID() { // TODO Auto-generated method stub return 0; } /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { final String docStatus = getDocStatus(); return DOCSTATUS_Completed.equals(docStatus) || DOCSTATUS_Closed.equals(docStatus) || DOCSTATUS_Reversed.equals(docStatus); } } // MDDOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\model\MDDOrder.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<JsonRequestBPartnerUpsertItem> mapPartnerToRequestItem(@NonNull final BPartnerRow partnerRow) { return mapPartnerToJsonRequest(partnerRow) .map(jsonRequestComposite -> JsonRequestBPartnerUpsertItem.builder() .bpartnerIdentifier(ExternalId.ofId(partnerRow.getBpartnerIdentifier()).toExternalIdentifierString()) .bpartnerComposite(jsonRequestComposite) .build()); } @NonNull private Optional<JsonRequestComposite> mapPartnerToJsonRequest(@NonNull final BPartnerRow partnerRow) { if (hasMissingFields(partnerRow)) { pInstanceLogger.logMessage("Skipping row due to missing mandatory information, see row: " + partnerRow); return Optional.empty(); } final JsonRequestComposite composite = JsonRequestComposite.builder() .orgCode(externalSystemRequest.getOrgCode()) .bpartner(getBPartnerRequest(partnerRow)) .locations(getBPartnerLocationRequest(partnerRow)) .build(); return Optional.of(composite); } @NonNull private JsonRequestBPartner getBPartnerRequest(@NonNull final BPartnerRow partnerRow) { final JsonRequestBPartner bPartner = new JsonRequestBPartner(); bPartner.setCode(partnerRow.getValue()); bPartner.setName(partnerRow.getName()); bPartner.setCompanyName(partnerRow.getName()); return bPartner; } @NonNull private JsonRequestLocationUpsert getBPartnerLocationRequest(@NonNull final BPartnerRow partnerRow)
{ final JsonRequestLocation location = new JsonRequestLocation(); location.setAddress1(StringUtils.trimBlankToNull(partnerRow.getAddress1())); location.setCity(StringUtils.trimBlankToNull(partnerRow.getCity())); location.setPostal(StringUtils.trimBlankToNull(partnerRow.getPostalCode())); location.setCountryCode(DEFAULT_COUNTRY_CODE); location.setBillToDefault(true); location.setShipToDefault(true); return JsonRequestLocationUpsert.builder() .requestItem(JsonRequestLocationUpsertItem.builder() .locationIdentifier(ExternalId.ofId(partnerRow.getBpartnerIdentifier()).toExternalIdentifierString()) .location(location) .build()) .build(); } private static boolean hasMissingFields(@NonNull final BPartnerRow row) { return Check.isBlank(row.getBpartnerIdentifier()) || Check.isBlank(row.getName()) || Check.isBlank(row.getValue()); } @NonNull private static JsonRequestBPartnerUpsert wrapUpsertItem(@NonNull final JsonRequestBPartnerUpsertItem upsertItem) { return JsonRequestBPartnerUpsert.builder() .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .requestItems(ImmutableList.of(upsertItem)) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\bpartner\BPartnerUpsertProcessor.java
2
请完成以下Java代码
public boolean isAssociated( final I_C_Invoice_Candidate ic, final IInvoiceLineRW il) { return isAssociated(ic.getC_Invoice_Candidate_ID(), il); } private boolean isAssociated( final int icId, final IInvoiceLineRW il) { return candIdAndLine2AllocatedQty.containsKey(icId) && candIdAndLine2AllocatedQty.get(icId).containsKey(il); } @Override public StockQtyAndUOMQty getAllocatedQty(@NonNull final I_C_Invoice_Candidate ic, @NonNull final IInvoiceLineRW il) { return getAllocatedQty(ic, ic.getC_Invoice_Candidate_ID(), il); } /** * This method does the actual work for {@link #getAllocatedQty(I_C_Invoice_Candidate, IInvoiceLineRW)}. For an explanation of why the method is here, see * {@link #addAssociation(I_C_Invoice_Candidate, int, IInvoiceLineRW, StockQtyAndUOMQty)}. */ StockQtyAndUOMQty getAllocatedQty(final I_C_Invoice_Candidate ic, final int icId, final IInvoiceLineRW il)
{ Check.assume(isAssociated(icId, il), ic + " with ID=" + icId + " is associated with " + il); return candIdAndLine2AllocatedQty.get(icId).get(il); } @Override public String toString() { return "InvoiceCandAggregateImpl [allLines=" + allLines + "]"; } @Override public void negateLineAmounts() { for (final IInvoiceLineRW line : getAllLines()) { line.negateAmounts(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandAggregateImpl.java
1
请完成以下Java代码
public class StampedAccount { private final AtomicInteger stamp = new AtomicInteger(0); private final AtomicStampedReference<Integer> account = new AtomicStampedReference<>(0, 0); public boolean deposit(int funds) { int[] stamps = new int[1]; int current = this.account.get(stamps); int newStamp = this.stamp.incrementAndGet(); // Thread is paused here to allow other threads to update the stamp and amount (for testing only) sleep(); return this.account.compareAndSet(current, current + funds, stamps[0], newStamp); } public boolean withdrawal(int funds) { int[] stamps = new int[1]; int current = this.account.get(stamps); int newStamp = this.stamp.incrementAndGet(); return this.account.compareAndSet(current, current - funds, stamps[0], newStamp); }
public int getBalance() { return account.getReference(); } public int getStamp() { return account.getStamp(); } private static void sleep() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ignored) { } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\atomicstampedreference\StampedAccount.java
1
请完成以下Java代码
public @Nullable String getHostValue() { return hostValue; } public Config setHostValue(String hostValue) { this.hostValue = hostValue; return this; } public String getProtocols() { return protocols; } public Config setProtocols(String protocols) { this.protocols = protocols; this.hostPortPattern = compileHostPortPattern(protocols);
this.hostPortVersionPattern = compileHostPortVersionPattern(protocols); return this; } public Pattern getHostPortPattern() { return hostPortPattern; } public Pattern getHostPortVersionPattern() { return hostPortVersionPattern; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteLocationResponseHeaderGatewayFilterFactory.java
1
请完成以下Java代码
public class CommonLoggingErrorHandler implements CommonErrorHandler { private static final LogAccessor LOGGER = new LogAccessor(LogFactory.getLog(CommonLoggingErrorHandler.class)); private boolean ackAfterHandle = true; @Override public boolean isAckAfterHandle() { return this.ackAfterHandle; } @Override public void setAckAfterHandle(boolean ackAfterHandle) { this.ackAfterHandle = ackAfterHandle; } @Override public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer, MessageListenerContainer container) { LOGGER.error(thrownException, () -> "Error occurred while processing: " + KafkaUtils.format(record)); return true; }
@Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { StringBuilder message = new StringBuilder("Error occurred while processing:\n"); for (ConsumerRecord<?, ?> record : data) { message.append(KafkaUtils.format(record)).append('\n'); } LOGGER.error(thrownException, () -> message.substring(0, message.length() - 1)); } @Override public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer, MessageListenerContainer container, boolean batchListener) { LOGGER.error(thrownException, () -> "Error occurred while not processing records"); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonLoggingErrorHandler.java
1
请完成以下Java代码
public HistoricExternalTaskLogQuery orderByRetries() { orderBy(HistoricExternalTaskLogQueryProperty.RETRIES); return this; } @Override public HistoricExternalTaskLogQuery orderByPriority() { orderBy(HistoricExternalTaskLogQueryProperty.PRIORITY); return this; } @Override public HistoricExternalTaskLogQuery orderByTopicName() { orderBy(HistoricExternalTaskLogQueryProperty.TOPIC_NAME); return this; } @Override public HistoricExternalTaskLogQuery orderByWorkerId() { orderBy(HistoricExternalTaskLogQueryProperty.WORKER_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByActivityId() { orderBy(HistoricExternalTaskLogQueryProperty.ACTIVITY_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByActivityInstanceId() { orderBy(HistoricExternalTaskLogQueryProperty.ACTIVITY_INSTANCE_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByExecutionId() { orderBy(HistoricExternalTaskLogQueryProperty.EXECUTION_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByProcessInstanceId() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_INSTANCE_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByProcessDefinitionId() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_ID);
return this; } @Override public HistoricExternalTaskLogQuery orderByProcessDefinitionKey() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_KEY); return this; } @Override public HistoricExternalTaskLogQuery orderByTenantId() { orderBy(HistoricExternalTaskLogQueryProperty.TENANT_ID); return this; } // results ////////////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsCountByQueryCriteria(this); } @Override public List<HistoricExternalTaskLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsByQueryCriteria(this, page); } // getters & setters //////////////////////////////////////////////////////////// protected void setState(ExternalTaskState state) { this.state = state; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricExternalTaskLogQueryImpl.java
1
请完成以下Java代码
public OrderItemBuilder createOrderItem() { return new OrderItemBuilder(this); } /** * Intended to be used by the persistence layer */ public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem) { final PurchaseCandidateId id = getId(); Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this); Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(), "The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}", purchaseOrderItem, this); purchaseOrderItems.add(purchaseOrderItem); } public Quantity getPurchasedQty()
{ return purchaseOrderItems.stream() .map(PurchaseOrderItem::getPurchasedQty) .reduce(Quantity::add) .orElseGet(() -> getQtyToPurchase().toZero()); } public List<PurchaseOrderItem> getPurchaseOrderItems() { return ImmutableList.copyOf(purchaseOrderItems); } public List<PurchaseErrorItem> getPurchaseErrorItems() { return ImmutableList.copyOf(purchaseErrorItems); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java
1
请完成以下Java代码
public void assertNotAllOrOther() { Check.errorIf(isOther() || isAll(), "AttributesKeys.OTHER or .ALL of the given attributesKey is not supported; attributesKey={}", this); } private static ImmutableSet<AttributesKeyPart> extractAttributeKeyParts(final String attributesKeyString) { if (attributesKeyString.trim().isEmpty()) { return ImmutableSet.of(); } try { return ATTRIBUTEVALUEIDS_SPLITTER.splitToList(attributesKeyString.trim()) .stream() .map(AttributesKeyPart::parseString) .filter(Optional::isPresent) .map(Optional::get) .collect(ImmutableSet.toImmutableSet()); } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex) .appendParametersToMessage() .setParameter("attributesKeyString", attributesKeyString); } } public boolean contains(@NonNull final AttributesKey attributesKey) { return parts.containsAll(attributesKey.parts); } public AttributesKey getIntersection(@NonNull final AttributesKey attributesKey) { final HashSet<AttributesKeyPart> ownMutableParts = new HashSet<>(parts); ownMutableParts.retainAll(attributesKey.parts); return AttributesKey.ofParts(ownMutableParts);
} /** * @return {@code true} if ad least one attributeValueId from the given {@code attributesKey} is included in this instance. */ public boolean intersects(@NonNull final AttributesKey attributesKey) { return parts.stream().anyMatch(attributesKey.parts::contains); } public String getValueByAttributeId(@NonNull final AttributeId attributeId) { for (final AttributesKeyPart part : parts) { if (part.getType() == AttributeKeyPartType.AttributeIdAndValue && AttributeId.equals(part.getAttributeId(), attributeId)) { return part.getValue(); } } throw new AdempiereException("Attribute `" + attributeId + "` was not found in `" + this + "`"); } public static boolean equals(@Nullable final AttributesKey k1, @Nullable final AttributesKey k2) { return Objects.equals(k1, k2); } @Override public int compareTo(@Nullable final AttributesKey o) { if (o == null) { return 1; // we assume that null is less than not-null } return this.getAsString().compareTo(o.getAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKey.java
1
请完成以下Java代码
public static boolean isSameMonth(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); boolean isSameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); return isSameYear && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH); } /** * 判断两个时间是否是同一年 * * @param date1 * @param date2 * @return */ public static boolean isSameYear(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); } /** * 获取两个日期之间的所有日期列表,包含开始和结束日期 * * @param begin * @param end * @return */ public static List<Date> getDateRangeList(Date begin, Date end) {
List<Date> dateList = new ArrayList<>(); if (begin == null || end == null) { return dateList; } // 清除时间部分,只比较日期 Calendar beginCal = Calendar.getInstance(); beginCal.setTime(begin); beginCal.set(Calendar.HOUR_OF_DAY, 0); beginCal.set(Calendar.MINUTE, 0); beginCal.set(Calendar.SECOND, 0); beginCal.set(Calendar.MILLISECOND, 0); Calendar endCal = Calendar.getInstance(); endCal.setTime(end); endCal.set(Calendar.HOUR_OF_DAY, 0); endCal.set(Calendar.MINUTE, 0); endCal.set(Calendar.SECOND, 0); endCal.set(Calendar.MILLISECOND, 0); if (endCal.before(beginCal)) { return dateList; } dateList.add(beginCal.getTime()); while (beginCal.before(endCal)) { beginCal.add(Calendar.DAY_OF_YEAR, 1); dateList.add(beginCal.getTime()); } return dateList; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateUtils.java
1
请完成以下Java代码
public Class<? extends BaseElement> getHandledType() { return BoundaryEvent.class; } @Override protected void executeParse(BpmnParse bpmnParse, BoundaryEvent boundaryEvent) { ActivityImpl parentActivity = findActivity(bpmnParse, boundaryEvent.getAttachedToRefId()); if (parentActivity == null) { LOGGER.warn("Invalid reference in boundary event. Make sure that the referenced activity is defined in the same scope as the boundary event {}", boundaryEvent.getId()); return; } ActivityImpl nestedActivity = createActivityOnScope(bpmnParse, boundaryEvent, BpmnXMLConstants.ELEMENT_EVENT_BOUNDARY, parentActivity); bpmnParse.setCurrentActivity(nestedActivity); EventDefinition eventDefinition = null; if (!boundaryEvent.getEventDefinitions().isEmpty()) { eventDefinition = boundaryEvent.getEventDefinitions().get(0); }
if (eventDefinition instanceof TimerEventDefinition || eventDefinition instanceof org.flowable.bpmn.model.ErrorEventDefinition || eventDefinition instanceof SignalEventDefinition || eventDefinition instanceof CancelEventDefinition || eventDefinition instanceof MessageEventDefinition || eventDefinition instanceof org.flowable.bpmn.model.CompensateEventDefinition) { bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition); } else { LOGGER.warn("Unsupported boundary event type for boundary event {}", boundaryEvent.getId()); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\BoundaryEventParseHandler.java
1
请完成以下Java代码
public boolean isXML() { final String name = getName().trim().toLowerCase(); return name.endsWith(".xml"); } public AttachmentEntry withAdditionalLinkedRecord(@NonNull final TableRecordReference modelRef) { if (getLinkedRecords().contains(modelRef)) { return this; } return toBuilder().linkedRecord(modelRef).build(); } public AttachmentEntry withAdditionalTag(@NonNull final String tagName, @NonNull final String tagValue) { return toBuilder() .tags(getTags().withTag(tagName, tagValue)) .build(); } public AttachmentEntry withRemovedLinkedRecord(@NonNull final TableRecordReference modelRef) { final HashSet<TableRecordReference> linkedRecords = new HashSet<>(getLinkedRecords()); if (linkedRecords.remove(modelRef)) { return toBuilder().clearLinkedRecords().linkedRecords(linkedRecords).build(); } else { return this; } } public AttachmentEntry withoutLinkedRecords() { return toBuilder().clearLinkedRecords().build(); } public AttachmentEntry withAdditionalLinkedRecords(@NonNull final List<TableRecordReference> additionalLinkedRecords) { if (getLinkedRecords().containsAll(additionalLinkedRecords)) { return this; } final Set<TableRecordReference> tmp = new HashSet<>(getLinkedRecords()); tmp.addAll(additionalLinkedRecords);
return toBuilder().linkedRecords(tmp).build(); } public AttachmentEntry withRemovedLinkedRecords(@NonNull final List<TableRecordReference> linkedRecordsToRemove) { final HashSet<TableRecordReference> linkedRecords = new HashSet<>(getLinkedRecords()); if (linkedRecords.removeAll(linkedRecordsToRemove)) { return toBuilder().clearLinkedRecords().linkedRecords(linkedRecords).build(); } else { return this; } } public AttachmentEntry withAdditionalTag(@NonNull final AttachmentTags attachmentTags) { return toBuilder() .tags(getTags().withTags(attachmentTags)) .build(); } public AttachmentEntry withoutTags(@NonNull final AttachmentTags attachmentTags) { return toBuilder() .tags(getTags().withoutTags(attachmentTags)) .build(); } /** * @return the attachment's filename as seen from the given {@code tableRecordReference}. Note that different records might share the same attachment, but refer to it under different file names. */ @NonNull public String getFilename(@NonNull final TableRecordReference tableRecordReference) { if (linkedRecord2AttachmentName == null) { return filename; } return CoalesceUtil.coalesceNotNull( linkedRecord2AttachmentName.get(tableRecordReference), filename); } public boolean hasLinkToRecord(@NonNull final TableRecordReference tableRecordReference) { return linkedRecords.contains(tableRecordReference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntry.java
1
请在Spring Boot框架中完成以下Java代码
final File getFile( @NonNull final GetAttachmentRouteContext context, @NonNull final String id) throws ApiException { final String apiKey = context.getApiKey(); final AttachmentApi attachmentApi = context.getAttachmentApi(); final File file = attachmentApi.getSingleAttachment(apiKey, id); if (file == null) { throw new RuntimeException("No data received for attachment id" + id); } return file; } @NonNull final List<JsonExternalReferenceTarget> computeTargets(@NonNull final AttachmentMetadata metadata) { final ImmutableList.Builder<JsonExternalReferenceTarget> targets = ImmutableList.builder(); final String createdBy = metadata.getCreatedBy(); if (!EmptyUtil.isEmpty(createdBy)) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_USERID, formatExternalId(createdBy))); } final String patientId = metadata.getPatientId(); if (!EmptyUtil.isEmpty(patientId)) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_BPARTNER, formatExternalId(patientId))); } final ImmutableList<JsonExternalReferenceTarget> computedTargets = targets.build(); if (EmptyUtil.isEmpty(computedTargets)) { throw new RuntimeException("Attachment targets cannot be null!"); } return computedTargets; } @NonNull final List<JsonTag> computeTags(@NonNull final Attachment attachment) { final ImmutableList.Builder<JsonTag> tags = ImmutableList.builder(); final AttachmentMetadata metadata = attachment.getMetadata(); final String id = attachment.getId(); if (!EmptyUtil.isEmpty(id)) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ID, id)); }
final String uploadDate = attachment.getUploadDate(); if (!EmptyUtil.isEmpty(uploadDate)) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_UPLOAD_DATE, uploadDate)); } final BigDecimal type = metadata.getType(); if (type != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_TYPE, String.valueOf(type))); } final OffsetDateTime createdAt = metadata.getCreatedAt(); if (createdAt != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_CREATEDAT, String.valueOf(createdAt))); } tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ENDPOINT, GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ENDPOINT_VALUE)); return tags.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\processor\AttachmentProcessor.java
2
请完成以下Java代码
public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); } @Override public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID) { if (M_Picking_Job_Schedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, M_Picking_Job_Schedule_ID); } @Override public int getM_Picking_Job_Schedule_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed);
} @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java
1
请完成以下Java代码
public class MigrationPlanExecutionBuilderImpl implements MigrationPlanExecutionBuilder { protected CommandExecutor commandExecutor; protected MigrationPlan migrationPlan; protected List<String> processInstanceIds; protected ProcessInstanceQuery processInstanceQuery; protected boolean skipCustomListeners; protected boolean skipIoMappings; public MigrationPlanExecutionBuilderImpl(CommandExecutor commandExecutor, MigrationPlan migrationPlan) { this.commandExecutor = commandExecutor; this.migrationPlan = migrationPlan; } public MigrationPlan getMigrationPlan() { return migrationPlan; } public MigrationPlanExecutionBuilder processInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; return this; } @Override public MigrationPlanExecutionBuilder processInstanceIds(String... processInstanceIds) { if (processInstanceIds == null) { this.processInstanceIds = Collections.emptyList(); } else { this.processInstanceIds = Arrays.asList(processInstanceIds); } return this; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public MigrationPlanExecutionBuilder processInstanceQuery(ProcessInstanceQuery processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery; return this; } public ProcessInstanceQuery getProcessInstanceQuery() { return processInstanceQuery; } public MigrationPlanExecutionBuilder skipCustomListeners() { this.skipCustomListeners = true; return this; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public MigrationPlanExecutionBuilder skipIoMappings() { this.skipIoMappings = true; return this; } public boolean isSkipIoMappings() { return skipIoMappings; } public void execute() { commandExecutor.execute(new MigrateProcessInstanceCmd(this, false)); } public Batch executeAsync() { return commandExecutor.execute(new MigrateProcessInstanceBatchCmd(this)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationPlanExecutionBuilderImpl.java
1
请完成以下Java代码
public GridFieldVOsLoader setTabIncludeFiltersStrategy(@NonNull final TabIncludeFiltersStrategy tabIncludeFiltersStrategy) { this.tabIncludeFiltersStrategy = tabIncludeFiltersStrategy; return this; } public GridFieldVOsLoader setTabReadOnly(final boolean tabReadOnly) { _tabReadOnly = tabReadOnly; return this; } private boolean isTabReadOnly() { return _tabReadOnly; } public GridFieldVOsLoader setLoadAllLanguages(final boolean loadAllLanguages) { _loadAllLanguages = loadAllLanguages; return this; }
private boolean isLoadAllLanguages() { return _loadAllLanguages; } public GridFieldVOsLoader setApplyRolePermissions(final boolean applyRolePermissions) { this._applyRolePermissions = applyRolePermissions; return this; } private boolean isApplyRolePermissions() { return _applyRolePermissions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVOsLoader.java
1
请完成以下Java代码
public void reactivatePaySelection(final I_C_PaySelection paySelection) { final IBankStatementBL bankStatementBL = Services.get(IBankStatementBL.class); for (final I_C_PaySelectionLine paySelectionLine : paySelectionDAO.retrievePaySelectionLines(paySelection)) { if (isReconciled(paySelectionLine)) { final BankStatementId bankStatementId = BankStatementId.ofRepoId(paySelectionLine.getC_BankStatement_ID()); final String bankStatementDocumentNo = bankStatementBL.getDocumentNo(bankStatementId); throw new AdempiereException( MSG_CannotReactivate_PaySelectionLineInBankStatement_2P, paySelectionLine.getLine(), bankStatementDocumentNo); } } paySelection.setProcessed(false); paySelection.setDocAction(IDocument.ACTION_Complete); } @Override public Set<PaymentId> getPaymentIds(@NonNull final PaySelectionId paySelectionId) { return paySelectionDAO.retrievePaySelectionLines(paySelectionId) .stream() .map(line -> PaymentId.ofRepoIdOrNull(line.getC_Payment_ID())) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } @Override public ImmutableSet<BPartnerId> getBPartnerIdsFromPaySelectionLineIds(@NonNull final Collection<PaySelectionLineId> paySelectionLineIds) { return paySelectionDAO.retrievePaySelectionLinesByIds(paySelectionLineIds) .stream() .map(paySelectionLine -> BPartnerId.ofRepoIdOrNull(paySelectionLine.getC_BPartner_ID())) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); }
@Override public PaySelectionLineType extractType(final I_C_PaySelectionLine line) { final OrderId orderId = OrderId.ofRepoIdOrNull(line.getC_Order_ID()); final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(line.getC_Invoice_ID()); if (orderId != null) { return PaySelectionLineType.Order; } else if (invoiceId != null) { return PaySelectionLineType.Invoice; } else { throw new AdempiereException("Unsupported pay selection type, for line: ") .appendParametersToMessage() .setParameter("line", line.getLine()) .setParameter("InvoiceId", invoiceId) .setParameter("originalPaymentId", orderId); } } @Override public I_C_PaySelectionLine getPaySelectionLineById(@NonNull final PaySelectionLineId paySelectionLineId) { return paySelectionDAO.getPaySelectionLinesById(paySelectionLineId); } @Override public List<I_C_PaySelectionLine> retrievePaySelectionLines(@NonNull final I_C_PaySelection paySelection) { return paySelectionDAO.retrievePaySelectionLines(paySelection); } @Override public List<I_C_PaySelectionLine> retrievePaySelectionLines(@NonNull final PaySelectionId paySelectionId) { return paySelectionDAO.retrievePaySelectionLines(paySelectionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionBL.java
1
请完成以下Java代码
public void start() { super.start(); retrospectivePrint(); } private void retrospectivePrint() { if (this.context == null) { return; } long now = System.currentTimeMillis(); List<Status> statusList = this.context.getStatusManager().getCopyOfStatusList(); statusList.stream() .filter((status) -> getElapsedTime(status, now) < RETROSPECTIVE_THRESHOLD) .forEach(this::addStatusEvent); } @Override public void addStatusEvent(Status status) { if (this.debug || status.getLevel() >= Status.WARN) { super.addStatusEvent(status);
} } @Override protected PrintStream getPrintStream() { return (!this.debug) ? System.err : System.out; } private static long getElapsedTime(Status status, long now) { return now - status.getTimestamp(); } static void addTo(LoggerContext loggerContext) { addTo(loggerContext, false); } static void addTo(LoggerContext loggerContext, boolean debug) { StatusListenerConfigHelper.addOnConsoleListenerInstance(loggerContext, new SystemStatusListener(debug)); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\SystemStatusListener.java
1
请完成以下Java代码
public class MWebProjectDomain extends X_CM_WebProject_Domain { /** serialVersionUID */ private static final long serialVersionUID = 5134789895039452551L; /** Logger */ private static Logger s_log = LogManager.getLogger(MContainer.class); /** * Web Project Domain Constructor * @param ctx context * @param CM_WebProject_Domain_ID id * @param trxName transaction */ public MWebProjectDomain (Properties ctx, int CM_WebProject_Domain_ID, String trxName) { super (ctx, CM_WebProject_Domain_ID, trxName); } // MWebProjectDomain /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MWebProjectDomain (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MWebProjectDomain /** * get WebProjectDomain by Name * @param ctx * @param ServerName * @param trxName * @return ContainerElement */ public static MWebProjectDomain get(Properties ctx, String ServerName, String trxName) { MWebProjectDomain thisWebProjectDomain = null; String sql = "SELECT * FROM CM_WebProject_Domain WHERE lower(FQDN) LIKE ? ORDER by CM_WebProject_Domain_ID DESC"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, trxName); pstmt.setString(1, ServerName);
ResultSet rs = pstmt.executeQuery(); if (rs.next()) thisWebProjectDomain = (new MWebProjectDomain(ctx, rs, trxName)); rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { s_log.error(sql, e); } try { if (pstmt != null) pstmt.close(); pstmt = null; } catch (Exception e) { pstmt = null; } return thisWebProjectDomain; } } // MWebProjectDomain
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWebProjectDomain.java
1
请在Spring Boot框架中完成以下Java代码
private Map<Integer, List<I_C_CommissionSettingsLine>> retrieveHierarchySettings0(@NonNull final Collection<Integer> settingsRecordIds) { final List<I_C_CommissionSettingsLine> settingsLineRecords = queryBL.createQueryBuilderOutOfTrx(I_C_CommissionSettingsLine.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_CommissionSettingsLine.COLUMN_C_HierarchyCommissionSettings_ID, settingsRecordIds) .orderBy(I_C_CommissionSettingsLine.COLUMN_C_HierarchyCommissionSettings_ID) .orderBy(I_C_CommissionSettingsLine.COLUMN_SeqNo) .create() .list(); final HashMap<Integer, List<I_C_CommissionSettingsLine>> result = new HashMap<>(); for (final I_C_CommissionSettingsLine settingsLineRecord : settingsLineRecords) { final List<I_C_CommissionSettingsLine> settingsLines = result.computeIfAbsent(settingsLineRecord.getC_HierarchyCommissionSettings_ID(), ignored -> new ArrayList<I_C_CommissionSettingsLine>()); settingsLines.add(settingsLineRecord); } return ImmutableMap.copyOf(result); } @Value @Builder public static class StagingData { @NonNull ImmutableMap<Integer, I_C_Flatrate_Term> id2TermRecord; @NonNull ImmutableMap<Integer, I_C_Flatrate_Conditions> id2ConditionsRecord; @NonNull ImmutableMap<Integer, I_C_HierarchyCommissionSettings> id2SettingsRecord;
@NonNull ImmutableMap<Integer, I_C_CommissionSettingsLine> id2SettingsLineRecord; @NonNull ImmutableListMultimap<BPartnerId, FlatrateTermId> bPartnerId2FlatrateTermIds; @NonNull ImmutableListMultimap<Integer, BPartnerId> conditionRecordId2BPartnerIds; @NonNull ImmutableMultimap<Integer, Integer> settingsId2termIds; @NonNull ImmutableListMultimap<Integer, Integer> settingsId2settingsLineIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionConfigStagingDataService.java
2
请在Spring Boot框架中完成以下Java代码
public String getCorrelationId() { return correlationId; } public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } 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 String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } public String getElementName() { return elementName; }
public void setElementName(String elementName) { this.elementName = elementName; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobResponse.java
2
请在Spring Boot框架中完成以下Java代码
private TableRuleConfiguration orderTableRule() { TableRuleConfiguration tableRule = new TableRuleConfiguration(); // 设置逻辑表名 tableRule.setLogicTable("t_order"); // ds${0..1}.t_order_${0..2} 也可以写成 ds$->{0..1}.t_order_$->{0..1} tableRule.setActualDataNodes("ds${0..1}.t_order_${0..2}"); tableRule.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order_$->{order_id % 3}")); tableRule.setKeyGenerator(customKeyGenerator()); tableRule.setKeyGeneratorColumnName("order_id"); return tableRule; } private Map<String, DataSource> dataSourceMap() { Map<String, DataSource> dataSourceMap = new HashMap<>(16); // 配置第一个数据源 HikariDataSource ds0 = new HikariDataSource(); ds0.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds0.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); ds0.setUsername("root"); ds0.setPassword("root");
// 配置第二个数据源 HikariDataSource ds1 = new HikariDataSource(); ds1.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds1.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo-2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); ds1.setUsername("root"); ds1.setPassword("root"); dataSourceMap.put("ds0", ds0); dataSourceMap.put("ds1", ds1); return dataSourceMap; } /** * 自定义主键生成器 */ private KeyGenerator customKeyGenerator() { return new CustomSnowflakeKeyGenerator(snowflake); } }
repos\spring-boot-demo-master\demo-sharding-jdbc\src\main\java\com\xkcoding\sharding\jdbc\config\DataSourceShardingConfig.java
2
请完成以下Java代码
public static int getYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } /** * 增加日期。 * * @param date * @param days * @return * @throws ServiceException */ public static Date dateAdd(Date date, int days) throws ServiceException { if (date == null) { throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DATE, days); return calendar.getTime(); } /** * 增加月份。 * * @param date * @param months * @return * @throws ServiceException */ public static Date monthAdd(Date date, int months) throws ServiceException { if (date == null) { throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, months); return calendar.getTime(); } /** * 获取两个日期之间的差值。 * * @param one * @param two * @return * @throws ServiceException */ public static int dateDiff(Date one, Date two) throws ServiceException { if (one == null || two == null) { throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR); } long diff = Math.abs((one.getTime() - two.getTime()) / (1000 * 3600 * 24)); return new Long(diff).intValue(); } /** * 计算几天前的时间 * * @param date 当前时间
* @param day 几天前 * @return */ public static Date getDateBefore(Date date, int day) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, now.get(Calendar.DATE) - day); return now.getTime(); } /** * 获取当前月第一天 * * @return Date * @throws ParseException */ public static Date getFirstAndLastOfMonth() { LocalDate today = LocalDate.now(); LocalDate firstDay = LocalDate.of(today.getYear(),today.getMonth(),1); ZoneId zone = ZoneId.systemDefault(); Instant instant = firstDay.atStartOfDay().atZone(zone).toInstant(); return Date.from(instant); } /** * 获取当前周第一天 * * @return Date * @throws ParseException */ public static Date getWeekFirstDate(){ Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date date = cal.getTime(); return date; } }
repos\springBoot-master\abel-util\src\main\java\cn\abel\utils\DateTimeUtils.java
1
请在Spring Boot框架中完成以下Java代码
protected <T extends HasOtaPackage> void validateOtaPackage(TenantId tenantId, T entity, DeviceProfileId deviceProfileId) { if (entity.getFirmwareId() != null) { OtaPackage firmware = otaPackageService.findOtaPackageById(tenantId, entity.getFirmwareId()); validateOtaPackage(tenantId, OtaPackageType.FIRMWARE, deviceProfileId, firmware); } if (entity.getSoftwareId() != null) { OtaPackage software = otaPackageService.findOtaPackageById(tenantId, entity.getSoftwareId()); validateOtaPackage(tenantId, OtaPackageType.SOFTWARE, deviceProfileId, software); } } private void validateOtaPackage(TenantId tenantId, OtaPackageType type, DeviceProfileId deviceProfileId, OtaPackage otaPackage) { if (otaPackage == null) { throw new DataValidationException(prepareMsg("Can't assign non-existent %s!", type)); } if (!otaPackage.getTenantId().equals(tenantId)) { throw new DataValidationException(prepareMsg("Can't assign %s from different tenant!", type));
} if (!otaPackage.getType().equals(type)) { throw new DataValidationException(prepareMsg("Can't assign %s with type: " + otaPackage.getType(), type)); } if (otaPackage.getData() == null && !otaPackage.hasUrl()) { throw new DataValidationException(prepareMsg("Can't assign %s with empty data!", type)); } if (!otaPackage.getDeviceProfileId().equals(deviceProfileId)) { throw new DataValidationException(prepareMsg("Can't assign %s with different deviceProfile!", type)); } } private String prepareMsg(String msg, OtaPackageType type) { return String.format(msg, type.name().toLowerCase()); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\AbstractHasOtaPackageValidator.java
2
请在Spring Boot框架中完成以下Java代码
public void processDataFromSQL( @NonNull final String sql, @NonNull final Evaluatee evalCtx, @NonNull final DataConsumer<ResultSet> dataConsumer) { final String sqlParsed = StringExpressionCompiler.instance .compile(sql) .evaluate(evalCtx, OnVariableNotFound.Fail); final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { loggable.addLog("Execute SQL={}", sqlParsed); final ImmutablePair<Connection, PreparedStatement> connAndStmt = DB.prepareConnectionAndStatementForDataExport(sqlParsed, null/* sqlParams */); conn = connAndStmt.getLeft(); pstmt = connAndStmt.getRight(); rs = pstmt.executeQuery(); loggable.addLog("Execute SQL done; push data to dataConsumer={}", dataConsumer); final ResultSetMetaData meta = rs.getMetaData(); // always show spreadsheet header, even if there are no rows final List<String> header = new ArrayList<>(); for (int col = 1; col <= meta.getColumnCount(); col++) { final String columnName = meta.getColumnLabel(col); header.add(columnName); }
// we need to do the consuming right here, while the resultset is open. dataConsumer.putHeader(header); dataConsumer.putResult(rs); loggable.addLog("Push data to dataConsumer done"); } catch (final SQLException ex) { throw new DBException(ex, sqlParsed); } finally { DB.close(rs, pstmt); DB.close(conn); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\service\SpreadsheetExporterService.java
2
请完成以下Spring Boot application配置
spring: application: name: user-service # 服务名 # Zipkin 配置项,对应 ZipkinProperties 类 zipkin: base-url: http://127.0.0.1:9411 # Zipkin 服务的地址 # Spring Cloud Sleuth 配置项 sleuth: # Spring Cloud Sleuth 针对 Web 组件的配置项,例如说 SpringMVC web: enabled: true
# 是否开启,默认为 true # Spring Cloud Sleuth 针对 Slf4j 组件的配置项 log: slf4j: enabled: true # 是否开启,默认为 true
repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-logback\src\main\resources\application.yml
2
请完成以下Java代码
private boolean isApplyForSOTrx(final IBPartnerAware bpartnerAware) { final boolean isSOTrx = bpartnerAware.isSOTrx(); // // Case: sales transaction if (isSOTrx) { // We shall not copy the attributes for Sales Transactions (06790) // Except when we are explicitly asked to do so. return forceApplyForSOTrx; } // // Case: purchase transaction else { // We must copy the attributes for Purchase Transactions (06790) return true; } } private boolean isAttrDocumentRelevant(final I_M_Attribute attribute) { final String docTableName = getSourceTableName(); if (I_C_InvoiceLine.Table_Name.equals(docTableName)) { return attribute.isAttrDocumentRelevant(); } else { return true; } } public BPartnerAwareAttributeUpdater setSourceModel(final Object sourceModel) { this.sourceModel = sourceModel; return this; } private Object getSourceModel() { Check.assumeNotNull(sourceModel, "sourceModel not null"); return sourceModel; } private String getSourceTableName() { return InterfaceWrapperHelper.getModelTableName(getSourceModel()); } public BPartnerAwareAttributeUpdater setBPartnerAwareFactory(final IBPartnerAwareFactory bpartnerAwareFactory)
{ this.bpartnerAwareFactory = bpartnerAwareFactory; return this; } private IBPartnerAwareFactory getBPartnerAwareFactory() { Check.assumeNotNull(bpartnerAwareFactory, "bpartnerAwareFactory not null"); return bpartnerAwareFactory; } public final BPartnerAwareAttributeUpdater setBPartnerAwareAttributeService(final IBPartnerAwareAttributeService bpartnerAwareAttributeService) { this.bpartnerAwareAttributeService = bpartnerAwareAttributeService; return this; } private IBPartnerAwareAttributeService getBPartnerAwareAttributeService() { Check.assumeNotNull(bpartnerAwareAttributeService, "bpartnerAwareAttributeService not null"); return bpartnerAwareAttributeService; } /** * Sets if we shall copy the attribute even if it's a sales transaction (i.e. IsSOTrx=true) */ public final BPartnerAwareAttributeUpdater setForceApplyForSOTrx(final boolean forceApplyForSOTrx) { this.forceApplyForSOTrx = forceApplyForSOTrx; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\BPartnerAwareAttributeUpdater.java
1
请完成以下Java代码
public void configure(WebSecurity web) { web.ignoring().antMatchers(POST, "/users", "/users/login"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.cors(); http.formLogin().disable(); http.logout().disable(); http.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); http.authorizeRequests() .antMatchers(GET, "/profiles/*").permitAll() .antMatchers(GET, "/articles/**").permitAll() .antMatchers(GET, "/tags/**").permitAll() .anyRequest().authenticated(); } @Bean JWTAuthenticationProvider jwtAuthenticationProvider(JWTDeserializer jwtDeserializer) { return new JWTAuthenticationProvider(jwtDeserializer); } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET", "HEAD", "POST", "DELETE", "PUT") .allowedOrigins(properties.getAllowedOrigins().toArray(new String[0])) .allowedHeaders("*") .allowCredentials(true);
} } @ConstructorBinding @ConfigurationProperties("security") class SecurityConfigurationProperties { private final List<String> allowedOrigins; SecurityConfigurationProperties(List<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public List<String> getAllowedOrigins() { return allowedOrigins; } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\security\SecurityConfiguration.java
1
请完成以下Java代码
private List<PickingCandidate> retrievePickingCandidates() { return pickingCandidateRepository.getByHUIds(ImmutableList.of(huId)); } private IAllocationDestination createAllocationDestinationAsSourceHUs() { final Collection<I_M_HU> sourceHUs = sourceHUsRepository.retrieveActualSourceHUs(ImmutableSet.of(huId)); if (sourceHUs.isEmpty()) { throw new AdempiereException("No source HUs found for M_HU_ID=" + huId); } return HUListAllocationSourceDestination.of(sourceHUs); } /** * Create the context with the tread-inherited transaction! Otherwise, the loader won't be able to access the HU's material item and therefore won't load anything! */ private IAllocationRequest createAllocationRequest( @NonNull final PickingCandidate candidate, @NonNull final Quantity qtyToRemove) { final IMutableHUContext huContext = huContextFactory.createMutableHUContextForProcessing(); return AllocationUtils.builder() .setHUContext(huContext) .setProduct(productId) .setQuantity(qtyToRemove)
.setDateAsToday() .setFromReferencedTableRecord(pickingCandidateRepository.toTableRecordReference(candidate)) // the m_hu_trx_Line coming out of this will reference the picking candidate .setForceQtyAllocation(true) .create(); } private HUListAllocationSourceDestination createAllocationSourceAsHU() { final I_M_HU hu = load(huId, I_M_HU.class); // we made sure that if the target HU is active, so the source HU also needs to be active. Otherwise, goods would just seem to vanish if (!X_M_HU.HUSTATUS_Active.equals(hu.getHUStatus())) { throw new AdempiereException("not an active HU").setParameter("hu", hu); } final HUListAllocationSourceDestination source = HUListAllocationSourceDestination.of(hu); source.setDestroyEmptyHUs(true); return source; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\RemoveQtyFromHUCommand.java
1
请完成以下Java代码
protected CmmnActivityBehavior getActivityBehavior() { return new DmnDecisionTaskActivityBehavior(); } protected DmnDecisionTaskActivityBehavior getActivityBehavior(CmmnActivity activity) { return (DmnDecisionTaskActivityBehavior) activity.getActivityBehavior(); } protected String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); String decision = definition.getDecision(); if (decision == null) { DecisionRefExpression decisionExpression = definition.getDecisionExpression(); if (decisionExpression != null) { decision = decisionExpression.getText(); } } return decision; } protected String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionBinding();
} protected String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionVersion(); } protected String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionTenantId(); } protected DecisionTask getDefinition(CmmnElement element) { return (DecisionTask) super.getDefinition(element); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\DecisionTaskItemHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void displayAuthorsWithBooksAndPublishersWithSpec() { List<Author> authors = authorRepository.findAll(isAgeGt45()); for (Author author : authors) { System.out.println("\nAuthor: " + author); List<Book> books = author.getBooks(); System.out.println("No of books: " + books.size() + ", " + books); for (Book book : books) { System.out.println("Book: " + book.getTitle() + " published by: " + book.getPublisher()); } } } public void displayPublishersWithBooksAndAuthors() { List<Publisher> publishers = publisherRepository.findAll(); for (Publisher publisher : publishers) { System.out.println("\nPublisher: " + publisher); List<Book> books = publisher.getBooks(); System.out.println("No of books: " + books.size() + ", " + books); for (Book book : books) { System.out.println("Book: " + book.getTitle() + " written by: " + book.getAuthor()); } } } public void displayPublishersByIdWithBooksAndAuthors() { List<Publisher> publishers = publisherRepository.findByIdLessThanOrderByCompanyDesc(2L); for (Publisher publisher : publishers) { System.out.println("\nPublisher: " + publisher); List<Book> books = publisher.getBooks(); System.out.println("No of books: " + books.size() + ", " + books); for (Book book : books) { System.out.println("Book: " + book.getTitle() + " written by: " + book.getAuthor()); } } } public void displayPublishersWithBooksAndAuthorsWithSpec() {
List<Publisher> publishers = publisherRepository.findAll(isIdGt2()); for (Publisher publisher : publishers) { System.out.println("\nPublisher: " + publisher); List<Book> books = publisher.getBooks(); System.out.println("No of books: " + books.size() + ", " + books); for (Book book : books) { System.out.println("Book: " + book.getTitle() + " written by: " + book.getAuthor()); } } } public void displayPublishersByIdBetween1And3WithBooksAndAuthors() { List<Publisher> publishers = publisherRepository.fetchAllIdBetween1And3(); for (Publisher publisher : publishers) { System.out.println("\nPublisher: " + publisher); List<Book> books = publisher.getBooks(); System.out.println("No of books: " + books.size() + ", " + books); for (Book book : books) { System.out.println("Book: " + book.getTitle() + " written by: " + book.getAuthor()); } } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedSubgraph\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setPOD(final org.compiere.model.I_C_Postal POD) { set_ValueFromPO(COLUMNNAME_POD_ID, org.compiere.model.I_C_Postal.class, POD); } @Override public void setPOD_ID (final int POD_ID) { if (POD_ID < 1) set_Value (COLUMNNAME_POD_ID, null); else set_Value (COLUMNNAME_POD_ID, POD_ID); } @Override public int getPOD_ID() { return get_ValueAsInt(COLUMNNAME_POD_ID); } @Override public org.compiere.model.I_C_Postal getPOL() { return get_ValueAsPO(COLUMNNAME_POL_ID, org.compiere.model.I_C_Postal.class); } @Override public void setPOL(final org.compiere.model.I_C_Postal POL) { set_ValueFromPO(COLUMNNAME_POL_ID, org.compiere.model.I_C_Postal.class, POL); } @Override public void setPOL_ID (final int POL_ID) { if (POL_ID < 1) set_Value (COLUMNNAME_POL_ID, null); else set_Value (COLUMNNAME_POL_ID, POL_ID); } @Override public int getPOL_ID() { return get_ValueAsInt(COLUMNNAME_POL_ID); } @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) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setShipper_BPartner_ID (final int Shipper_BPartner_ID) { if (Shipper_BPartner_ID < 1) set_Value (COLUMNNAME_Shipper_BPartner_ID, null); else set_Value (COLUMNNAME_Shipper_BPartner_ID, Shipper_BPartner_ID); } @Override public int getShipper_BPartner_ID() {
return get_ValueAsInt(COLUMNNAME_Shipper_BPartner_ID); } @Override public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID() { return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public int getM_FreightCost_NormalVAT_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_FreightCost_NormalVAT_Product_ID); } @Override public void setM_FreightCost_ReducedVAT_Product_ID (final int M_FreightCost_ReducedVAT_Product_ID) { if (M_FreightCost_ReducedVAT_Product_ID < 1) set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, null); else set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, M_FreightCost_ReducedVAT_Product_ID); } @Override public int getM_FreightCost_ReducedVAT_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); }
/** * ProductLookup AD_Reference_ID=541499 * Reference name: _ProductLookup */ public static final int PRODUCTLOOKUP_AD_Reference_ID=541499; /** Product Id = ProductId */ public static final String PRODUCTLOOKUP_ProductId = "ProductId"; /** Product Number = ProductNumber */ public static final String PRODUCTLOOKUP_ProductNumber = "ProductNumber"; @Override public void setProductLookup (final java.lang.String ProductLookup) { set_Value (COLUMNNAME_ProductLookup, ProductLookup); } @Override public java.lang.String getProductLookup() { return get_ValueAsString(COLUMNNAME_ProductLookup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6.java
1
请完成以下Java代码
protected @NonNull OutputStream decorate(@Nullable OutputStream outputStream) { return outputStream instanceof BufferedOutputStream ? outputStream : outputStream != null ? new BufferedOutputStream(outputStream, getBufferSize()) : newFileOutputStream(); } /** * Tries to construct a new {@link File} based {@link OutputStream} from the {@literal target} {@link Resource}. * * By default, the constructed {@link OutputStream} is also buffered (e.g. {@link BufferedOutputStream}). * * @return a {@link OutputStream} writing to a {@link File} identified by the {@literal target} {@link Resource}. * @throws IllegalStateException if the {@literal target} {@link Resource} cannot be handled as a {@link File}. * @throws DataAccessResourceFailureException if the {@link OutputStream} could not be created. * @see java.io.BufferedOutputStream * @see java.io.OutputStream * @see #getBufferSize() * @see #getOpenOptions() * @see #getResource() */ protected OutputStream newFileOutputStream() { return getResource() .filter(this::isAbleToHandle) .map(resource -> { try { OutputStream fileOutputStream = Files.newOutputStream(resource.getFile().toPath(), getOpenOptions());
return new BufferedOutputStream(fileOutputStream, getBufferSize()); } catch (IOException cause) { String message = String.format("Failed to access the Resource [%s] as a file", resource.getDescription()); throw new ResourceDataAccessException(message, cause); } }) .orElseThrow(() -> newIllegalStateException("Resource [%s] is not a file based resource", getResource().map(Resource::getDescription).orElse(null))); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\FileResourceWriter.java
1
请完成以下Java代码
private String createSelectSql() { final Evaluatee evalCtx = createEvaluationContext(); String sql = datasource .getSqlSelect() .evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Preserve); if (datasource.isApplySecuritySettings()) { sql = permissionsProvider.addAccessSQL(sql, datasource.getSourceTableName(), context); } return sql; } private Evaluatee createEvaluationContext() { return Evaluatees.mapBuilder() .put("MainFromMillis", DB.TO_DATE(timeRange.getFrom())) .put("MainToMillis", DB.TO_DATE(timeRange.getTo())) .put("FromMillis", DB.TO_DATE(timeRange.getFrom())) .put("ToMillis", DB.TO_DATE(timeRange.getTo())) .put(KPIDataContext.CTXNAME_AD_User_ID, UserId.toRepoId(context.getUserId())) .put(KPIDataContext.CTXNAME_AD_Role_ID, RoleId.toRepoId(context.getRoleId())) .put(KPIDataContext.CTXNAME_AD_Client_ID, ClientId.toRepoId(context.getClientId())) .put(KPIDataContext.CTXNAME_AD_Org_ID, OrgId.toRepoId(context.getOrgId())) .put("#Date", DB.TO_DATE(SystemTime.asZonedDateTime())) .build(); }
public KPIZoomIntoDetailsInfo getKPIZoomIntoDetailsInfo() { final String sqlWhereClause = datasource .getSqlDetailsWhereClause() .evaluate(createEvaluationContext(), IExpressionEvaluator.OnVariableNotFound.Fail); return KPIZoomIntoDetailsInfo.builder() .filterCaption(kpiCaption) .targetWindowId(datasource.getTargetWindowId()) .tableName(datasource.getSourceTableName()) .sqlWhereClause(sqlWhereClause) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\SQLKPIDataLoader.java
1
请完成以下Java代码
public void addListener(final IAggregationListener listener) { if (listener == null) { return; } listeners.addIfAbsent(listener); } @Override public void onAggregationCreated(final I_C_Aggregation aggregation) { for (final IAggregationListener listener : listeners) { listener.onAggregationCreated(aggregation); } } @Override
public void onAggregationChanged(final I_C_Aggregation aggregation) { for (final IAggregationListener listener : listeners) { listener.onAggregationChanged(aggregation); } } @Override public void onAggregationDeleted(final I_C_Aggregation aggregation) { for (final IAggregationListener listener : listeners) { listener.onAggregationDeleted(aggregation); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\listeners\impl\CompositeAggregationListener.java
1
请完成以下Java代码
public static final class Builder { private BigDecimal invoicedAmt = BigDecimal.ZERO; private BigDecimal paymentExistingAmt = BigDecimal.ZERO; private BigDecimal paymentCandidatesAmt = BigDecimal.ZERO; private Builder() { super(); } public PaymentAllocationTotals build() { return new PaymentAllocationTotals(this); } public Builder setInvoicedAmt(final BigDecimal invoicedAmt) {
this.invoicedAmt = invoicedAmt; return this; } public Builder setPaymentExistingAmt(final BigDecimal paymentExistingAmt) { this.paymentExistingAmt = paymentExistingAmt; return this; } public Builder setPaymentCandidatesAmt(final BigDecimal paymentCandidatesAmt) { this.paymentCandidatesAmt = paymentCandidatesAmt; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationTotals.java
1
请完成以下Java代码
public E poll() { if (count <= 0) { return null; } E item = (E) items[0]; shiftLeft(); count--; return item; } private void shiftLeft() { int i = 1; while (i < items.length) { if (items[i] == null) { break; } items[i - 1] = items[i]; i++; } } @Override public E peek() { if (count <= 0) {
return null; } return (E) items[0]; } @Override public int size() { return count; } @Override public Iterator<E> iterator() { List<E> list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add((E) items[i]); } return list.iterator(); } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\fixedsizequeues\FifoFixedSizeQueue.java
1
请完成以下Java代码
private static Color extractSecondaryAWTColor(@NonNull final I_AD_Color colorRecord) { return new Color(colorRecord.getRed(), colorRecord.getGreen(), colorRecord.getBlue()); } @Override public ColorId saveFlatColorAndReturnId(@NonNull String flatColorHexString) { final Color flatColor = MFColor.ofFlatColorHexString(flatColorHexString).getFlatColor(); final I_AD_Color existingColorRecord = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Color.class) .addOnlyActiveRecordsFilter() .addOnlyContextClientOrSystem() .addEqualsFilter(I_AD_Color.COLUMNNAME_ColorType, X_AD_Color.COLORTYPE_NormalFlat) .addEqualsFilter(I_AD_Color.COLUMNNAME_Red, flatColor.getRed()) .addEqualsFilter(I_AD_Color.COLUMNNAME_Green, flatColor.getGreen()) .addEqualsFilter(I_AD_Color.COLUMNNAME_Blue, flatColor.getBlue()) .orderByDescending(I_AD_Color.COLUMNNAME_AD_Client_ID) .orderBy(I_AD_Color.COLUMNNAME_AD_Color_ID) .create() .first(); if (existingColorRecord != null) { return ColorId.ofRepoId(existingColorRecord.getAD_Color_ID()); } final I_AD_Color newColorRecord = InterfaceWrapperHelper.newInstanceOutOfTrx(I_AD_Color.class); newColorRecord.setAD_Org_ID(Env.CTXVALUE_AD_Org_ID_Any); newColorRecord.setName(flatColorHexString.toLowerCase()); newColorRecord.setColorType(X_AD_Color.COLORTYPE_NormalFlat); newColorRecord.setRed(flatColor.getRed()); newColorRecord.setGreen(flatColor.getGreen()); newColorRecord.setBlue(flatColor.getBlue()); // newColorRecord.setAlpha(0); newColorRecord.setImageAlpha(BigDecimal.ZERO); // InterfaceWrapperHelper.save(newColorRecord); return ColorId.ofRepoId(newColorRecord.getAD_Color_ID()); }
@Override public ColorId getColorIdByName(final String colorName) { return colorIdByName.getOrLoad(colorName, () -> retrieveColorIdByName(colorName)); } private ColorId retrieveColorIdByName(final String colorName) { final int colorRepoId = Services.get(IQueryBL.class) .createQueryBuilder(I_AD_Color.class) .addOnlyActiveRecordsFilter() .addOnlyContextClientOrSystem() .addEqualsFilter(I_AD_Color.COLUMNNAME_Name, colorName) .create() .firstIdOnly(); return ColorId.ofRepoIdOrNull(colorRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\impl\ColorRepository.java
1
请在Spring Boot框架中完成以下Java代码
ClientCacheConfigurer clientCacheLocatorsConfigurer() { return (beanName, clientCacheFactoryBean) -> { Logger logger = getLogger(); getLocators().ifPresent(locators -> { if (logger.isWarnEnabled()) { logger.warn("The '{}' property was configured [{}];" + " however, this value does not have any effect for ClientCache instances", LOCATORS_PROPERTY, locators); } }); getRemoteLocators().ifPresent(remoteLocators -> { if (logger.isWarnEnabled()) { logger.warn("The '{}' property was configured [{}];" + " however, this value does not have any effect for ClientCache instances", REMOTE_LOCATORS_PROPERTY, remoteLocators); } }); }; } @Bean LocatorConfigurer locatorLocatorsConfigurer() { return (beanName, locatorFactoryBean) -> { Properties gemfireProperties = locatorFactoryBean.getGemFireProperties(); getLocators().ifPresent(locators -> gemfireProperties.setProperty(LOCATORS_PROPERTY, locators)); getRemoteLocators().ifPresent(remoteLocators -> gemfireProperties.setProperty(REMOTE_LOCATORS_PROPERTY, remoteLocators));
}; } @Bean PeerCacheConfigurer peerCacheLocatorsConfigurer() { return (beanName, cacheFactoryBean) -> { Properties gemfireProperties = cacheFactoryBean.getProperties(); getLocators().ifPresent(locators -> gemfireProperties.setProperty(LOCATORS_PROPERTY, locators)); getRemoteLocators().ifPresent(remoteLocators -> gemfireProperties.setProperty(REMOTE_LOCATORS_PROPERTY, remoteLocators)); }; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\LocatorsConfiguration.java
2
请完成以下Java代码
public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getCreated()); } /** * Retrieves all the charge lines that is present on the document * @return Charge Lines */ public MRMALine[] getChargeLines() { StringBuffer whereClause = new StringBuffer(); whereClause.append("IsActive='Y' AND M_RMA_ID="); whereClause.append(get_ID()); whereClause.append(" AND C_Charge_ID IS NOT null"); int rmaLineIds[] = MRMALine.getAllIDs(MRMALine.Table_Name, whereClause.toString(), get_TrxName()); ArrayList<MRMALine> chargeLineList = new ArrayList<>(); for (int rmaLineId : rmaLineIds) { MRMALine rmaLine = new MRMALine(getCtx(), rmaLineId, get_TrxName()); chargeLineList.add(rmaLine); } MRMALine lines[] = new MRMALine[chargeLineList.size()]; chargeLineList.toArray(lines); return lines; } /** * Get whether Tax is included (based on the original order) * @return True if tax is included */ public boolean isTaxIncluded(final I_C_Tax tax) { final I_C_Order order = getOriginalOrder(); if (order != null && order.getC_Order_ID() > 0) { return Services.get(IOrderBL.class).isTaxIncluded(order, TaxUtils.from(tax)); } return true; } /** * 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 getSalesRep_ID(); } // getDoc_User_ID /** * Get Document Approval Amount * @return amount */ @Override public BigDecimal getApprovalAmt() { return getAmt(); } // getApprovalAmt /** * Document Status is Complete or Closed * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MRMA
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMA.java
1
请完成以下Java代码
protected String doIt() throws Exception { final IQueryFilter<I_M_ReceiptSchedule> selectedSchedsFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final Iterator<I_M_ReceiptSchedule> scheds = queryBL.createQueryBuilder(I_M_ReceiptSchedule.class) .addOnlyActiveRecordsFilter() .filter(selectedSchedsFilter) .create() .iterate(I_M_ReceiptSchedule.class); int counter = 0; for (final I_M_ReceiptSchedule receiptSchedule : IteratorUtils.asIterable(scheds)) { if (receiptScheduleBL.isClosed(receiptSchedule)) { addLog(msgBL.getMsg(getCtx(), MSG_SKIP_CLOSED_1P, new Object[] { receiptSchedule.getM_ReceiptSchedule_ID() })); continue; }
closeInTrx(receiptSchedule); counter++; } return "@Processed@: " + counter; } private void closeInTrx(final I_M_ReceiptSchedule receiptSchedule) { Services.get(ITrxManager.class) .runInNewTrx((TrxRunnable)localTrxName -> { InterfaceWrapperHelper.setThreadInheritedTrxName(receiptSchedule); receiptScheduleBL.close(receiptSchedule); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_Close.java
1
请完成以下Java代码
public void onMessage(Message message, byte[] pattern) { super.onMessage(message, pattern); ChannelTopicEnum channelTopic = ChannelTopicEnum.getChannelTopicEnum(new String(message.getChannel())); logger.info("redis消息订阅者接收到频道【{}】发布的消息。消息内容:{}", channelTopic.getChannelTopicStr(), message.toString().getBytes()); // 解析订阅发布的信息,获取缓存的名称和缓存的key String ms = new String(message.getBody()); @SuppressWarnings("unchecked") Map<String, Object> map = JSON.parseObject(ms, HashMap.class); String cacheName = (String) map.get("cacheName"); Object key = map.get("key"); // 根据缓存名称获取多级缓存 Cache cache = cacheManager.getCache(cacheName); // 判断缓存是否是多级缓存 if (cache != null && cache instanceof LayeringCache) { switch (channelTopic) { case REDIS_CACHE_DELETE_TOPIC: // 获取一级缓存,并删除一级缓存数据 ((LayeringCache) cache).getFirstCache().evict(key); logger.info("删除一级缓存{}数据,key:{}", cacheName, key.toString().getBytes());
break; case REDIS_CACHE_CLEAR_TOPIC: // 获取一级缓存,并删除一级缓存数据 ((LayeringCache) cache).getFirstCache().clear(); logger.info("清除一级缓存{}数据", cacheName); break; default: logger.info("接收到没有定义的订阅消息频道数据"); break; } } } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\listener\RedisMessageListener.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { @Bean SecurityFilterChain defaultSecurityFileterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity.authorizeHttpRequests(authorizedRequest -> authorizedRequest.anyRequest() .authenticated()) .csrf(Customizer.withDefaults()) .build(); } @Bean static Customizer<AuthorizationAdvisorProxyFactory> skipValueTypes() { return (factory) -> factory.setTargetVisitor(TargetVisitor.defaultsSkipValueTypes()); }
@Bean UserDetailsService userDetailsService() { PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); UserDetails user = User.builder() .username("john") .password("password") .passwordEncoder(passwordEncoder::encode) .authorities("read") .build(); return new InMemoryUserDetailsManager(user); } }
repos\tutorials-master\spring-security-modules\spring-security-authorization\spring-security-secure-domain-object\src\main\java\com\baeldung\config\SecurityConfiguration.java
2
请完成以下Java代码
public byte[] getBody() { return this.body; //NOSONAR } public MessageProperties getMessageProperties() { return this.messageProperties; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("("); buffer.append("Body:'").append(this.getBodyContentAsString()).append("'"); buffer.append(" ").append(this.messageProperties.toString()); buffer.append(")"); return buffer.toString(); } private String getBodyContentAsString() { try { String contentType = this.messageProperties.getContentType(); if (MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT.equals(contentType)) { return "[serialized object]"; } String encoding = encoding(); if (this.body.length <= maxBodyLength // NOSONAR && (MessageProperties.CONTENT_TYPE_TEXT_PLAIN.equals(contentType) || MessageProperties.CONTENT_TYPE_JSON.equals(contentType) || MessageProperties.CONTENT_TYPE_JSON_ALT.equals(contentType) || MessageProperties.CONTENT_TYPE_XML.equals(contentType))) { return new String(this.body, encoding); } } catch (Exception e) { // ignore } // Comes out as '[B@....b' (so harmless) return this.body.toString() + "(byte[" + this.body.length + "])"; //NOSONAR } private String encoding() { String encoding = this.messageProperties.getContentEncoding();
if (encoding == null) { encoding = bodyEncoding; } return encoding; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(this.body); result = prime * result + ((this.messageProperties == null) ? 0 : this.messageProperties.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Message other = (Message) obj; if (!Arrays.equals(this.body, other.body)) { return false; } if (this.messageProperties == null) { return other.messageProperties == null; } return this.messageProperties.equals(other.messageProperties); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\Message.java
1
请完成以下Java代码
public class BookSpliterator<T> implements Spliterator<T> { private final Object[] books; private int startIndex; public BookSpliterator(Object[] books, int startIndex) { this.books = books; this.startIndex = startIndex; } @Override public Spliterator<T> trySplit() { // Always Assuming that the source is too small to split, returning null return null; } // Other overridden methods such as tryAdvance(), estimateSize() etc @Override public boolean tryAdvance(Consumer<? super T> action) { if (startIndex < books.length) {
startIndex += 2; return true; } return false; } @Override public long estimateSize() { return books.length - startIndex; } @Override public int characteristics() { return CONCURRENT; } }
repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\parallelstream\BookSpliterator.java
1
请完成以下Java代码
public class X_AD_NotificationGroup_CC extends org.compiere.model.PO implements I_AD_NotificationGroup_CC, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1342697129L; /** Standard Constructor */ public X_AD_NotificationGroup_CC (final Properties ctx, final int AD_NotificationGroup_CC_ID, @Nullable final String trxName) { super (ctx, AD_NotificationGroup_CC_ID, trxName); } /** Load Constructor */ public X_AD_NotificationGroup_CC (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_NotificationGroup_CC_ID (final int AD_NotificationGroup_CC_ID) { if (AD_NotificationGroup_CC_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_CC_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_CC_ID, AD_NotificationGroup_CC_ID); } @Override public int getAD_NotificationGroup_CC_ID() { return get_ValueAsInt(COLUMNNAME_AD_NotificationGroup_CC_ID); } @Override public org.compiere.model.I_AD_NotificationGroup getAD_NotificationGroup()
{ return get_ValueAsPO(COLUMNNAME_AD_NotificationGroup_ID, org.compiere.model.I_AD_NotificationGroup.class); } @Override public void setAD_NotificationGroup(final org.compiere.model.I_AD_NotificationGroup AD_NotificationGroup) { set_ValueFromPO(COLUMNNAME_AD_NotificationGroup_ID, org.compiere.model.I_AD_NotificationGroup.class, AD_NotificationGroup); } @Override public void setAD_NotificationGroup_ID (final int AD_NotificationGroup_ID) { if (AD_NotificationGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_ID, AD_NotificationGroup_ID); } @Override public int getAD_NotificationGroup_ID() { return get_ValueAsInt(COLUMNNAME_AD_NotificationGroup_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_NotificationGroup_CC.java
1
请在Spring Boot框架中完成以下Java代码
public static class Config { boolean isGolden = true; @NotEmpty String customerIdCookie = "customerId"; public Config() {} public Config( boolean isGolden, String customerIdCookie) { this.isGolden = isGolden; this.customerIdCookie = customerIdCookie; } public boolean isGolden() { return isGolden; } public void setGolden(boolean value) {
this.isGolden = value; } /** * @return the customerIdCookie */ public String getCustomerIdCookie() { return customerIdCookie; } /** * @param customerIdCookie the customerIdCookie to set */ public void setCustomerIdCookie(String customerIdCookie) { this.customerIdCookie = customerIdCookie; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\spring-cloud-gateway-intro\src\main\java\com\baeldung\springcloudgateway\custompredicates\factories\GoldenCustomerRoutePredicateFactory.java
2
请完成以下Java代码
public void setIsManual_IPA_SSCC18 (final boolean IsManual_IPA_SSCC18) { set_Value (COLUMNNAME_IsManual_IPA_SSCC18, IsManual_IPA_SSCC18); } @Override public boolean isManual_IPA_SSCC18() { return get_ValueAsBoolean(COLUMNNAME_IsManual_IPA_SSCC18); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID) { if (M_HU_PackagingCode_ID < 1) set_Value (COLUMNNAME_M_HU_PackagingCode_ID, null); else set_Value (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID); } @Override public int getM_HU_PackagingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID); } @Override public void setM_HU_PackagingCode_Text (final @Nullable java.lang.String M_HU_PackagingCode_Text) { throw new IllegalArgumentException ("M_HU_PackagingCode_Text is virtual column"); } @Override public java.lang.String getM_HU_PackagingCode_Text() { return get_ValueAsString(COLUMNNAME_M_HU_PackagingCode_Text); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); }
@Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { throw new IllegalArgumentException ("M_InOut_ID is virtual column"); } @Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java
1
请完成以下Java代码
public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } // persistent object methods //////////////////////////////////////////////// @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id;
} @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("id", this.id); persistentState.put("timestamp", this.timestamp); persistentState.put("version", this.version); return persistentState; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", timestamp=" + timestamp + ", version=" + version + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\SchemaLogEntryEntity.java
1
请完成以下Java代码
default Optional<BPartnerContactId> getBPartnerContactId() { return Optional.ofNullable(BPartnerContactId.ofRepoIdOrNull(getC_BPartner_ID(), getAD_User_ID())); } @Override default void setRenderedAddressAndCapturedLocation(@NonNull final RenderedAddressAndCapturedLocation from) { setC_BPartner_Location_Value_ID(LocationId.toRepoId(from.getCapturedLocationId())); setRenderedAddress(from); } @Override default void setRenderedAddress(@NonNull final RenderedAddressAndCapturedLocation from) { setBPartnerAddress(from.getRenderedAddress()); } default DocumentLocation toDocumentLocation() { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(getC_BPartner_ID()); return DocumentLocation.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(bpartnerId, getC_BPartner_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, getAD_User_ID())) .locationId(LocationId.ofRepoIdOrNull(getC_BPartner_Location_Value_ID())) .bpartnerAddress(getBPartnerAddress()) .build(); } default void setFrom(@NonNull final DocumentLocation from) {
setC_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); setC_BPartner_Location_ID(BPartnerLocationId.toRepoId(from.getBpartnerLocationId())); setC_BPartner_Location_Value_ID(LocationId.toRepoId(from.getLocationId())); setAD_User_ID(BPartnerContactId.toRepoId(from.getContactId())); setBPartnerAddress(from.getBpartnerAddress()); } default void setFrom(@NonNull final BPartnerInfo from) { setC_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); setC_BPartner_Location_ID(BPartnerLocationId.toRepoId(from.getBpartnerLocationId())); setC_BPartner_Location_Value_ID(LocationId.toRepoId(from.getLocationId())); setAD_User_ID(BPartnerContactId.toRepoId(from.getContactId())); setBPartnerAddress(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\adapter\IDocumentLocationAdapter.java
1
请完成以下Java代码
public boolean hasClosedLUs( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @NonNull final UserId callerId) { return !getClosedLUs(wfProcessId, lineId, callerId).isEmpty(); } @NonNull public List<HuId> getClosedLUs( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @NonNull final UserId callerId) { final WFProcess wfProcess = getWFProcessById(wfProcessId); wfProcess.assertHasAccess(callerId); final PickingJob pickingJob = getPickingJob(wfProcess); return pickingJobRestService.getClosedLUs(pickingJob, lineId); } public WFProcess pickAll(@NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId) { final PickingJobId pickingJobId = toPickingJobId(wfProcessId); final PickingJob pickingJob = pickingJobRestService.pickAll(pickingJobId, callerId); return toWFProcess(pickingJob);
} public PickingJobQtyAvailable getQtyAvailable(final WFProcessId wfProcessId, final @NotNull UserId callerId) { final PickingJobId pickingJobId = toPickingJobId(wfProcessId); return pickingJobRestService.getQtyAvailable(pickingJobId, callerId); } public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(final @NonNull JsonGetNextEligibleLineRequest request, final @NotNull UserId callerId) { final GetNextEligibleLineToPackResponse response = pickingJobRestService.getNextEligibleLineToPack( GetNextEligibleLineToPackRequest.builder() .callerId(callerId) .pickingJobId(toPickingJobId(request.getWfProcessId())) .excludeLineId(request.getExcludeLineId()) .huScannedCode(request.getHuScannedCode()) .build() ); return JsonGetNextEligibleLineResponse.builder() .lineId(response.getLineId()) .logs(response.getLogs()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\PickingMobileApplication.java
1
请在Spring Boot框架中完成以下Java代码
public class ItemHint implements Comparable<ItemHint> { private final String name; private final List<ValueHint> values; private final List<ValueProvider> providers; public ItemHint(String name, List<ValueHint> values, List<ValueProvider> providers) { this.name = toCanonicalName(name); this.values = (values != null) ? new ArrayList<>(values) : new ArrayList<>(); this.providers = (providers != null) ? new ArrayList<>(providers) : new ArrayList<>(); } private String toCanonicalName(String name) { int dot = name.lastIndexOf('.'); if (dot != -1) { String prefix = name.substring(0, dot); String originalName = name.substring(dot); return prefix + ConventionUtils.toDashedCase(originalName); } return ConventionUtils.toDashedCase(name); } public String getName() { return this.name; } public List<ValueHint> getValues() { return Collections.unmodifiableList(this.values); } public List<ValueProvider> getProviders() { return Collections.unmodifiableList(this.providers); } /** * Return an {@link ItemHint} with the given prefix applied. * @param prefix the prefix to apply * @return a new {@link ItemHint} with the same of this instance whose property name * has the prefix applied to it */ public ItemHint applyPrefix(String prefix) { return new ItemHint(ConventionUtils.toDashedCase(prefix) + "." + this.name, this.values, this.providers); } @Override public int compareTo(ItemHint other) { return getName().compareTo(other.getName()); } public static ItemHint newHint(String name, ValueHint... values) { return new ItemHint(name, Arrays.asList(values), Collections.emptyList()); } @Override public String toString() { return "ItemHint{name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}'; } /** * A hint for a value. */ public static class ValueHint { private final Object value; private final String description; public ValueHint(Object value, String description) { this.value = value; this.description = description; } public Object getValue() { return this.value; } public String getDescription() { return this.description; }
@Override public String toString() { return "ValueHint{value=" + this.value + ", description='" + this.description + '\'' + '}'; } } /** * A value provider. */ public static class ValueProvider { private final String name; private final Map<String, Object> parameters; public ValueProvider(String name, Map<String, Object> parameters) { this.name = name; this.parameters = parameters; } public String getName() { return this.name; } public Map<String, Object> getParameters() { return this.parameters; } @Override public String toString() { return "ValueProvider{name='" + this.name + "', parameters=" + this.parameters + '}'; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemHint.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_PP_WF_Node_Asset[") .append(get_ID()).append("]"); return sb.toString(); } public I_A_Asset getA_Asset() throws RuntimeException { return (I_A_Asset)MTable.get(getCtx(), I_A_Asset.Table_Name) .getPO(getA_Asset_ID(), get_TrxName()); } /** Set Asset. @param A_Asset_ID Asset used internally or by customers */ public void setA_Asset_ID (int A_Asset_ID) { if (A_Asset_ID < 1) set_Value (COLUMNNAME_A_Asset_ID, null); else set_Value (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID)); } /** Get Asset. @return Asset used internally or by customers */ public int getA_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_WF_Node getAD_WF_Node() throws RuntimeException { return (I_AD_WF_Node)MTable.get(getCtx(), I_AD_WF_Node.Table_Name) .getPO(getAD_WF_Node_ID(), get_TrxName()); } /** Set Node. @param AD_WF_Node_ID Workflow Node (activity), step or process */ public void setAD_WF_Node_ID (int AD_WF_Node_ID) { if (AD_WF_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, Integer.valueOf(AD_WF_Node_ID)); } /** Get Node. @return Workflow Node (activity), step or process */ public int getAD_WF_Node_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Node_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Workflow Node Asset. @param PP_WF_Node_Asset_ID Workflow Node Asset */ public void setPP_WF_Node_Asset_ID (int PP_WF_Node_Asset_ID) { if (PP_WF_Node_Asset_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, Integer.valueOf(PP_WF_Node_Asset_ID)); } /** Get Workflow Node Asset. @return Workflow Node Asset */ public int getPP_WF_Node_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_WF_Node_Asset_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_WF_Node_Asset.java
1
请完成以下Java代码
public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPostLogoutRedirectUri() { return postLogoutRedirectUri; } public void setPostLogoutRedirectUri(String postLogoutRedirectUri) { this.postLogoutRedirectUri = postLogoutRedirectUri; } } public static class OAuth2IdentityProviderProperties { /** * Enable {@link OAuth2IdentityProvider}. Default {@code true}. */ private boolean enabled = true; /** * Name of the attribute (claim) that holds the groups. */ private String groupNameAttribute; /** * Group name attribute delimiter. Only used if the {@link #groupNameAttribute} is a {@link String}. */ private String groupNameDelimiter = ","; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getGroupNameAttribute() { return groupNameAttribute; } public void setGroupNameAttribute(String groupNameAttribute) { this.groupNameAttribute = groupNameAttribute; } public String getGroupNameDelimiter() {
return groupNameDelimiter; } public void setGroupNameDelimiter(String groupNameDelimiter) { this.groupNameDelimiter = groupNameDelimiter; } } public OAuth2SSOLogoutProperties getSsoLogout() { return ssoLogout; } public void setSsoLogout(OAuth2SSOLogoutProperties ssoLogout) { this.ssoLogout = ssoLogout; } public OAuth2IdentityProviderProperties getIdentityProvider() { return identityProvider; } public void setIdentityProvider(OAuth2IdentityProviderProperties identityProvider) { this.identityProvider = identityProvider; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\OAuth2Properties.java
1
请在Spring Boot框架中完成以下Java代码
public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } @ApiOperation(value = "Get an employee by Id") @GetMapping("/employees/{id}") public ResponseEntity<Employee> getEmployeeById( @ApiParam(value = "Employee id from which employee object will retrieve", required = true) @PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); return ResponseEntity.ok().body(employee); } @ApiOperation(value = "Add an employee") @PostMapping("/employees") public Employee createEmployee( @ApiParam(value = "Employee object store in database table", required = true) @Valid @RequestBody Employee employee) { return employeeRepository.save(employee); } @ApiOperation(value = "Update an employee") @PutMapping("/employees/{id}") public ResponseEntity<Employee> updateEmployee( @ApiParam(value = "Employee Id to update employee object", required = true) @PathVariable(value = "id") Long employeeId, @ApiParam(value = "Update employee object", required = true) @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId()); employee.setLastName(employeeDetails.getLastName()); employee.setFirstName(employeeDetails.getFirstName()); final Employee updatedEmployee = employeeRepository.save(employee); return ResponseEntity.ok(updatedEmployee); } @ApiOperation(value = "Delete an employee") @DeleteMapping("/employees/{id}") public Map<String, Boolean> deleteEmployee( @ApiParam(value = "Employee Id from which employee object will delete from database table", required = true) @PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employeeRepository.delete(employee); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jpa-swagger2\src\main\java\net\alanbinu\springboot2\springboot2swagger2\controller\EmployeeController.java
2
请完成以下Java代码
public class GetProcessDefinitionsPayload implements Payload { private String id; private String processDefinitionId; private Set<String> processDefinitionKeys; private boolean latestVersionOnly; public GetProcessDefinitionsPayload() { this.id = UUID.randomUUID().toString(); } public GetProcessDefinitionsPayload(String processDefinitionId, Set<String> processDefinitionKeys) { this(); this.processDefinitionId = processDefinitionId; this.processDefinitionKeys = processDefinitionKeys; } public GetProcessDefinitionsPayload( String processDefinitionId, Set<String> processDefinitionKeys, boolean latestVersionOnly ) { this(); this.processDefinitionId = processDefinitionId; this.processDefinitionKeys = processDefinitionKeys; this.latestVersionOnly = latestVersionOnly; } @Override public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; }
public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public boolean hasDefinitionKeys() { return processDefinitionKeys != null && !processDefinitionKeys.isEmpty(); } public void setProcessDefinitionKeys(Set<String> processDefinitionKeys) { this.processDefinitionKeys = processDefinitionKeys; } public boolean isLatestVersionOnly() { return latestVersionOnly; } public void setLatestVersionOnly(boolean latestVersionOnly) { this.latestVersionOnly = latestVersionOnly; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\GetProcessDefinitionsPayload.java
1
请完成以下Java代码
public class RestrictedPersonIdentificationSchemeNameSEPA { @XmlElement(name = "Prtry", required = true) @XmlSchemaType(name = "string") protected IdentificationSchemeNameSEPA prtry; /** * Gets the value of the prtry property. * * @return * possible object is * {@link IdentificationSchemeNameSEPA } * */ public IdentificationSchemeNameSEPA getPrtry() { return prtry;
} /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link IdentificationSchemeNameSEPA } * */ public void setPrtry(IdentificationSchemeNameSEPA value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\RestrictedPersonIdentificationSchemeNameSEPA.java
1
请完成以下Java代码
public JdbcExporterBuilder addOrderBy(final String sqlOrderBy) { Check.assumeNotEmpty(sqlOrderBy, "sqlOrderBy is not empty"); this.sqlOrderBys.add(sqlOrderBy); return this; } private List<String> getSqlOrderBys() { return sqlOrderBys; } public static class Column { private final String name; private final String dbTableNameOrAlias; private final String dbColumnName; private final String dbColumnSQL; private boolean exported; public Column(String name, String dbTableNameOrAlias, String dbColumnName, String dbColumnSQL) { super(); this.name = name; this.dbTableNameOrAlias = dbTableNameOrAlias; this.dbColumnName = dbColumnName; this.dbColumnSQL = dbColumnSQL; this.exported = true; } @Override public String toString() { return "Column [" + "name=" + name + ", dbTableNameOrAlias=" + dbTableNameOrAlias + ", dbColumnName=" + dbColumnName + ", dbColumnSQL=" + dbColumnSQL + ", exported=" + exported
+ "]"; } public String getName() { return name; } public String getDbTableNameOrAlias() { return dbTableNameOrAlias; } public String getDbColumnName() { return dbColumnName; } public String getDbColumnSQL() { return dbColumnSQL; } public boolean isExported() { return exported; } public void setExported(boolean exported) { this.exported = exported; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExporterBuilder.java
1