instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class ToDoController { @Autowired private ToDoRepository todoRepository; @GetMapping("") public String index(){ return "index"; } @GetMapping("/logout") public String logoutPage(){ return "logout"; } @GetMapping("/todos") public String todos(Model model){ model.addAttribute("todos", todoRepository.findAll()); return "todos"; } @PostMapping("/todoNew") public String add(@RequestParam String todoItem, @RequestParam String status, Model model){ ToDo todo = new ToDo(); todo.setTodoItem(todoItem); todo.setCompleted(status); todoRepository.save(todo); model.addAttribute("todos", todoRepository.findAll()); return "redirect:/todos"; } @PostMapping("/todoDelete/{id}") public String delete(@PathVariable long id, Model model){ todoRepository.deleteById(id);
model.addAttribute("todos", todoRepository.findAll()); return "redirect:/todos"; } @PostMapping("/todoUpdate/{id}") public String update(@PathVariable long id, Model model){ ToDo toDo = todoRepository.findById(id).get(); if("Yes".equals(toDo.getCompleted())){ toDo.setCompleted("No"); } else { toDo.setCompleted("Yes"); } todoRepository.save(toDo); model.addAttribute("todos", todoRepository.findAll()); return "redirect:/todos"; } }
repos\Spring-Boot-Advanced-Projects-main\SpringBoot-Todo-Project\src\main\java\spring\project\controller\ToDoController.java
2
请在Spring Boot框架中完成以下Java代码
static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory { private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); DefaultMethodSecurityExpressionHandler getBean() { this.handler.setDefaultRolePrefix(this.rolePrefix); return this.handler; } } abstract static class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware { protected String rolePrefix = "ROLE_"; @Override public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException { applicationContext.getBeanProvider(GrantedAuthorityDefaults.class) .ifUnique((grantedAuthorityDefaults) -> this.rolePrefix = grantedAuthorityDefaults.getRolePrefix()); } } /** * Delays setting a bean of a given name to be lazyily initialized until after all the * beans are registered. * * @author Rob Winch * @since 3.2 */ private static final class LazyInitBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { private final String beanName; private LazyInitBeanDefinitionRegistryPostProcessor(String beanName) {
this.beanName = beanName; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { if (!registry.containsBeanDefinition(this.beanName)) { return; } BeanDefinition beanDefinition = registry.getBeanDefinition(this.beanName); beanDefinition.setLazyInit(true); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\GlobalMethodSecurityBeanDefinitionParser.java
2
请完成以下Java代码
public void addKeyListener (KeyListener l) { m_textPane.addKeyListener(l); } /** * Add Input Method Listener * @param l listener */ @Override public void addInputMethodListener (InputMethodListener l) { m_textPane.addInputMethodListener(l); } /** * Get Input Method Requests * @return requests */ @Override public InputMethodRequests getInputMethodRequests() { return m_textPane.getInputMethodRequests(); } /** * Set Input Verifier * @param l verifyer */ @Override public void setInputVerifier (InputVerifier l) { m_textPane.setInputVerifier(l); } // metas: begin public String getContentType() { if (m_textPane != null) return m_textPane.getContentType(); return null; } private void setHyperlinkListener() { if (hyperlinkListenerClass == null) {
return; } try { final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance(); m_textPane.addHyperlinkListener(listener); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e); } } private static Class<?> hyperlinkListenerClass; static { final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler"; try { hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e); } } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } // metas: end } // CTextPane
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java
1
请在Spring Boot框架中完成以下Java代码
public class SignDatabaseBuildHouseKeepingTask implements IStartupHouseKeepingTask { private static final transient Logger logger = LogManager.getLogger(SignDatabaseBuildHouseKeepingTask.class); @Override public void executeTask() { if (!DB.isConnected()) { throw new DBException("No database connection"); } final String lastBuildInfo = Adempiere.getImplementationVersion(); if (lastBuildInfo!= null && lastBuildInfo.endsWith(Adempiere.CLIENT_VERSION_LOCAL_BUILD)) { Loggables.withLogger(logger, Level.WARN).addLog("Not signing the database build with our version={}, because it makes no sense", lastBuildInfo); return; }
try { final String sql = "UPDATE AD_System SET LastBuildInfo = ?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { lastBuildInfo }, ITrx.TRXNAME_None); CacheMgt.get().reset("AD_System"); logger.info("Set AD_System.LastBuildInfo={}", lastBuildInfo); } catch (final Exception ex) { Loggables.withLogger(logger, Level.ERROR).addLog("Failed updating the LastBuildInfo", ex); } Loggables.withLogger(logger, Level.INFO).addLog("Signed the database build with version: {}", lastBuildInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\housekeep\SignDatabaseBuildHouseKeepingTask.java
2
请在Spring Boot框架中完成以下Java代码
public InfoFromBuyer returnShipmentTracking(List<TrackingInfo> returnShipmentTracking) { this.returnShipmentTracking = returnShipmentTracking; return this; } public InfoFromBuyer addReturnShipmentTrackingItem(TrackingInfo returnShipmentTrackingItem) { if (this.returnShipmentTracking == null) { this.returnShipmentTracking = new ArrayList<>(); } this.returnShipmentTracking.add(returnShipmentTrackingItem); return this; } /** * This array shows shipment tracking information for one or more shipping packages being returned to the buyer after a payment dispute. * * @return returnShipmentTracking **/ @javax.annotation.Nullable @ApiModelProperty(value = "This array shows shipment tracking information for one or more shipping packages being returned to the buyer after a payment dispute.") public List<TrackingInfo> getReturnShipmentTracking() { return returnShipmentTracking; } public void setReturnShipmentTracking(List<TrackingInfo> returnShipmentTracking) { this.returnShipmentTracking = returnShipmentTracking; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InfoFromBuyer infoFromBuyer = (InfoFromBuyer)o; return Objects.equals(this.note, infoFromBuyer.note) && Objects.equals(this.returnShipmentTracking, infoFromBuyer.returnShipmentTracking); }
@Override public int hashCode() { return Objects.hash(note, returnShipmentTracking); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InfoFromBuyer {\n"); sb.append(" note: ").append(toIndentedString(note)).append("\n"); sb.append(" returnShipmentTracking: ").append(toIndentedString(returnShipmentTracking)).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\InfoFromBuyer.java
2
请在Spring Boot框架中完成以下Java代码
protected void initializeDefaultPreservedHeaders() { this.sync.add(executionId); this.sync.add(processDefinitionId); this.sync.add(processInstanceId); } public void execute(IntegrationActivityBehavior receiveTaskActivityBehavior, DelegateExecution execution) { Map<String, Object> stringObjectMap = new HashMap<>(); stringObjectMap.put(executionId, execution.getId()); stringObjectMap.put(processInstanceId, execution.getProcessInstanceId()); stringObjectMap.put(processDefinitionId, execution.getProcessDefinitionId()); stringObjectMap.putAll(headerMapper.toHeaders(execution.getVariables())); MessageBuilder<?> mb = MessageBuilder.withPayload(execution).copyHeaders(stringObjectMap); Message<?> reply = sendAndReceiveMessage(mb.build());
if (null != reply) { Map<String, Object> vars = new HashMap<>(); headerMapper.fromHeaders(reply.getHeaders(), vars); for (String k : vars.keySet()) { processEngine.getRuntimeService().setVariable(execution.getId(), k, vars.get(k)); } receiveTaskActivityBehavior.leave(execution); } } public void signal(IntegrationActivityBehavior receiveTaskActivityBehavior, DelegateExecution execution, String signalName, Object data) { receiveTaskActivityBehavior.leave(execution); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\integration\FlowableInboundGateway.java
2
请完成以下Java代码
public java.math.BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return BigDecimal.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 Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Gesamtbetrag. @param TotalAmt Gesamtbetrag */ @Override public void setTotalAmt (java.math.BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Gesamtbetrag. @return Gesamtbetrag */ @Override public java.math.BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate.java
1
请完成以下Java代码
public class BestellstatusAntwort { @XmlElement(name = "BestellSupportId", required = true, type = Integer.class, nillable = true) protected Integer bestellSupportId; @XmlElement(name = "Auftraege") protected List<BestellungAntwortAuftrag> auftraege; @XmlAttribute(name = "Id", required = true) protected String id; @XmlAttribute(name = "Status", required = true) protected Bestellstatus status; /** * Gets the value of the bestellSupportId property. * * @return * possible object is * {@link Integer } * */ public Integer getBestellSupportId() { return bestellSupportId; } /** * Sets the value of the bestellSupportId property. * * @param value * allowed object is * {@link Integer } * */ public void setBestellSupportId(Integer value) { this.bestellSupportId = value; } /** * Gets the value of the auftraege 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 auftraege property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAuftraege().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BestellungAntwortAuftrag } * * */
public List<BestellungAntwortAuftrag> getAuftraege() { if (auftraege == null) { auftraege = new ArrayList<BestellungAntwortAuftrag>(); } return this.auftraege; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link Bestellstatus } * */ public Bestellstatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link Bestellstatus } * */ public void setStatus(Bestellstatus value) { this.status = 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\BestellstatusAntwort.java
1
请完成以下Java代码
public List<I_AD_ColumnCallout> retrieveAllColumnCallouts(final Properties ctx, final int adColumnId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_ColumnCallout.class, ctx, ITrx.TRXNAME_None) .addEqualsFilter(I_AD_ColumnCallout.COLUMNNAME_AD_Column_ID, adColumnId) // .orderBy() .addColumn(I_AD_ColumnCallout.COLUMNNAME_SeqNo) .addColumn(I_AD_ColumnCallout.COLUMNNAME_AD_ColumnCallout_ID) .endOrderBy() // .create() .list(I_AD_ColumnCallout.class); } @Override public int retrieveColumnCalloutLastSeqNo(final Properties ctx, final int adColumnId)
{ final Integer lastSeqNo = Services.get(IQueryBL.class) .createQueryBuilder(I_AD_ColumnCallout.class, ctx, ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_ColumnCallout.COLUMNNAME_AD_Column_ID, adColumnId) // .create() .aggregate(I_AD_ColumnCallout.COLUMNNAME_SeqNo, Aggregate.MAX, Integer.class); if (lastSeqNo == null || lastSeqNo < 0) { return 0; } return lastSeqNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\ADColumnCalloutDAO.java
1
请完成以下Java代码
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_M_LotCtlExclude[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ public boolean isSOTrx () {
Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Exclude Lot. @param M_LotCtlExclude_ID Exclude the ability to create Lots in Attribute Sets */ public void setM_LotCtlExclude_ID (int M_LotCtlExclude_ID) { if (M_LotCtlExclude_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, Integer.valueOf(M_LotCtlExclude_ID)); } /** Get Exclude Lot. @return Exclude the ability to create Lots in Attribute Sets */ public int getM_LotCtlExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtlExclude_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_LotCtl getM_LotCtl() throws RuntimeException { return (I_M_LotCtl)MTable.get(getCtx(), I_M_LotCtl.Table_Name) .getPO(getM_LotCtl_ID(), get_TrxName()); } /** Set Lot Control. @param M_LotCtl_ID Product Lot Control */ public void setM_LotCtl_ID (int M_LotCtl_ID) { if (M_LotCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID)); } /** Get Lot Control. @return Product Lot Control */ public int getM_LotCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_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_LotCtlExclude.java
1
请完成以下Spring Boot application配置
# Available profiles # - none for no profile # - oracle-pooling-basic - Oracle database with HikariCP. Loads configuration from application-oracle-pooling-basic.properties # - oracle - Uses OracleDataSource. This profile also needs "oracle-pooling-basic" # - oracle-ucp - Uses PoolDataSource. This profile also needs "oracle-pooling-basic" # - c3p0 - Uses ComboPooledDataSource. This profile also needs "oracle-pooling-basic" spring: profiles: active: none jpa: hibernate:
naming: implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl defer-datasource-initialization: true sql: init: data-locations: import_*_users.sql
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setExternalId (final @Nullable java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setExternalUrl (final @Nullable java.lang.String ExternalUrl) { set_Value (COLUMNNAME_ExternalUrl, ExternalUrl); } @Override public java.lang.String getExternalUrl() { return get_ValueAsString(COLUMNNAME_ExternalUrl); } @Override public void setMilestone_DueDate (final @Nullable java.sql.Timestamp Milestone_DueDate) { set_Value (COLUMNNAME_Milestone_DueDate, Milestone_DueDate); } @Override public java.sql.Timestamp getMilestone_DueDate() { return get_ValueAsTimestamp(COLUMNNAME_Milestone_DueDate); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setS_Milestone_ID (final int S_Milestone_ID) { if (S_Milestone_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, S_Milestone_ID); } @Override public int getS_Milestone_ID() { return get_ValueAsInt(COLUMNNAME_S_Milestone_ID); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Milestone.java
2
请完成以下Java代码
public void beforeSave(final I_AD_Workflow workflow, final ModelChangeType changeType) { final String errorMsg = Services.get(IADWorkflowBL.class).validateAndGetErrorMsg(workflow); // NOTE: don't prevent workflow from saving, just let the IsValid flag to be reset // Don't log warning if new, because new WFs are not valid (no start node can be set because there is none). if (!Check.isEmpty(errorMsg, true) && !changeType.isNew()) { logger.warn("Workflow {} is marked as invalid because {}", workflow, errorMsg); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }) public void afterSave(final I_AD_Workflow workflow, final ModelChangeType changeType) { if (changeType.isNew()) { // nothing } // Menu/Workflow update else if (InterfaceWrapperHelper.isValueChanged( workflow, I_AD_Workflow.COLUMNNAME_IsActive, I_AD_Workflow.COLUMNNAME_Name, I_AD_Workflow.COLUMNNAME_Description, I_AD_Workflow.COLUMNNAME_Help)) { final MMenu[] menues = MMenu.get(Env.getCtx(), "AD_Workflow_ID=" + workflow.getAD_Workflow_ID(), ITrx.TRXNAME_ThreadInherited); for (final MMenu menue : menues) { menue.setIsActive(workflow.isActive()); menue.setName(workflow.getName()); menue.setDescription(workflow.getDescription()); menue.saveEx();
} // TODO: teo_sarca: why do we need to sync node name with workflow name? - see BF 2665963 // X_AD_WF_Node[] nodes = MWindow.getWFNodes(getCtx(), "AD_Workflow_ID=" + getAD_Workflow_ID(), get_TrxName()); // for (int i = 0; i < nodes.length; i++) // { // boolean changed = false; // if (nodes[i].isActive() != isActive()) // { // nodes[i].setIsActive(isActive()); // changed = true; // } // if (nodes[i].isCentrallyMaintained()) // { // nodes[i].setName(getName()); // nodes[i].setDescription(getDescription()); // nodes[i].setHelp(getHelp()); // changed = true; // } // if (changed) // nodes[i].saveEx(); // } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\interceptors\AD_Workflow.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_HR_ListType[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Payroll List Type. @param HR_ListType_ID Payroll List Type */ public void setHR_ListType_ID (int HR_ListType_ID) { if (HR_ListType_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID)); } /** Get Payroll List Type. @return Payroll List Type */ public int getHR_ListType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_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 Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java
1
请完成以下Java代码
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return invoiceLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { invoiceLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() {
return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
1
请完成以下Java代码
public Integer getHistoryIntegration() { return historyIntegration; } public void setHistoryIntegration(Integer historyIntegration) { this.historyIntegration = historyIntegration; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberLevelId=").append(memberLevelId); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", nickname=").append(nickname); sb.append(", phone=").append(phone);
sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", icon=").append(icon); sb.append(", gender=").append(gender); sb.append(", birthday=").append(birthday); sb.append(", city=").append(city); sb.append(", job=").append(job); sb.append(", personalizedSignature=").append(personalizedSignature); sb.append(", sourceType=").append(sourceType); sb.append(", integration=").append(integration); sb.append(", growth=").append(growth); sb.append(", luckeyCount=").append(luckeyCount); sb.append(", historyIntegration=").append(historyIntegration); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMember.java
1
请完成以下Java代码
public List<IncidentDto> queryIncidents(IncidentQueryDto queryParameter, @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults) { paginateQueryParameters(queryParameter, firstResult, maxResults); configureExecutionQuery(queryParameter); List<IncidentDto> matchingIncidents = getQueryService().executeQuery("selectIncidentWithCauseAndRootCauseIncidents", queryParameter); return matchingIncidents; } private void paginateQueryParameters(IncidentQueryDto queryParameter, Integer firstResult, Integer maxResults) { if (firstResult == null) { firstResult = 0; } if (maxResults == null) { maxResults = Integer.MAX_VALUE; } queryParameter.setFirstResult(firstResult); queryParameter.setMaxResults(maxResults); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) public CountResultDto getIncidentsCount(@Context UriInfo uriInfo) { IncidentQueryDto queryParameter = new IncidentQueryDto(uriInfo.getQueryParameters()); return queryIncidentsCount(queryParameter); } @POST @Path("/count") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public CountResultDto queryIncidentsCount(IncidentQueryDto queryParameter) { CountResultDto result = new CountResultDto(); configureExecutionQuery(queryParameter); long count = getQueryService().executeQueryRowCount("selectIncidentWithCauseAndRootCauseIncidentsCount", queryParameter); result.setCount(count); return result; } protected void configureExecutionQuery(IncidentQueryDto query) { configureAuthorizationCheck(query); configureTenantCheck(query); addPermissionCheck(query, PROCESS_INSTANCE, "RES.PROC_INST_ID_", READ); addPermissionCheck(query, PROCESS_DEFINITION, "PROCDEF.KEY_", READ_INSTANCE); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\IncidentRestService.java
1
请完成以下Java代码
public <T extends RepoIdAware> T getParameterValueAsRepoIdOrNull(@NonNull final String parameterName, @NonNull final IntFunction<T> repoIdMapper) { final DocumentFilterParam param = getParameterOrNull(parameterName); if (param == null) { return null; } return param.getValueAsRepoIdOrNull(repoIdMapper); } @Nullable public <T extends ReferenceListAwareEnum> T getParameterValueAsRefListOrNull(@NonNull final String parameterName, @NonNull final Function<String, T> mapper) { final DocumentFilterParam param = getParameterOrNull(parameterName); if (param == null) { return null; } return param.getValueAsRefListOrNull(mapper); } @Nullable public <T> T getParameterValueAs(@NonNull final String parameterName) { final DocumentFilterParam param = getParameterOrNull(parameterName); if (param == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)param.getValue(); return value; } // // // // // public static final class DocumentFilterBuilder {
public DocumentFilterBuilder setFilterId(final String filterId) { return filterId(filterId); } public DocumentFilterBuilder setCaption(@NonNull final ITranslatableString caption) { return caption(caption); } public DocumentFilterBuilder setCaption(@NonNull final String caption) { return caption(TranslatableStrings.constant(caption)); } public DocumentFilterBuilder setFacetFilter(final boolean facetFilter) { return facetFilter(facetFilter); } public boolean hasParameters() { return !Check.isEmpty(parameters) || !Check.isEmpty(internalParameterNames); } public DocumentFilterBuilder setParameters(@NonNull final List<DocumentFilterParam> parameters) { return parameters(parameters); } public DocumentFilterBuilder addParameter(@NonNull final DocumentFilterParam parameter) { return parameter(parameter); } public DocumentFilterBuilder addInternalParameter(@NonNull final DocumentFilterParam parameter) { parameter(parameter); internalParameterName(parameter.getFieldName()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilter.java
1
请完成以下Java代码
public class CaseDefinitionCacheEntry { protected CaseDefinition caseDefinition; protected CmmnModel cmmnModel; protected Case caze; public CaseDefinitionCacheEntry(CaseDefinition caseDefinition, CmmnModel cmmnModel, Case caze) { this.caseDefinition = caseDefinition; this.cmmnModel = cmmnModel; this.caze = caze; } public CaseDefinition getCaseDefinition() { return caseDefinition; } public void setCaseDefinition(CaseDefinition caseDefinition) { this.caseDefinition = caseDefinition;
} public CmmnModel getCmmnModel() { return cmmnModel; } public void setCmmnModel(CmmnModel cmmnModel) { this.cmmnModel = cmmnModel; } public Case getCase() { return caze; } public void setCase(Case caze) { this.caze = caze; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\deploy\CaseDefinitionCacheEntry.java
1
请完成以下Java代码
public boolean isBackupNull () { Object oo = get_Value(COLUMNNAME_IsBackupNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set New value null. @param IsNewNull The new value is null. */ @Override public void setIsNewNull (boolean IsNewNull) { set_Value (COLUMNNAME_IsNewNull, Boolean.valueOf(IsNewNull)); } /** Get New value null. @return The new value is null. */ @Override public boolean isNewNull () { Object oo = get_Value(COLUMNNAME_IsNewNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Old value null. @param IsOldNull The old value was null. */ @Override public void setIsOldNull (boolean IsOldNull) { set_Value (COLUMNNAME_IsOldNull, Boolean.valueOf(IsOldNull)); } /** Get Old value null. @return The old value was null. */ @Override public boolean isOldNull () {
Object oo = get_Value(COLUMNNAME_IsOldNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set New Value. @param NewValue New field value */ @Override public void setNewValue (java.lang.String NewValue) { set_Value (COLUMNNAME_NewValue, NewValue); } /** Get New Value. @return New field value */ @Override public java.lang.String getNewValue () { return (java.lang.String)get_Value(COLUMNNAME_NewValue); } /** Set Old Value. @param OldValue The old file data */ @Override public void setOldValue (java.lang.String OldValue) { set_Value (COLUMNNAME_OldValue, OldValue); } /** Get Old Value. @return The old file data */ @Override public java.lang.String getOldValue () { return (java.lang.String)get_Value(COLUMNNAME_OldValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationData.java
1
请完成以下Java代码
default boolean isNoResult(final Object result) { // because evaluation is throwing exception in case of failure, the only "no result" would be the NULL return result == null; } @Override default boolean isNullExpression() { // there is no such thing for logic expressions return false; } /** * Compose this logic expression with the given one, using logic AND and return it */ default ILogicExpression and(final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_AND, expression); } default ILogicExpression andNot(final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_AND, expression.negate()); } /** * Compose this logic expression with the given one, using logic OR and return it
*/ default ILogicExpression or(final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_OR, expression); } default ILogicExpression negate() { // NOTE: because we don't have unary operator support atm, we will use XOR as : !a = a XOR true //return xor(TRUE); fails, TRUE==null !! return xor(ConstantLogicExpression.TRUE); // works, not null! } default ILogicExpression xor(@NonNull final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_XOR, expression); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ILogicExpression.java
1
请完成以下Java代码
private void addToCPostal(@NonNull final I_C_Location location) { final I_C_Postal postal = InterfaceWrapperHelper.newInstance(I_C_Postal.class); postal.setPostal(location.getPostal()); // postal.setPostal_Add(location.getPostal_Add()); final int countryId = location.getC_Country_ID(); if (countryId <= 0) { throw new AdempiereException("@NotFound@ @C_Country_ID@: " + location); } postal.setC_Country_ID(countryId); // final int regionId = location.getC_Region_ID(); if (regionId > 0) { postal.setC_Region_ID(regionId); } postal.setRegionName(location.getRegionName()); // final int cityId = location.getC_City_ID(); if (cityId > 0) { postal.setC_City_ID(cityId); } postal.setCity(location.getCity()); InterfaceWrapperHelper.save(postal); logger.debug("Created a new C_Postal record for {}: {}", location, postal); } @Override public String toString(I_C_Location location) { return location.toString(); } @Override public String mkAddress(final I_C_Location location) { final String bPartnerBlock = null; final String userBlock = null; final I_C_BPartner bPartner = null; return mkAddress(location, bPartner, bPartnerBlock, userBlock); } @Override
public String mkAddress(final I_C_Location location, final I_C_BPartner bPartner, String bPartnerBlock, String userBlock) { final I_C_Country countryLocal = countryDAO.getDefault(Env.getCtx()); final boolean isLocalAddress = location.getC_Country_ID() == countryLocal.getC_Country_ID(); return mkAddress(location, isLocalAddress, bPartner, bPartnerBlock, userBlock); } public String mkAddress( I_C_Location location, boolean isLocalAddress, final I_C_BPartner bPartner, String bPartnerBlock, String userBlock) { final String adLanguage; final OrgId orgId; if (bPartner == null) { adLanguage = countryDAO.getDefault(Env.getCtx()).getAD_Language(); orgId = Env.getOrgId(); } else { adLanguage = bPartner.getAD_Language(); orgId = OrgId.ofRepoId(bPartner.getAD_Org_ID()); } return AddressBuilder.builder() .orgId(orgId) .adLanguage(adLanguage) .build() .buildAddressString(location, isLocalAddress, bPartnerBlock, userBlock); } @Override public I_C_Location duplicate(@NonNull final I_C_Location location) { final I_C_Location locationNew = InterfaceWrapperHelper.newInstance(I_C_Location.class, location); InterfaceWrapperHelper.copyValues(location, locationNew); InterfaceWrapperHelper.save(locationNew); return locationNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\LocationBL.java
1
请完成以下Java代码
public class MobileApp extends BaseData<MobileAppId> implements HasTenantId, HasName { @Schema(description = "JSON object with Tenant Id") private TenantId tenantId; @Schema(description = "Application package name. Cannot be empty", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank @Length(fieldName = "pkgName") private String pkgName; @Schema(description = "Application title") @Length(fieldName = "title") private String title; @Schema(description = "Application secret. The length must be at least 16 characters", requiredMode = Schema.RequiredMode.REQUIRED) @NotEmpty @Length(fieldName = "appSecret", min = 16, max = 2048, message = "must be at least 16 and max 2048 characters") private String appSecret; @Schema(description = "Application platform type: ANDROID or IOS", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull private PlatformType platformType; @Schema(description = "Application status: PUBLISHED, DEPRECATED, SUSPENDED, DRAFT", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull private MobileAppStatus status; @Schema(description = "Application version info") @Valid private MobileAppVersionInfo versionInfo; @Schema(description = "Application store information") @Valid private StoreInfo storeInfo;
public MobileApp() { super(); } public MobileApp(MobileAppId id) { super(id); } public MobileApp(MobileApp mobile) { super(mobile); this.tenantId = mobile.tenantId; this.pkgName = mobile.pkgName; this.title = mobile.title; this.appSecret = mobile.appSecret; this.platformType = mobile.platformType; this.status = mobile.status; this.versionInfo = mobile.versionInfo; this.storeInfo = mobile.storeInfo; } @Override @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Schema(description = "Mobile app package name", example = "my.mobile.app", accessMode = Schema.AccessMode.READ_ONLY) public String getName() { return pkgName; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\mobile\app\MobileApp.java
1
请在Spring Boot框架中完成以下Java代码
public class Post { @Id @GeneratedValue private int id; private String title; private String body; public Post() { } public Post(String title, String body) { this.title = title; this.body = body; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return "Post{" + "id=" + id + ", title='" + title + '\'' + ", body='" + body + '\'' + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\pojo\Post.java
2
请完成以下Java代码
private Issue getIssue(String issueKey) { return restClient.getIssueClient().getIssue(issueKey).claim(); } private void voteForAnIssue(Issue issue) { restClient.getIssueClient().vote(issue.getVotesUri()).claim(); } private int getTotalVotesCount(String issueKey) { BasicVotes votes = getIssue(issueKey).getVotes(); return votes == null ? 0 : votes.getVotes(); } private void addComment(Issue issue, String commentBody) { restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody)); } private List<Comment> getAllComments(String issueKey) { return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false) .collect(Collectors.toList()); }
private void updateIssueDescription(String issueKey, String newDescription) { IssueInput input = new IssueInputBuilder().setDescription(newDescription).build(); restClient.getIssueClient().updateIssue(issueKey, input).claim(); } private void deleteIssue(String issueKey, boolean deleteSubtasks) { restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim(); } private JiraRestClient getJiraRestClient() { return new AsynchronousJiraRestClientFactory() .createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password); } private URI getJiraUri() { return URI.create(this.jiraUrl); } }
repos\tutorials-master\saas-modules\jira-rest-integration\src\main\java\com\baeldung\saas\jira\MyJiraClient.java
1
请完成以下Spring Boot application配置
spring: application: name: config-server cloud: config: server: git: uri: xxx username: xxx password: xxx # search-paths: '{application}' clone-on-start: true server: port: 12580 security: user: name: mrbird password: 123456 #
eureka: # client: # serviceUrl: # defaultZone: http://mrbird:123456@peer1:8080/eureka/,http://mrbird:123456@peer2:8081/eureka/
repos\SpringAll-master\41.Spring-Cloud-Config\config-server\src\main\resources\application.yml
2
请完成以下Java代码
public class OutputClauseImpl extends DmnElementImpl implements OutputClause { protected static Attribute<String> nameAttribute; protected static Attribute<String> typeRefAttribute; protected static ChildElement<OutputValues> outputValuesChild; protected static ChildElement<DefaultOutputEntry> defaultOutputEntryChild; public OutputClauseImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getTypeRef() { return typeRefAttribute.getValue(this); } public void setTypeRef(String typeRef) { typeRefAttribute.setValue(this, typeRef); } public OutputValues getOutputValues() { return outputValuesChild.getChild(this); } public void setOutputValues(OutputValues outputValues) { outputValuesChild.setChild(this, outputValues); } public DefaultOutputEntry getDefaultOutputEntry() { return defaultOutputEntryChild.getChild(this); } public void setDefaultOutputEntry(DefaultOutputEntry defaultOutputEntry) { defaultOutputEntryChild.setChild(this, defaultOutputEntry); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OutputClause.class, DMN_ELEMENT_OUTPUT_CLAUSE) .namespaceUri(LATEST_DMN_NS)
.extendsType(DmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<OutputClause>() { public OutputClause newInstance(ModelTypeInstanceContext instanceContext) { return new OutputClauseImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAME) .build(); typeRefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_REF) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); outputValuesChild = sequenceBuilder.element(OutputValues.class) .build(); defaultOutputEntryChild = sequenceBuilder.element(DefaultOutputEntry.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OutputClauseImpl.java
1
请完成以下Java代码
public static boolean isExecutionRelatedEntityCountEnabledGlobally() { return CommandContextUtil.getProcessEngineConfiguration().getPerformanceSettings().isEnableExecutionRelationshipCounts(); } /** * Check if the Task Relationship Count performance improvement is enabled. */ public static boolean isTaskRelatedEntityCountEnabledGlobally() { return CommandContextUtil.getProcessEngineConfiguration().getPerformanceSettings().isEnableTaskRelationshipCounts(); } public static boolean isExecutionRelatedEntityCountEnabled(ExecutionEntity executionEntity) { if (executionEntity.isProcessInstanceType() || executionEntity instanceof CountingExecutionEntity) { return isExecutionRelatedEntityCountEnabled((CountingExecutionEntity) executionEntity); } return false; } public static boolean isTaskRelatedEntityCountEnabled(TaskEntity taskEntity) { if (taskEntity instanceof CountingTaskEntity) { return isTaskRelatedEntityCountEnabled((CountingTaskEntity) taskEntity); } return false; } /** * There are two flags here: a global flag and a flag on the execution entity. * The global flag can be switched on and off between different reboots, however the flag on the executionEntity refers * to the state at that particular moment of the last insert/update. * * Global flag / ExecutionEntity flag : result *
* T / T : T (all true, regular mode with flags enabled) * T / F : F (global is true, but execution was of a time when it was disabled, thus treating it as disabled as the counts can't be guessed) * F / T : F (execution was of time when counting was done. But this is overruled by the global flag and thus the queries will o * be done) * F / F : F (all disabled) * * From this table it is clear that only when both are true, the result should be true, which is the regular AND rule for booleans. */ public static boolean isExecutionRelatedEntityCountEnabled(CountingExecutionEntity executionEntity) { return !executionEntity.isProcessInstanceType() && isExecutionRelatedEntityCountEnabledGlobally() && executionEntity.isCountEnabled(); } /** * Similar functionality with <b>ExecutionRelatedEntityCount</b>, but on the TaskEntity level. */ public static boolean isTaskRelatedEntityCountEnabled(CountingTaskEntity taskEntity) { return isTaskRelatedEntityCountEnabledGlobally() && taskEntity.isCountEnabled(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CountingEntityUtil.java
1
请完成以下Java代码
public ITableCacheConfig create() { final IMutableTableCacheConfig cacheConfig = new MutableTableCacheConfig(tableName); cacheConfig.setEnabled(isEnabled()); cacheConfig.setTrxLevel(getTrxLevel()); cacheConfig.setCacheMapType(getCacheMapType()); cacheConfig.setExpireMinutes(getExpireMinutes()); cacheConfig.setInitialCapacity(getInitialCapacity()); cacheConfig.setMaxCapacity(getMaxCapacity()); return cacheConfig; } @Override public ITableCacheConfigBuilder setTemplate(final ITableCacheConfig template) { this.template = template; return this; } @Override public ITableCacheConfigBuilder setEnabled(final boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { if (enabled != null) { return enabled; } if (template != null) { return template.isEnabled(); } throw new IllegalStateException("Cannot get IsEnabled"); } @Override public ITableCacheConfigBuilder setTrxLevel(final TrxLevel trxLevel) { this.trxLevel = trxLevel; return this; } public TrxLevel getTrxLevel() { if (trxLevel != null) { return trxLevel; } if (template != null) { return template.getTrxLevel(); } throw new IllegalStateException("Cannot get TrxLevel"); } @Override public ITableCacheConfigBuilder setCacheMapType(final CacheMapType cacheMapType) { this.cacheMapType = cacheMapType; return this; } public CacheMapType getCacheMapType() { if (cacheMapType != null) { return cacheMapType; } if (template != null) { return template.getCacheMapType(); } throw new IllegalStateException("Cannot get CacheMapType"); } public int getInitialCapacity() { if (initialCapacity > 0) { return initialCapacity;
} else if (template != null) { return template.getInitialCapacity(); } throw new IllegalStateException("Cannot get InitialCapacity"); } @Override public ITableCacheConfigBuilder setInitialCapacity(final int initialCapacity) { this.initialCapacity = initialCapacity; return this; } public int getMaxCapacity() { if (maxCapacity > 0) { return maxCapacity; } else if (template != null) { return template.getMaxCapacity(); } return -1; } @Override public ITableCacheConfigBuilder setMaxCapacity(final int maxCapacity) { this.maxCapacity = maxCapacity; return this; } public int getExpireMinutes() { if (expireMinutes > 0 || expireMinutes == ITableCacheConfig.EXPIREMINUTES_Never) { return expireMinutes; } else if (template != null) { return template.getExpireMinutes(); } throw new IllegalStateException("Cannot get ExpireMinutes"); } @Override public ITableCacheConfigBuilder setExpireMinutes(final int expireMinutes) { this.expireMinutes = expireMinutes; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheConfigBuilder.java
1
请完成以下Java代码
public IHUDocumentLine getReversal() { throw new UnsupportedOperationException("Getting reversal for " + this + " is not supported"); } @Override public ProductId getProductId() { return storage.getProductId(); } @Override public BigDecimal getQty() { return storage.getQtyCapacity(); } @Override public I_C_UOM getC_UOM() { return storage.getC_UOM(); } @Override public BigDecimal getQtyAllocated() { return storage.getQtyFree(); } @Override public BigDecimal getQtyToAllocate() { return storage.getQty().toBigDecimal(); }
@Override public Object getTrxReferencedModel() { return referenceModel; } protected IProductStorage getStorage() { return storage; } @Override public IAllocationSource createAllocationSource(final I_M_HU hu) { return HUListAllocationSourceDestination.of(hu); } @Override public boolean isReadOnly() { return readonly; } @Override public void setReadOnly(final boolean readonly) { this.readonly = readonly; } @Override public I_M_HU_Item getInnerHUItem() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java
1
请完成以下Java代码
default Set<URL> getClassPathUrls(Predicate<Entry> includeFilter) throws IOException { return getClassPathUrls(includeFilter, ALL_ENTRIES); } /** * Returns classpath URLs for the archive that match the specified filters. * @param includeFilter filter used to determine which entries should be included * @param directorySearchFilter filter used to optimize tree walking for exploded * archives by determining if a directory needs to be searched or not * @return the classpath URLs * @throws IOException on IO error */ Set<URL> getClassPathUrls(Predicate<Entry> includeFilter, Predicate<Entry> directorySearchFilter) throws IOException; /** * Returns if this archive is backed by an exploded archive directory. * @return if the archive is exploded */ default boolean isExploded() { return getRootDirectory() != null; } /** * Returns the root directory of this archive or {@code null} if the archive is not * backed by a directory. * @return the root directory */ default File getRootDirectory() { return null; } /** * Closes the {@code Archive}, releasing any open resources. * @throws Exception if an error occurs during close processing */ @Override default void close() throws Exception { } /** * Factory method to create an appropriate {@link Archive} from the given * {@link Class} target. * @param target a target class that will be used to find the archive code source * @return an new {@link Archive} instance * @throws Exception if the archive cannot be created */ static Archive create(Class<?> target) throws Exception { return create(target.getProtectionDomain()); } static Archive create(ProtectionDomain protectionDomain) throws Exception { CodeSource codeSource = protectionDomain.getCodeSource(); URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null; if (location == null) { throw new IllegalStateException("Unable to determine code source archive"); } return create(Path.of(location).toFile()); } /** * Factory method to create an {@link Archive} from the given {@link File} target. * @param target a target {@link File} used to create the archive. May be a directory * or a jar file.
* @return a new {@link Archive} instance. * @throws Exception if the archive cannot be created */ static Archive create(File target) throws Exception { if (!target.exists()) { throw new IllegalStateException("Unable to determine code source archive from " + target); } return (target.isDirectory() ? new ExplodedArchive(target) : new JarFileArchive(target)); } /** * Represents a single entry in the archive. */ interface Entry { /** * Returns the name of the entry. * @return the name of the entry */ String name(); /** * Returns {@code true} if the entry represents a directory. * @return if the entry is a directory */ boolean isDirectory(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\Archive.java
1
请在Spring Boot框架中完成以下Java代码
private BooleanWithReason validateQRCode_GTIN( @NonNull final GS1HUQRCode pickFromHUQRCode, @NonNull final ProductId expectedProductId) { final GTIN gtin = pickFromHUQRCode.getGTIN().orElse(null); if (gtin != null) { final ProductId gs1ProductId = productService.getProductIdByGTINStrictlyNotNull(gtin, ClientId.METASFRESH); if (!ProductId.equals(expectedProductId, gs1ProductId)) { return BooleanWithReason.falseBecause(ERR_QR_ProductNotMatching); // throw new AdempiereException(ERR_QR_ProductNotMatching) // .setParameter("GTIN", gtin) // .setParameter("expected", expectedProductId) // .setParameter("actual", gs1ProductId); } } return BooleanWithReason.TRUE; } private BooleanWithReason validateQRCode_EAN13ProductNo( @NonNull final EAN13HUQRCode pickFromQRCode, @NonNull final ProductId expectedProductId, @NonNull final BPartnerId customerId) { final EAN13 ean13 = pickFromQRCode.unbox(); if (!productService.isValidEAN13Product(ean13, expectedProductId, customerId)) { return BooleanWithReason.falseBecause(ERR_QR_ProductNotMatching); // final String expectedProductNo = productService.getProductValue(expectedProductId); // final EAN13ProductCode ean13ProductNo = ean13.getProductNo(); // throw new AdempiereException(ERR_QR_ProductNotMatching) // .setParameter("ean13ProductNo", ean13ProductNo) // .setParameter("expectedProductNo", expectedProductNo) // .setParameter("expectedProductId", expectedProductId); } return BooleanWithReason.TRUE;
} private BooleanWithReason validateQRCode_ProductNo( @NonNull final CustomHUQRCode customQRCode, @NonNull final ProductId expectedProductId) { final String qrCodeProductNo = customQRCode.getProductNo().orElse(null); if (qrCodeProductNo == null) {return BooleanWithReason.TRUE;} final String expectedProductNo = productService.getProductValue(expectedProductId); if (!Objects.equals(qrCodeProductNo, expectedProductNo)) { return BooleanWithReason.falseBecause(ERR_QR_ProductNotMatching); // throw new AdempiereException(ERR_QR_ProductNotMatching) // .setParameter("qrCodeProductNo", qrCodeProductNo) // .setParameter("expectedProductNo", expectedProductNo) // .setParameter("expectedProductId", expectedProductId); } return BooleanWithReason.TRUE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\PickFromHUQRCodeResolveCommand.java
2
请完成以下Java代码
public void afterAll(ExtensionContext context) { BROKER_RUNNING_HOLDER.remove(); Store store = getStore(context); BrokerRunningSupport brokerRunning = store.remove(BROKER_RUNNING_BEAN, BrokerRunningSupport.class); if (brokerRunning != null) { brokerRunning.removeTestQueues(); } } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { Class<?> type = parameterContext.getParameter().getType(); return type.equals(ConnectionFactory.class) || type.equals(BrokerRunningSupport.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) throws ParameterResolutionException { // in parent for method injection, Composite key causes a store miss BrokerRunningSupport brokerRunning = getParentStore(context).get(BROKER_RUNNING_BEAN, BrokerRunningSupport.class) == null ? getStore(context).get(BROKER_RUNNING_BEAN, BrokerRunningSupport.class) : getParentStore(context).get(BROKER_RUNNING_BEAN, BrokerRunningSupport.class); Assert.state(brokerRunning != null, "Could not find brokerRunning instance"); Class<?> type = parameterContext.getParameter().getType(); return type.equals(ConnectionFactory.class) ? brokerRunning.getConnectionFactory() : brokerRunning; }
private Store getStore(ExtensionContext context) { return context.getStore(Namespace.create(getClass(), context)); } private Store getParentStore(ExtensionContext context) { ExtensionContext parent = context.getParent().get(); return parent.getStore(Namespace.create(getClass(), parent)); } public static BrokerRunningSupport getBrokerRunning() { return BROKER_RUNNING_HOLDER.get(); } }
repos\spring-amqp-main\spring-rabbit-junit\src\main\java\org\springframework\amqp\rabbit\junit\RabbitAvailableCondition.java
1
请在Spring Boot框架中完成以下Java代码
public I_AD_Sequence retrieveTableSequenceOrNull(@NonNull final Properties ctx, @NonNull final String tableName) { final String trxName = ITrx.TRXNAME_None; return retrieveTableSequenceOrNull(ctx, tableName, trxName); } @Override public ITableSequenceChecker createTableSequenceChecker(final Properties ctx) { return new TableSequenceChecker(ctx); } @Override public void renameTableSequence(final Properties ctx, final String tableNameOld, final String tableNameNew) { // // Rename the AD_Sequence final I_AD_Sequence adSequence = retrieveTableSequenceOrNull(ctx, tableNameOld, ITrx.TRXNAME_ThreadInherited); if (adSequence != null) { adSequence.setName(tableNameNew); InterfaceWrapperHelper.save(adSequence); } // // Rename the database native sequence { final String dbSequenceNameOld = DB.getTableSequenceName(tableNameOld); final String dbSequenceNameNew = DB.getTableSequenceName(tableNameNew); DB.getDatabase().renameSequence(dbSequenceNameOld, dbSequenceNameNew); } } @Override @NonNull public Optional<I_AD_Sequence> retrieveSequenceByName(@NonNull final String sequenceName, @NonNull final ClientId clientId) { return queryBL
.createQueryBuilder(I_AD_Sequence.class) .addEqualsFilter(I_AD_Sequence.COLUMNNAME_Name, sequenceName) .addEqualsFilter(I_AD_Sequence.COLUMNNAME_AD_Client_ID, clientId) .addEqualsFilter(I_AD_Sequence.COLUMNNAME_IsTableID, false) .addOnlyActiveRecordsFilter() .create() .firstOptional(I_AD_Sequence.class); } @Override public DocSequenceId cloneToOrg(@NonNull final DocSequenceId fromDocSequenceId, @NonNull final OrgId toOrgId) { final I_AD_Sequence fromSequence = InterfaceWrapperHelper.load(fromDocSequenceId, I_AD_Sequence.class); final I_AD_Sequence newSequence = InterfaceWrapperHelper.copy() .setFrom(fromSequence) .setSkipCalculatedColumns(true) .copyToNew(I_AD_Sequence.class); newSequence.setAD_Org_ID(toOrgId.getRepoId()); newSequence.setCurrentNext(100000); InterfaceWrapperHelper.save(newSequence); return DocSequenceId.ofRepoId(newSequence.getAD_Sequence_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\SequenceDAO.java
2
请完成以下Java代码
public void setXPosition (int XPosition) { set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition)); } /** Get X Position. @return Absolute X (horizontal) position in 1/72 of an inch */ public int getXPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_XPosition); if (ii == null) return 0; return ii.intValue(); } /** Set X Space. @param XSpace Relative X (horizontal) space in 1/72 of an inch */ public void setXSpace (int XSpace) { set_Value (COLUMNNAME_XSpace, Integer.valueOf(XSpace)); } /** Get X Space. @return Relative X (horizontal) space in 1/72 of an inch */ public int getXSpace () { Integer ii = (Integer)get_Value(COLUMNNAME_XSpace); if (ii == null) return 0; return ii.intValue(); } /** Set Y Position. @param YPosition
Absolute Y (vertical) position in 1/72 of an inch */ public void setYPosition (int YPosition) { set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition)); } /** Get Y Position. @return Absolute Y (vertical) position in 1/72 of an inch */ public int getYPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_YPosition); if (ii == null) return 0; return ii.intValue(); } /** Set Y Space. @param YSpace Relative Y (vertical) space in 1/72 of an inch */ public void setYSpace (int YSpace) { set_Value (COLUMNNAME_YSpace, Integer.valueOf(YSpace)); } /** Get Y Space. @return Relative Y (vertical) space in 1/72 of an inch */ public int getYSpace () { Integer ii = (Integer)get_Value(COLUMNNAME_YSpace); 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_AD_PrintFormatItem.java
1
请在Spring Boot框架中完成以下Java代码
public class HybridClientRegistrationRepository implements ClientRegistrationRepository { private static final String defaultRedirectUriTemplate = "{baseUrl}/login/oauth2/code/{registrationId}"; @Autowired private OAuth2ClientService oAuth2ClientService; @Override public ClientRegistration findByRegistrationId(String registrationId) { OAuth2Client oAuth2Client = oAuth2ClientService.findOAuth2ClientById(TenantId.SYS_TENANT_ID, new OAuth2ClientId(UUID.fromString(registrationId))); if (oAuth2Client == null) { return null; } return toSpringClientRegistration(oAuth2Client); } private ClientRegistration toSpringClientRegistration(OAuth2Client oAuth2Client) { String registrationId = oAuth2Client.getUuidId().toString(); // NONE is used if we need pkce-based code challenge ClientAuthenticationMethod authMethod = ClientAuthenticationMethod.NONE; if (oAuth2Client.getClientAuthenticationMethod().equals("POST")) { authMethod = ClientAuthenticationMethod.CLIENT_SECRET_POST; } else if (oAuth2Client.getClientAuthenticationMethod().equals("BASIC")) { authMethod = ClientAuthenticationMethod.CLIENT_SECRET_BASIC; } return ClientRegistration.withRegistrationId(registrationId)
.clientName(oAuth2Client.getName()) .clientId(oAuth2Client.getClientId()) .authorizationUri(oAuth2Client.getAuthorizationUri()) .clientSecret(oAuth2Client.getClientSecret()) .tokenUri(oAuth2Client.getAccessTokenUri()) .scope(oAuth2Client.getScope()) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .userInfoUri(oAuth2Client.getUserInfoUri()) .userNameAttributeName(oAuth2Client.getUserNameAttributeName()) .jwkSetUri(oAuth2Client.getJwkSetUri()) .clientAuthenticationMethod(authMethod) .redirectUri(defaultRedirectUriTemplate) .build(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\oauth2\HybridClientRegistrationRepository.java
2
请完成以下Spring Boot application配置
# ======================== # APPLICATION # ======================== # Directory where will be saved uploaded files. Make sure that the application # have write permissions on such directory. netgloo.paths.uploadedFiles = /var/netgloo_blog/uploads # ======================== # SPRING BOOT: MULTIPART # ======================== # Set the file size limit (default 1Mb). If you want to specify that files be # unlimit
ed set the multipart.maxFileSize property to -1. multipart.maxFileSize = 3Mb # Set the total request size for a multipart/form-data (default 10Mb) #multipart.maxRequestSize = 10Mb
repos\spring-boot-samples-master\spring-boot-file-upload-with-ajax\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class AlbertaOrderService { private final AlbertaOrderDAO albertaOrderDAO; public AlbertaOrderService(final AlbertaOrderDAO albertaOrderDAO) { this.albertaOrderDAO = albertaOrderDAO; } public void saveAlbertaOrderInfo(@NonNull final AlbertaOrderInfo albertaOrderInfo) { if (Check.isNotBlank(albertaOrderInfo.getTherapy())) { albertaOrderDAO.createAlbertaOrderTherapy(albertaOrderInfo.getOlCandId(), albertaOrderInfo.getTherapy(),
albertaOrderInfo.getOrgId()); } if (!Check.isEmpty(albertaOrderInfo.getTherapyTypes())) { albertaOrderInfo.getTherapyTypes() .forEach(therapyType -> albertaOrderDAO .createAlbertaOrderTherapyType(albertaOrderInfo.getOlCandId(), therapyType, albertaOrderInfo.getOrgId())); } albertaOrderDAO.createAlbertaOrder(albertaOrderInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\order\service\AlbertaOrderService.java
2
请完成以下Java代码
public boolean isCancelCurrentActiveActivityInstances() { return cancelCurrentActiveActivityInstances; } public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) { this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances; } public abstract void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper); public abstract void applyTo(InstantiationBuilder<?> builder, ProcessEngine engine, ObjectMapper mapper); protected String buildErrorMessage(String message) { return "For instruction type '" + type + "': " + message; } protected void applyVariables(ActivityInstantiationBuilder<?> builder, ProcessEngine engine, ObjectMapper mapper) {
if (variables != null) { for (Map.Entry<String, TriggerVariableValueDto> variableValue : variables.entrySet()) { TriggerVariableValueDto value = variableValue.getValue(); if (value.isLocal()) { builder.setVariableLocal(variableValue.getKey(), value.toTypedValue(engine, mapper)); } else { builder.setVariable(variableValue.getKey(), value.toTypedValue(engine, mapper)); } } } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\modification\ProcessInstanceModificationInstructionDto.java
1
请在Spring Boot框架中完成以下Java代码
Cache responseCache(CacheManager cacheManager) { return cacheManager.getCache(RESPONSE_CACHE_NAME); } public static class OnGlobalLocalResponseCacheCondition extends AllNestedConditions { OnGlobalLocalResponseCacheCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(value = GatewayProperties.PREFIX + ".enabled", havingValue = "true", matchIfMissing = true) static class OnGatewayPropertyEnabled { }
@ConditionalOnProperty(value = GatewayProperties.PREFIX + ".filter.local-response-cache.enabled", havingValue = "true") static class OnLocalResponseCachePropertyEnabled { } @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".global-filter.local-response-cache.enabled", havingValue = "true", matchIfMissing = true) static class OnGlobalLocalResponseCachePropertyEnabled { } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\LocalResponseCacheAutoConfiguration.java
2
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; }
/** Set Ratio. @param Ratio Relative Ratio for Distributions */ public void setRatio (BigDecimal Ratio) { set_Value (COLUMNNAME_Ratio, Ratio); } /** Get Ratio. @return Relative Ratio for Distributions */ public BigDecimal getRatio () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Ratio); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_DistributionRunDetail.java
1
请完成以下Java代码
public final class CardinalityOrderComparator<T> implements Comparator<T> { public static final <T> Builder<T> builder() { return new Builder<>(); } private List<T> cardinalityList; private CardinalityOrderComparator(final Builder<T> builder) { super(); // NOTE: we shall not copy the cardinality list because we don't know what type is it, // and maybe the developer is rellying on a specific indexOf implementation of that list. Check.assumeNotNull(builder.cardinalityList, "cardinalityList not null"); this.cardinalityList = builder.cardinalityList; } @Override public int compare(final T o1, final T o2) { final int cardinality1 = cardinality(o1); final int cardinality2 = cardinality(o2); return cardinality1 - cardinality2; } private final int cardinality(final T item) { final int cardinality = cardinalityList.indexOf(item); // If item was not found in our cardinality list, return MAX_VALUE // => not found items will be comsidered last ones if (cardinality < 0) { return Integer.MAX_VALUE; } return cardinality; } public static final class Builder<T> {
private List<T> cardinalityList; Builder() { super(); } public CardinalityOrderComparator<T> build() { return new CardinalityOrderComparator<>(this); } /** * Convenient method to copy and sort a given list. * * @param list * @return sorted list (as a new copy) */ public List<T> copyAndSort(final List<T> list) { final CardinalityOrderComparator<T> comparator = build(); final List<T> listSorted = new ArrayList<>(list); Collections.sort(listSorted, comparator); return listSorted; } /** * Sets the list of all items. * When sorting, this is the list which will give the cardinality of a given item (i.e. the indexOf). * * WARNING: the given cardinality list will be used on line, as it is and it won't be copied, because we don't know what indexOf implementation to use. * So, please make sure you are not chaning the list in meantime. * * @param cardinalityList * @return */ public Builder<T> setCardinalityList(final List<T> cardinalityList) { this.cardinalityList = cardinalityList; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\CardinalityOrderComparator.java
1
请完成以下Java代码
private static int extractExpireMinutes(Cached cachedAnnotation) { int expireMinutes = cachedAnnotation.expireMinutes(); if (expireMinutes == Cached.EXPIREMINUTES_Never) { return Cached.EXPIREMINUTES_Never; } else if (expireMinutes <= 0) { return DEFAULT_CacheExpireMinutes; } else { return expireMinutes; } } public CacheKeyBuilder createKeyBuilder(final Object targetObject, final Object[] methodArgs) { final Class<?> methodDeclaringClass = method.getDeclaringClass(); final Object targetObjToUse = staticMethod ? methodDeclaringClass : targetObject; final CacheKeyBuilder keyBuilder = new CacheKeyBuilder(); // // Key: Method signature // NOTE: avoid adding Class/Field/Method etc to key => would lead to ClassLoader(s) memory leaks/fucked-up keyBuilder.add(methodDeclaringClass.getName()); keyBuilder.add(method.getName());
keyBuilder.add(method.getReturnType().getName()); for (final ICachedMethodPartDescriptor descriptor : descriptors) { descriptor.extractKeyParts(keyBuilder, targetObjToUse, methodArgs); if (keyBuilder.isSkipCaching()) { return keyBuilder; } } return keyBuilder; } @NonNull private CCache<ArrayKey, Object> createCCache() { return CCache.<ArrayKey, Object>builder() .cacheName(cacheName) .initialCapacity(DEFAULT_CacheInitialCapacity) .expireMinutes(expireMinutes) .additionalLabels(ADDITIONAL_CACHE_LABELS) .build(); } /** * Callable used to create method level cache container. */ public Callable<CCache<ArrayKey, Object>> createCCacheCallable() {return this::createCCache;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CachedMethodDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public class WEBUI_M_HU_MoveToDirectWarehouse extends HUEditorProcessTemplate implements IProcessPrecondition { @Autowired private DocumentCollection documentsCollection; private static final HUEditorRowFilter rowsFilter = HUEditorRowFilter.builder().select(Select.ONLY_TOPLEVEL).onlyActiveHUs().build(); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if(!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!streamSelectedHUIds(rowsFilter).findAny().isPresent()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU)); } return ProcessPreconditionsResolution.accept(); }
@Override @RunOutOfTrx protected String doIt() { final Stream<I_M_HU> selectedTopLevelHUs = streamSelectedHUs(rowsFilter); HUMoveToDirectWarehouseService.newInstance() .setDocumentsCollection(documentsCollection) .setHUView(getView()) .setMovementDate(SystemTime.asInstant()) // now // .setDescription(description) // none .setFailOnFirstError(true) .setFailIfNoHUs(true) .setLoggable(this) .move(selectedTopLevelHUs.iterator()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToDirectWarehouse.java
2
请完成以下Java代码
private void createBeginOfPause( @NonNull final I_C_Flatrate_Term term, @NonNull final Timestamp pauseFrom, final int seqNoOfPauseRecord) { final I_C_SubscriptionProgress pauseBegin = newInstance(I_C_SubscriptionProgress.class); pauseBegin.setEventType(X_C_SubscriptionProgress.EVENTTYPE_BeginOfPause); pauseBegin.setC_Flatrate_Term(term); pauseBegin.setStatus(X_C_SubscriptionProgress.STATUS_Planned); pauseBegin.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_DeliveryPause); pauseBegin.setEventDate(pauseFrom); pauseBegin.setSeqNo(seqNoOfPauseRecord); save(pauseBegin); } private ImmutableList<I_C_SubscriptionProgress> processAndCollectRecordWithinPause( @NonNull final List<I_C_SubscriptionProgress> sps, @NonNull final Timestamp pauseUntil) { final Builder<I_C_SubscriptionProgress> spsWithinPause = ImmutableList.builder(); for (final I_C_SubscriptionProgress sp : sps) { if (sp.getEventDate().after(pauseUntil)) { continue; } spsWithinPause.add(sp); sp.setSeqNo(sp.getSeqNo() + 1); if (sp.getM_ShipmentSchedule_ID() > 0) { Services.get(IShipmentScheduleBL.class).closeShipmentSchedule(ShipmentScheduleId.ofRepoId(sp.getM_ShipmentSchedule_ID())); } final boolean notYetDone = !Objects.equals(sp.getStatus(), X_C_SubscriptionProgress.STATUS_Done); if (notYetDone) { sp.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_DeliveryPause); } } return spsWithinPause.build(); } private static int computeEndOfPauseSeqNo(final I_C_SubscriptionProgress firstSpAfterBeginOfPause, final ImmutableList<I_C_SubscriptionProgress> spsWithinPause) { return spsWithinPause.isEmpty() ? firstSpAfterBeginOfPause.getSeqNo() + 1 : spsWithinPause.get(spsWithinPause.size() - 1).getSeqNo() + 1;
} private void createEndOfPause( final I_C_Flatrate_Term term, final Timestamp pauseUntil, final int seqNoOfPauseRecord) { final I_C_SubscriptionProgress pauseEnd = newInstance(I_C_SubscriptionProgress.class); pauseEnd.setEventType(X_C_SubscriptionProgress.EVENTTYPE_EndOfPause); pauseEnd.setC_Flatrate_Term(term); pauseEnd.setStatus(X_C_SubscriptionProgress.STATUS_Planned); pauseEnd.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running); pauseEnd.setEventDate(pauseUntil); pauseEnd.setSeqNo(seqNoOfPauseRecord); save(pauseEnd); } private ImmutableList<I_C_SubscriptionProgress> collectSpsAfterEndOfPause(final List<I_C_SubscriptionProgress> sps, final Timestamp pauseUntil) { final ImmutableList<I_C_SubscriptionProgress> spsAfterPause = sps.stream() .filter(sp -> sp.getEventDate().after(pauseUntil)) .collect(ImmutableList.toImmutableList()); return spsAfterPause; } private void increaseSeqNosByTwo(@NonNull final List<I_C_SubscriptionProgress> sps) { final int seqNoOffSet = 2; for (final I_C_SubscriptionProgress currentSP : sps) { currentSP.setSeqNo(currentSP.getSeqNo() + seqNoOffSet); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\InsertPause.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult<HomeContentResult> content() { HomeContentResult contentResult = homeService.content(); return CommonResult.success(contentResult); } @ApiOperation("分页获取推荐商品") @RequestMapping(value = "/recommendProductList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> recommendProductList(@RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProduct> productList = homeService.recommendProductList(pageSize, pageNum); return CommonResult.success(productList); } @ApiOperation("获取首页商品分类") @RequestMapping(value = "/productCateList/{parentId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductCategory>> getProductCateList(@PathVariable Long parentId) { List<PmsProductCategory> productCategoryList = homeService.getProductCateList(parentId); return CommonResult.success(productCategoryList); } @ApiOperation("根据分类分页获取专题") @RequestMapping(value = "/subjectList", method = RequestMethod.GET) @ResponseBody
public CommonResult<List<CmsSubject>> getSubjectList(@RequestParam(required = false) Long cateId, @RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<CmsSubject> subjectList = homeService.getSubjectList(cateId,pageSize,pageNum); return CommonResult.success(subjectList); } @ApiOperation("分页获取人气推荐商品") @RequestMapping(value = "/hotProductList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> hotProductList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize) { List<PmsProduct> productList = homeService.hotProductList(pageNum,pageSize); return CommonResult.success(productList); } @ApiOperation("分页获取新品推荐商品") @RequestMapping(value = "/newProductList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> newProductList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize) { List<PmsProduct> productList = homeService.newProductList(pageNum,pageSize); return CommonResult.success(productList); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\HomeController.java
2
请完成以下Java代码
public class PersonIdentification5 { @XmlElement(name = "DtAndPlcOfBirth") protected DateAndPlaceOfBirth dtAndPlcOfBirth; @XmlElement(name = "Othr") protected List<GenericPersonIdentification1> othr; /** * Gets the value of the dtAndPlcOfBirth property. * * @return * possible object is * {@link DateAndPlaceOfBirth } * */ public DateAndPlaceOfBirth getDtAndPlcOfBirth() { return dtAndPlcOfBirth; } /** * Sets the value of the dtAndPlcOfBirth property. * * @param value * allowed object is * {@link DateAndPlaceOfBirth } * */ public void setDtAndPlcOfBirth(DateAndPlaceOfBirth value) { this.dtAndPlcOfBirth = value; } /** * Gets the value of the othr 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 othr property. *
* <p> * For example, to add a new item, do as follows: * <pre> * getOthr().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link GenericPersonIdentification1 } * * */ public List<GenericPersonIdentification1> getOthr() { if (othr == null) { othr = new ArrayList<GenericPersonIdentification1>(); } return this.othr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PersonIdentification5.java
1
请在Spring Boot框架中完成以下Java代码
private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) { String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY); if (StringUtils.hasLength(springApplicationName) && !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) { defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName); } } private void setDubboConfigMultipleProperty(Map<String, Object> defaultProperties) { defaultProperties.put(DUBBO_CONFIG_MULTIPLE_PROPERTY, Boolean.TRUE.toString()); } private void setDubboApplicationQosEnableProperty(Map<String, Object> defaultProperties) { defaultProperties.put(DUBBO_APPLICATION_QOS_ENABLE_PROPERTY, Boolean.FALSE.toString()); } /** * Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be * <code>true</code> as default. * * @param defaultProperties the default {@link Properties properties} * @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY * @since 2.7.1 */ private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) { defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString()); } /** * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map) * * @param propertySources {@link MutablePropertySources}
* @param map Default Dubbo Properties */ private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) { MapPropertySource target = null; if (propertySources.contains(PROPERTY_SOURCE_NAME)) { PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME); if (source instanceof MapPropertySource) { target = (MapPropertySource) source; for (String key : map.keySet()) { if (!target.containsProperty(key)) { target.getSource().put(key, map.get(key)); } } } } if (target == null) { target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); } if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { propertySources.addLast(target); } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\env\DubboDefaultPropertiesEnvironmentPostProcessor.java
2
请完成以下Java代码
public boolean isCU() { return isPickedHURow() && getType().isCU(); } public boolean isCUOrStorage() { return isPickedHURow() && getType().isCUOrStorage(); } /** * * @return {@code true} if this row represents an HU that is a source-HU for fine-picking. */ public boolean isPickingSourceHURow() { return pickingSlotRowId.isPickingSourceHURow(); } public WarehouseId getPickingSlotWarehouseId() { return pickingSlotWarehouse != null ? WarehouseId.ofRepoId(pickingSlotWarehouse.getIdAsInt()) : null; } public BigDecimal getHuQtyCU() { return huQtyCU; } public ProductId getHuProductId() { return huProduct != null ? ProductId.ofRepoId(huProduct.getKeyAsInt()) : null; } @Override public ViewId getIncludedViewId() { return includedViewId; } public LocatorId getPickingSlotLocatorId() { return pickingSlotLocatorId; } public int getBPartnerId() { return pickingSlotBPartner != null ? pickingSlotBPartner.getIdAsInt() : -1; } public int getBPartnerLocationId() { return pickingSlotBPLocation != null ? pickingSlotBPLocation.getIdAsInt() : -1; } @NonNull public Optional<PickingSlotRow> findRowMatching(@NonNull final Predicate<PickingSlotRow> predicate) { return streamThisRowAndIncludedRowsRecursivelly() .filter(predicate) .findFirst(); }
public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId) { final HuId huId = getHuId(); if (huId == null) { throw new AdempiereException("Not a PickedHURow!") .appendParametersToMessage() .setParameter("PickingSlotRow", this); } final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId); if (hasOpenPickingForOrderId) { return true; } if (isLU()) { return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId)) .isPresent(); } return false; } @NonNull private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId) { return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId)) .orElse(ImmutableSet.of()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java
1
请完成以下Java代码
public UserQuery memberOfTenant(String tenantId) { ensureNotNull("Provided tenantId", tenantId); this.tenantId = tenantId; return this; } //sorting ////////////////////////////////////////////////////////// public UserQuery orderByUserId() { return orderBy(UserQueryProperty.USER_ID); } public UserQuery orderByUserEmail() { return orderBy(UserQueryProperty.EMAIL); } public UserQuery orderByUserFirstName() { return orderBy(UserQueryProperty.FIRST_NAME); } public UserQuery orderByUserLastName() { return orderBy(UserQueryProperty.LAST_NAME); } //getters ////////////////////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getFirstName() {
return firstName; } public String getFirstNameLike() { return firstNameLike; } public String getLastName() { return lastName; } public String getLastNameLike() { return lastNameLike; } public String getEmail() { return email; } public String getEmailLike() { return emailLike; } public String getGroupId() { return groupId; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public PatientNoteMapping _id(UUID _id) { this._id = _id; return this; } /** * Alberta-Id der Patientennotiz * @return _id **/ @Schema(example = "85186471-634d-43a1-bb33-c4d0bccc0c60", required = true, description = "Alberta-Id der Patientennotiz") public UUID getId() { return _id; } public void setId(UUID _id) { this._id = _id; } public PatientNoteMapping updatedAt(String updatedAt) { this.updatedAt = updatedAt; return this; } /** * Der Zeitstempel der letzten Änderung * @return updatedAt **/ @Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(java.lang.Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientNoteMapping patientNoteMapping = (PatientNoteMapping) o; return Objects.equals(this._id, patientNoteMapping._id) && Objects.equals(this.updatedAt, patientNoteMapping.updatedAt); } @Override public int hashCode() { return Objects.hash(_id, updatedAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientNoteMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientNoteMapping.java
2
请完成以下Java代码
public class ShipmentSchedule { @NonNull private final ShipmentScheduleId id; @NonNull private final OrgId orgId; @NonNull private final BPartnerId shipBPartnerId; @NonNull private final BPartnerLocationId shipLocationId; @Nullable private final BPartnerContactId shipContactId; @Nullable private final BPartnerId billBPartnerId; @Nullable private final BPartnerLocationId billLocationId; @Nullable private final BPartnerContactId billContactId; @Nullable private final OrderAndLineId orderAndLineId; @Nullable private final LocalDateTime dateOrdered; @Nullable private final LocalDate deliveryDateEffective; private int numberOfItemsForSameShipment; @NonNull private final ProductId productId; @NonNull private final WarehouseId warehouseId; @NonNull private final Quantity quantityToDeliver; @NonNull private final Quantity orderedQuantity; @NonNull private final Quantity deliveredQuantity; @Nullable private final AttributeSetInstanceId attributeSetInstanceId; @NonNull private APIExportStatus exportStatus; @Nullable private final ShipperId shipperId; private boolean isProcessed; private boolean isClosed; private boolean isActive; @NonNull private CarrierAdviseStatus carrierAdvisingStatus; @Nullable private String carrierAdviseErrorMessage; @Nullable private CarrierProductId carrierProductId; @Nullable private CarrierGoodsTypeId carrierGoodsTypeId; @Nullable private PriorityRule priorityRule; @Nullable private ExternalSystemId externalSystemId; @Getter(AccessLevel.NONE) @Nullable private Set<CarrierServiceId> carrierServices;
@NonNull public Set<CarrierServiceId> getCarrierServicesIfLoaded() { if (carrierServices == null) { throw new AdempiereException("Carrier services were not loaded for " + this); } return carrierServices; } @Nullable public OrderId getOrderId() { return getOrderAndLineId() != null ? getOrderAndLineId().getOrderId() : null; } public boolean hasAttributes(@NonNull final ImmutableSet<AttributeSetInstanceId> targetAsiIds, @NonNull final IAttributeSetInstanceBL asiBL) { final ImmutableSet<AttributeSetInstanceId> nonNullTargetAsiIds = targetAsiIds.stream().filter(asiId -> !AttributeSetInstanceId.NONE.equals(asiId)).collect(ImmutableSet.toImmutableSet()); if (nonNullTargetAsiIds.isEmpty()) { return true; // targetAsiIds was effectively empty, so we return true } if (getAttributeSetInstanceId() == null) { return false; } final ImmutableAttributeSet shipmentScheduleAsi = asiBL.getImmutableAttributeSetById(getAttributeSetInstanceId()); return nonNullTargetAsiIds.stream().map(asiBL::getImmutableAttributeSetById).anyMatch(shipmentScheduleAsi::containsAttributeValues); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ShipmentSchedule.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { AttachmentEntity attachment = null; if (taskId != null && !taskId.isBlank()) { attachment = (AttachmentEntity) commandContext .getAttachmentManager() .findAttachmentByTaskIdAndAttachmentId(taskId, attachmentId); ensureNotNull("No attachment exists for task id '" + taskId + " and attachmentId '" + attachmentId + "'.", "attachment", attachment); } else { attachment = commandContext .getDbEntityManager() .selectById(AttachmentEntity.class, attachmentId); ensureNotNull("No attachment exists with attachmentId '" + attachmentId + "'.", "attachment", attachment); } commandContext .getDbEntityManager() .delete(attachment); if (attachment.getContentId() != null) { commandContext .getByteArrayManager() .deleteByteArrayById(attachment.getContentId()); }
if (attachment.getTaskId() != null && !attachment.getTaskId().isBlank()) { TaskEntity task = commandContext .getTaskManager() .findTaskById(attachment.getTaskId()); if (task != null) { PropertyChange propertyChange = new PropertyChange("name", null, attachment.getName()); commandContext.getOperationLogManager() .logAttachmentOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_ATTACHMENT, task, propertyChange); task.triggerUpdateEvent(); } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteAttachmentCmd.java
1
请在Spring Boot框架中完成以下Java代码
BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer() { return (builder) -> { List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { builder.add(BaggagePropagationConfig.SingleBaggageField.remote(BaggageField.create(fieldName))); } List<String> localFields = this.tracingProperties.getBaggage().getLocalFields(); for (String localFieldName : localFields) { builder.add(BaggagePropagationConfig.SingleBaggageField.local(BaggageField.create(localFieldName))); } }; } @Bean @ConditionalOnMissingBean @ConditionalOnEnabledTracingExport Factory propagationFactory(BaggagePropagation.FactoryBuilder factoryBuilder) { return factoryBuilder.build(); } @Bean @ConditionalOnMissingBean CorrelationScopeDecorator.Builder mdcCorrelationScopeDecoratorBuilder( ObjectProvider<CorrelationScopeCustomizer> correlationScopeCustomizers) { CorrelationScopeDecorator.Builder builder = MDCScopeDecorator.newBuilder(); correlationScopeCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Order(0) @ConditionalOnBooleanProperty(name = "management.tracing.baggage.correlation.enabled", matchIfMissing = true) CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() { return (builder) -> { Correlation correlationProperties = this.tracingProperties.getBaggage().getCorrelation(); for (String field : correlationProperties.getFields()) { BaggageField baggageField = BaggageField.create(field); SingleCorrelationField correlationField = SingleCorrelationField.newBuilder(baggageField) .flushOnUpdate() .build(); builder.add(correlationField); } }; }
@Bean @ConditionalOnMissingBean(CorrelationScopeDecorator.class) ScopeDecorator correlationScopeDecorator(CorrelationScopeDecorator.Builder builder) { return builder.build(); } } /** * Propagates neither traces nor baggage. */ @Configuration(proxyBeanMethods = false) static class NoPropagation { @Bean @ConditionalOnMissingBean(Factory.class) CompositePropagationFactory noopPropagationFactory() { return CompositePropagationFactory.noop(); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-brave\src\main\java\org\springframework\boot\micrometer\tracing\brave\autoconfigure\BravePropagationConfigurations.java
2
请完成以下Java代码
public static PickingJobCandidateProducts of(@NonNull final PickingJobCandidateProduct product) { return new PickingJobCandidateProducts(ImmutableMap.of(product.getProductId(), product)); } public static Collector<PickingJobCandidateProduct, ?, PickingJobCandidateProducts> collect() { return GuavaCollectors.collectUsingListAccumulator(PickingJobCandidateProducts::ofList); } public Set<ProductId> getProductIds() {return byProductId.keySet();} @Override @NonNull public Iterator<PickingJobCandidateProduct> iterator() {return byProductId.values().iterator();} public OptionalBoolean hasQtyAvailableToPick() { final QtyAvailableStatus qtyAvailableStatus = getQtyAvailableStatus().orElse(null); return qtyAvailableStatus == null ? OptionalBoolean.UNKNOWN : OptionalBoolean.ofBoolean(qtyAvailableStatus.isPartialOrFullyAvailable()); } public Optional<QtyAvailableStatus> getQtyAvailableStatus() { Optional<QtyAvailableStatus> qtyAvailableStatus = this._qtyAvailableStatus; //noinspection OptionalAssignedToNull if (qtyAvailableStatus == null) { qtyAvailableStatus = this._qtyAvailableStatus = computeQtyAvailableStatus(); } return qtyAvailableStatus; } private Optional<QtyAvailableStatus> computeQtyAvailableStatus() { return QtyAvailableStatus.computeOfLines(byProductId.values(), product -> product.getQtyAvailableStatus().orElse(null)); } public PickingJobCandidateProducts updatingEachProduct(@NonNull UnaryOperator<PickingJobCandidateProduct> updater) { if (byProductId.isEmpty()) {
return this; } final ImmutableMap<ProductId, PickingJobCandidateProduct> byProductIdNew = byProductId.values() .stream() .map(updater) .collect(ImmutableMap.toImmutableMap(PickingJobCandidateProduct::getProductId, product -> product)); return Objects.equals(this.byProductId, byProductIdNew) ? this : new PickingJobCandidateProducts(byProductIdNew); } @Nullable public ProductId getSingleProductIdOrNull() { return singleProduct != null ? singleProduct.getProductId() : null; } @Nullable public Quantity getSingleQtyToDeliverOrNull() { return singleProduct != null ? singleProduct.getQtyToDeliver() : null; } @Nullable public Quantity getSingleQtyAvailableToPickOrNull() { return singleProduct != null ? singleProduct.getQtyAvailableToPick() : null; } @Nullable public ITranslatableString getSingleProductNameOrNull() { return singleProduct != null ? singleProduct.getProductName() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidateProducts.java
1
请在Spring Boot框架中完成以下Java代码
public class User { private Long id; private String name; private Integer age; public User() { } public User(Long id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id;
} public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\model\User.java
2
请完成以下Java代码
public int getPayPal_PayerApprovalRequest_MailTemplate_ID() { return get_ValueAsInt(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID); } @Override public void setPayPal_PaymentApprovedCallbackUrl (final @Nullable java.lang.String PayPal_PaymentApprovedCallbackUrl) { set_Value (COLUMNNAME_PayPal_PaymentApprovedCallbackUrl, PayPal_PaymentApprovedCallbackUrl); } @Override public java.lang.String getPayPal_PaymentApprovedCallbackUrl() { return get_ValueAsString(COLUMNNAME_PayPal_PaymentApprovedCallbackUrl); } @Override public void setPayPal_Sandbox (final boolean PayPal_Sandbox) { set_Value (COLUMNNAME_PayPal_Sandbox, PayPal_Sandbox); } @Override public boolean isPayPal_Sandbox() {
return get_ValueAsBoolean(COLUMNNAME_PayPal_Sandbox); } @Override public void setPayPal_WebUrl (final @Nullable java.lang.String PayPal_WebUrl) { set_Value (COLUMNNAME_PayPal_WebUrl, PayPal_WebUrl); } @Override public java.lang.String getPayPal_WebUrl() { return get_ValueAsString(COLUMNNAME_PayPal_WebUrl); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Config.java
1
请完成以下Java代码
public static Json result(String operate, boolean success, Object data) { return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE), (success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), data); } public static Json result(String operate, boolean success, String dataKey, Object dataVal) { return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE), (success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), null).data(dataKey, dataVal); } /////////////////////// 各种链式调用方法 /////////////////////// /** 设置操作名称 */ public Json oper(String operate) { this.put(KEY_OPER, operate); return this; } /** 设置操作结果是否成功的标记 */ public Json succ(boolean success) { this.put(KEY_SUCC, success); return this; } /** 设置操作结果的代码 */ public Json code(int code) { this.put(KEY_CODE, code); return this;
} /** 设置操作结果的信息 */ public Json msg(String message) { this.put(KEY_MSG, message); return this; } /** 设置操作返回的数据 */ public Json data(Object dataVal) { this.put(KEY_DATA, dataVal); return this; } /** 设置操作返回的数据,数据使用自定义的key存储 */ public Json data(String dataKey, Object dataVal) { this.put(dataKey, dataVal); return this; } }
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\vo\Json.java
1
请完成以下Java代码
public IQueryBuilder<ModelType> endOrderBy() { return parent; } @Override public IQueryOrderBy createQueryOrderBy() { return orderByBuilder.createQueryOrderBy(); } @Override public IQueryBuilderOrderByClause<ModelType> clear() { orderByBuilder.clear(); return this; } @Override public QueryBuilderOrderByClause<ModelType> copy() { return new QueryBuilderOrderByClause<>(this); } @Override public IQueryBuilderOrderByClause<ModelType> addColumn(String columnName) { orderByBuilder.addColumn(columnName); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumn(ModelColumn<ModelType, ?> column) { orderByBuilder.addColumn(column); return this; }
@Override public IQueryBuilderOrderByClause<ModelType> addColumnAscending(String columnName) { orderByBuilder.addColumnAscending(columnName); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumnDescending(String columnName) { orderByBuilder.addColumnDescending(columnName); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumn(String columnName, Direction direction, Nulls nulls) { orderByBuilder.addColumn(columnName, direction, nulls); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumn(ModelColumn<ModelType, ?> column, Direction direction, Nulls nulls) { orderByBuilder.addColumn(column, direction, nulls); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBuilderOrderByClause.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((author == null) ? 0 : author.hashCode()); result = prime * result + ((tags == null) ? 0 : tags.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); 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; Post other = (Post) obj; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (tags == null) { if (other.tags != null) return false;
} else if (!tags.equals(other.tags)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Post [title=" + title + ", author=" + author + ", tags=" + tags + "]"; } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\tagging\Post.java
1
请完成以下Java代码
public void syncSendOrderly(String topic, Message<?> message, String hashKey, long timeout) { LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey + ",timeout:" + timeout); rocketMQTemplate.syncSendOrderly(topic, message, hashKey, timeout); } /** * 默认CallBack函数 * * @return */ private SendCallback getDefaultSendCallBack() { return new SendCallback() { @Override public void onSuccess(SendResult sendResult) { LOG.info("---发送MQ成功---"); } @Override public void onException(Throwable throwable) { throwable.printStackTrace(); LOG.error("---发送MQ失败---"+throwable.getMessage(), throwable.getMessage());
} }; } @PreDestroy public void destroy() { LOG.info("---RocketMq助手注销---"); } }
repos\springboot-demo-master\rocketmq\src\main\java\demo\et59\rocketmq\util\RocketMqHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class ApplicationPropertiesConfigurations { @Autowired AmazonDynamoDB amazonDynamoDb; @Autowired private ArchaiusPropertiesRepository repository; @Bean public AbstractConfiguration addApplicationPropertiesSource() { // Normally, the DB Table would be already created and populated. // In this case, we'll do it just before creating the archaius config source that uses it initDatabase(); PolledConfigurationSource source = new DynamoDbConfigurationSource(amazonDynamoDb); return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
} private void initDatabase() { // Create the table DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDb); CreateTableRequest tableRequest = mapper.generateCreateTableRequest(ArchaiusProperties.class); tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L)); TableUtils.createTableIfNotExists(amazonDynamoDb, tableRequest); // Populate the table ArchaiusProperties property = new ArchaiusProperties("baeldung.archaius.properties.one", "one FROM:dynamoDB"); ArchaiusProperties property3 = new ArchaiusProperties("baeldung.archaius.properties.three", "three FROM:dynamoDB"); repository.saveAll(Arrays.asList(property, property3)); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-archaius\spring-cloud-archaius-dynamodb-config\src\main\java\com\baeldung\spring\cloud\archaius\dynamosources\config\ApplicationPropertiesConfigurations.java
2
请在Spring Boot框架中完成以下Java代码
public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } @ApiModelProperty(example = "oneTaskCase%3A1%3A4") public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-runtime/case-definitions/oneTaskCase%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } @ApiModelProperty(example = "123") public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; }
@ApiModelProperty(example = "123") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "123") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "123") public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskResponse.java
2
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Demand. @param M_Demand_ID Material Demand */ public void setM_Demand_ID (int M_Demand_ID) { if (M_Demand_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Demand_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Demand_ID, Integer.valueOf(M_Demand_ID)); } /** Get Demand. @return Material Demand */ public int getM_Demand_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_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 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_Demand.java
1
请在Spring Boot框架中完成以下Java代码
public class WebServicesProperties { /** * Path that serves as the base URI for the services. */ private String path = "/services"; private final Servlet servlet = new Servlet(); public String getPath() { return this.path; } public void setPath(String path) { Assert.notNull(path, "'path' must not be null"); Assert.isTrue(path.length() > 1, "'path' must have length greater than 1"); Assert.isTrue(path.startsWith("/"), "'path' must start with '/'"); this.path = path; } public Servlet getServlet() { return this.servlet; } public static class Servlet { /** * Servlet init parameters to pass to Spring Web Services. */ private Map<String, String> init = new HashMap<>(); /** * Load on startup priority of the Spring Web Services servlet.
*/ private int loadOnStartup = -1; public Map<String, String> getInit() { return this.init; } public void setInit(Map<String, String> init) { this.init = init; } public int getLoadOnStartup() { return this.loadOnStartup; } public void setLoadOnStartup(int loadOnStartup) { this.loadOnStartup = loadOnStartup; } } }
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\autoconfigure\WebServicesProperties.java
2
请完成以下Java代码
private static final class GenericTypeFilter<C, A> implements Filter<C, A> { @Override public boolean match(Class<C> callbackType, C callbackInstance, A argument, Object[] additionalArguments) { ResolvableType type = ResolvableType.forClass(callbackType, callbackInstance.getClass()); if (type.getGenerics().length == 1 && type.resolveGeneric() != null) { return type.resolveGeneric().isInstance(argument); } return true; } } /** * The result of a callback which may be a value, {@code null} or absent entirely if * the callback wasn't suitable. Similar in design to {@link Optional} but allows for * {@code null} as a valid value. * * @param <R> the result type */ public static final class InvocationResult<R> { private static final InvocationResult<?> NONE = new InvocationResult<>(null); private final R value; private InvocationResult(R value) { this.value = value; } /** * Return true if a result in present. * @return if a result is present */ public boolean hasResult() { return this != NONE; } /** * Return the result of the invocation or {@code null} if the callback wasn't * suitable. * @return the result of the invocation or {@code null} */ public R get() { return this.value; }
/** * Return the result of the invocation or the given fallback if the callback * wasn't suitable. * @param fallback the fallback to use when there is no result * @return the result of the invocation or the fallback */ public R get(R fallback) { return (this != NONE) ? this.value : fallback; } /** * Create a new {@link InvocationResult} instance with the specified value. * @param value the value (may be {@code null}) * @param <R> the result type * @return an {@link InvocationResult} */ public static <R> InvocationResult<R> of(R value) { return new InvocationResult<>(value); } /** * Return an {@link InvocationResult} instance representing no result. * @param <R> the result type * @return an {@link InvocationResult} */ @SuppressWarnings("unchecked") public static <R> InvocationResult<R> noResult() { return (InvocationResult<R>) NONE; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\util\LambdaSafe.java
1
请完成以下Java代码
public final class ALoginRes_de extends ListResourceBundle { // TODO Run native2ascii to convert to plain ASCII !! /** Translation Content */ static final Object[][] contents = new String[][] { { "Connection", "Anmeldung" }, { "Defaults", "Standardwerte" }, { "Login", "Anmeldung" }, { "File", "Datei" }, { "Exit", "Beenden" }, { "Help", "Hilfe" }, { "About", "\u00dcber" }, { "Host", "Server" }, { "Database", "Datenbank" }, { "User", "Nutzer" }, { "EnterUser", "Nutzer eingeben" }, { "Password", "Passwort" }, { "EnterPassword", "Passwort eingeben" }, { "Language", "Sprache" }, { "SelectLanguage", "Sprache ausw\u00e4hlen" }, { "Role", "Rolle" }, { "Client", "Mandant" }, { "Organization", "Organisation" }, { "Date", "Datum" }, { "Warehouse", "Lager" }, { "Printer", "Drucker" },
{ "Connected", "Verbunden" }, { "NotConnected", "Nicht verbunden" }, { "DatabaseNotFound", "Datenbank nicht gefunden" }, { "UserPwdError", "Nutzer oder Passwort nicht korrekt" }, { "RoleNotFound", "Rolle nicht gefunden/komplett" }, { "Authorized", "Nutzer ist angemeldet" }, { "Ok", "Ok" }, { "Cancel", "Abbruch" }, { "VersionConflict", "Versions-Konflikt:" }, { "VersionInfo", "Versions-Information" }, { "PleaseUpgrade", "Bitte eine Versions-Aktualisierung veranlassen" } }; /** * Get Contents * @return context */ public Object[][] getContents() { return contents; } // getContents } // LoginRes_de
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_de.java
1
请完成以下Java代码
public Definitions newInstance(ModelTypeInstanceContext instanceContext) { return new DefinitionsImpl(instanceContext); } }); idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID) .idAttribute() .build(); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); targetNamespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_NAMESPACE) .required() .build(); expressionLanguageAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPRESSION_LANGUAGE) .defaultValue(XPATH_NS) .build(); exporterAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER) .build(); exporterVersionAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER_VERSION) .build(); authorAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHOR) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); importCollection = sequenceBuilder.elementCollection(Import.class) .build();
caseFileItemDefinitionCollection = sequenceBuilder.elementCollection(CaseFileItemDefinition.class) .build(); caseCollection = sequenceBuilder.elementCollection(Case.class) .build(); processCollection = sequenceBuilder.elementCollection(Process.class) .build(); decisionCollection = sequenceBuilder.elementCollection(Decision.class) .build(); extensionElementsChild = sequenceBuilder.element(ExtensionElements.class) .minOccurs(0) .maxOccurs(1) .build(); relationshipCollection = sequenceBuilder.elementCollection(Relationship.class) .build(); artifactCollection = sequenceBuilder.elementCollection(Artifact.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DefinitionsImpl.java
1
请完成以下Java代码
public class DBRes_ms extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][] { { "CConnectionDialog", "Kotak Sambungan" }, { "Name", "Nama" }, { "AppsHost", "Aplikasi Induk" }, { "AppsPort", "Port Aplikasi" }, { "TestApps", "Uji Aplikasi" }, { "DBHost", "Hos Pengkalan Data" }, { "DBPort", "Port Pengkalan Data" }, { "DBName", "Nama Pengkalan Data" }, { "DBUidPwd", "Pengguna / Kata-laluan" }, { "ViaFirewall", "menerusi Pendinding" }, { "FWHost", "Hos Pendinding" }, { "FWPort", "Port Pendinding" }, { "TestConnection", "Uji Pengkalan Data" }, { "Type", "Jenis Pengkalan Data" }, { "BequeathConnection", "Memberi Sambungan" }, { "Overwrite", "Mengatasi" }, { "ConnectionProfile", "Sambungan" }, { "LAN", "Rangkaian Dalaman" }, { "TerminalServer", "Pelayan Terminal" },
{ "VPN", "Rangkaian Maya" }, { "WAN", "Rangkaian Luar" }, { "ConnectionError", "Kesilapan Sambungan" }, { "ServerNotActive", "Pelayan Tidak Aktif" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_ms.java
1
请在Spring Boot框架中完成以下Java代码
public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @ApiModelProperty(example = "86400056") public Long getDurationInMillis() {
return durationInMillis; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public ExceptionTranslatingServerInterceptor exceptionTranslatingServerInterceptor() { return new ExceptionTranslatingServerInterceptor(); } /** * The security interceptor that handles the authentication of requests. * * @param authenticationManager The authentication manager used to verify the credentials. * @param authenticationReader The authentication reader used to extract the credentials from the call. * @return The authenticatingServerInterceptor bean. */ @Bean @ConditionalOnMissingBean(AuthenticatingServerInterceptor.class) public DefaultAuthenticatingServerInterceptor authenticatingServerInterceptor( final AuthenticationManager authenticationManager, final GrpcAuthenticationReader authenticationReader) { return new DefaultAuthenticatingServerInterceptor(authenticationManager, authenticationReader); } /** * The security interceptor that handles the authorization of requests.
* * @param accessDecisionManager The access decision manager used to check the requesting user. * @param securityMetadataSource The source for the security metadata (access constraints). * @return The authorizationCheckingServerInterceptor bean. */ @Bean @ConditionalOnMissingBean @ConditionalOnBean({AccessDecisionManager.class, GrpcSecurityMetadataSource.class}) public AuthorizationCheckingServerInterceptor authorizationCheckingServerInterceptor( final AccessDecisionManager accessDecisionManager, final GrpcSecurityMetadataSource securityMetadataSource) { return new AuthorizationCheckingServerInterceptor(accessDecisionManager, securityMetadataSource); } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerSecurityAutoConfiguration.java
2
请完成以下Java代码
public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed);
} @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java
1
请完成以下Java代码
public class JsonKPILayout { public static JsonKPILayout of(final KPI kpi, final KPIJsonOptions jsonOpts) { return new JsonKPILayout(kpi, jsonOpts); } // private final int id; // don't exported because is useless and confusing // @JsonProperty("caption") // private final String caption; // don't exported because is useless and confusing; frontend shall display the dashboard item caption anyways @JsonProperty("description") @JsonInclude(JsonInclude.Include.NON_EMPTY) private final String description; @JsonProperty("chartType") private final String chartType; @JsonProperty("groupByField") @JsonInclude(JsonInclude.Include.NON_NULL) private final JsonKPIFieldLayout groupByField; @JsonProperty("fields") private final List<JsonKPIFieldLayout> fields; @JsonProperty("zoomToDetailsAvailable") private final boolean zoomToDetailsAvailable; public JsonKPILayout(final KPI kpi, final KPIJsonOptions jsonOpts) { // id = kpi.getId(); // caption = kpi.getCaption(jsonOpts.getAdLanguage()); description = Strings.emptyToNull(kpi.getDescription(jsonOpts.getAdLanguage())); chartType = kpi.getChartType().toJson(); groupByField = extractGroupByField(kpi, jsonOpts); fields = extractFields(kpi, jsonOpts); zoomToDetailsAvailable = kpi.isZoomToDetailsAvailable();
} @Nullable static JsonKPIFieldLayout extractGroupByField(final KPI kpi, final KPIJsonOptions jsonOpts) { final KPIField groupByField = kpi.getGroupByFieldOrNull(); return groupByField != null ? JsonKPIFieldLayout.field(groupByField, jsonOpts) : null; } static ImmutableList<JsonKPIFieldLayout> extractFields(final KPI kpi, final KPIJsonOptions jsonOpts) { final ImmutableList.Builder<JsonKPIFieldLayout> jsonFields = ImmutableList.builder(); final boolean hasCompareOffset = kpi.hasCompareOffset(); for (final KPIField kpiField : kpi.getFields()) { // Don't add the group by field to our fields list if (kpiField.isGroupBy()) { continue; } jsonFields.add(JsonKPIFieldLayout.field(kpiField, jsonOpts)); if (hasCompareOffset && !kpiField.isGroupBy()) { jsonFields.add(JsonKPIFieldLayout.offsetField(kpiField, jsonOpts)); } } return jsonFields.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JsonKPILayout.java
1
请完成以下Java代码
public class DateFormType extends AbstractFormType { private static final long serialVersionUID = 1L; protected String datePattern; protected Format dateFormat; public DateFormType(String datePattern) { this.datePattern = datePattern; this.dateFormat = FastDateFormat.getInstance(datePattern); } @Override public String getName() { return "date"; } @Override public Object getInformation(String key) { if ("datePattern".equals(key)) { return datePattern; } return null; } @Override public Object convertFormValueToModelValue(String propertyValue) { if (StringUtils.isEmpty(propertyValue)) {
return null; } try { return dateFormat.parseObject(propertyValue); } catch (ParseException e) { throw new FlowableIllegalArgumentException("invalid date value " + propertyValue, e); } } @Override public String convertModelValueToFormValue(Object modelValue) { if (modelValue == null) { return null; } return dateFormat.format(modelValue); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\DateFormType.java
1
请完成以下Java代码
public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition;
this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceAreaProductRelationExample.java
1
请在Spring Boot框架中完成以下Java代码
private IHUProductStorage getProductStorage(final I_M_HU hu) { final IHUStorage huStorage = handlingUnitsBL .getStorageFactory() .getStorage(hu); final ProductId productId = huStorage.getSingleProductIdOrNull(); if (productId == null) { throw new AdempiereException("HU is empty"); } return huStorage.getProductStorage(productId); } private void updateHUAttributes( @NonNull final I_M_HU hu, @NonNull final HUAttributesUpdateRequest from) { final IAttributeStorage huAttributes = getHUAttributes(hu); updateHUAttributes(huAttributes, from); huAttributes.saveChangesIfNeeded(); } private static void updateHUAttributes( @NonNull final IAttributeStorage huAttributes, @NonNull final HUAttributesUpdateRequest from) { huAttributes.setValue(AttributeConstants.ATTR_SecurPharmScannedStatus, from.getStatus().getCode()); if (!from.isSkipUpdatingBestBeforeDate()) { final JsonExpirationDate bestBeforeDate = from.getBestBeforeDate(); huAttributes.setValue(AttributeConstants.ATTR_BestBeforeDate, bestBeforeDate != null ? bestBeforeDate.toLocalDate() : null); } if (!from.isSkipUpdatingLotNo()) { huAttributes.setValue(AttributeConstants.ATTR_LotNumber, from.getLotNo()); } if (!from.isSkipUpdatingSerialNo()) { huAttributes.setValue(AttributeConstants.ATTR_SerialNo, from.getSerialNo()); } }
@Value @Builder private static class HUAttributesUpdateRequest { public static final HUAttributesUpdateRequest ERROR = builder() .status(SecurPharmAttributesStatus.ERROR) // UPDATE just the status field, skip the others .skipUpdatingBestBeforeDate(true) .skipUpdatingLotNo(true) .skipUpdatingSerialNo(true) .build(); @NonNull SecurPharmAttributesStatus status; boolean skipUpdatingBestBeforeDate; @Nullable JsonExpirationDate bestBeforeDate; boolean skipUpdatingLotNo; @Nullable String lotNo; boolean skipUpdatingSerialNo; String serialNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\service\SecurPharmHUAttributesScanner.java
2
请完成以下Java代码
public class TreeNode { private int value; private TreeNode rightChild; private TreeNode leftChild; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public TreeNode getRightChild() { return rightChild; } public void setRightChild(TreeNode rightChild) { this.rightChild = rightChild; } public TreeNode getLeftChild() {
return leftChild; } public void setLeftChild(TreeNode leftChild) { this.leftChild = leftChild; } public TreeNode(int value, TreeNode leftChild, TreeNode rightChild) { this.value = value; this.rightChild = rightChild; this.leftChild = leftChild; } public TreeNode(int value) { this.value = value; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\reversingtree\TreeNode.java
1
请完成以下Java代码
public Void call() throws Exception { ConnectorRequest<?> request = connectorInstance.createRequest(); applyInputParameters(execution, request); // execute the request and obtain a response: ConnectorResponse response = request.execute(); applyOutputParameters(execution, response); leave(execution); return null; } }); } protected void applyInputParameters(ActivityExecution execution, ConnectorRequest<?> request) { if(ioMapping != null) { // create variable scope for input parameters ConnectorVariableScope connectorInputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution); // execute the connector input parameters ioMapping.executeInputParameters(connectorInputVariableScope); // write the local variables to the request. connectorInputVariableScope.writeToRequest(request); } } protected void applyOutputParameters(ActivityExecution execution, ConnectorResponse response) { if(ioMapping != null) { // create variable scope for output parameters ConnectorVariableScope connectorOutputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution); // read parameters from response connectorOutputVariableScope.readFromResponse(response); // map variables to parent scope. ioMapping.executeOutputParameters(connectorOutputVariableScope);
} } protected void ensureConnectorInitialized() { if(connectorInstance == null) { synchronized (this) { if(connectorInstance == null) { connectorInstance = Connectors.getConnector(connectorId); if (connectorInstance == null) { throw new ConnectorException("No connector found for connector id '" + connectorId + "'"); } } } } } }
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ServiceTaskConnectorActivityBehavior.java
1
请完成以下Java代码
public class M_AttributeInstance { @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }) public void updateASIDescription(final I_M_AttributeInstance instance) { final I_M_AttributeSetInstance asi = instance.getM_AttributeSetInstance(); if (null != asi) { Services.get(IAttributeSetInstanceBL.class).setDescription(asi); InterfaceWrapperHelper.save(asi); } } /** * In case {@link I_M_AttributeInstance#COLUMNNAME_Value} column changed, and we deal with a List attribute, search and set corresponding attribute value record */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE } // , ifColumnsChanged = I_M_AttributeInstance.COLUMNNAME_Value) public void updateAttributeValueIfList(final I_M_AttributeInstance ai) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
final I_M_Attribute attribute = attributesRepo.getAttributeRecordById(ai.getM_Attribute_ID()); // // Skip it if attribute value type is not of type List final String valueType = attribute.getAttributeValueType(); if (!X_M_Attribute.ATTRIBUTEVALUETYPE_List.equals(valueType)) { return; } // // Search for M_AttributeValue and set M_Attribute.M_AttributeValue_ID final String value = ai.getValue(); final AttributeListValue attributeValue = attributesRepo.retrieveAttributeValueOrNull(attribute, value); ai.setM_AttributeValue_ID(attributeValue != null ? attributeValue.getId().getRepoId() : -1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\modelvalidator\M_AttributeInstance.java
1
请在Spring Boot框架中完成以下Java代码
private Config loadConfig(URL configUrl) throws IOException { try (InputStream stream = configUrl.openStream()) { return Config.loadFromStream(stream); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnSingleCandidate(Config.class) static class HazelcastServerConfigConfiguration { @Bean HazelcastInstance hazelcastInstance(Config config) { return getHazelcastInstance(config); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(SpringManagedContext.class) static class SpringManagedContextHazelcastConfigCustomizerConfiguration { @Bean @Order(0) HazelcastConfigCustomizer springManagedContextHazelcastConfigCustomizer(ApplicationContext applicationContext) { return (config) -> { SpringManagedContext managementContext = new SpringManagedContext(); managementContext.setApplicationContext(applicationContext); config.setManagedContext(managementContext); }; }
} @Configuration(proxyBeanMethods = false) @ConditionalOnClass(org.slf4j.Logger.class) static class HazelcastLoggingConfigCustomizerConfiguration { @Bean @Order(0) HazelcastConfigCustomizer loggingHazelcastConfigCustomizer() { return (config) -> { if (!config.getProperties().containsKey(HAZELCAST_LOGGING_TYPE)) { config.setProperty(HAZELCAST_LOGGING_TYPE, "slf4j"); } }; } } /** * {@link HazelcastConfigResourceCondition} that checks if the * {@code spring.hazelcast.config} configuration key is defined. */ static class ConfigAvailableCondition extends HazelcastConfigResourceCondition { ConfigAvailableCondition() { super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", "classpath:/hazelcast.xml", "file:./hazelcast.yaml", "classpath:/hazelcast.yaml", "file:./hazelcast.yml", "classpath:/hazelcast.yml"); } } }
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\autoconfigure\HazelcastServerConfiguration.java
2
请完成以下Java代码
public class AdminApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(JacksonConfigurator.class); classes.add(JacksonJsonProvider.class); classes.add(RestExceptionHandler.class); classes.add(ExceptionHandler.class); classes.add(UserAuthenticationResource.class); classes.add(SetupResource.class); addPluginResourceClasses(classes); return classes; }
private void addPluginResourceClasses(Set<Class<?>> classes) { List<AdminPlugin> plugins = getPlugins(); for (AdminPlugin plugin : plugins) { classes.addAll(plugin.getResourceClasses()); } } private List<AdminPlugin> getPlugins() { return Admin.getRuntimeDelegate().getAppPluginRegistry().getPlugins(); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\web\AdminApplication.java
1
请完成以下Java代码
public QueueBuilder deliveryLimit(int limit) { return withArgument("x-delivery-limit", limit); } /** * Builds a final queue. * @return the Queue instance. */ public Queue build() { return new Queue(this.name, this.durable, this.exclusive, this.autoDelete, getArguments()); } /** * Overflow argument values. */ public enum Overflow { /** * Drop the oldest message. */ dropHead("drop-head"), /** * Reject the new message. */ rejectPublish("reject-publish"); private final String value; Overflow(String value) { this.value = value; } /** * Return the value. * @return the value. */ public String getValue() { return this.value; } } /** * Locate the queue leader. * * @since 2.3.7 * */ public enum LeaderLocator {
/** * Deploy on the node with the fewest queue leaders. */ minLeaders("min-masters"), /** * Deploy on the node we are connected to. */ clientLocal("client-local"), /** * Deploy on a random node. */ random("random"); private final String value; LeaderLocator(String value) { this.value = value; } /** * Return the value. * @return the value. */ public String getValue() { return this.value; } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\QueueBuilder.java
1
请完成以下Java代码
public static final VPAttributeWindowContext of(final GridField gridField) { final Properties ctx = gridField.getCtx(); final int windowNo = gridField.getWindowNo(); final int tabNo = gridField.getTabNo(); return new VPAttributeWindowContext(ctx, windowNo, tabNo); } private final Properties ctx; private final int windowNo; private final int tabNo; private VPAttributeWindowContext(final Properties ctx, final int windowNo, final int tabNo) { super(); Check.assumeNotNull(ctx, "ctx not null"); this.ctx = ctx; this.windowNo = windowNo; this.tabNo = tabNo; } private final int getContextAsInt(final String columnName) { return Env.getContextAsInt(ctx, windowNo, tabNo, columnName); } @Override public final int getWindowNo() { return windowNo; } @Override public final int getTabNo() { return tabNo; } @Override public BPartnerId getBpartnerId() { return BPartnerId.ofRepoIdOrNull(getContextAsInt("C_BPartner_ID")); }
@Override public ProductId getProductId() { return ProductId.ofRepoIdOrNull(getContextAsInt("M_Product_ID")); } @Override public boolean isSOTrx() { return SOTrx.toBoolean(getSoTrx()); } @Override public SOTrx getSoTrx() { final Boolean soTrx = Env.getSOTrxOrNull(ctx, windowNo); return SOTrx.ofBoolean(soTrx); } @Override public WarehouseId getWarehouseId() { return WarehouseId.ofRepoIdOrNull(getContextAsInt("M_Warehouse_ID")); } @Override public int getM_Locator_ID() { return getContextAsInt("M_Locator_ID"); } @Override public DocTypeId getDocTypeId() { return DocTypeId.ofRepoIdOrNull(getContextAsInt("C_DocType_ID")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VPAttributeWindowContext.java
1
请完成以下Java代码
protected void setAllOrders(final List<IQualityInspectionOrder> allOrders) { assumeQualityInspection(); Check.assumeNotNull(allOrders, "allOrders not null"); this.allOrders = Collections.unmodifiableList(new ArrayList<>(allOrders)); } @Override public List<IQualityInspectionOrder> getAllOrders() { return allOrders; } @Override public BigDecimal getAlreadyInvoicedNetSum() { if (_alreadyInvoicedSum == null) { final IInvoicedSumProvider invoicedSumProvider = qualityBasedConfigProviderService.getInvoicedSumProvider(); _alreadyInvoicedSum = invoicedSumProvider.getAlreadyInvoicedNetSum(_materialTracking); } if (_alreadyInvoicedSum == null) { _alreadyInvoicedSum = BigDecimal.ZERO; } return _alreadyInvoicedSum; } @Override public String toString() { final StringBuilder builder = new StringBuilder();
builder.append("QualityInspectionOrder [_ppOrder="); builder.append(_ppOrder); builder.append(", _qualityInspection="); builder.append(_qualityInspection); builder.append(", _materialTracking="); builder.append(_materialTracking); builder.append(", _qualityBasedConfig="); builder.append(_qualityBasedConfig); builder.append(", _inspectionNumber="); builder.append(_inspectionNumber); builder.append(", _productionMaterials="); builder.append(_productionMaterials); builder.append(", _productionMaterial_Raw="); builder.append(_productionMaterial_Raw); builder.append(", _productionMaterial_Main="); builder.append(_productionMaterial_Main); builder.append(", _productionMaterial_Scrap="); builder.append(_productionMaterial_Scrap); builder.append(", _alreadyInvoicedSum="); builder.append(_alreadyInvoicedSum); // builder.append(", preceedingOrders="); // builder.append(preceedingOrders); builder.append("]"); return builder.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionOrder.java
1
请完成以下Java代码
public class Address implements Serializable { private static final long serialVersionUID = -3258839839160856613L; @Id private String id; private String province; private String city; public Address(String province, String city) { this.province = province; this.city = city; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProvince() {
return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\2.x_data\2-3 Spring Boot 和 MongodDB 多数据源,混合数据源的使用\spring-boot-multi-mysql-mongodb\src\main\java\com\neo\model\mongodb\Address.java
1
请完成以下Java代码
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final StringBuilder builder = new StringBuilder(); builder.append(ex.getMethod()); builder.append(" method is not supported for this request. Supported methods are "); ex.getSupportedHttpMethods().forEach(t -> builder.append(t + " ")); final ApiError apiError = new ApiError(HttpStatus.METHOD_NOT_ALLOWED, ex.getLocalizedMessage(), builder.toString()); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); } // 415 @Override protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(final HttpMediaTypeNotSupportedException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final StringBuilder builder = new StringBuilder(); builder.append(ex.getContentType()); builder.append(" media type is not supported. Supported media types are ");
ex.getSupportedMediaTypes().forEach(t -> builder.append(t + " ")); final ApiError apiError = new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ex.getLocalizedMessage(), builder.substring(0, builder.length() - 2)); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); } // 500 @ExceptionHandler({ Exception.class }) public ResponseEntity<Object> handleAll(final Exception ex, final WebRequest request) { logger.info(ex.getClass().getName()); logger.error("error", ex); // final ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "error occurred"); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); } }
repos\tutorials-master\spring-security-modules\spring-security-web-rest\src\main\java\com\baeldung\errorhandling\CustomRestExceptionHandler.java
1
请完成以下Java代码
private void loadPointcut(final CalloutMethod annModelChange, final Method method) { final CalloutMethodPointcut pointcut = createPointcut(annModelChange, method); addPointcutToMap(pointcut); } private CalloutMethodPointcut createPointcut(final CalloutMethod annModelChange, final Method method) { if (method.getReturnType() != void.class) { throw new CalloutInitException("Return type should be void for " + method); } final Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes == null || parameterTypes.length == 0) { throw new CalloutInitException("Invalid method " + method + ": It has no arguments"); } if (parameterTypes.length < 1 || parameterTypes.length > 2) { throw new CalloutInitException("Invalid method " + method + ": It shall have following paramters: model and optionally ICalloutField"); } // // Validate parameter 1: Model Class for binding final Class<?> modelClass = parameterTypes[0]; { // // Validate Model Class's TableName final String tableName = InterfaceWrapperHelper.getTableNameOrNull(modelClass); if (Check.isEmpty(tableName)) { throw new CalloutInitException("Cannot find tablename for " + modelClass); } if (tableName != null && !tableName.contains(tableName)) { throw new CalloutInitException("Table " + tableName + " is not in the list of allowed tables names specified by " + Callout.class + " annotation: " + tableName); } } // // Validate parameter 2: ICalloutField final boolean paramCalloutFieldRequired; if (parameterTypes.length >= 2) { if (!ICalloutField.class.isAssignableFrom(parameterTypes[1])) { throw new CalloutInitException("Invalid method " + method + ": second parameter shall be " + ICalloutField.class + " or not specified at all"); } paramCalloutFieldRequired = true; } else {
paramCalloutFieldRequired = false; } return new CalloutMethodPointcut(modelClass, method, annModelChange.columnNames(), paramCalloutFieldRequired, annModelChange.skipIfCopying(), annModelChange.skipIfIndirectlyCalled()); } private void addPointcutToMap(final CalloutMethodPointcut pointcut) { // // Add pointcut to map for (final String columnName : pointcut.getColumnNames()) { final CalloutMethodPointcutKey key = CalloutMethodPointcutKey.of(columnName); mapPointcuts.put(key, pointcut); columnNames.add(columnName); } logger.debug("Loaded {}", pointcut); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\AnnotatedCalloutInstanceFactory.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getYearPublished() {
return yearPublished; } public void setYearPublished(String yearPublished) { this.yearPublished = yearPublished; } public Vector getEmbedding() { return embedding; } public void setEmbedding(Vector embedding) { this.embedding = embedding; } }
repos\tutorials-master\persistence-modules\spring-data-vector\src\main\java\com\baeldung\springdata\mongodb\Book.java
1
请完成以下Java代码
public static HousekeeperTask deleteAttributes(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_ATTRIBUTES); } public static HousekeeperTask deleteTelemetry(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_TELEMETRY); } public static HousekeeperTask deleteEvents(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_EVENTS); } public static HousekeeperTask unassignAlarms(User user) { return new AlarmsUnassignHousekeeperTask(user); } public static HousekeeperTask deleteAlarms(TenantId tenantId, EntityId entityId) { return new AlarmsDeletionHousekeeperTask(tenantId, entityId); }
public static HousekeeperTask deleteTenantEntities(TenantId tenantId, EntityType entityType) { return new TenantEntitiesDeletionHousekeeperTask(tenantId, entityType); } public static HousekeeperTask deleteCalculatedFields(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_CALCULATED_FIELDS); } public static HousekeeperTask deleteJobs(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_JOBS); } @JsonIgnore public String getDescription() { return taskType.getDescription() + " for " + entityId.getEntityType().getNormalName().toLowerCase() + " " + entityId.getId(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\housekeeper\HousekeeperTask.java
1
请完成以下Java代码
private static ITranslatableString retrieveColumnDisplayName( @NonNull final ResultSet rs, @NonNull final POTrlInfo adColumnTrlInfo) throws SQLException { final int adColumnId = rs.getInt("AD_Column_ID"); final String columnDisplayNameDefault = rs.getString("ColumnDisplayName"); final IModelTranslationMap adColumnTrlMap = trlRepo.retrieveAll(adColumnTrlInfo, adColumnId); return adColumnTrlMap.getColumnTrl(I_AD_Column.COLUMNNAME_Name, columnDisplayNameDefault); } private static ITranslatableString retrieveColumnTrl(final POInfoColumn columnInfo) { final IModelTranslationMap adColumnTrlMap = trlRepo.retrieveAll( adColumnPOInfo.getTrlInfo(), AdColumnId.toRepoId(columnInfo.getAD_Column_ID())); final ITranslatableString columnTrl = adColumnTrlMap.getColumnTrl(I_AD_Column.COLUMNNAME_Name, columnInfo.getColumnName()); return columnTrl; } @Value @VisibleForTesting static class SqlWithParams { @NonNull String sql; @NonNull ImmutableList<Object> sqlParams; @VisibleForTesting static SqlWithParams createEmpty() {
return new SqlWithParams("", ImmutableList.of()); } @VisibleForTesting SqlWithParams add(@NonNull final SqlWithParams sqlWithParams) { StringBuilder completeSQL = new StringBuilder(sql); ImmutableList.Builder<Object> completeParams = ImmutableList.builder().addAll(sqlParams); final boolean firstSQL = completeSQL.length() == 0; if (!firstSQL) { completeSQL.append(" UNION\n"); } completeSQL.append(sqlWithParams.getSql()); completeSQL.append("\n"); completeParams.addAll(sqlWithParams.getSqlParams()); return new SqlWithParams(completeSQL.toString(), completeParams.build()); } @VisibleForTesting SqlWithParams withFinalOrderByClause(@NonNull final String orderBy) { final StringBuilder completeSQL = new StringBuilder(sql).append(orderBy); return new SqlWithParams(completeSQL.toString(), sqlParams); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogEntryLoader.java
1
请完成以下Java代码
private @Nullable CacheEntryDescriptor extractUniqueCacheEntry(String cache, List<CacheEntryDescriptor> entries) { if (entries.size() > 1) { throw new NonUniqueCacheException(cache, entries.stream().map(CacheEntryDescriptor::getCacheManager).distinct().toList()); } return (!entries.isEmpty() ? entries.get(0) : null); } private boolean clearCache(CacheEntryDescriptor entry) { String cacheName = entry.getName(); String cacheManagerName = entry.getCacheManager(); CacheManager cacheManager = this.cacheManagers.get(cacheManagerName); Assert.state(cacheManager != null, "'cacheManager' must not be null"); Cache cache = cacheManager.getCache(cacheName); if (cache != null) { cache.clear(); return true; } return false; } private Predicate<String> isNameMatch(@Nullable String name) { return (name != null) ? ((requested) -> requested.equals(name)) : matchAll(); } private Predicate<String> matchAll() { return (name) -> true; } /** * Description of the caches. */ public static final class CachesDescriptor implements OperationResponseBody { private final Map<String, CacheManagerDescriptor> cacheManagers; public CachesDescriptor(Map<String, CacheManagerDescriptor> cacheManagers) { this.cacheManagers = cacheManagers; } public Map<String, CacheManagerDescriptor> getCacheManagers() { return this.cacheManagers; } } /** * Description of a {@link CacheManager}. */ public static final class CacheManagerDescriptor { private final Map<String, CacheDescriptor> caches; public CacheManagerDescriptor(Map<String, CacheDescriptor> caches) { this.caches = caches; } public Map<String, CacheDescriptor> getCaches() { return this.caches; }
} /** * Description of a {@link Cache}. */ public static class CacheDescriptor implements OperationResponseBody { private final String target; public CacheDescriptor(String target) { this.target = target; } /** * Return the fully qualified name of the native cache. * @return the fully qualified name of the native cache */ public String getTarget() { return this.target; } } /** * Description of a {@link Cache} entry. */ public static final class CacheEntryDescriptor extends CacheDescriptor { private final String name; private final String cacheManager; public CacheEntryDescriptor(Cache cache, String cacheManager) { super(cache.getNativeCache().getClass().getName()); this.name = cache.getName(); this.cacheManager = cacheManager; } public String getName() { return this.name; } public String getCacheManager() { return this.cacheManager; } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\actuate\endpoint\CachesEndpoint.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Belegart. @param C_DocType_ID Belegart oder Verarbeitungsvorgaben */ @Override public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Belegart oder Verarbeitungsvorgaben */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** 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); } /** * IsDirectPrint AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISDIRECTPRINT_AD_Reference_ID=319; /** Yes = Y */ public static final String ISDIRECTPRINT_Yes = "Y"; /** No = N */
public static final String ISDIRECTPRINT_No = "N"; /** Set Direct print. @param IsDirectPrint Print without dialog */ @Override public void setIsDirectPrint (java.lang.String IsDirectPrint) { set_Value (COLUMNNAME_IsDirectPrint, IsDirectPrint); } /** Get Direct print. @return Print without dialog */ @Override public java.lang.String getIsDirectPrint () { return (java.lang.String)get_Value(COLUMNNAME_IsDirectPrint); } /** Set Letzte Seiten. @param LastPages Letzte Seiten */ @Override public void setLastPages (int LastPages) { set_Value (COLUMNNAME_LastPages, Integer.valueOf(LastPages)); } /** Get Letzte Seiten. @return Letzte Seiten */ @Override public int getLastPages () { Integer ii = (Integer)get_Value(COLUMNNAME_LastPages); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_PrinterRouting.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; }
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Boolean getSelectOnlyFormProperties() { return selectOnlyFormProperties; } public void setSelectOnlyFormProperties(Boolean selectOnlyFormProperties) { this.selectOnlyFormProperties = selectOnlyFormProperties; } public Boolean getSelectOnlyVariableUpdates() { return selectOnlyVariableUpdates; } public void setSelectOnlyVariableUpdates(Boolean selectOnlyVariableUpdates) { this.selectOnlyVariableUpdates = selectOnlyVariableUpdates; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailQueryRequest.java
2
请完成以下Java代码
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddress(from); } public void setFrom(@NonNull final I_M_InOut from) { setFrom(new DocumentLocationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Invoice from) { setFrom(InvoiceDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_M_InOut getWrappedRecord() { return delegate;
} @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentLocationAdapter.java
1
请完成以下Java代码
public VariableMap execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull("Cannot find task with id " + taskId, "task", task); checkCompleteTask(task, commandContext); if (variables != null) { task.setExecutionVariables(variables); } ExecutionEntity execution = task.getProcessInstance(); ExecutionVariableSnapshotObserver variablesListener = null; if (returnVariables && execution != null) { variablesListener = new ExecutionVariableSnapshotObserver(execution, false, deserializeReturnedVariables); } completeTask(task); if (returnVariables) { if (variablesListener != null) { return variablesListener.getVariables(); } else { return task.getCaseDefinitionId() != null ? null : task.getVariablesTyped(false); } } else
{ return null; } } protected void completeTask(TaskEntity task) { task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_COMPLETE); task.complete(); } protected void checkCompleteTask(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskWork(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CompleteTaskCmd.java
1
请完成以下Java代码
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_K_EntryRelated[") .append(get_ID()).append("]"); return sb.toString(); } public I_K_Entry getK_Entry() throws RuntimeException { return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name) .getPO(getK_Entry_ID(), get_TrxName()); } /** Set Entry. @param K_Entry_ID Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID) { if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Related Entry. @param K_EntryRelated_ID Related Entry for this Enntry
*/ public void setK_EntryRelated_ID (int K_EntryRelated_ID) { if (K_EntryRelated_ID < 1) set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, null); else set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, Integer.valueOf(K_EntryRelated_ID)); } /** Get Related Entry. @return Related Entry for this Enntry */ public int getK_EntryRelated_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_EntryRelated_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(getK_EntryRelated_ID())); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_EntryRelated.java
1
请完成以下Java代码
private List<Attribute> retrieveAvailableAttributeSetAndInstanceAttributes( @Nullable final AttributeSetId attributeSetId, @Nullable final AttributeSetInstanceId attributeSetInstanceId) { final LinkedHashMap<AttributeId, Attribute> attributes = new LinkedHashMap<>(); // preserve the order // // Retrieve attribute set's instance attributes, // and index them by M_Attribute_ID if (attributeSetId != null && !attributeSetId.isNone()) { attributesRepo.getAttributesByAttributeSetId(attributeSetId) .stream() .filter(Attribute::isInstanceAttribute) .forEach(attribute -> attributes.put(attribute.getAttributeId(), attribute)); } // // If we have an ASI then fetch the attributes from ASI which are missing in attributeSet
// and add them to our "attributes" index. if (AttributeSetInstanceId.isRegular(attributeSetInstanceId)) { final Set<AttributeId> alreadyLoadedAttributeIds = attributes.keySet(); final Set<AttributeId> asiAttributeIds = asiBL.getAttributeIdsByAttributeSetInstanceId(attributeSetInstanceId); final Set<AttributeId> attributeIdsToLoad = Sets.difference(asiAttributeIds, alreadyLoadedAttributeIds); attributesRepo.getAttributesByIds(attributeIdsToLoad) .forEach(attribute -> attributes.put(attribute.getAttributeId(), attribute)); } // return ImmutableList.copyOf(attributes.values()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\util\ASIEditingInfo.java
1
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = 6222176558369919436L; public interface UserNameView { }; public interface AllUserFieldView extends UserNameView { }; @JsonView(UserNameView.class) private String userName; @JsonView(AllUserFieldView.class) private int age; // @JsonIgnore @JsonView(AllUserFieldView.class) private String password; // @JsonProperty("bth") // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonView(AllUserFieldView.class) private Date birthday; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }
public int getAge() { return age; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
repos\SpringAll-master\18.Spring-Boot-Jackson\src\main\java\com\example\pojo\User.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (context.getSelectionSize().isMoreThanOneSelected()) { final IQueryFilter<I_EDI_Desadv_Pack> selectedRecordsFilter = context.getQueryFilter(I_EDI_Desadv_Pack.class); final int differentConfigsSize = queryBL .createQueryBuilder(I_EDI_Desadv_Pack.class) .filter(selectedRecordsFilter) .andCollect(I_EDI_Desadv.COLUMN_EDI_Desadv_ID, I_EDI_Desadv.class) .create() .list() .stream() .map(ediDesadv -> BPartnerId.ofRepoId(ediDesadv.getC_BPartner_ID())) .map(bpartnerId -> zebraConfigRepository.retrieveZebraConfigId(bpartnerId, zebraConfigRepository.getDefaultZebraConfigId())) .collect(Collectors.toSet()) .size(); if (differentConfigsSize > 1) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(EDI_GenerateCSV_FileForSSCC_Labels.MSG_DIFFERENT_ZEBRA_CONFIG_NOT_SUPPORTED)); }
} return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final IQueryFilter<I_EDI_Desadv_Pack> selectedRecordsFilter = getProcessInfo() .getQueryFilterOrElse(ConstantQueryFilter.of(false)); final List<EDIDesadvPackId> list = queryBL .createQueryBuilder(I_EDI_Desadv_Pack.class) .filter(selectedRecordsFilter) .create() .stream() .map(I_EDI_Desadv_Pack::getEDI_Desadv_Pack_ID) .map(EDIDesadvPackId::ofRepoId) .collect(ImmutableList.toImmutableList()); if (!Check.isEmpty(list)) { generateCSV_FileForSSCC_Labels(list); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_DesadvPackGenerateCSV_FileForSSCC_Labels.java
1
请完成以下Java代码
public class CachingDocumentSource implements DocumentSource { private final DocumentSource delegate; private boolean cacheEnabled = true; private final Map<String, Mono<String>> documentCache = new ConcurrentHashMap<>(); /** * Constructor with the {@code DocumentSource} to actually load documents. * @param delegate the delegate document source */ public CachingDocumentSource(DocumentSource delegate) { this.delegate = delegate; } /** * Enable or disable caching of resolved documents. * <p>By default, set to {@code true}. * @param cacheEnabled enable if {@code true} and disable if {@code false} */ public void setCacheEnabled(boolean cacheEnabled) { this.cacheEnabled = cacheEnabled; if (!cacheEnabled) {
this.documentCache.clear(); } } /** * Whether {@link #setCacheEnabled(boolean) caching} is enabled. */ public boolean isCacheEnabled() { return this.cacheEnabled; } @Override public Mono<String> getDocument(String name) { return ((isCacheEnabled()) ? this.documentCache.computeIfAbsent(name, (k) -> this.delegate.getDocument(name).cache()) : this.delegate.getDocument(name)); } /** * Remove all entries from the document cache. */ public void clearCache() { this.documentCache.clear(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\CachingDocumentSource.java
1