instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public java.math.BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) { return Env.ZERO; } return bd; } /** Set Preis (old). @param Price_Old Preis (old) */ @Override public void setPrice_Old (java.math.BigDecimal Price_Old) { set_Value (COLUMNNAME_Price_Old, Price_Old); } /** Get Preis (old). @return Preis (old) */ @Override public java.math.BigDecimal getPrice_Old () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price_Old); if (bd == null) { return Env.ZERO; } return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Produkt UUID. @param Product_UUID Produkt UUID */ @Override public void setProduct_UUID (java.lang.String Product_UUID) { set_Value (COLUMNNAME_Product_UUID, Product_UUID); } /** Get Produkt UUID. @return Produkt UUID */ @Override public java.lang.String getProduct_UUID () { return (java.lang.String)get_Value(COLUMNNAME_Product_UUID); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) { return Env.ZERO; } return bd; } /** Set Menge (old). @param Qty_Old Menge (old) */ @Override public void setQty_Old (java.math.BigDecimal Qty_Old)
{ set_Value (COLUMNNAME_Qty_Old, Qty_Old); } /** Get Menge (old). @return Menge (old) */ @Override public java.math.BigDecimal getQty_Old () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty_Old); if (bd == null) { return Env.ZERO; } return bd; } /** * Type AD_Reference_ID=540660 * Reference name: PMM_RfQResponse_ChangeEvent_Type */ public static final int TYPE_AD_Reference_ID=540660; /** Price = P */ public static final String TYPE_Price = "P"; /** Quantity = Q */ public static final String TYPE_Quantity = "Q"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_RfQResponse_ChangeEvent.java
1
请完成以下Java代码
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; }
/** * The session handling strategy which will be invoked immediately after an * authentication request is successfully processed by the * <tt>AuthenticationManager</tt>. Used, for example, to handle changing of the * session identifier to prevent session fixation attacks. * @param sessionStrategy the implementation to use. If not set a null implementation * is used. * @since 6.4 */ public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) { Assert.notNull(sessionStrategy, "sessionStrategy cannot be null"); this.sessionStrategy = sessionStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilter.java
1
请完成以下Java代码
public class CharacterHelper { public static boolean isSpaceLetter(char input) { return input == 8 || input == 9 || input == 10 || input == 13 || input == 32 || input == 160; } public static boolean isEnglishLetter(char input) { return (input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z'); } public static boolean isArabicNumber(char input) { return input >= '0' && input <= '9'; } public static boolean isCJKCharacter(char input) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(input); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A //全角数字字符和日韩字符 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS //韩文字符集 || ub == Character.UnicodeBlock.HANGUL_SYLLABLES || ub == Character.UnicodeBlock.HANGUL_JAMO || ub == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO //日文字符集 || ub == Character.UnicodeBlock.HIRAGANA //平假名 || ub == Character.UnicodeBlock.KATAKANA //片假名 || ub == Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS ) { return true; } else { return false; }
//其他的CJK标点符号,可以不做处理 //|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION //|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION } /** * 进行字符规格化(全角转半角,大写转小写处理) * * @param input * @return char */ public static char regularize(char input) { if (input == 12288) { input = (char) 32; } else if (input > 65280 && input < 65375) { input = (char) (input - 65248); } else if (input >= 'A' && input <= 'Z') { input += 32; } return input; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\CharacterHelper.java
1
请在Spring Boot框架中完成以下Java代码
public void setRelatedDocuments(RelatedDocumentsType value) { this.relatedDocuments = value; } /** * Consignment reference of the invoice. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference; } /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */ public void setConsignmentReference(String value) { this.consignmentReference = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence maxOccurs="unbounded"&gt; * &lt;element ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}InvoiceFooter" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "invoiceFooter" })
public static class InvoiceFooters { @XmlElement(name = "InvoiceFooter") protected List<InvoiceFooterType> invoiceFooter; /** * Gets the value of the invoiceFooter property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the invoiceFooter property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInvoiceFooter().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link InvoiceFooterType } * * */ public List<InvoiceFooterType> getInvoiceFooter() { if (invoiceFooter == null) { invoiceFooter = new ArrayList<InvoiceFooterType>(); } return this.invoiceFooter; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICExtensionType.java
2
请完成以下Java代码
public class FindActiveActivityIdsCmd implements Command<List<String>>, Serializable { private static final long serialVersionUID = 1L; protected String executionId; public FindActiveActivityIdsCmd(String executionId) { this.executionId = executionId; } @Override public List<String> execute(CommandContext commandContext) { if (executionId == null) { throw new FlowableIllegalArgumentException("executionId is null"); } ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext); ExecutionEntity execution = executionEntityManager.findById(executionId); if (execution == null) { throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class); } return findActiveActivityIds(execution); }
public List<String> findActiveActivityIds(ExecutionEntity executionEntity) { List<String> activeActivityIds = new ArrayList<>(); collectActiveActivityIds(executionEntity, activeActivityIds); return activeActivityIds; } protected void collectActiveActivityIds(ExecutionEntity executionEntity, List<String> activeActivityIds) { if (executionEntity.isActive() && executionEntity.getActivityId() != null) { activeActivityIds.add(executionEntity.getActivityId()); } for (ExecutionEntity childExecution : executionEntity.getExecutions()) { collectActiveActivityIds(childExecution, activeActivityIds); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\FindActiveActivityIdsCmd.java
1
请完成以下Java代码
public class X_CM_AccessNewsChannel extends PO implements I_CM_AccessNewsChannel, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_CM_AccessNewsChannel (Properties ctx, int CM_AccessNewsChannel_ID, String trxName) { super (ctx, CM_AccessNewsChannel_ID, trxName); /** if (CM_AccessNewsChannel_ID == 0) { setCM_AccessProfile_ID (0); setCM_NewsChannel_ID (0); } */ } /** Load Constructor */ public X_CM_AccessNewsChannel (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_CM_AccessNewsChannel[") .append(get_ID()).append("]"); return sb.toString(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile
*/ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_NewsChannel getCM_NewsChannel() throws RuntimeException { return (I_CM_NewsChannel)MTable.get(getCtx(), I_CM_NewsChannel.Table_Name) .getPO(getCM_NewsChannel_ID(), get_TrxName()); } /** Set News Channel. @param CM_NewsChannel_ID News channel for rss feed */ public void setCM_NewsChannel_ID (int CM_NewsChannel_ID) { if (CM_NewsChannel_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_NewsChannel_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_NewsChannel_ID, Integer.valueOf(CM_NewsChannel_ID)); } /** Get News Channel. @return News channel for rss feed */ public int getCM_NewsChannel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_NewsChannel_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessNewsChannel.java
1
请在Spring Boot框架中完成以下Java代码
public class AiOcrController { @Autowired private RedisUtil redisUtil; private static final String AI_OCR_REDIS_KEY = "airag:ocr"; @GetMapping("/list") public Result<?> list(){ Object aiOcr = redisUtil.get(AI_OCR_REDIS_KEY); IPage<AiOcr> page = new Page<>(1,10); if(null != aiOcr){ List<AiOcr> aiOcrList = JSONObject.parseArray(aiOcr.toString(), AiOcr.class); page.setRecords(aiOcrList); page.setTotal(aiOcrList.size()); page.setPages(aiOcrList.size()); } return Result.OK(page); } @PostMapping("/add") public Result<String> add(@RequestBody AiOcr aiOcr){ Object aiOcrList = redisUtil.get(AI_OCR_REDIS_KEY); aiOcr.setId(UUID.randomUUID().toString().replace("-","")); if(null == aiOcrList){ List<AiOcr> list = new ArrayList<>(); list.add(aiOcr); redisUtil.set(AI_OCR_REDIS_KEY, JSONObject.toJSONString(list)); }else{ List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrList.toString(), AiOcr.class); aiOcrs.add(aiOcr); redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrs)); } return Result.OK("添加成功"); } @PutMapping("/edit") public Result<String> updateById(@RequestBody AiOcr aiOcr){ Object aiOcrList = redisUtil.get(AI_OCR_REDIS_KEY); if(null != aiOcrList){ List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrList.toString(), AiOcr.class); aiOcrs.forEach(item->{ if(item.getId().equals(aiOcr.getId())){ BeanUtils.copyProperties(aiOcr,item); } }); redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrs)); }else{ return Result.OK("编辑失败,未找到该数据");
} return Result.OK("编辑成功"); } @DeleteMapping("/deleteById") public Result<String> deleteById(@RequestBody AiOcr aiOcr){ Object aiOcrObj = redisUtil.get(AI_OCR_REDIS_KEY); if(null != aiOcrObj){ List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrObj.toString(), AiOcr.class); List<AiOcr> aiOcrList = new ArrayList<>(); for(AiOcr ocr: aiOcrs){ if(!ocr.getId().equals(aiOcr.getId())){ aiOcrList.add(ocr); } } if(CollectionUtils.isNotEmpty(aiOcrList)){ redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrList)); }else{ redisUtil.removeAll(AI_OCR_REDIS_KEY); } }else{ return Result.OK("删除失败,未找到该数据"); } return Result.OK("删除成功"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\ocr\controller\AiOcrController.java
2
请完成以下Java代码
public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException { return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name) .getPO(getM_PromotionGroup_ID(), get_TrxName()); } /** Set Promotion Group. @param M_PromotionGroup_ID Promotion Group */ public void setM_PromotionGroup_ID (int M_PromotionGroup_ID) { if (M_PromotionGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID)); } /** Get Promotion Group. @return Promotion Group */ public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Group Line. @param M_PromotionGroupLine_ID Promotion Group Line */ public void setM_PromotionGroupLine_ID (int M_PromotionGroupLine_ID) { if (M_PromotionGroupLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, Integer.valueOf(M_PromotionGroupLine_ID)); } /** Get Promotion Group Line. @return Promotion Group Line */ public int getM_PromotionGroupLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroupLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroupLine.java
1
请完成以下Java代码
public void setDocumentNo (java.lang.String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } @Override public void setFirstname (java.lang.String Firstname) { set_ValueNoCheck (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return (java.lang.String)get_Value(COLUMNNAME_Firstname); } @Override public void setGrandTotal (java.math.BigDecimal GrandTotal) { set_ValueNoCheck (COLUMNNAME_GrandTotal, GrandTotal); } @Override public java.math.BigDecimal getGrandTotal() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_GrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setLastname (java.lang.String Lastname) { set_ValueNoCheck (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return (java.lang.String)get_Value(COLUMNNAME_Lastname); } @Override public void setprintjob (java.lang.String printjob) { set_ValueNoCheck (COLUMNNAME_printjob, printjob); } @Override public java.lang.String getprintjob() { return (java.lang.String)get_Value(COLUMNNAME_printjob); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_RV_Prt_Bericht_Statistik_List_Per_Org.java
1
请完成以下Java代码
public String getPrefix() { return "spring.rabbit.stream.template"; } @Override public KeyName[] getLowCardinalityKeyNames() { return TemplateLowCardinalityTags.values(); } }; /** * Low cardinality tags. */ public enum TemplateLowCardinalityTags implements KeyName { /** * Bean name of the template. */ BEAN_NAME { @Override public String asString() { return "spring.rabbit.stream.template.name"; } }
} /** * Default {@link RabbitStreamTemplateObservationConvention} for Rabbit template key values. */ public static class DefaultRabbitStreamTemplateObservationConvention implements RabbitStreamTemplateObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultRabbitStreamTemplateObservationConvention INSTANCE = new DefaultRabbitStreamTemplateObservationConvention(); @Override public KeyValues getLowCardinalityKeyValues(RabbitStreamMessageSenderContext context) { return KeyValues.of(RabbitStreamTemplateObservation.TemplateLowCardinalityTags.BEAN_NAME.asString(), context.getBeanName()); } @Override public String getContextualName(RabbitStreamMessageSenderContext context) { return context.getDestination() + " send"; } } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\micrometer\RabbitStreamTemplateObservation.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("caption", caption) .add("processId", processId) .add("quickAction", quickAction) .add("defaultQuickAction", defaultQuickAction) .toString(); } public String getCaption() { return caption; } public String getDescription() { return description; } @JsonIgnore public boolean isDisabled() { return disabled != null && disabled; } @JsonIgnore public boolean isEnabled() { return !isDisabled(); }
public boolean isQuickAction() { return quickAction; } public boolean isDefaultQuickAction() { return defaultQuickAction; } private int getSortNo() { return sortNo; } @JsonAnyGetter public Map<String, Object> getDebugProperties() { return debugProperties; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONDocumentAction.java
1
请在Spring Boot框架中完成以下Java代码
public class WorkplaceId implements RepoIdAware { int repoId; private WorkplaceId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Workplace_ID"); } public static WorkplaceId ofRepoId(final int repoId) {return new WorkplaceId(repoId);} @Nullable public static WorkplaceId ofRepoIdOrNull(final int repoId) {return repoId > 0 ? new WorkplaceId(repoId) : null;} public static Optional<WorkplaceId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static int toRepoId(@Nullable final WorkplaceId workplaceId) {return workplaceId != null ? workplaceId.getRepoId() : -1;} @Nullable
@JsonCreator public static WorkplaceId ofNullableObject(@Nullable final Object obj) { if (obj == null) { return null; } return RepoIdAwares.ofObject(obj, WorkplaceId.class, WorkplaceId::ofRepoId); } @Override @JsonValue public int getRepoId() {return repoId;} public static boolean equals(@Nullable final WorkplaceId id1, @Nullable final WorkplaceId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceId.java
2
请完成以下Java代码
private MLookup getLookupByColumnName(final String columnName) { final int displayType = poInfo.getColumnDisplayType(columnName); if (DisplayType.List == displayType) { final ReferenceId adReferenceId = poInfo.getColumnReferenceValueId(columnName); if (adReferenceId == null) { return null; } return listLookupsByReferenceId.computeIfAbsent(adReferenceId, k -> MLookupFactory.newInstance().searchInList(adReferenceId)); } else { final String referencedTableName = poInfo.getReferencedTableNameOrNull(columnName); if (referencedTableName == null) { return null; } return tableLookupsByTableName.computeIfAbsent(referencedTableName, k -> MLookupFactory.newInstance().searchInTable(referencedTableName)); } } private static Object normalizeLookupId(final Object idObj, final boolean isNumericId) {
// shall not happen if (idObj == null) { return null; } if (isNumericId) { return NumberUtils.asInteger(idObj, null); } else { return idObj.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogEntryValuesResolver.java
1
请在Spring Boot框架中完成以下Java代码
public void insertNewBook() { Author author = authorRepository.getOne(4L); // or, less efficient since a SELECT is triggered // Author author = authorRepository.findByName("Joana Nimar"); Book book = new Book(); book.setIsbn("003-JN"); book.setTitle("History Of Present"); book.setAuthor(author); bookRepository.save(book); } public void fetchBooksOfAuthorById() { List<Book> books = bookRepository.fetchBooksOfAuthorById(4L); System.out.println(books); } public void fetchPageBooksOfAuthorById() { Page<Book> books = bookRepository.fetchPageBooksOfAuthorById(4L, PageRequest.of(0, 2, Sort.by(Sort.Direction.ASC, "title"))); books.get().forEach(System.out::println); } @Transactional public void fetchBooksOfAuthorByIdAndAddNewBook() { List<Book> books = bookRepository.fetchBooksOfAuthorById(4L); Book book = new Book(); book.setIsbn("004-JN"); book.setTitle("History Facts");
book.setAuthor(books.get(0).getAuthor()); books.add(bookRepository.save(book)); System.out.println(books); } @Transactional public void fetchBooksOfAuthorByIdAndDeleteFirstBook() { List<Book> books = bookRepository.fetchBooksOfAuthorById(4L); bookRepository.delete(books.remove(0)); System.out.println(books); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJustManyToOne\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
default void processBatch(ConsumerRecords<K, V> records, List<ConsumerRecord<K, V>> recordList, Consumer<K, V> consumer, MessageListenerContainer container, Exception exception, boolean recoverable, ContainerProperties.EOSMode eosMode) { process(recordList, consumer, container, exception, recoverable, eosMode); } /** * Optional method to clear thread state; will be called just before a consumer * thread terminates. * @since 2.2 */ default void clearThreadState() { } /**
* Return true to invoke * {@link #process(List, Consumer, MessageListenerContainer, Exception, boolean, ContainerProperties.EOSMode)} * in a new transaction. Because the container cannot infer the desired behavior, the * processor is responsible for sending the offset to the transaction if it decides to * skip the failing record. * @return true to run in a transaction; default false. * @since 2.2.5 * @see #process(List, Consumer, MessageListenerContainer, Exception, boolean, * ContainerProperties.EOSMode) */ default boolean isProcessInTransaction() { return false; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\AfterRollbackProcessor.java
1
请完成以下Java代码
public ProcessInstance execute(CommandContext commandContext) { if (messageName == null) { throw new FlowableIllegalArgumentException("Cannot start process instance by message: message name is null"); } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); MessageEventSubscriptionEntity messageEventSubscription = processEngineConfiguration.getEventSubscriptionServiceConfiguration().getEventSubscriptionService() .findMessageStartEventSubscriptionByName(messageName, tenantId); if (messageEventSubscription == null) { throw new FlowableObjectNotFoundException("Cannot start process instance by message: no subscription to message with name '" + messageName + "' found.", MessageEventSubscriptionEntity.class); } String processDefinitionId = messageEventSubscription.getConfiguration(); if (processDefinitionId == null) { throw new FlowableException("Cannot start process instance by message: subscription to message with name '" + messageName + "' is not a message start event."); }
DeploymentManager deploymentCache = processEngineConfiguration.getDeploymentManager(); ProcessDefinition processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); if (processDefinition == null) { throw new FlowableObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", ProcessDefinition.class); } ProcessInstanceHelper processInstanceHelper = processEngineConfiguration.getProcessInstanceHelper(); ProcessInstance processInstance = processInstanceHelper.createAndStartProcessInstanceByMessage(processDefinition, messageName, businessKey, businessStatus, processVariables, transientVariables, callbackId, callbackType, referenceId, referenceType, ownerId, assigneeId); return processInstance; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\StartProcessInstanceByMessageCmd.java
1
请在Spring Boot框架中完成以下Java代码
public ItemPreparedStatementSetter<WriterSO> setter() { return (item, ps) -> { ps.setLong(1, item.getId()); ps.setString(2, item.getFullName()); ps.setString(3, item.getRandomNum()); }; } @Bean public Job importUserJob(JobBuilderFactory jobs, Step s1, JobExecutionListener listener) { return jobs.get("importUserJob") .incrementer(new RunIdIncrementer()) .listener(listener) .flow(s1) .end() .build(); }
@Bean public Step step1(StepBuilderFactory stepBuilderFactory, ItemReader<RecordSO> reader, ItemWriter<WriterSO> writer, ItemProcessor<RecordSO, WriterSO> processor) { return stepBuilderFactory.get("step1") .<RecordSO, WriterSO>chunk(5) .reader(reader) .processor(processor) .writer(writer) .build(); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }
repos\spring-boot-quick-master\quick-batch\src\main\java\com\quick\batch\config\BatchConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
boolean isPresent() { return this.matcher != null; } /** * Return the extension from the hint or return the parameter if the hint is not * {@link #isPresent() present}. * @param extension the fallback extension * @return the extension either from the hint or fallback */ String orElse(String extension) { return (this.matcher != null) ? toString() : extension; } @Override public String toString() { return (this.matcher != null) ? this.matcher.group(2) : ""; } /** * Return the {@link FileExtensionHint} from the given value. * @param value the source value
* @return the {@link FileExtensionHint} (never {@code null}) */ static FileExtensionHint from(String value) { Matcher matcher = PATTERN.matcher(value); return (matcher.matches()) ? new FileExtensionHint(matcher) : NONE; } /** * Remove any hint from the given value. * @param value the source value * @return the value without any hint */ static String removeFrom(String value) { Matcher matcher = PATTERN.matcher(value); return (matcher.matches()) ? matcher.group(1) : value; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\FileExtensionHint.java
2
请完成以下Java代码
public TypedValue getVariable(String variableName) { ExecutionEntity execution = getExecutionFromContext(); if (execution != null) { return execution.getVariableTyped(variableName); } else { return getScopedAssociation().getVariable(variableName); } } @Override public void setVariable(String variableName, Object value) { ExecutionEntity execution = getExecutionFromContext(); if(execution != null) { execution.setVariable(variableName, value); execution.getVariable(variableName); } else { getScopedAssociation().setVariable(variableName, value); } } @Override public TypedValue getVariableLocal(String variableName) { ExecutionEntity execution = getExecutionFromContext(); if (execution != null) { return execution.getVariableLocalTyped(variableName); } else { return getScopedAssociation().getVariableLocal(variableName); } } @Override public void setVariableLocal(String variableName, Object value) { ExecutionEntity execution = getExecutionFromContext(); if(execution != null) { execution.setVariableLocal(variableName, value); execution.getVariableLocal(variableName); } else { getScopedAssociation().setVariableLocal(variableName, value); } } protected ExecutionEntity getExecutionFromContext() { if(Context.getCommandContext() != null) { BpmnExecutionContext executionContext = Context.getBpmnExecutionContext();
if(executionContext != null) { return executionContext.getExecution(); } } return null; } public Task getTask() { ensureCommandContextNotActive(); return getScopedAssociation().getTask(); } public void setTask(Task task) { ensureCommandContextNotActive(); getScopedAssociation().setTask(task); } public VariableMap getCachedVariables() { ensureCommandContextNotActive(); return getScopedAssociation().getCachedVariables(); } public VariableMap getCachedLocalVariables() { ensureCommandContextNotActive(); return getScopedAssociation().getCachedVariablesLocal(); } public void flushVariableCache() { ensureCommandContextNotActive(); getScopedAssociation().flushVariableCache(); } protected void ensureCommandContextNotActive() { if(Context.getCommandContext() != null) { throw new ProcessEngineCdiException("Cannot work with scoped associations inside command context."); } } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\DefaultContextAssociationManager.java
1
请在Spring Boot框架中完成以下Java代码
public Object getDetails() { return this.delegate.getDetails(); } @Override public void setAuthenticated(boolean authenticated) { this.delegate.setAuthenticated(authenticated); } @Override public boolean isAuthenticated() { return this.delegate.isAuthenticated(); } @Override public String getName() { return this.delegate.getName(); } @Override public Collection<GrantedAuthority> getAuthorities() { return this.delegate.getAuthorities(); }
@Override public Map<String, Object> getTokenAttributes() { return this.delegate.getTokenAttributes(); } /** * Returns a JWT. It usually refers to a token string expressing with 'eyXXX.eyXXX.eyXXX' format. * * @return the token value as a String */ public String tokenValue() { return delegate.getToken().getTokenValue(); } /** * Extract Subject from JWT. Here, Subject is the user ID in UUID format. * * @return the user ID as a UUID */ public UUID userId() { return UUID.fromString(delegate.getName()); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthToken.java
2
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Approved. @param IsApproved Indicates if this document requires approval */ public void setIsApproved (boolean IsApproved) { set_Value (COLUMNNAME_IsApproved, Boolean.valueOf(IsApproved)); } /** Get Approved. @return Indicates if this document requires approval */ public boolean isApproved () { Object oo = get_Value(COLUMNNAME_IsApproved); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Change Notice. @param M_ChangeNotice_ID Bill of Materials (Engineering) Change Notice (Version) */ public void setM_ChangeNotice_ID (int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID)); } /** Get Change Notice. @return Bill of Materials (Engineering) Change Notice (Version) */ public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeNotice.java
1
请完成以下Java代码
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 org.compiere.model.I_M_Inventory getReversal() { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_M_Inventory.class); } @Override public void setReversal(final org.compiere.model.I_M_Inventory Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_M_Inventory.class, Reversal); } @Override public void setReversal_ID (final int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Reversal_ID); } @Override public int getReversal_ID() { return get_ValueAsInt(COLUMNNAME_Reversal_ID); } @Override public void setUpdateQty (final @Nullable java.lang.String UpdateQty) { set_Value (COLUMNNAME_UpdateQty, UpdateQty); } @Override public java.lang.String getUpdateQty() { return get_ValueAsString(COLUMNNAME_UpdateQty); } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID);
} @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Inventory.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceWithDetailsService { private final InvoiceWithDetailsRepository invoiceWithDetailsRepository; private final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class); public InvoiceWithDetailsService(@NonNull final InvoiceWithDetailsRepository invoiceWithDetailsRepository) { this.invoiceWithDetailsRepository = invoiceWithDetailsRepository; } public void copyDetailsToReversal(@NonNull final InvoiceId originalInvoiceId, @NonNull final InvoiceId reversalInvoiceId) { final List<I_C_Invoice_Detail> invoiceDetailRecords = invoiceWithDetailsRepository.getInvoiceDetailsListForInvoiceId(originalInvoiceId); for (final I_C_Invoice_Detail detail : invoiceDetailRecords) {
final I_C_Invoice_Detail reversedDetail = InterfaceWrapperHelper.newInstance(I_C_Invoice_Detail.class); InterfaceWrapperHelper.copyValues(detail, reversedDetail); if (reversedDetail.getC_InvoiceLine_ID() > 0) { reversedDetail.setC_InvoiceLine_ID(invoiceDAO .retrieveReversalLine(invoiceDAO .retrieveLineById(InvoiceAndLineId.ofRepoId(detail.getC_Invoice_ID(), detail.getC_InvoiceLine_ID())), reversalInvoiceId.getRepoId()).getC_InvoiceLine_ID()); } reversedDetail.setC_Invoice_ID(reversalInvoiceId.getRepoId()); InterfaceWrapperHelper.save(reversedDetail); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\detail\InvoiceWithDetailsService.java
2
请完成以下Java代码
public int getC_Job_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getC_Job_ID())); } /** 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); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); }
/** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java
1
请完成以下Java代码
public T getDelegate() { return this.delegate; } @Override public void registerSeekCallback(ConsumerSeekCallback callback) { if (this.seekAware != null) { this.seekAware.registerSeekCallback(callback); } } @Override public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) { if (this.seekAware != null) { this.seekAware.onPartitionsAssigned(assignments, callback); }
} @Override public void onPartitionsRevoked(@Nullable Collection<TopicPartition> partitions) { if (this.seekAware != null) { this.seekAware.onPartitionsRevoked(partitions); } } @Override public void onIdleContainer(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) { if (this.seekAware != null) { this.seekAware.onIdleContainer(assignments, callback); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\AbstractDelegatingMessageListenerAdapter.java
1
请完成以下Java代码
public class LaneImpl extends BaseElementImpl implements Lane { protected static Attribute<String> nameAttribute; protected static AttributeReference<PartitionElement> partitionElementRefAttribute; protected static ChildElement<PartitionElement> partitionElementChild; protected static ElementReferenceCollection<FlowNode, FlowNodeRef> flowNodeRefCollection; protected static ChildElement<ChildLaneSet> childLaneSetChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Lane.class, BPMN_ELEMENT_LANE) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<Lane>() { public Lane newInstance(ModelTypeInstanceContext instanceContext) { return new LaneImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); partitionElementRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_PARTITION_ELEMENT_REF) .qNameAttributeReference(PartitionElement.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); partitionElementChild = sequenceBuilder.element(PartitionElement.class) .build(); flowNodeRefCollection = sequenceBuilder.elementCollection(FlowNodeRef.class) .idElementReferenceCollection(FlowNode.class) .build(); childLaneSetChild = sequenceBuilder.element(ChildLaneSet.class) .build(); typeBuilder.build(); } public LaneImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name);
} public PartitionElement getPartitionElement() { return partitionElementRefAttribute.getReferenceTargetElement(this); } public void setPartitionElement(PartitionElement partitionElement) { partitionElementRefAttribute.setReferenceTargetElement(this, partitionElement); } public PartitionElement getPartitionElementChild() { return partitionElementChild.getChild(this); } public void setPartitionElementChild(PartitionElement partitionElement) { partitionElementChild.setChild(this, partitionElement); } public Collection<FlowNode> getFlowNodeRefs() { return flowNodeRefCollection.getReferenceTargetElements(this); } public ChildLaneSet getChildLaneSet() { return childLaneSetChild.getChild(this); } public void setChildLaneSet(ChildLaneSet childLaneSet) { childLaneSetChild.setChild(this, childLaneSet); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\LaneImpl.java
1
请完成以下Java代码
public abstract class BaseAiModelProcessor extends BaseEdgeProcessor { @Autowired private DataValidator<AiModel> aiModelValidator; protected Pair<Boolean, Boolean> saveOrUpdateAiModel(TenantId tenantId, AiModelId aiModelId, AiModelUpdateMsg aiModelUpdateMsg) { boolean isCreated = false; boolean isNameUpdated = false; try { AiModel aiModel = JacksonUtil.fromString(aiModelUpdateMsg.getEntity(), AiModel.class, true); if (aiModel == null) { throw new RuntimeException("[{" + tenantId + "}] aiModelUpdateMsg {" + aiModelUpdateMsg + " } cannot be converted to aiModel"); } Optional<AiModel> aiModelById = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId); if (aiModelById.isEmpty()) { aiModel.setCreatedTime(Uuids.unixTimestamp(aiModelId.getId())); isCreated = true; aiModel.setId(null); } else { aiModel.setId(aiModelId); } String aiModelName = aiModel.getName(); Optional<AiModel> aiModelByName = edgeCtx.getAiModelService().findAiModelByTenantIdAndName(aiModel.getTenantId(), aiModelName); if (aiModelByName.isPresent() && !aiModelByName.get().getId().equals(aiModelId)) { aiModelName = aiModelName + "_" + StringUtils.randomAlphabetic(15); log.warn("[{}] aiModel with name {} already exists. Renaming aiModel name to {}", tenantId, aiModel.getName(), aiModelByName.get().getName()); isNameUpdated = true; } aiModel.setName(aiModelName); aiModelValidator.validate(aiModel, AiModel::getTenantId); if (isCreated) {
aiModel.setId(aiModelId); } edgeCtx.getAiModelService().save(aiModel, false); } catch (Exception e) { log.error("[{}] Failed to process aiModel update msg [{}]", tenantId, aiModelUpdateMsg, e); throw e; } return Pair.of(isCreated, isNameUpdated); } protected void deleteAiModel(TenantId tenantId, Edge edge, AiModelId aiModelId) { Optional<AiModel> aiModel = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId); if (aiModel.isPresent()) { edgeCtx.getAiModelService().deleteByTenantIdAndId(tenantId, aiModelId); pushEntityEventToRuleEngine(tenantId, edge, aiModel.get(), TbMsgType.ENTITY_DELETED); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\ai\BaseAiModelProcessor.java
1
请完成以下Java代码
public List<CellValue> getHeaderNames() { final List<String> headerNames = new ArrayList<>(); if (m_columnHeaders == null || m_columnHeaders.isEmpty()) { // use the next data row; can be the first, but if we add another sheet, it can also be another one. stepToNextRow(); for (Object headerNameObj : currentRow) { headerNames.add(headerNameObj != null ? headerNameObj.toString() : null); } } else { headerNames.addAll(m_columnHeaders); } final ArrayList<CellValue> result = new ArrayList<>(); final String adLanguage = getLanguage().getAD_Language(); for (final String rawHeaderName : headerNames) { final String headerName; if (translateHeaders) { headerName = msgBL.translatable(rawHeaderName).translate(adLanguage); } else { headerName = rawHeaderName; } result.add(CellValues.toCellValue(headerName)); } return result; } @Override public int getRowCount() { return m_data.size() - 1; } @Override public boolean isColumnPrinted(final int col)
{ return true; } @Override public boolean isFunctionRow(final int row) { return false; } @Override public boolean isPageBreak(final int row, final int col) { return false; } @Override protected List<CellValue> getNextRow() { stepToNextRow(); return CellValues.toCellValues(currentRow); } private void stepToNextRow() { currentRow = m_data.get(currentRowNumber); currentRowNumber++; } @Override protected boolean hasNextRow() { return currentRowNumber < m_data.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ArrayExcelExporter.java
1
请在Spring Boot框架中完成以下Java代码
private boolean killProcess() { boolean flag = false; try { if (OSUtils.IS_OS_WINDOWS) { Process p = Runtime.getRuntime().exec("cmd /c tasklist "); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } String s = baos.toString(); if (s.contains("soffice.bin")) { Runtime.getRuntime().exec("taskkill /im " + "soffice.bin" + " /f"); flag = true; } } else if (OSUtils.IS_OS_MAC || OSUtils.IS_OS_MAC_OSX) { Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", "ps -ef | grep " + "soffice.bin"}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } String s = baos.toString(); if (StringUtils.ordinalIndexOf(s, "soffice.bin", 3) > 0) { String[] cmd = {"sh", "-c", "kill -15 `ps -ef|grep " + "soffice.bin" + "|awk 'NR==1{print $2}'`"}; Runtime.getRuntime().exec(cmd); flag = true; } } else { Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", "ps -ef | grep " + "soffice.bin" + " |grep -v grep | wc -l"}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } String s = baos.toString(); if (!s.startsWith("0")) { String[] cmd = {"sh", "-c", "ps -ef | grep soffice.bin | grep -v grep | awk '{print \"kill -9 \"$2}' | sh"}; Runtime.getRuntime().exec(cmd);
flag = true; } } } catch (IOException e) { logger.error("检测office进程异常", e); } return flag; } @PreDestroy public void destroyOfficeManager() { if (null != officeManager && officeManager.isRunning()) { logger.info("Shutting down office process"); OfficeUtils.stopQuietly(officeManager); } } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\OfficePluginManager.java
2
请完成以下Java代码
public static void disconnect(Session session) { if (session != null) { if (session.isConnected()) { try { session.disconnect(); log.info("session disconnect successfully"); } catch (Exception e) { log.error("JSch session disconnect error:", e); } } } } /** * close connection * * @param channel channel connection */ 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 Integer getConcurrency() { return concurrency; } public void setConcurrency(Integer concurrency) { this.concurrency = concurrency; } @Override public Boolean getAutoStartup() { return null; } @Override public Properties getConsumerProperties() { return consumerProperties; } public void setConsumerProperties(Properties consumerProperties) { this.consumerProperties = consumerProperties; } @Override public void setupListenerContainer(MessageListenerContainer listenerContainer, MessageConverter messageConverter) { GenericMessageListener<ConsumerRecord<K, V>> messageListener = getMessageListener(); Assert.state(messageListener != null, () -> "Endpoint [" + this + "] must provide a non null message listener"); listenerContainer.setupMessageListener(messageListener); } @Override public boolean isSplitIterables() { return splitIterables; } public void setSplitIterables(boolean splitIterables) { this.splitIterables = splitIterables; } @Override public String getMainListenerId() { return mainListenerId; } public void setMainListenerId(String mainListenerId) { this.mainListenerId = mainListenerId; } @Override
public void afterPropertiesSet() throws Exception { boolean topicsEmpty = getTopics().isEmpty(); boolean topicPartitionsEmpty = ObjectUtils.isEmpty(getTopicPartitionsToAssign()); if (!topicsEmpty && !topicPartitionsEmpty) { throw new IllegalStateException("Topics or topicPartitions must be provided but not both for " + this); } if (this.topicPattern != null && (!topicsEmpty || !topicPartitionsEmpty)) { throw new IllegalStateException("Only one of topics, topicPartitions or topicPattern must are allowed for " + this); } if (this.topicPattern == null && topicsEmpty && topicPartitionsEmpty) { throw new IllegalStateException("At least one of topics, topicPartitions or topicPattern must be provided " + "for " + this); } } @Override public String toString() { return getClass().getSimpleName() + "[" + this.id + "] topics=" + this.topics + "' | topicPattern='" + this.topicPattern + "'" + "' | topicPartitions='" + this.topicPartitions + "'" + " | messageListener='" + messageListener + "'"; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\SimpleKafkaListenerEndpoint.java
1
请完成以下Java代码
public IValidationContext createValidationContext(@NonNull final GridField gridField) { final GridTab gridTab = gridField.getGridTab(); // Check.assumeNotNull(gridTab, "gridTab not null"); if (gridTab == null) { return createValidationContext(gridField, ROWINDEX_None); } // If GridTab is not open we don't have an Row Index anyways // Case: open a window with High Volume. Instead of getting the window opened, // you will get a popup to filter records before window actually opens. // If you try to set on of the filtering fields you will get "===========> GridTab.verifyRow: Table not open". if (!gridTab.isOpen()) { return createValidationContext(gridField, ROWINDEX_None); } final int rowIndex = gridTab.getCurrentRow(); return createValidationContext(gridField, rowIndex); } @Override public IValidationContext createValidationContext(final GridField gridField, final int rowIndex) { final Properties ctx = Env.getCtx(); String tableName = null; final Lookup lookup = gridField.getLookup(); if (lookup != null) { final IValidationContext parentEvalCtx = lookup.getValidationContext(); if (parentEvalCtx != null) { tableName = parentEvalCtx.getTableName(); }
} if (tableName == null) { return IValidationContext.DISABLED; } // // Check if is a Process Parameter/Form field final GridFieldVO gridFieldVO = gridField.getVO(); if (gridFieldVO.isProcessParameter() || gridFieldVO.isFormField()) { return createValidationContext(ctx, gridField.getWindowNo(), Env.TAB_None, tableName); } final GridTab gridTab = gridField.getGridTab(); if (gridTab != null) { return createValidationContext(ctx, tableName, gridTab, rowIndex); } return IValidationContext.NULL; } @Override public IValidationContext createValidationContext(final Evaluatee evaluatee) { return new EvaluateeValidationContext(evaluatee); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\ValidationRuleFactory.java
1
请完成以下Java代码
protected void writePlanItemDefinitionBody(CmmnModel model, T serviceTask, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception { super.writePlanItemDefinitionBody(model, serviceTask, xtw, options); } public static class ServiceTaskExport extends AbstractServiceTaskExport<ServiceTask> { @Override protected Class<? extends ServiceTask> getExportablePlanItemDefinitionClass() { return ServiceTask.class; } } public static class HttpServiceTaskExport extends AbstractServiceTaskExport<HttpServiceTask> { @Override protected Class<? extends HttpServiceTask> getExportablePlanItemDefinitionClass() { return HttpServiceTask.class; } } public static class ScriptServiceTaskExport extends AbstractServiceTaskExport<ScriptServiceTask> { @Override protected Class<? extends ScriptServiceTask> getExportablePlanItemDefinitionClass() { return ScriptServiceTask.class; } @Override protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, ScriptServiceTask serviceTask, boolean didWriteExtensionElement, XMLStreamWriter xtw) throws Exception { boolean extensionElementWritten = super.writePlanItemDefinitionExtensionElements(model, serviceTask, didWriteExtensionElement, xtw); extensionElementWritten = CmmnXmlUtil.writeIOParameters(ELEMENT_EXTERNAL_WORKER_IN_PARAMETER, serviceTask.getInParameters(), extensionElementWritten, xtw); return extensionElementWritten; } }
public static class FormAwareServiceTaskExport extends AbstractServiceTaskExport<FormAwareServiceTask> { @Override protected Class<? extends FormAwareServiceTask> getExportablePlanItemDefinitionClass() { return FormAwareServiceTask.class; } @Override public void writePlanItemDefinitionSpecificAttributes(FormAwareServiceTask formAwareServiceTask, XMLStreamWriter xtw) throws Exception { super.writePlanItemDefinitionSpecificAttributes(formAwareServiceTask, xtw); if (StringUtils.isNotBlank(formAwareServiceTask.getFormKey())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_KEY, formAwareServiceTask.getFormKey()); } if (StringUtils.isNotBlank(formAwareServiceTask.getValidateFormFields())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FIELD_VALIDATION, formAwareServiceTask.getValidateFormFields()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\AbstractServiceTaskExport.java
1
请完成以下Java代码
public Mono<Instance> save(Instance instance) { return super.save(instance).doOnError(OptimisticLockingException.class, (e) -> this.outdatedSnapshots.add(instance.getId())); } public void start() { this.subscription = this.eventStore.findAll().concatWith(this.eventStore).subscribe(this::updateSnapshot); } public void stop() { if (this.subscription != null) { this.subscription.dispose(); this.subscription = null; } } protected Mono<Instance> rehydrateSnapshot(InstanceId id) { return super.find(id).map((instance) -> this.snapshots.compute(id, (key, snapshot) -> { // check if the loaded version hasn't been already outdated by a snapshot if (snapshot == null || instance.getVersion() >= snapshot.getVersion()) { return instance; } else { return snapshot; } })); }
protected void updateSnapshot(InstanceEvent event) { try { this.snapshots.compute(event.getInstance(), (key, old) -> { Instance instance = (old != null) ? old : Instance.create(key); if (event.getVersion() > instance.getVersion()) { return instance.apply(event); } return instance; }); } catch (Exception ex) { log.warn("Error while updating the snapshot with event {}", event, ex); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\SnapshottingInstanceRepository.java
1
请完成以下Java代码
void doFind() { FindDialog dlg = new FindDialog(); //dlg.setLocation(linkActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getSize(); //dlg.setSize(400, 300); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); if (editor.getSelectedText() != null) dlg.txtSearch.setText(editor.getSelectedText()); else if (Context.get("LAST_SEARCHED_WORD") != null) dlg.txtSearch.setText(Context.get("LAST_SEARCHED_WORD").toString()); dlg.setVisible(true); if (dlg.CANCELLED) return; Context.put("LAST_SEARCHED_WORD", dlg.txtSearch.getText()); String repl = null; if (dlg.chkReplace.isSelected()) repl = dlg.txtReplace.getText(); Finder finder = new Finder( this, dlg.txtSearch.getText(), dlg.chkWholeWord.isSelected(), dlg.chkCaseSens.isSelected(), dlg.chkRegExp.isSelected(), repl); finder.start(); } // metas: begin public String getHtmlText() { try { StringWriter sw = new StringWriter(); new AltHTMLWriter(sw, this.document).write(); // new HTMLWriter(sw, editor.document).write(); String html = sw.toString(); return html; } catch (Exception e) { e.printStackTrace(); } return null; } public HTMLDocument getDocument() { return this.document; }
@Override public void requestFocus() { this.editor.requestFocus(); } @Override public boolean requestFocus(boolean temporary) { return this.editor.requestFocus(temporary); } @Override public boolean requestFocusInWindow() { return this.editor.requestFocusInWindow(); } public void setText(String html) { this.editor.setText(html); } public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public ActionMap getEditorActionMap() { return this.editor.getActionMap(); } public InputMap getEditorInputMap(int condition) { return this.editor.getInputMap(condition); } public Keymap getEditorKeymap() { return this.editor.getKeymap(); } public JTextComponent getTextComponent() { return this.editor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java
1
请完成以下Java代码
public String getFirstName() { return this.firstName; } public String getEmail() { return email; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; CustomUserDetails that = (CustomUserDetails) o; return firstName.equals(that.firstName) && lastName.equals(that.lastName) && email.equals(that.email); } @Override public int hashCode() { return Objects.hash(super.hashCode(), firstName, lastName, email); } public static class Builder { private String firstName; private String lastName; private String email; private String username; private String password; private Collection<? extends GrantedAuthority> authorities; public Builder withFirstName(String firstName) { this.firstName = firstName; return this;
} public Builder withLastName(String lastName) { this.lastName = lastName; return this; } public Builder withEmail(String email) { this.email = email; return this; } public Builder withUsername(String username) { this.username = username; return this; } public Builder withPassword(String password) { this.password = password; return this; } public Builder withAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; return this; } public CustomUserDetails build() { return new CustomUserDetails(this); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-thymeleaf\src\main\java\com\baeldung\customuserdetails\CustomUserDetails.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { return CommandContextUtil.getTokenEntityManager(commandContext).findTokenCountByQueryCriteria(this); } @Override public List<Token> executeList(CommandContext commandContext) { return CommandContextUtil.getTokenEntityManager(commandContext).findTokenByQueryCriteria(this); } // getters ////////////////////////////////////////////////////////// @Override public String getId() { return id; } public List<String> getIds() { return ids; } public String getTokenValue() { return tokenValue; } public Date getTokenDate() { return tokenDate; } public Date getTokenDateBefore() { return tokenDateBefore; } public Date getTokenDateAfter() { return tokenDateAfter; } public String getIpAddress() { return ipAddress; }
public String getIpAddressLike() { return ipAddressLike; } public String getUserAgent() { return userAgent; } public String getUserAgentLike() { return userAgentLike; } public String getUserId() { return userId; } public String getUserIdLike() { return userIdLike; } public String getTokenData() { return tokenData; } public String getTokenDataLike() { return tokenDataLike; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\TokenQueryImpl.java
1
请完成以下Java代码
public Integer getCaseDefinitionVersion() { return caseDefinitionVersion; } @Override public void setCaseDefinitionVersion(Integer caseDefinitionVersion) { this.caseDefinitionVersion = caseDefinitionVersion; } @Override public String getCaseDefinitionDeploymentId() { return caseDefinitionDeploymentId; } @Override public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) {
this.caseDefinitionDeploymentId = caseDefinitionDeploymentId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricCaseInstance[id=").append(id) .append(", caseDefinitionId=").append(caseDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityImpl.java
1
请完成以下Java代码
public boolean isTenantIdSet() { return isTenantIdSet; } public void setTenantIdSet(boolean isTenantIdSet) { this.isTenantIdSet = isTenantIdSet; } public String[] getTenantIds() { return tenantIds; } public void setTenantIds(String[] tenantIds) { isTenantIdSet = true; this.tenantIds = tenantIds; } public List<QueryVariableValue> getFilterVariables() { return filterVariables; } public void setFilterVariables(Map<String, Object> filterVariables) { QueryVariableValue variableValue; for (Map.Entry<String, Object> filter : filterVariables.entrySet()) { variableValue = new QueryVariableValue(filter.getKey(), filter.getValue(), null, false); this.filterVariables.add(variableValue); } } public void addFilterVariable(String name, Object value) { QueryVariableValue variableValue = new QueryVariableValue(name, value, QueryOperator.EQUALS, true); this.filterVariables.add(variableValue); } public Long getLockDuration() { return lockDuration; } public String getTopicName() { return topicName; } public boolean isDeserializeVariables() { return deserializeVariables; } public void setDeserializeVariables(boolean deserializeVariables) {
this.deserializeVariables = deserializeVariables; } public void ensureVariablesInitialized() { if (!filterVariables.isEmpty()) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers(); String dbType = processEngineConfiguration.getDatabaseType(); for(QueryVariableValue queryVariableValue : filterVariables) { queryVariableValue.initialize(variableSerializers, dbType); } } } public boolean isLocalVariables() { return localVariables; } public void setLocalVariables(boolean localVariables) { this.localVariables = localVariables; } public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\TopicFetchInstruction.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setMovementDate (final java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setMovementQty (final BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } @Override public BigDecimal getMovementQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPosted (final boolean Posted) { set_Value (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_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 org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine() { return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class); } @Override public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine) { set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine); } @Override public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID) { if (S_TimeExpenseLine_ID < 1) set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null); else set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID); } @Override public int getS_TimeExpenseLine_ID() { return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java
1
请完成以下Java代码
public static char bytesHighFirstToChar(byte[] bytes, int start) { char c = (char) (((bytes[start] & 0xFF) << 8) | (bytes[start + 1] & 0xFF)); return c; } /** * 读取float,高位在前 * * @param bytes * @param start * @return */ public static float bytesHighFirstToFloat(byte[] bytes, int start) { int l = bytesHighFirstToInt(bytes, start); return Float.intBitsToFloat(l); } /** * 无符号整型输出 * @param out * @param uint * @throws IOException */
public static void writeUnsignedInt(DataOutputStream out, int uint) throws IOException { out.writeByte((byte) ((uint >>> 8) & 0xFF)); out.writeByte((byte) ((uint >>> 0) & 0xFF)); } public static int convertTwoCharToInt(char high, char low) { int result = high << 16; result |= low; return result; } public static char[] convertIntToTwoChar(int n) { char[] result = new char[2]; result[0] = (char) (n >>> 16); result[1] = (char) (0x0000FFFF & n); return result; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\ByteUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class UaaSignatureVerifierClient implements OAuth2SignatureVerifierClient { private final Logger log = LoggerFactory.getLogger(UaaSignatureVerifierClient.class); private final RestTemplate restTemplate; protected final OAuth2Properties oAuth2Properties; public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate, OAuth2Properties oAuth2Properties) { this.restTemplate = restTemplate; this.oAuth2Properties = oAuth2Properties; // Load available UAA servers discoveryClient.getServices(); } /** * Fetches the public key from the UAA. * * @return the public key used to verify JWT tokens; or null. */ @Override public SignatureVerifier getSignatureVerifier() throws Exception { try { HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders());
String key = (String) restTemplate .exchange(getPublicKeyEndpoint(), HttpMethod.GET, request, Map.class).getBody() .get("value"); return new RsaVerifier(key); } catch (IllegalStateException ex) { log.warn("could not contact UAA to get public key"); return null; } } /** Returns the configured endpoint URI to retrieve the public key. */ private String getPublicKeyEndpoint() { String tokenEndpointUrl = oAuth2Properties.getSignatureVerification().getPublicKeyEndpointUri(); if (tokenEndpointUrl == null) { throw new InvalidClientException("no token endpoint configured in application properties"); } return tokenEndpointUrl; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\UaaSignatureVerifierClient.java
2
请完成以下Java代码
public XMLGregorianCalendar getFctvDt() { return fctvDt; } /** * Sets the value of the fctvDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setFctvDt(XMLGregorianCalendar value) { this.fctvDt = value; } /** * Gets the value of the xpryDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getXpryDt() { return xpryDt; } /** * Sets the value of the xpryDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setXpryDt(XMLGregorianCalendar value) { this.xpryDt = value; } /** * Gets the value of the svcCd property. * * @return * possible object is * {@link String } * */ public String getSvcCd() { return svcCd; } /** * Sets the value of the svcCd property. * * @param value * allowed object is * {@link String } * */ public void setSvcCd(String value) { this.svcCd = value; } /** * Gets the value of the trckData property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the trckData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTrckData().add(newItem); * </pre> * * * <p>
* Objects of the following type(s) are allowed in the list * {@link TrackData1 } * * */ public List<TrackData1> getTrckData() { if (trckData == null) { trckData = new ArrayList<TrackData1>(); } return this.trckData; } /** * Gets the value of the cardSctyCd property. * * @return * possible object is * {@link CardSecurityInformation1 } * */ public CardSecurityInformation1 getCardSctyCd() { return cardSctyCd; } /** * Sets the value of the cardSctyCd property. * * @param value * allowed object is * {@link CardSecurityInformation1 } * */ public void setCardSctyCd(CardSecurityInformation1 value) { this.cardSctyCd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PlainCardData1.java
1
请完成以下Java代码
public class DefaultAttributeValueContext implements IAttributeValueContext { private final Map<String, Object> parameters; public DefaultAttributeValueContext() { this(null); } protected DefaultAttributeValueContext(final Map<String, Object> parameters) { super(); if (parameters == null || parameters.isEmpty()) { this.parameters = new HashMap<String, Object>(); } else { this.parameters = new HashMap<String, Object>(parameters); } } @Override public IAttributeValueContext copy() { return new DefaultAttributeValueContext(parameters); } @Override public final Object setParameter(final String parameterName, final Object value) { final Object valueOld = parameters.put(parameterName, value);
return valueOld; } @Override public final <T> T getParameter(final String parameterName) { @SuppressWarnings("unchecked") final T value = (T)parameters.get(parameterName); return value; } protected final Map<String, Object> getParameters() { return new HashMap<String, Object>(parameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\spi\impl\DefaultAttributeValueContext.java
1
请完成以下Java代码
public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Mandatory Parameters. @param IsManadatoryParams Mandatory Parameters */ @Override public void setIsManadatoryParams (boolean IsManadatoryParams) { set_Value (COLUMNNAME_IsManadatoryParams, Boolean.valueOf(IsManadatoryParams)); } /** Get Mandatory Parameters. @return Mandatory Parameters */ @Override public boolean isManadatoryParams () { Object oo = get_Value(COLUMNNAME_IsManadatoryParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Display All Parameters. @param IsShowAllParams Display All Parameters */ @Override public void setIsShowAllParams (boolean IsShowAllParams) {
set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams)); } /** Get Display All Parameters. @return Display All Parameters */ @Override public boolean isShowAllParams () { Object oo = get_Value(COLUMNNAME_IsShowAllParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
1
请完成以下Java代码
int[] middleOfArrayWithStartEnd(int[] array, int start, int end) { int mid = start + (end - start) / 2; int n = end - start; if (n % 2 == 0) { int mid2 = mid - 1; return new int[] { array[mid2], array[mid] }; } else { return new int[] { array[mid] }; } } int[] middleOfArrayWithStartEndBitwise(int[] array, int start, int end) { int mid = (start + end) >>> 1; int n = end - start; if (n % 2 == 0) { int mid2 = mid - 1; return new int[] { array[mid2], array[mid] };
} else { return new int[] { array[mid] }; } } int medianOfArray(int[] array, int start, int end) { Arrays.sort(array); // for safety. This can be ignored int mid = (start + end) >>> 1; int n = end - start; if (n % 2 == 0) { int mid2 = mid - 1; return (array[mid2] + array[mid]) / 2; } else { return array[mid]; } } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\arraymiddle\MiddleOfArray.java
1
请完成以下Java代码
public static Exception lookupExceptionInCause(Throwable source, Class<? extends Exception>... clazzes) { while (source != null) { for (Class<? extends Exception> clazz : clazzes) { if (clazz.isAssignableFrom(source.getClass())) { return (Exception) source; } } source = source.getCause(); } return null; } public static String toString(Exception e, EntityId componentId, boolean stackTraceEnabled) { Exception exception = lookupExceptionInCause(e, ScriptException.class, JsonParseException.class); if (exception != null && StringUtils.isNotEmpty(exception.getMessage())) { return exception.getMessage(); } else { if (stackTraceEnabled) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return sw.toString(); } else {
log.debug("[{}] Unknown error during message processing", componentId, e); return "Please contact system administrator"; } } } public static String getMessage(Throwable t) { String message = t.getMessage(); if (StringUtils.isNotEmpty(message)) { return message; } else { return t.getClass().getSimpleName(); } } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\ExceptionUtil.java
1
请完成以下Java代码
public Authentication convert(HttpServletRequest request) { MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request); if (parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE) == null || parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION) == null) { return null; } // client_assertion_type (REQUIRED) String clientAssertionType = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE); if (parameters.get(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } if (!JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD.getValue().equals(clientAssertionType)) { return null; } // client_assertion (REQUIRED) String jwtAssertion = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION); if (parameters.get(OAuth2ParameterNames.CLIENT_ASSERTION).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
} // client_id (OPTIONAL as per specification but REQUIRED by this implementation) String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID); if (!StringUtils.hasText(clientId) || parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } Map<String, Object> additionalParameters = OAuth2EndpointUtils .getParametersIfMatchesAuthorizationCodeGrantRequest(request, OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, OAuth2ParameterNames.CLIENT_ASSERTION, OAuth2ParameterNames.CLIENT_ID); return new OAuth2ClientAuthenticationToken(clientId, JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, jwtAssertion, additionalParameters); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\JwtClientAssertionAuthenticationConverter.java
1
请完成以下Java代码
public final void setClob(final String parameterName, final Clob x) throws SQLException { getCCallableStatementImpl().setClob(parameterName, x); } @Override public final void setAsciiStream(final String parameterName, final InputStream x, final long length) throws SQLException { getCCallableStatementImpl().setAsciiStream(parameterName, x, length); } @Override public final void setBinaryStream(final String parameterName, final InputStream x, final long length) throws SQLException { getCCallableStatementImpl().setBinaryStream(parameterName, x, length); } @Override public final void setCharacterStream(final String parameterName, final Reader reader, final long length) throws SQLException { getCCallableStatementImpl().setCharacterStream(parameterName, reader, length); } @Override public final void setAsciiStream(final String parameterName, final InputStream x) throws SQLException { getCCallableStatementImpl().setAsciiStream(parameterName, x); } @Override public final void setBinaryStream(final String parameterName, final InputStream x) throws SQLException { getCCallableStatementImpl().setBinaryStream(parameterName, x); } @Override public final void setCharacterStream(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setCharacterStream(parameterName, reader); } @Override public final void setNCharacterStream(final String parameterName, final Reader value) throws SQLException { getCCallableStatementImpl().setNCharacterStream(parameterName, value); }
@Override public final void setClob(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setClob(parameterName, reader); } @Override public final void setBlob(final String parameterName, final InputStream inputStream) throws SQLException { getCCallableStatementImpl().setBlob(parameterName, inputStream); } @Override public final void setNClob(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setNClob(parameterName, reader); } @Override public <T> T getObject(int parameterIndex, Class<T> type) throws SQLException { return getCCallableStatementImpl().getObject(parameterIndex, type); } @Override public <T> T getObject(String parameterName, Class<T> type) throws SQLException { return getCCallableStatementImpl().getObject(parameterName, type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CCallableStatementProxy.java
1
请完成以下Java代码
public static <A extends Annotation> SecurityAnnotationScanner<A> requireUnique(Class<A> type) { return requireUnique(type, new AnnotationTemplateExpressionDefaults()); } /** * Create a {@link SecurityAnnotationScanner} that requires synthesized annotations to * be unique on the given {@link AnnotatedElement}. * * <p> * When a {@link AnnotationTemplateExpressionDefaults} is provided, it will return a * scanner that supports placeholders in the annotation's attributes in addition to * the meta-annotation synthesizing provided by {@link #requireUnique(Class)}. * @param type the annotation type * @param templateDefaults the defaults for resolving placeholders in the annotation's * attributes * @param <A> the annotation type * @return the default {@link SecurityAnnotationScanner} */ public static <A extends Annotation> SecurityAnnotationScanner<A> requireUnique(Class<A> type, AnnotationTemplateExpressionDefaults templateDefaults) { return (SecurityAnnotationScanner<A>) uniqueTemplateScanners.computeIfAbsent(type,
(t) -> new ExpressionTemplateSecurityAnnotationScanner<>(t, templateDefaults)); } /** * Create a {@link SecurityAnnotationScanner} that requires synthesized annotations to * be unique on the given {@link AnnotatedElement}. Supplying multiple types implies * that the synthesized annotation must be unique across all specified types. * @param types the annotation types * @return the default {@link SecurityAnnotationScanner} */ public static SecurityAnnotationScanner<Annotation> requireUnique(List<Class<? extends Annotation>> types) { List<Class<Annotation>> casted = new ArrayList<>(); types.forEach((type) -> casted.add((Class<Annotation>) type)); return (SecurityAnnotationScanner<Annotation>) uniqueTypesScanners.computeIfAbsent(types, (t) -> new UniqueSecurityAnnotationScanner<>(casted)); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\annotation\SecurityAnnotationScanners.java
1
请完成以下Java代码
public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } /** Set SKU. @param SKU Stock Keeping Unit */ public void setSKU (String SKU) { set_Value (COLUMNNAME_SKU, SKU); } /** Get SKU. @return Stock Keeping Unit */ public String getSKU () { return (String)get_Value(COLUMNNAME_SKU); } /** Set Tax Amount. @param TaxAmt Tax Amount for a document */ public void setTaxAmt (BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Tax Amount. @return Tax Amount for a document */ public BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Tax Indicator. @param TaxIndicator Short form for Tax to be printed on documents */ public void setTaxIndicator (String TaxIndicator)
{ set_Value (COLUMNNAME_TaxIndicator, TaxIndicator); } /** Get Tax Indicator. @return Short form for Tax to be printed on documents */ public String getTaxIndicator () { return (String)get_Value(COLUMNNAME_TaxIndicator); } /** Set UPC/EAN. @param UPC Bar Code (Universal Product Code or its superset European Article Number) */ public void setUPC (String UPC) { set_Value (COLUMNNAME_UPC, UPC); } /** Get UPC/EAN. @return Bar Code (Universal Product Code or its superset European Article Number) */ public String getUPC () { return (String)get_Value(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java
1
请完成以下Java代码
public Builder notifyDevice(boolean notifyDevice) { this.notifyDevice = notifyDevice; return this; } public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = previousCalculatedFieldIds; return this; } public Builder tbMsgId(UUID tbMsgId) { this.tbMsgId = tbMsgId; return this; } public Builder tbMsgType(TbMsgType tbMsgType) { this.tbMsgType = tbMsgType; return this; } public Builder callback(FutureCallback<Void> callback) { this.callback = callback; return this; } public Builder future(SettableFuture<Void> future) { return callback(new FutureCallback<>() { @Override public void onSuccess(Void result) { future.set(result); } @Override
public void onFailure(Throwable t) { future.setException(t); } }); } public AttributesDeleteRequest build() { return new AttributesDeleteRequest( tenantId, entityId, scope, keys, notifyDevice, previousCalculatedFieldIds, tbMsgId, tbMsgType, requireNonNullElse(callback, NoOpFutureCallback.instance()) ); } } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\AttributesDeleteRequest.java
1
请完成以下Spring Boot application配置
spring.ai.ollama.chat.options.model=hf.co/microsoft/Phi-3-mini-4k-instruct-gguf spring.ai.ollama.embedding.options.model=hf.co/nomic-ai/nomic-embed-tex
t-v1.5-GGUF spring.ai.ollama.init.pull-model-strategy=when_missing
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\resources\application-huggingface.properties
2
请完成以下Java代码
public void setJsonResponse (java.lang.String JsonResponse) { set_Value (COLUMNNAME_JsonResponse, JsonResponse); } @Override public java.lang.String getJsonResponse() { return (java.lang.String)get_Value(COLUMNNAME_JsonResponse); } @Override public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID) { if (PP_Cost_Collector_ImportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID)); } @Override public int getPP_Cost_Collector_ImportAudit_ID()
{ return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAudit.java
1
请完成以下Java代码
public void ctxRefreshed(ContextRefreshedEvent evt) { initData(); } public void initData() { log.info("Context Refreshed !!, Initializing environment (db, folders etc)... "); File uploadFolder = new File(appProperties.getFileStorage().getUploadFolder()); if (!uploadFolder.exists()) { if (uploadFolder.mkdirs() && Stream.of(ReceivedFile.FileGroup.values()).allMatch(f -> new File(uploadFolder.getAbsolutePath() + File.separator + f.path).mkdir())) { log.info("Upload folder created successfully"); } else { log.info("Failure to create upload folder"); } } if (userService.existsByUsername("system")) { log.info("DB already initialized !!!"); return; } Authority adminAuthority = new Authority(); adminAuthority.setName(Constants.ROLE_ADMIN); authorityService.save(adminAuthority); Authority userAuthority = new Authority(); userAuthority.setName(Constants.ROLE_USER); authorityService.save(userAuthority); String systemUserId = "a621ac4c-6172-4103-9050-b27c053b11eb"; if (userService.exists(UUID.fromString(systemUserId))) { log.info("DB already initialized !!!"); return; } //ID and login are linked with the keycloak export json AppUser adminUser = new AppUser(systemUserId, "system", "System", "Tiwari", "system@email"); userService.save(adminUser); AppUser user1 = new AppUser("d1460f56-7f7e-43e1-8396-bddf39dba08f", "user1", "Ganesh", "Tiwari", "user1@email"); userService.save(user1); AppUser user2 = new AppUser("fa6820a5-cf39-4cbf-9e50-89cc832bebee", "user2", "Jyoti", "Kattel", "user2@email"); userService.save(user2); createArticle(adminUser, "Admin's First Article", "Content1 Admin"); createArticle(adminUser, "Admin's Second Article", "Content2 Admin"); createArticle(user1, "User1 Article", "Content User 1");
createArticle(user2, "User2 Article", "Content User 2"); } void createArticle(AppUser user, String title, String content) { var n = new Article(); n.setCreatedByUser(user); n.setTitle(title); n.setContent(content); articleRepository.save(n); Comment c = new Comment(); c.setStatus(CommentStatus.SHOWING); c.setContent("Test comment for " + title); c.setArticleId(n.getId()); c.setCreatedByUser(user); //self commentRepository.save(c); } }
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\DataCreator.java
1
请完成以下Java代码
public I_C_Withholding getC_Withholding() throws RuntimeException { return (I_C_Withholding)MTable.get(getCtx(), I_C_Withholding.Table_Name) .getPO(getC_Withholding_ID(), get_TrxName()); } /** Set Withholding. @param C_Withholding_ID Withholding type defined */ public void setC_Withholding_ID (int C_Withholding_ID) { if (C_Withholding_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Withholding_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Withholding_ID, Integer.valueOf(C_Withholding_ID)); } /** Get Withholding. @return Withholding type defined */ public int getC_Withholding_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Withholding_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Exempt reason. @param ExemptReason Reason for not withholding */ public void setExemptReason (String ExemptReason) { set_Value (COLUMNNAME_ExemptReason, ExemptReason); } /** Get Exempt reason. @return Reason for not withholding */ public String getExemptReason () { return (String)get_Value(COLUMNNAME_ExemptReason); } /** Set Mandatory Withholding. @param IsMandatoryWithholding Monies must be withheld */ public void setIsMandatoryWithholding (boolean IsMandatoryWithholding) { set_Value (COLUMNNAME_IsMandatoryWithholding, Boolean.valueOf(IsMandatoryWithholding)); } /** Get Mandatory Withholding. @return Monies must be withheld */ public boolean isMandatoryWithholding () { Object oo = get_Value(COLUMNNAME_IsMandatoryWithholding); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo);
} return false; } /** Set Temporary exempt. @param IsTemporaryExempt Temporarily do not withhold taxes */ public void setIsTemporaryExempt (boolean IsTemporaryExempt) { set_Value (COLUMNNAME_IsTemporaryExempt, Boolean.valueOf(IsTemporaryExempt)); } /** Get Temporary exempt. @return Temporarily do not withhold taxes */ public boolean isTemporaryExempt () { Object oo = get_Value(COLUMNNAME_IsTemporaryExempt); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Withholding.java
1
请完成以下Java代码
public class MigratingActivityInstanceValidationReportImpl implements MigratingActivityInstanceValidationReport { protected String activityInstanceId; protected String sourceScopeId; protected MigrationInstruction migrationInstruction; protected List<String> failures = new ArrayList<String>(); public MigratingActivityInstanceValidationReportImpl(MigratingActivityInstance migratingActivityInstance) { this.activityInstanceId = migratingActivityInstance.getActivityInstance().getId(); this.sourceScopeId = migratingActivityInstance.getSourceScope().getId(); this.migrationInstruction = migratingActivityInstance.getMigrationInstruction(); } public String getSourceScopeId() { return sourceScopeId; } public String getActivityInstanceId() { return activityInstanceId; } public MigrationInstruction getMigrationInstruction() {
return migrationInstruction; } public void addFailure(String failure) { failures.add(failure); } public boolean hasFailures() { return !failures.isEmpty(); } public List<String> getFailures() { return failures; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\MigratingActivityInstanceValidationReportImpl.java
1
请完成以下Java代码
public DimensionSpec retrieveForInternalNameOrNull(final String internalName) { final I_DIM_Dimension_Spec record = Services.get(IQueryBL.class).createQueryBuilder(I_DIM_Dimension_Spec.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DIM_Dimension_Spec.COLUMN_InternalName, internalName) .create() .firstOnly(I_DIM_Dimension_Spec.class); if(record == null) { return null; } return DimensionSpec.ofRecord(record); } @Override public List<String> retrieveAttributeValueForGroup(final String dimensionSpectInternalName,
final String groupName, final IContextAware ctxAware) { final KeyNamePair[] keyNamePairs = DB.getKeyNamePairs("SELECT M_AttributeValue_ID, ValueName " + "FROM " + DimensionConstants.VIEW_DIM_Dimension_Spec_Attribute_AllValue + " WHERE InternalName=? AND GroupName=?", false, dimensionSpectInternalName, groupName); final List<String> result = new ArrayList<String>(keyNamePairs.length); for (final KeyNamePair keyNamePair : keyNamePairs) { result.add(keyNamePair.getName()); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\impl\DimensionspecDAO.java
1
请完成以下Java代码
public abstract class KafkaResourceFactory { private @Nullable Supplier<String> bootstrapServersSupplier; @Nullable protected String getBootstrapServers() { return this.bootstrapServersSupplier == null ? null : this.bootstrapServersSupplier.get(); } /** * Set a supplier for the bootstrap server list to override any configured in a * subclass. * @param bootstrapServersSupplier the supplier. */ public void setBootstrapServersSupplier(Supplier<String> bootstrapServersSupplier) { this.bootstrapServersSupplier = bootstrapServersSupplier; }
/** * Enhance the properties by calling the * {@link #setBootstrapServersSupplier(Supplier)} and replace the bootstrap servers * properties. * @param configs the configs. */ protected void checkBootstrap(Map<String, Object> configs) { String bootstrapServers = getBootstrapServers(); if (bootstrapServers != null) { configs.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaResourceFactory.java
1
请在Spring Boot框架中完成以下Java代码
public TimerJobEntity findTimerJobById(String jobId) { return getTimerJobEntityManager().findById(jobId); } @Override public List<TimerJobEntity> findTimerJobsByExecutionId(String executionId) { return getTimerJobEntityManager().findJobsByExecutionId(executionId); } @Override public List<TimerJobEntity> findTimerJobsByProcessInstanceId(String processInstanceId) { return getTimerJobEntityManager().findJobsByProcessInstanceId(processInstanceId); } @Override public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionId(String type, String processDefinitionId) { return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionId(type, processDefinitionId); } @Override public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyNoTenantId(String type, String processDefinitionKey) { return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyNoTenantId(type, processDefinitionKey); } @Override public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyAndTenantId(String type, String processDefinitionKey, String tenantId) { return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyAndTenantId(type, processDefinitionKey, tenantId); } @Override public void scheduleTimerJob(TimerJobEntity timerJob) { getJobManager().scheduleTimerJob(timerJob); } @Override public AbstractRuntimeJobEntity moveJobToTimerJob(JobEntity job) {
return getJobManager().moveJobToTimerJob(job); } @Override public TimerJobEntity createTimerJob() { return getTimerJobEntityManager().create(); } @Override public void insertTimerJob(TimerJobEntity timerJob) { getTimerJobEntityManager().insert(timerJob); } @Override public void deleteTimerJob(TimerJobEntity timerJob) { getTimerJobEntityManager().delete(timerJob); } @Override public void deleteTimerJobsByExecutionId(String executionId) { TimerJobEntityManager timerJobEntityManager = getTimerJobEntityManager(); Collection<TimerJobEntity> timerJobsForExecution = timerJobEntityManager.findJobsByExecutionId(executionId); for (TimerJobEntity job : timerJobsForExecution) { timerJobEntityManager.delete(job); if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent( FlowableEngineEventType.JOB_CANCELED, job), configuration.getEngineName()); } } } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\TimerJobServiceImpl.java
2
请完成以下Java代码
protected void mergeScopeExecutions(ExecutionEntity leaf) { Map<ScopeImpl, PvmExecutionImpl> mapping = leaf.createActivityExecutionMapping(); for (Map.Entry<ScopeImpl, PvmExecutionImpl> mappingEntry : mapping.entrySet()) { ScopeImpl scope = mappingEntry.getKey(); ExecutionEntity scopeExecution = (ExecutionEntity) mappingEntry.getValue(); submitExecution(scopeExecution, scope); } } protected List<ExecutionEntity> fetchExecutionsForProcessInstance(ExecutionEntity execution) { List<ExecutionEntity> executions = new ArrayList<ExecutionEntity>(); executions.addAll(execution.getExecutions()); for (ExecutionEntity child : execution.getExecutions()) { executions.addAll(fetchExecutionsForProcessInstance(child)); } return executions; } protected List<ExecutionEntity> findLeaves(List<ExecutionEntity> executions) { List<ExecutionEntity> leaves = new ArrayList<ExecutionEntity>(); for (ExecutionEntity execution : executions) {
if (isLeaf(execution)) { leaves.add(execution); } } return leaves; } /** * event-scope executions are not considered in this mapping and must be ignored */ protected boolean isLeaf(ExecutionEntity execution) { if (CompensationBehavior.isCompensationThrowing(execution)) { return true; } else { return !execution.isEventScope() && execution.getNonEventScopeExecutions().isEmpty(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityExecutionTreeMapping.java
1
请在Spring Boot框架中完成以下Java代码
private DruidDataSource coreDataSource() { DruidDataSource dataSource = new DruidDataSource(); druidProperties.config(dataSource); return dataSource; } /** * 另一个数据源 */ private DruidDataSource bizDataSource() { DruidDataSource dataSource = new DruidDataSource(); druidProperties.config(dataSource); mutiDataSourceProperties.config(dataSource); return dataSource; } /** * 单数据源连接池配置 */ @Bean @ConditionalOnProperty(prefix = "xncoding", name = "muti-datasource-open", havingValue = "false") public DruidDataSource singleDatasource() { return coreDataSource(); } /** * 多数据源连接池配置 */ @Bean
@ConditionalOnProperty(prefix = "xncoding", name = "muti-datasource-open", havingValue = "true") public DynamicDataSource mutiDataSource() { DruidDataSource coreDataSource = coreDataSource(); DruidDataSource bizDataSource = bizDataSource(); try { coreDataSource.init(); bizDataSource.init(); } catch (SQLException sql) { sql.printStackTrace(); } DynamicDataSource dynamicDataSource = new DynamicDataSource(); HashMap<Object, Object> hashMap = new HashMap<>(); hashMap.put(DSEnum.DATA_SOURCE_CORE, coreDataSource); hashMap.put(DSEnum.DATA_SOURCE_BIZ, bizDataSource); dynamicDataSource.setTargetDataSources(hashMap); dynamicDataSource.setDefaultTargetDataSource(coreDataSource); return dynamicDataSource; } /** * mybatis-plus分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
repos\SpringBootBucket-master\springboot-multisource\src\main\java\com\xncoding\pos\config\MybatisPlusConfig.java
2
请完成以下Java代码
public final class OAuth2AuthorizedClientRefreshedEvent extends ApplicationEvent { @Serial private static final long serialVersionUID = -2178028089321556476L; private final OAuth2AuthorizedClient authorizedClient; /** * Creates a new instance with the provided parameters. * @param accessTokenResponse the {@link OAuth2AccessTokenResponse} that triggered the * event * @param authorizedClient the refreshed {@link OAuth2AuthorizedClient} */ public OAuth2AuthorizedClientRefreshedEvent(OAuth2AccessTokenResponse accessTokenResponse, OAuth2AuthorizedClient authorizedClient) { super(accessTokenResponse); Assert.notNull(authorizedClient, "authorizedClient cannot be null"); this.authorizedClient = authorizedClient; } /** * Returns the {@link OAuth2AccessTokenResponse} that triggered the event.
* @return the access token response */ public OAuth2AccessTokenResponse getAccessTokenResponse() { return (OAuth2AccessTokenResponse) this.getSource(); } /** * Returns the refreshed {@link OAuth2AuthorizedClient}. * @return the authorized client */ public OAuth2AuthorizedClient getAuthorizedClient() { return this.authorizedClient; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\event\OAuth2AuthorizedClientRefreshedEvent.java
1
请完成以下Java代码
public final List<I_C_DunningDoc_Line> retrieveDunningDocLines(@NonNull final I_C_DunningDoc dunningDoc) { return Services.get(IQueryBL.class).createQueryBuilder(I_C_DunningDoc_Line.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_DunningDoc_Line.COLUMN_C_DunningDoc_ID, dunningDoc.getC_DunningDoc_ID()) .orderBy() .addColumn(I_C_DunningDoc_Line.COLUMN_C_DunningDoc_Line_ID).endOrderBy() .create() .list(); } @Override public final List<I_C_DunningDoc_Line_Source> retrieveDunningDocLineSources(@NonNull final I_C_DunningDoc_Line line) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_DunningDoc_Line_Source.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_DunningDoc_Line_Source.COLUMN_C_DunningDoc_Line_ID, line.getC_DunningDoc_Line_ID()) .orderBy() .addColumn(I_C_DunningDoc_Line_Source.COLUMN_C_DunningDoc_Line_Source_ID).endOrderBy() .create() .list(); } @Cached(cacheName = I_C_DunningLevel.Table_Name + "_for_C_Dunning_ID") /* package */ List<I_C_DunningLevel> retrieveDunningLevels(@CacheCtx Properties ctx, int dunningId, @CacheTrx String trxName) { return Services.get(IQueryBL.class).createQueryBuilder(I_C_DunningLevel.class, ctx, trxName) .addEqualsFilter(I_C_DunningLevel.COLUMNNAME_C_Dunning_ID, dunningId) .addOnlyActiveRecordsFilter() .orderBy() .addColumn(I_C_DunningLevel.COLUMNNAME_DaysAfterDue) .addColumn(I_C_DunningLevel.COLUMNNAME_DaysBetweenDunning)
.addColumn(I_C_DunningLevel.COLUMNNAME_C_DunningLevel_ID) .endOrderBy() .create() .list(); } protected abstract List<I_C_Dunning_Candidate> retrieveDunningCandidates(IDunningContext context, IDunningCandidateQuery query); protected abstract I_C_Dunning_Candidate retrieveDunningCandidate(IDunningContext context, IDunningCandidateQuery query); protected abstract Iterator<I_C_Dunning_Candidate> retrieveDunningCandidatesIterator(IDunningContext context, IDunningCandidateQuery query); @Override public I_C_DunningDoc getByIdInTrx(@NonNull final DunningDocId dunningDocId) { return load(dunningDocId, I_C_DunningDoc.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\AbstractDunningDAO.java
1
请完成以下Java代码
public Builder principal(String principalName) { return principal(createAuthentication(principalName)); } private static Authentication createAuthentication(final String principalName) { Assert.hasText(principalName, "principalName cannot be empty"); return new AbstractAuthenticationToken((Collection<? extends GrantedAuthority>) null) { @Override public Object getCredentials() { return ""; } @Override public Object getPrincipal() { return principalName; } }; } /** * Sets the {@code Principal} (to be) associated to the authorized client. * @param principal the {@code Principal} (to be) associated to the authorized * client * @return the {@link Builder} */ public Builder principal(Authentication principal) { this.principal = principal; return this; } /** * Provides a {@link Consumer} access to the attributes associated to the request. * @param attributesConsumer a {@link Consumer} of the attributes associated to * the request * @return the {@link Builder} */ public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) { if (this.attributes == null) { this.attributes = new HashMap<>(); } attributesConsumer.accept(this.attributes); return this; } /** * Sets an attribute associated to the request. * @param name the name of the attribute * @param value the value of the attribute * @return the {@link Builder} */
public Builder attribute(String name, Object value) { if (this.attributes == null) { this.attributes = new HashMap<>(); } this.attributes.put(name, value); return this; } /** * Builds a new {@link OAuth2AuthorizeRequest}. * @return a {@link OAuth2AuthorizeRequest} */ public OAuth2AuthorizeRequest build() { Assert.notNull(this.principal, "principal cannot be null"); OAuth2AuthorizeRequest authorizeRequest = new OAuth2AuthorizeRequest(); if (this.authorizedClient != null) { authorizeRequest.clientRegistrationId = this.authorizedClient.getClientRegistration() .getRegistrationId(); authorizeRequest.authorizedClient = this.authorizedClient; } else { authorizeRequest.clientRegistrationId = this.clientRegistrationId; } authorizeRequest.principal = this.principal; authorizeRequest.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes) ? Collections.emptyMap() : new LinkedHashMap<>(this.attributes)); return authorizeRequest; } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizeRequest.java
1
请完成以下Java代码
public Optional<DistributedSystem> getDistributedSystem() { return Optional.ofNullable(getDistributionManager().getSystem()); } /** * Returns a reference to the configured {@link DistributionManager} which is use as the {@link #getSource() source} * of this event. * * @return a reference to the {@link DistributionManager}. * @see org.apache.geode.distributed.internal.DistributionManager */ public DistributionManager getDistributionManager() { return (DistributionManager) getSource(); } /** * Returns the {@link Type} of this {@link MembershipEvent}, such as {@link Type#MEMBER_JOINED}. * * @return the {@link MembershipEvent.Type}. */ public Type getType() { return Type.UNQUALIFIED; } /** * Null-safe builder method used to configure the {@link DistributedMember member} that is the subject * of this event. * * @param distributedMember {@link DistributedMember} that is the subject of this event. * @return this {@link MembershipEvent}.
* @see org.apache.geode.distributed.DistributedMember * @see #getDistributedMember() */ @SuppressWarnings("unchecked") public T withMember(DistributedMember distributedMember) { this.distributedMember = distributedMember; return (T) this; } /** * An {@link Enum enumeration} of different type of {@link MembershipEvent MembershipEvents}. */ public enum Type { MEMBER_DEPARTED, MEMBER_JOINED, MEMBER_SUSPECT, QUORUM_LOST, UNQUALIFIED; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipEvent.java
1
请完成以下Java代码
public String getKey() { return this.key; } public String getRolePrefix() { return this.rolePrefix; } public void setKey(String key) { this.key = key; } /** * Allows the default role prefix of <code>ROLE_</code> to be overridden. May be set * to an empty value, although this is usually not desirable. * @param rolePrefix the new prefix */ public void setRolePrefix(String rolePrefix) { this.rolePrefix = rolePrefix; } @Override public boolean supports(ConfigAttribute attribute) {
return attribute.getAttribute() != null && attribute.getAttribute().startsWith("RUN_AS_"); } /** * This implementation supports any type of class, because it does not query the * presented secure object. * @param clazz the secure object * @return always <code>true</code> */ @Override public boolean supports(Class<?> clazz) { return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\RunAsManagerImpl.java
1
请完成以下Java代码
protected void updateSuspensionState(CommandContext commandContext, SuspensionState suspensionState) { JobManager jobManager = commandContext.getJobManager(); if (jobId != null) { jobManager.updateJobSuspensionStateById(jobId, suspensionState); } else if (jobDefinitionId != null) { jobManager.updateJobSuspensionStateByJobDefinitionId(jobDefinitionId, suspensionState); } else if (processInstanceId != null) { jobManager.updateJobSuspensionStateByProcessInstanceId(processInstanceId, suspensionState); } else if (processDefinitionId != null) { jobManager.updateJobSuspensionStateByProcessDefinitionId(processDefinitionId, suspensionState); } else if (processDefinitionKey != null) {
if (!processDefinitionTenantIdSet) { jobManager.updateJobSuspensionStateByProcessDefinitionKey(processDefinitionKey, suspensionState); } else { jobManager.updateJobSuspensionStateByProcessDefinitionKeyAndTenantId(processDefinitionKey, processDefinitionTenantId, suspensionState); } } } @Override protected void logUserOperation(CommandContext commandContext) { PropertyChange propertyChange = new PropertyChange(SUSPENSION_STATE_PROPERTY, null, getNewSuspensionState().getName()); commandContext.getOperationLogManager().logJobOperation(getLogEntryOperation(), jobId, jobDefinitionId, processInstanceId, processDefinitionId, processDefinitionKey, propertyChange); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetJobStateCmd.java
1
请完成以下Java代码
public class Graph { private Map<Vertex, List<Vertex>> adjVertices; Graph() { this.adjVertices = new HashMap<Vertex, List<Vertex>>(); } void addVertex(String label) { adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>()); } void removeVertex(String label) { Vertex v = new Vertex(label); adjVertices.values().stream().forEach(e -> e.remove(v)); adjVertices.remove(new Vertex(label)); } void addEdge(String label1, String label2) { Vertex v1 = new Vertex(label1); Vertex v2 = new Vertex(label2); adjVertices.get(v1).add(v2); adjVertices.get(v2).add(v1); } void removeEdge(String label1, String label2) { Vertex v1 = new Vertex(label1); Vertex v2 = new Vertex(label2); List<Vertex> eV1 = adjVertices.get(v1); List<Vertex> eV2 = adjVertices.get(v2); if (eV1 != null) eV1.remove(v2); if (eV2 != null) eV2.remove(v1); } List<Vertex> getAdjVertices(String label) { return adjVertices.get(new Vertex(label)); } String printGraph() { StringBuffer sb = new StringBuffer(); for(Vertex v : adjVertices.keySet()) { sb.append(v); sb.append(adjVertices.get(v)); } return sb.toString(); } class Vertex { String label; Vertex(String label) { this.label = label; } @Override public int hashCode() { final int prime = 31; int result = 1;
result = prime * result + getOuterType().hashCode(); result = prime * result + ((label == null) ? 0 : label.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; Vertex other = (Vertex) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (label == null) { if (other.label != null) return false; } else if (!label.equals(other.label)) return false; return true; } @Override public String toString() { return label; } private Graph getOuterType() { return Graph.this; } } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\graph\Graph.java
1
请完成以下Java代码
class RedisDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<DataRedisConnectionDetails> { private static final String[] REDIS_CONTAINER_NAMES = { "redis", "redis/redis-stack", "redis/redis-stack-server" }; private static final int REDIS_PORT = 6379; RedisDockerComposeConnectionDetailsFactory() { super(REDIS_CONTAINER_NAMES); } @Override protected DataRedisConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new RedisDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link DataRedisConnectionDetails} backed by a {@code redis} * {@link RunningService}. */ static class RedisDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements DataRedisConnectionDetails { private final Standalone standalone;
private final @Nullable SslBundle sslBundle; RedisDockerComposeConnectionDetails(RunningService service) { super(service); this.standalone = Standalone.of(service.host(), service.ports().get(REDIS_PORT)); this.sslBundle = getSslBundle(service); } @Override public @Nullable SslBundle getSslBundle() { return this.sslBundle; } @Override public Standalone getStandalone() { return this.standalone; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\docker\compose\RedisDockerComposeConnectionDetailsFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getStoreGLN() { return storeGLN; } /** * Sets the value of the storeGLN property. * * @param value * allowed object is * {@link String } * */ public void setStoreGLN(String value) { this.storeGLN = value; } /** * Gets the value of the lookupLabel property. * * @return * possible object is * {@link String } * */ public String getLookupLabel() { return lookupLabel;
} /** * Sets the value of the lookupLabel property. * * @param value * allowed object is * {@link String } * */ public void setLookupLabel(String value) { this.lookupLabel = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EDICBPartnerLookupBPLGLNVType.java
2
请完成以下Java代码
public final List<String> getDependsOnColumnNames() { // NOTE: we cannot know which are the column names until we load the actual aggregation key builder throw new UnsupportedOperationException(); } @Override public final AggregationKey buildAggregationKey(final I_C_Invoice_Candidate ic) { final InvoiceCandidateHeaderAggregationId headerAggregationIdOverride = InvoiceCandidateHeaderAggregationId.ofRepoIdOrNull(ic.getC_Invoice_Candidate_HeaderAggregation_Override_ID()); if (headerAggregationIdOverride != null && X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header.equals(aggregationUsageLevel)) { //An override is set, use the already calculated header aggregation key return new AggregationKey(ic.getHeaderAggregationKey()); } final IAggregationKeyBuilder<I_C_Invoice_Candidate> icAggregationKeyBuilder = getDelegate(ic); if (icAggregationKeyBuilder == null) { return AggregationKey.NULL; } return icAggregationKeyBuilder.buildAggregationKey(ic); } /** * Finds the actual {@link IAggregationKeyBuilder} to be used, based on invoice candidate's settings. * * @param ic * @return actual {@link IAggregationKeyBuilder} to be used */ protected IAggregationKeyBuilder<I_C_Invoice_Candidate> getDelegate(final I_C_Invoice_Candidate ic) { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final I_C_BPartner bpartner = bpartnerDAO.getById(ic.getBill_BPartner_ID(), I_C_BPartner.class); if (bpartner == null) { return null; } final Properties ctx = InterfaceWrapperHelper.getCtx(ic); final OrderId prepayOrderId = OrderId.ofRepoIdOrNull(ic.getC_Order_ID());
if (prepayOrderId != null && Services.get(IOrderBL.class).isPrepay(prepayOrderId) && X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header.equals(aggregationUsageLevel)) { return invoiceAggregationFactory.getPrepayOrderAggregationKeyBuilder(ctx); } final boolean isSOTrx = ic.isSOTrx(); return invoiceAggregationFactory.getAggregationKeyBuilder(ctx, bpartner, isSOTrx, aggregationUsageLevel); } @Override public final boolean isSame(final I_C_Invoice_Candidate ic1, final I_C_Invoice_Candidate ic2) { final AggregationKey aggregationKey1 = buildAggregationKey(ic1); if (aggregationKey1 == null) { return false; } final AggregationKey aggregationKey2 = buildAggregationKey(ic2); if (aggregationKey2 == null) { return false; } final boolean same = Objects.equals(aggregationKey1, aggregationKey2); return same; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ForwardingICAggregationKeyBuilder.java
1
请完成以下Java代码
public AbstractFlowNodeBuilder builder() { throw new BpmnModelException("No builder implemented for type " + getElementType().getTypeNamespace() +":" + getElementType().getTypeName()); } @SuppressWarnings("rawtypes") public void updateAfterReplacement() { super.updateAfterReplacement(); Collection<Reference> incomingReferences = getIncomingReferencesByType(SequenceFlow.class); for (Reference<?> reference : incomingReferences) { for (ModelElementInstance sourceElement : reference.findReferenceSourceElements(this)) { String referenceIdentifier = reference.getReferenceIdentifier(sourceElement); if (referenceIdentifier != null && referenceIdentifier.equals(getId()) && reference instanceof AttributeReference) { String attributeName = ((AttributeReference) reference).getReferenceSourceAttribute().getAttributeName(); if (attributeName.equals(BPMN_ATTRIBUTE_SOURCE_REF)) { getOutgoing().add((SequenceFlow) sourceElement); } else if (attributeName.equals(BPMN_ATTRIBUTE_TARGET_REF)) { getIncoming().add((SequenceFlow) sourceElement); } } } } } public Collection<SequenceFlow> getIncoming() { return incomingCollection.getReferenceTargetElements(this); } public Collection<SequenceFlow> getOutgoing() { return outgoingCollection.getReferenceTargetElements(this); } public Query<FlowNode> getPreviousNodes() { Collection<FlowNode> previousNodes = new HashSet<FlowNode>(); for (SequenceFlow sequenceFlow : getIncoming()) { previousNodes.add(sequenceFlow.getSource()); } return new QueryImpl<FlowNode>(previousNodes); } public Query<FlowNode> getSucceedingNodes() {
Collection<FlowNode> succeedingNodes = new HashSet<FlowNode>(); for (SequenceFlow sequenceFlow : getOutgoing()) { succeedingNodes.add(sequenceFlow.getTarget()); } return new QueryImpl<FlowNode>(succeedingNodes); } /** Camunda Attributes */ public boolean isCamundaAsyncBefore() { return camundaAsyncBefore.getValue(this); } public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) { camundaAsyncBefore.setValue(this, isCamundaAsyncBefore); } public boolean isCamundaAsyncAfter() { return camundaAsyncAfter.getValue(this); } public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) { camundaAsyncAfter.setValue(this, isCamundaAsyncAfter); } public boolean isCamundaExclusive() { return camundaExclusive.getValue(this); } public void setCamundaExclusive(boolean isCamundaExclusive) { camundaExclusive.setValue(this, isCamundaExclusive); } public String getCamundaJobPriority() { return camundaJobPriority.getValue(this); } public void setCamundaJobPriority(String jobPriority) { camundaJobPriority.setValue(this, jobPriority); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\FlowNodeImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductBOMVersionsDAO { private final IQueryBL queryBL = Services.get(IQueryBL.class); @NonNull public ProductBOMVersionsId createBOMVersions(@NonNull final BOMVersionsCreateRequest request) { final OrgId orgId = request.getOrgId(); final I_PP_Product_BOMVersions bomVersionsRecord = newInstance(I_PP_Product_BOMVersions.class); bomVersionsRecord.setAD_Org_ID(orgId.getRepoId()); bomVersionsRecord.setM_Product_ID(request.getProductId().getRepoId()); bomVersionsRecord.setName(request.getName()); bomVersionsRecord.setDescription(request.getDescription()); saveRecord(bomVersionsRecord); return ProductBOMVersionsId.ofRepoId(bomVersionsRecord.getPP_Product_BOMVersions_ID()); } @NonNull public Optional<ProductBOMVersionsId> retrieveBOMVersionsId(@NonNull final ProductId productId) { return getBOMVersionsByProductId(productId) .map(I_PP_Product_BOMVersions::getPP_Product_BOMVersions_ID) .map(ProductBOMVersionsId::ofRepoId); } @NonNull
public I_PP_Product_BOMVersions getBOMVersions(@NonNull final ProductBOMVersionsId versionsId) { return InterfaceWrapperHelper.load(versionsId, I_PP_Product_BOMVersions.class); } @NonNull private Optional<I_PP_Product_BOMVersions> getBOMVersionsByProductId(@NonNull final ProductId productId) { return queryBL.createQueryBuilder(I_PP_Product_BOMVersions.class) .addEqualsFilter(I_PP_Product_BOMVersions.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .firstOnlyOptional(I_PP_Product_BOMVersions.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMVersionsDAO.java
2
请完成以下Java代码
public Date getPublished() { return published; } public void setPublished(Date published) { this.published = published; } public BigDecimal getPages() { return pages; } public void setPages(BigDecimal pages) { this.pages = pages; } public UUID getId() { return id; } public void setId(UUID id) {
this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\deserialization\jsondeserialize\Book.java
1
请完成以下Java代码
public class Person { @JsonIgnore private UUID id; private String firstName; private String lastName; public Person(){} public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public UUID getId() { return id; } }
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\inclusion\jsonignore\Person.java
1
请完成以下Java代码
public void setBestPosition(long[] bestPosition) { this.bestPosition = bestPosition; } /** * Sets the {@link #bestFitness}. * * @param bestFitness * the new {@link #bestFitness} */ public void setBestFitness(double bestFitness) { this.bestFitness = bestFitness; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(bestFitness); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(bestPosition); temp = Double.doubleToLongBits(fitness); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(position); result = prime * result + Arrays.hashCode(speed); return result; } /* * (non-Javadoc)
* * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Particle other = (Particle) obj; if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness)) return false; if (!Arrays.equals(bestPosition, other.bestPosition)) return false; if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness)) return false; if (!Arrays.equals(position, other.position)) return false; if (!Arrays.equals(speed, other.speed)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness=" + fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]"; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Particle.java
1
请完成以下Java代码
private AdProcessId getReportProcessIdToUse(final Object record) { if (InterfaceWrapperHelper.isInstanceOf(record, I_C_Letter.class)) { final I_C_Letter letter = InterfaceWrapperHelper.create(record, I_C_Letter.class); final BoilerPlateId boilderPlateId = BoilerPlateId.ofRepoIdOrNull(letter.getAD_BoilerPlate_ID()); if (boilderPlateId != null) { return TextTemplateBL.getJasperProcessId(boilderPlateId).orElse(null); } } // fallback return null; }
private boolean computeInvoiceEmailEnabledFromRecord(@NonNull final Object record) { final TableRecordReference recordRef = TableRecordReference.of(record); return docOutboundLogMailRecipientRegistry .getRecipient( DocOutboundLogMailRecipientRequest.builder() .recordRef(recordRef) .clientId(InterfaceWrapperHelper.getClientId(record).orElseThrow(() -> new AdempiereException("Cannot get AD_Client_ID from " + record))) .orgId(InterfaceWrapperHelper.getOrgId(record).orElseThrow(() -> new AdempiereException("Cannot get AD_Org_ID from " + record))) .docTypeId(documentBL.getDocTypeId(record).orElse(null)) .build()) .map(DocOutBoundRecipients::isInvoiceAsEmail) .orElse(false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\async\spi\impl\DocOutboundWorkpackageProcessor.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { if (jobId == null && job == null) { throw new ActivitiIllegalArgumentException("jobId and job is null"); } if (job == null) { job = commandContext .getJobEntityManager() .findJobById(jobId); } if (job == null) { throw new JobNotFoundException(jobId); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Executing job {}", job.getId()); } JobExecutorContext jobExecutorContext = Context.getJobExecutorContext(); if (jobExecutorContext != null) { // if null, then we are not called by the job executor jobExecutorContext.setCurrentJob(job); } FailedJobListener failedJobListener = null; try { // When transaction is rolled back, decrement retries failedJobListener = new FailedJobListener(commandContext.getProcessEngineConfiguration().getCommandExecutor(), job.getId()); commandContext.getTransactionContext().addTransactionListener( TransactionState.ROLLED_BACK, failedJobListener); job.execute(commandContext); if (commandContext.getEventDispatcher().isEnabled()) { commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent( FlowableEngineEventType.JOB_EXECUTION_SUCCESS, job), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); }
} catch (Throwable exception) { failedJobListener.setException(exception); // Dispatch an event, indicating job execution failed in a try-catch block, to prevent the original // exception to be swallowed if (commandContext.getEventDispatcher().isEnabled()) { try { commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityExceptionEvent( FlowableEngineEventType.JOB_EXECUTION_FAILURE, job, exception), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } catch (Throwable ignore) { LOGGER.warn("Exception occurred while dispatching job failure event, ignoring.", ignore); } } // Finally, Throw the exception to indicate the ExecuteJobCmd failed if (!(exception instanceof ActivitiException)) { throw new ActivitiException("Job " + jobId + " failed", exception); } else { throw (ActivitiException) exception; } } finally { if (jobExecutorContext != null) { jobExecutorContext.setCurrentJob(null); } } return null; } public String getJobId() { return jobId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\ExecuteJobsCmd.java
1
请完成以下Java代码
public java.lang.String getLoginApiUrl () { return (java.lang.String)get_Value(COLUMNNAME_LoginApiUrl); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } /** * PaperFormat AD_Reference_ID=541073 * Reference name: DpdPaperFormat */ public static final int PAPERFORMAT_AD_Reference_ID=541073; /** A6 = A6 */ public static final String PAPERFORMAT_A6 = "A6"; /** A5 = A5 */ public static final String PAPERFORMAT_A5 = "A5"; /** A4 = A4 */ public static final String PAPERFORMAT_A4 = "A4"; /** Set Papierformat. @param PaperFormat Papierformat */ @Override public void setPaperFormat (java.lang.String PaperFormat) { set_Value (COLUMNNAME_PaperFormat, PaperFormat); } /** Get Papierformat. @return Papierformat */ @Override
public java.lang.String getPaperFormat () { return (java.lang.String)get_Value(COLUMNNAME_PaperFormat); } /** Set URL Api Shipment Service. @param ShipmentServiceApiUrl URL Api Shipment Service */ @Override public void setShipmentServiceApiUrl (java.lang.String ShipmentServiceApiUrl) { set_Value (COLUMNNAME_ShipmentServiceApiUrl, ShipmentServiceApiUrl); } /** Get URL Api Shipment Service. @return URL Api Shipment Service */ @Override public java.lang.String getShipmentServiceApiUrl () { return (java.lang.String)get_Value(COLUMNNAME_ShipmentServiceApiUrl); } /** Set Shipper Product. @param ShipperProduct Shipper Product */ @Override public void setShipperProduct (java.lang.String ShipperProduct) { set_Value (COLUMNNAME_ShipperProduct, ShipperProduct); } /** Get Shipper Product. @return Shipper Product */ @Override public java.lang.String getShipperProduct () { return (java.lang.String)get_Value(COLUMNNAME_ShipperProduct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_Shipper_Config.java
1
请完成以下Java代码
public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException("decision result is immutable"); } @Override public DmnDecisionResultEntries set(int index, DmnDecisionResultEntries element) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public void add(int index, DmnDecisionResultEntries element) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public DmnDecisionResultEntries remove(int index) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public int indexOf(Object o) { return ruleResults.indexOf(o); } @Override
public int lastIndexOf(Object o) { return ruleResults.lastIndexOf(o); } @Override public ListIterator<DmnDecisionResultEntries> listIterator() { return asUnmodifiableList().listIterator(); } @Override public ListIterator<DmnDecisionResultEntries> listIterator(int index) { return asUnmodifiableList().listIterator(index); } @Override public List<DmnDecisionResultEntries> subList(int fromIndex, int toIndex) { return asUnmodifiableList().subList(fromIndex, toIndex); } @Override public String toString() { return ruleResults.toString(); } protected List<DmnDecisionResultEntries> asUnmodifiableList() { return Collections.unmodifiableList(ruleResults); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultImpl.java
1
请完成以下Java代码
public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public HttpHeaders filter(HttpHeaders originalHeaders, ServerWebExchange exchange) { HttpHeaders filtered = new HttpHeaders(); List<String> connectionOptions = originalHeaders.getConnection().stream().map(String::toLowerCase).toList(); Set<String> headersToRemove = new HashSet<>(headers); headersToRemove.addAll(connectionOptions);
for (Map.Entry<String, List<String>> entry : originalHeaders.headerSet()) { if (!headersToRemove.contains(entry.getKey().toLowerCase(Locale.ROOT))) { filtered.addAll(entry.getKey(), entry.getValue()); } } return filtered; } @Override public boolean supports(Type type) { return type.equals(Type.REQUEST) || type.equals(Type.RESPONSE); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\RemoveHopByHopHeadersFilter.java
1
请完成以下Java代码
public class IgnoranceAnnotationStructure { public static abstract class Vehicle { private String make; private String model; protected Vehicle() { } protected Vehicle(String make, String model) { this.make = make; this.model = model; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } } @JsonIgnoreProperties({ "model", "seatingCapacity" }) public static abstract class Car extends Vehicle { private int seatingCapacity; @JsonIgnore private double topSpeed; protected Car() { } protected Car(String make, String model, int seatingCapacity, double topSpeed) { super(make, model); this.seatingCapacity = seatingCapacity; this.topSpeed = topSpeed; } public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed;
} } public static class Sedan extends Car { public Sedan() { } public Sedan(String make, String model, int seatingCapacity, double topSpeed) { super(make, model, seatingCapacity, topSpeed); } } public static class Crossover extends Car { private double towingCapacity; public Crossover() { } public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) { super(make, model, seatingCapacity, topSpeed); this.towingCapacity = towingCapacity; } public double getTowingCapacity() { return towingCapacity; } public void setTowingCapacity(double towingCapacity) { this.towingCapacity = towingCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\IgnoranceAnnotationStructure.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } final DunningCandidateQuery other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(AD_Table_ID, other.AD_Table_ID) .append(Record_ID, other.Record_ID) .append(C_DunningLevels, other.C_DunningLevels) .append(active, other.active) .append(applyClientSecurity, other.applyClientSecurity) .append(processed, this.processed) .append(writeOff, this.writeOff) .isEqual(); } @Override public int getAD_Table_ID() { return AD_Table_ID; } public void setAD_Table_ID(int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } public void setRecord_ID(int record_ID) { Record_ID = record_ID; } @Override public List<I_C_DunningLevel> getC_DunningLevels() { return C_DunningLevels; } public void setC_DunningLevels(List<I_C_DunningLevel> c_DunningLevels) { C_DunningLevels = c_DunningLevels; } @Override public boolean isActive() { return active;
} public void setActive(boolean active) { this.active = active; } @Override public boolean isApplyClientSecurity() { return applyClientSecurity; } public void setApplyClientSecurity(boolean applyClientSecurity) { this.applyClientSecurity = applyClientSecurity; } @Override public Boolean getProcessed() { return processed; } public void setProcessed(Boolean processed) { this.processed = processed; } @Override public Boolean getWriteOff() { return writeOff; } public void setWriteOff(Boolean writeOff) { this.writeOff = writeOff; } @Override public String getAdditionalWhere() { return additionalWhere; } public void setAdditionalWhere(String additionalWhere) { this.additionalWhere = additionalWhere; } @Override public ApplyAccessFilter getApplyAccessFilter() { return applyAccessFilter; } public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter) { this.applyAccessFilter = applyAccessFilter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java
1
请完成以下Java代码
public Long getPetId() { return petId; } public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { this.quantity = quantity; return this; } /** * Get quantity * @return quantity **/ @ApiModelProperty(value = "") public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } /** * Get shipDate * @return shipDate **/ @ApiModelProperty(value = "") public DateTime getShipDate() { return shipDate; } public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { this.status = status; return this; } /** * Order Status * @return status **/ @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { this.complete = complete; return this; } /** * Get complete * @return complete **/ @ApiModelProperty(value = "") public Boolean getComplete() { return complete; } public void setComplete(Boolean complete) { this.complete = complete; }
@Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; return Objects.equals(this.id, order.id) && Objects.equals(this.petId, order.petId) && Objects.equals(this.quantity, order.quantity) && Objects.equals(this.shipDate, order.shipDate) && Objects.equals(this.status, order.status) && Objects.equals(this.complete, order.complete); } @Override public int hashCode() { return Objects.hash(id, petId, quantity, shipDate, status, complete); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Order.java
1
请完成以下Java代码
public class OrganizationUnitImpl extends BusinessContextElementImpl implements OrganizationUnit { protected static ElementReferenceCollection<Decision, DecisionMadeReference> decisionDecisionMadeRefCollection; protected static ElementReferenceCollection<Decision, DecisionOwnedReference> decisionDecisionOwnedRefCollection; public OrganizationUnitImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Collection<Decision> getDecisionsMade() { return decisionDecisionMadeRefCollection.getReferenceTargetElements(this); } public Collection<Decision> getDecisionsOwned() { return decisionDecisionOwnedRefCollection.getReferenceTargetElements(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OrganizationUnit.class, DMN_ELEMENT_ORGANIZATION_UNIT) .namespaceUri(LATEST_DMN_NS) .extendsType(BusinessContextElement.class) .instanceProvider(new ModelTypeInstanceProvider<OrganizationUnit>() { public OrganizationUnit newInstance(ModelTypeInstanceContext instanceContext) { return new OrganizationUnitImpl(instanceContext); } });
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); decisionDecisionMadeRefCollection = sequenceBuilder.elementCollection(DecisionMadeReference.class) .uriElementReferenceCollection(Decision.class) .build(); decisionDecisionOwnedRefCollection = sequenceBuilder.elementCollection(DecisionOwnedReference.class) .uriElementReferenceCollection(Decision.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OrganizationUnitImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class TaxQuery { @NonNull OrgId orgId; @Nullable WarehouseId warehouseId; @Nullable CountryId fromCountryId; @NonNull Timestamp dateOfInterest; @NonNull BPartnerId bPartnerId; @Nullable BPartnerLocationAndCaptureId bPartnerLocationId; @NonNull SOTrx soTrx; @Nullable TaxCategoryId taxCategoryId; @Nullable CountryId shippingCountryId; @Nullable Boolean isTaxExempt; @Builder public TaxQuery( @NonNull final OrgId orgId, @Nullable final WarehouseId warehouseId, @Nullable final CountryId fromCountryId,
@Nullable final Timestamp dateOfInterest, @Nullable final BPartnerLocationAndCaptureId bPartnerLocationId, @NonNull final SOTrx soTrx, @Nullable final TaxCategoryId taxCategoryId, @Nullable final BPartnerId bPartnerId, @Nullable final CountryId shippingCountryId, @Nullable final Boolean isTaxExempt) { this.orgId = orgId; this.warehouseId = warehouseId; this.fromCountryId = fromCountryId; this.dateOfInterest = coalesce(dateOfInterest, Env.getDate()); this.bPartnerLocationId = bPartnerLocationId; this.soTrx = soTrx; this.taxCategoryId = taxCategoryId; if (bPartnerLocationId != null) { this.bPartnerId = bPartnerLocationId.getBpartnerId(); } else { Check.assumeNotNull(bPartnerId, "BPartnerId must not be null if no bPartnerLocationId was provided!"); Check.assumeNotNull(shippingCountryId, "ShippingCountryId must not be null if no bPartnerLocationId was provided!"); this.bPartnerId = bPartnerId; } this.shippingCountryId = shippingCountryId; this.isTaxExempt = isTaxExempt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\TaxQuery.java
2
请完成以下Java代码
public void setVerfuegbarkeitBulkVereinbart(boolean value) { this.verfuegbarkeitBulkVereinbart = value; } /** * Gets the value of the ruecknahmeangebotVereinbart property. * */ public boolean isRuecknahmeangebotVereinbart() { return ruecknahmeangebotVereinbart; } /** * Sets the value of the ruecknahmeangebotVereinbart property. * */ public void setRuecknahmeangebotVereinbart(boolean value) { this.ruecknahmeangebotVereinbart = value; } /** * Gets the value of the gueltigAb property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getGueltigAb() { return gueltigAb; } /** * Sets the value of the gueltigAb property. *
* @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setGueltigAb(XMLGregorianCalendar value) { this.gueltigAb = value; } /** * Gets the value of the kundenKennung property. * * @return * possible object is * {@link String } * */ public String getKundenKennung() { return kundenKennung; } /** * Sets the value of the kundenKennung property. * * @param value * allowed object is * {@link String } * */ public void setKundenKennung(String value) { this.kundenKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenAntwort.java
1
请在Spring Boot框架中完成以下Java代码
public class SayHelloController { //"say-hello" => "Hello! What are you learning today?" //say-hello // http://localhost:8080/say-hello @RequestMapping("say-hello") @ResponseBody public String sayHello() { return "Hello! What are you learning today?"; } @RequestMapping("say-hello-html") @ResponseBody public String sayHelloHtml() { StringBuffer sb = new StringBuffer(); sb.append("<html>"); sb.append("<head>"); sb.append("<title> My First HTML Page - Changed</title>"); sb.append("</head>");
sb.append("<body>"); sb.append("My first html page with body - Changed"); sb.append("</body>"); sb.append("</html>"); return sb.toString(); } // // "say-hello-jsp" => sayHello.jsp // /src/main/resources/META-INF/resources/WEB-INF/jsp/sayHello.jsp // /src/main/resources/META-INF/resources/WEB-INF/jsp/welcome.jsp // /src/main/resources/META-INF/resources/WEB-INF/jsp/login.jsp // /src/main/resources/META-INF/resources/WEB-INF/jsp/todos.jsp @RequestMapping("say-hello-jsp") public String sayHelloJsp() { return "sayHello"; } }
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\hello\SayHelloController.java
2
请完成以下Java代码
public class ExternalWorkerTaskCompleteJobHandler implements JobHandler { public static final String TYPE = "external-worker-complete"; @Override public String getType() { return TYPE; } @Override public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) { ExecutionEntity executionEntity = (ExecutionEntity) variableScope; ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); VariableService variableService = processEngineConfiguration.getVariableServiceConfiguration().getVariableService(); List<VariableInstanceEntity> jobVariables = variableService.findVariableInstanceBySubScopeIdAndScopeType(executionEntity.getId(), ScopeTypes.BPMN_EXTERNAL_WORKER); for (VariableInstanceEntity jobVariable : jobVariables) { executionEntity.setVariable(jobVariable.getName(), jobVariable.getValue()); CountingEntityUtil.handleDeleteVariableInstanceEntityCount(jobVariable, false); variableService.deleteVariableInstance(jobVariable); }
if (configuration != null && configuration.startsWith("error:")) { String errorCode; if (configuration.length() > 6) { errorCode = configuration.substring(6); } else { errorCode = null; } ErrorPropagation.propagateError(errorCode, executionEntity); } else { CommandContextUtil.getAgenda(commandContext).planTriggerExecutionOperation(executionEntity); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\jobexecutor\ExternalWorkerTaskCompleteJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
LocalContainerEntityManagerFactoryBean entityManagerFactory() throws IOException { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } @Bean @ConditionalOnProperty(name = "usemysql", havingValue = "local") DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:mem:testdb"); dataSource.setUsername( "sa" );
dataSource.setPassword( "" ); return dataSource; } @ConditionalOnResource(resources = "classpath:mysql.properties") Properties additionalProperties() throws IOException { final Properties additionalProperties = new Properties(); try (InputStream inputStream = new ClassPathResource("classpath:mysql.properties").getInputStream()) { additionalProperties.load(inputStream); } return additionalProperties; } }
repos\tutorials-master\spring-boot-modules\spring-boot-annotations\src\main\java\com\baeldung\annotations\MySQLAutoconfiguration.java
2
请完成以下Java代码
public TrxItemProcessorContext copy() { final TrxItemProcessorContext contextNew = new TrxItemProcessorContext(ctx); contextNew.trx = trx; contextNew.params = params; return contextNew; } @Override public Properties getCtx() { return ctx; } @Override public String getTrxName() { if (trx == null) { return ITrx.TRXNAME_None; } return trx.getTrxName(); } @Override public void setTrx(final ITrx trx) { this.trx = trx; } @Override public ITrx getTrx() { return trx; } @Override public IParams getParams()
{ return params; } public void setParams(IParams params) { this.params = params; } @Override public String toString() { return "TrxItemProcessorContext [trx=" + trx + ", params=" + params + "]"; } /** * Returning <code>false</code> to ensure that the trx which was set via {@link #setTrx(ITrx)} is actually used, even if it's <code>null</code>. */ @Override public boolean isAllowThreadInherited() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessorContext.java
1
请完成以下Java代码
public static class Builder { private final CompositeStringExpression.Builder sql = IStringExpression.composer(); private final ArrayList<Object> sqlParams = new ArrayList<>(); private Builder() {} public SqlAndParamsExpression build() { return new SqlAndParamsExpression(this); } public Builder appendIfNotEmpty(@Nullable final String sqlToAppend) { if (sqlToAppend != null) { sql.appendIfNotEmpty(sqlToAppend); } return this; } public Builder append(@NonNull final String sqlToAppend, final Object... sqlParamsToAppend) { sql.append(sqlToAppend); sqlParams.addAll(Arrays.asList(sqlParamsToAppend)); return this; } public Builder append(@Nullable final SqlAndParams sqlAndParams) { if (sqlAndParams != null) { sql.append(sqlAndParams.getSql()); sqlParams.addAll(sqlAndParams.getSqlParams()); } return this; } public Builder append(@NonNull final SqlAndParamsExpression sqlToAppend) { sql.append(sqlToAppend.getSql()); sqlParams.addAll(sqlToAppend.getSqlParams()); return this; } public Builder append(@NonNull final SqlAndParamsExpression.Builder sqlToAppend) { sql.append(sqlToAppend.sql); sqlParams.addAll(sqlToAppend.sqlParams); return this; } public Builder append(@NonNull final IStringExpression sqlToAppend) { sql.append(sqlToAppend); return this;
} public Builder append(@Nullable final String sqlToAppend) { if (sqlToAppend != null) { sql.append(sqlToAppend); } return this; } public Builder appendSqlList(@NonNull final String sqlColumnName, @NonNull final Collection<?> values) { final String sqlToAppend = DB.buildSqlList(sqlColumnName, values, sqlParams); sql.append(sqlToAppend); return this; } public boolean isEmpty() { return sql.isEmpty() && sqlParams.isEmpty(); } public Builder wrap(@NonNull final IStringExpressionWrapper wrapper) { sql.wrap(wrapper); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParamsExpression.java
1
请完成以下Java代码
public class AnimalActivity { final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class); public static void sleep(Animal animal) { logger.info("Animal is sleeping"); } public static void sleep(Dog dog) { logger.info("Cat is sleeping"); } public static void main(String[] args) { Animal animal = new Animal(); //calling methods of animal object
animal.makeNoise(); animal.makeNoise(3); //assigning a dog object to reference of type Animal Animal catAnimal = new Dog(); catAnimal.makeNoise(); // calling static function AnimalActivity.sleep(catAnimal); return; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-others\src\main\java\com\baeldung\binding\AnimalActivity.java
1
请完成以下Java代码
public class RemoveExecutionVariablesCmd extends NeedsActiveExecutionCmd<Void> { private static final long serialVersionUID = 1L; private Collection<String> variableNames; private boolean isLocal; public RemoveExecutionVariablesCmd(String executionId, Collection<String> variableNames, boolean isLocal) { super(executionId); this.variableNames = variableNames; this.isLocal = isLocal; } @Override protected Void execute(CommandContext commandContext, ExecutionEntity execution) { if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, execution.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.removeExecutionVariables(executionId, variableNames, isLocal); return null;
} if (isLocal) { execution.removeVariablesLocal(variableNames); } else { execution.removeVariables(variableNames); } return null; } @Override protected String getSuspendedExceptionMessagePrefix() { return "Cannot remove variables from"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\RemoveExecutionVariablesCmd.java
1
请在Spring Boot框架中完成以下Java代码
private synchronized void playHole(@NonNull GolfTournament golfTournament) { GolfCourse golfCourse = golfTournament.getGolfCourse(); Set<Integer> occupiedHoles = new HashSet<>(); for (GolfTournament.Pairing pairing : golfTournament) { int hole = pairing.nextHole(); if (!occupiedHoles.contains(hole)) { if (golfCourse.isValidHoleNumber(hole)) { occupiedHoles.add(hole); pairing.setHole(hole); updateScore(this::calculateRunningScore, pairing.getPlayerOne()); updateScore(this::calculateRunningScore, pairing.getPlayerTwo()); } } } } private Golfer updateScore(@NonNull Function<Integer, Integer> scoreFunction, @NonNull Golfer player) { player.setScore(scoreFunction.apply(player.getScore())); this.golferService.update(player); return player; } private int calculateFinalScore(@Nullable Integer scoreRelativeToPar) { int finalScore = scoreRelativeToPar != null ? scoreRelativeToPar : 0;
int parForCourse = getGolfTournament() .map(GolfTournament::getGolfCourse) .map(GolfCourse::getParForCourse) .orElse(GolfCourse.STANDARD_PAR_FOR_COURSE); return parForCourse + finalScore; } private int calculateRunningScore(@Nullable Integer currentScore) { int runningScore = currentScore != null ? currentScore : 0; int scoreDelta = this.random.nextInt(SCORE_DELTA_BOUND); scoreDelta *= this.random.nextBoolean() ? -1 : 1; return runningScore + scoreDelta; } private void finish(@NonNull GolfTournament golfTournament) { for (GolfTournament.Pairing pairing : golfTournament) { if (pairing.signScorecard()) { updateScore(this::calculateFinalScore, pairing.getPlayerOne()); updateScore(this::calculateFinalScore, pairing.getPlayerTwo()); } } } } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\service\PgaTourService.java
2
请完成以下Java代码
protected List<IFacet<I_C_Invoice_Candidate>> collectFacets(final IQueryBuilder<I_C_Invoice_Candidate> icQueryBuilder) { // FRESH-560: Add default filter final IQueryBuilder<I_C_Invoice_Candidate> queryBuilderWithDefaultFilters = Services.get(IInvoiceCandDAO.class).applyDefaultFilter(icQueryBuilder); // Match only Products which are Packing Materials final IQuery<I_M_HU_PackingMaterial> isPackingMaterialQueryFilter = queryBL.createQueryBuilder(I_M_HU_PackingMaterial.class, queryBuilderWithDefaultFilters.getCtx(), queryBuilderWithDefaultFilters.getTrxName()) .create(); // // Query invoice candidates, aggregate them by packing material products and sum the QtyToInvoice final IQueryAggregateBuilder<I_C_Invoice_Candidate, I_M_Product> aggregateOnQtyToInvoiceInPriceUOM = queryBuilderWithDefaultFilters .addInSubQueryFilter(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID, I_M_HU_PackingMaterial.COLUMNNAME_M_Product_ID, isPackingMaterialQueryFilter) .aggregateOnColumn(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID, I_M_Product.class); aggregateOnQtyToInvoiceInPriceUOM .sum(DYNATTR_QtyToInvoiceInPriceUOM, I_C_Invoice_Candidate.COLUMN_QtyToInvoiceInPriceUOM); // // Get aggregated products and create facets from them. final List<I_M_Product> products = aggregateOnQtyToInvoiceInPriceUOM.aggregate(); final List<IFacet<I_C_Invoice_Candidate>> facets = new ArrayList<>(products.size()); for (final I_M_Product product : products) { final IFacet<I_C_Invoice_Candidate> facet = createPackingMaterialFacet(product); facets.add(facet); }
return facets; } private final IFacet<I_C_Invoice_Candidate> createPackingMaterialFacet(final I_M_Product product) { final IFacetCategory facetCategory = getFacetCategory(); final BigDecimal qtyToInvoiceInPriceUOM = DYNATTR_QtyToInvoiceInPriceUOM.getValue(product); final int productId = product.getM_Product_ID(); final String packingMaterialInfo = new StringBuilder() .append(product.getName()) .append(": ") .append(qtyToInvoiceInPriceUOM == null ? "?" : NumberUtils.stripTrailingDecimalZeros(qtyToInvoiceInPriceUOM)) .toString(); return Facet.<I_C_Invoice_Candidate> builder() .setFacetCategory(facetCategory) .setId(facetCategory.getDisplayName() + "_" + productId) .setDisplayName(packingMaterialInfo) .setFilter(TypedSqlQueryFilter.of(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID + "=" + productId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\invoicecandidate\facet\C_Invoice_Candidate_HUPackingMaterials_FacetCollector.java
1
请完成以下Java代码
public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); } @Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_Picking_Job_Line_ID (final int M_Picking_Job_Line_ID) { if (M_Picking_Job_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Line_ID, M_Picking_Job_Line_ID); } @Override public int getM_Picking_Job_Line_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Line_ID); } @Override public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID) { if (M_Picking_Job_Schedule_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_Schedule_ID, null); else set_Value (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_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_Value (COLUMNNAME_M_PickingSlot_ID, null); else set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID()
{ return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Line.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaConsumerConfig { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaConsumerConfig.class); @Value(value = "${spring.kafka.bootstrap-servers}") private String bootstrapAddress; @Value(value = "${kafka.backoff.interval}") private Long interval; @Value(value = "${kafka.backoff.max_failure}") private Long maxAttempts; public ConsumerFactory<String, BookEvent> consumerFactory() { Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, "20971520"); props.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, "20971520"); props.put(JsonDeserializer.TRUSTED_PACKAGES, "*"); props.put(JsonDeserializer.TYPE_MAPPINGS, "bookEvent:com.baeldung.spring.kafka.multiplelisteners.BookEvent"); return new DefaultKafkaConsumerFactory<>(props); }
@Bean public ConcurrentKafkaListenerContainerFactory<String, BookEvent> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, BookEvent> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setCommonErrorHandler(errorHandler()); return factory; } @Bean public DefaultErrorHandler errorHandler() { BackOff fixedBackOff = new FixedBackOff(interval, maxAttempts); return new DefaultErrorHandler((consumerRecord, e) -> LOGGER.error(String.format("consumed record %s because this exception was thrown", consumerRecord.toString())), fixedBackOff); } }
repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\multiplelisteners\KafkaConsumerConfig.java
2
请在Spring Boot框架中完成以下Java代码
public Buyer taxAddress(TaxAddress taxAddress) { this.taxAddress = taxAddress; return this; } /** * Get taxAddress * * @return taxAddress **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public TaxAddress getTaxAddress() { return taxAddress; } public void setTaxAddress(TaxAddress taxAddress) { this.taxAddress = taxAddress; } public Buyer taxIdentifier(TaxIdentifier taxIdentifier) { this.taxIdentifier = taxIdentifier; return this; } /** * Get taxIdentifier * * @return taxIdentifier **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public TaxIdentifier getTaxIdentifier() { return taxIdentifier; } public void setTaxIdentifier(TaxIdentifier taxIdentifier) { this.taxIdentifier = taxIdentifier; } public Buyer username(String username) { this.username = username; return this; } /** * The buyer&#39;s eBay user ID. * * @return username **/
@javax.annotation.Nullable @ApiModelProperty(value = "The buyer's eBay user ID.") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Buyer buyer = (Buyer)o; return Objects.equals(this.taxAddress, buyer.taxAddress) && Objects.equals(this.taxIdentifier, buyer.taxIdentifier) && Objects.equals(this.username, buyer.username); } @Override public int hashCode() { return Objects.hash(taxAddress, taxIdentifier, username); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Buyer {\n"); sb.append(" taxAddress: ").append(toIndentedString(taxAddress)).append("\n"); sb.append(" taxIdentifier: ").append(toIndentedString(taxIdentifier)).append("\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Buyer.java
2