instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setMSV3_Liefervorgabe (java.lang.String MSV3_Liefervorgabe) { set_Value (COLUMNNAME_MSV3_Liefervorgabe, MSV3_Liefervorgabe); } /** Get Liefervorgabe. @return Liefervorgabe */ @Override public java.lang.String getMSV3_Liefervorgabe () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Liefervorgabe); } /** Set MSV3_Menge. @param MSV3_Menge MSV3_Menge */ @Override public void setMSV3_Menge (int MSV3_Menge) { set_Value (COLUMNNAME_MSV3_Menge, Integer.valueOf(MSV3_Menge)); } /** Get MSV3_Menge. @return MSV3_Menge */ @Override public int getMSV3_Menge () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Menge); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3_Pzn.
@param MSV3_Pzn MSV3_Pzn */ @Override public void setMSV3_Pzn (java.lang.String MSV3_Pzn) { set_Value (COLUMNNAME_MSV3_Pzn, MSV3_Pzn); } /** Get MSV3_Pzn. @return MSV3_Pzn */ @Override public java.lang.String getMSV3_Pzn () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungPosition.java
1
请完成以下Java代码
public PurchaseLastMaxPriceProvider newProvider() { return PurchaseLastMaxPriceProvider.builder() .sysConfigBL(sysConfigBL) .moneyService(moneyService) .build(); } public void invalidateByOrder(final I_C_Order order) { // Consider only purchase orders if (order.isSOTrx()) { return; } final LocalDate date = extractDate(order); final ImmutableSet<ProductId> productIds = getProductIds(order); invalidateByProducts(productIds, date); } private static LocalDate extractDate(final I_C_Order order) { return order.getDateOrdered().toLocalDateTime().toLocalDate(); } private ImmutableSet<ProductId> getProductIds(final I_C_Order order) { final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID()); return orderDAO.retrieveOrderLines(orderId) .stream() .map(orderLine -> ProductId.ofRepoId(orderLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); }
public void invalidateByProducts(@NonNull Set<ProductId> productIds, @NonNull LocalDate date) { if (productIds.isEmpty()) { return; } final ArrayList<Object> sqlValuesParams = new ArrayList<>(); final StringBuilder sqlValues = new StringBuilder(); for (final ProductId productId : productIds) { if (sqlValues.length() > 0) { sqlValues.append(","); } sqlValues.append("(?,?)"); sqlValuesParams.add(productId); sqlValuesParams.add(date); } final String sql = "INSERT INTO " + TABLENAME_Recompute + " (m_product_id, date)" + "VALUES " + sqlValues; DB.executeUpdateAndThrowExceptionOnFail(sql, sqlValuesParams.toArray(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\stats\purchase_max_price\PurchaseLastMaxPriceService.java
1
请完成以下Java代码
public final int getReversalLine_ID() { return m_ReversalLine_ID; } /** * @return is the reversal document line (not the original) */ public final boolean isReversalLine() { return m_ReversalLine_ID > 0 // has a reversal counterpart && get_ID() > m_ReversalLine_ID; // this document line was created after it's reversal counterpart } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("id", get_ID()) .add("description", getDescription()) .add("productId", getProductId()) .add("qty", getQty()) .add("amtSource", getAmtSource()) .toString(); } /** * Is Tax Included * * @return true if tax is included in amounts */ public final boolean isTaxIncluded() { return _taxIncluded; } // isTaxIncluded /** * Set Tax Included * * @param taxIncluded Is Tax Included? */ protected final void setIsTaxIncluded(final boolean taxIncluded) { _taxIncluded = taxIncluded; } /** * @see Doc#isSOTrx() */ public boolean isSOTrx() { return m_doc.isSOTrx(); } /** * @return document currency precision * @see Doc#getStdPrecision()
*/ protected final CurrencyPrecision getStdPrecision() { return m_doc.getStdPrecision(); } /** * @return document (header) */ protected final DT getDoc() { return m_doc; } public final PostingException newPostingException() { return m_doc.newPostingException() .setDocument(getDoc()) .setDocLine(this); } public final PostingException newPostingException(final Throwable ex) { return m_doc.newPostingException(ex) .setDocument(getDoc()) .setDocLine(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { AntPathMatcher antPathMatcher = new AntPathMatcher(); // AntPathMatcher is mainly used to implement ant-style URL matching. @Resource MenuMapper menuMapper; // Spring Security uses the getAttributes method in the FilterInvocationSecurityMetadataSource interface to determine which roles are required for a request. @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { /* * The parameter of this method is a FilterInvocation. Developers can extract the currently requested URL from the FilterInvocation. * The return value is Collection<ConfigAttribute>, indicating the role required by the current request URL. */ String requestUrl = ((FilterInvocation) object).getRequestUrl(); /* * Obtain all resource information from the database, that is, the menu table in this case and the role corresponding to the menu, * In a real project environment, developers can cache resource information in Redis or other cache databases. */ List<Menu> allMenus = menuMapper.getAllMenus(); // Traverse the resource information. During the traversal process, obtain the role information required for the currently requested URL and return it. for (Menu menu : allMenus) { if (antPathMatcher.match(menu.getPattern(), requestUrl)) { List<Role> roles = menu.getRoles(); String[] roleArr = new String[roles.size()]; for (int i = 0; i < roleArr.length; i++) { roleArr[i] = roles.get(i).getName(); } return SecurityConfig.createList(roleArr); } } // If the currently requested URL does not have a corresponding pattern in the resource table, it is assumed that the request can be accessed after logging in, that is, ROLE_LOGIN is returned directly. return SecurityConfig.createList("ROLE_LOGIN"); }
/** * The getAllConfigAttributes method is used to return all defined permission resources. SpringSecurity will verify whether the relevant configuration is correct when starting. * If verification is not required, this method can directly return null. */ @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } /** * The supports method returns whether the class object supports verification. */ @Override public boolean supports(Class<?> clazz) { return FilterInvocation.class.isAssignableFrom(clazz); } }
repos\springboot-demo-master\security\src\main\java\com\et\security\config\CustomFilterInvocationSecurityMetadataSource.java
2
请完成以下Java代码
public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine) { for (final IHUTrxListener listener : listeners) { listener.trxLineProcessed(huContext, trxLine); } } @Override public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld) { for (final IHUTrxListener listener : listeners) { listener.huParentChanged(hu, parentHUItemOld); } } @Override public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines) { for (final IHUTrxListener listener : listeners) { listener.afterTrxProcessed(trxHdrRef, trxLines); } } @Override public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { for (final IHUTrxListener listener : listeners) { listener.afterLoad(huContext, loadResults); } } @Override public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners)
{ listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx); } } @Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onSplitTransaction(huContext, unloadTrx, loadTrx); } } @Override public String toString() { return "CompositeHUTrxListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java
1
请完成以下Java代码
public boolean isEdiEnabled () { Object oo = get_Value(COLUMNNAME_IsEdiEnabled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override
public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_AD_InputDataSource.java
1
请完成以下Java代码
public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); }
@Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit_DocumentDetail.java
1
请完成以下Java代码
public void save(@NonNull final I_C_DocType docTypeRecord) { InterfaceWrapperHelper.saveRecord(docTypeRecord); } @Override public DocBaseType getDocBaseTypeById(@NonNull final DocTypeId docTypeId) { final I_C_DocType docTypeRecord = getById(docTypeId); return DocBaseType.ofCode(docTypeRecord.getDocBaseType()); } @NonNull @Override public DocBaseAndSubType getDocBaseAndSubTypeById(@NonNull final DocTypeId docTypeId) { final I_C_DocType docTypeRecord = getById(docTypeId); return DocBaseAndSubType.of(docTypeRecord.getDocBaseType(), docTypeRecord.getDocSubType()); } @NonNull public ImmutableList<I_C_DocType> retrieveForSelection(@NonNull final PInstanceId pinstanceId) { return queryBL .createQueryBuilder(I_C_DocType.class) .setOnlySelection(pinstanceId) .orderBy(I_C_DocType.COLUMNNAME_C_DocType_ID) .create() .listImmutable(); } @EqualsAndHashCode @ToString private static class DocBaseTypeCountersMap
{ public static DocBaseTypeCountersMap ofMap(@NonNull final ImmutableMap<DocBaseType, DocBaseType> map) { return !map.isEmpty() ? new DocBaseTypeCountersMap(map) : EMPTY; } private static final DocBaseTypeCountersMap EMPTY = new DocBaseTypeCountersMap(ImmutableMap.of()); private final ImmutableMap<DocBaseType, DocBaseType> counterDocBaseTypeByDocBaseType; private DocBaseTypeCountersMap(@NonNull final ImmutableMap<DocBaseType, DocBaseType> map) { this.counterDocBaseTypeByDocBaseType = map; } public Optional<DocBaseType> getCounterDocBaseTypeByDocBaseType(@NonNull final DocBaseType docBaseType) { return Optional.ofNullable(counterDocBaseTypeByDocBaseType.get(docBaseType)); } } @NonNull private ImmutableSet<DocTypeId> retrieveDocTypeIdsByInvoicingPoolId(@NonNull final DocTypeInvoicingPoolId docTypeInvoicingPoolId) { return queryBL.createQueryBuilder(I_C_DocType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_DocType.COLUMNNAME_C_DocType_Invoicing_Pool_ID, docTypeInvoicingPoolId) .create() .idsAsSet(DocTypeId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeDAO.java
1
请完成以下Java代码
public class DeleteCaseInstanceStartEventSubscriptionCmd extends AbstractCaseStartEventSubscriptionCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected final CaseInstanceStartEventSubscriptionDeletionBuilderImpl builder; public DeleteCaseInstanceStartEventSubscriptionCmd(CaseInstanceStartEventSubscriptionDeletionBuilderImpl builder) { this.builder = builder; } @Override public Void execute(CommandContext commandContext) { Case caze = getCase(builder.getCaseDefinitionId(), commandContext); String eventDefinitionKey = caze.getStartEventType(); String startCorrelationConfiguration = getStartCorrelationConfiguration(builder.getCaseDefinitionId(), commandContext);
if (eventDefinitionKey != null && Objects.equals(startCorrelationConfiguration, CmmnXmlConstants.START_EVENT_CORRELATION_MANUAL)) { String correlationKey = null; if (builder.hasCorrelationParameterValues()) { correlationKey = generateCorrelationConfiguration(eventDefinitionKey, builder.getTenantId(), builder.getCorrelationParameterValues(), commandContext); } getEventSubscriptionService(commandContext).deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(builder.getCaseDefinitionId(), eventDefinitionKey, correlationKey); } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\DeleteCaseInstanceStartEventSubscriptionCmd.java
1
请完成以下Java代码
public Integer getDefaultScheduleVersion() { return defaultScheduleVersion == null ? DEFAULT_VERSION : defaultScheduleVersion; } public void setDefaultScheduleVersion(Integer defaultScheduleVersion) { this.defaultScheduleVersion = defaultScheduleVersion; } @Override public Date resolveDuedate(String duedateDescription, int maxIterations) { logger.info("Resolving Due Date: " + duedateDescription); String timeZone = getValueFrom("DSTZONE", duedateDescription); String version = getValueFrom("VER", duedateDescription); // START is a legacy value that is no longer used, but may still exist // in // deployed job schedules // Could be used in the future as a start date for a CRON job // String startDate = getValueFrom("START", duedateDescription); duedateDescription = removeValueFrom( "VER", removeValueFrom("START", removeValueFrom("DSTZONE", duedateDescription)) ).trim(); try { logger.info("Base Due Date: " + duedateDescription); Date date = resolvers .get(version == null ? getDefaultScheduleVersion() : Integer.valueOf(version)) .resolve( duedateDescription, clockReader, timeZone == null ? clockReader.getCurrentTimeZone() : TimeZone.getTimeZone(timeZone) ); logger.info("Calculated Date: " + (date == null ? "Will Not Run Again" : date)); return date; } catch (Exception e) { throw new ActivitiIllegalArgumentException("Cannot parse duration", e); } }
private String getValueFrom(String field, String duedateDescription) { int fieldIndex = duedateDescription.indexOf(field + ":"); if (fieldIndex > -1) { int nextWhiteSpace = duedateDescription.indexOf(" ", fieldIndex); fieldIndex += field.length() + 1; if (nextWhiteSpace > -1) { return duedateDescription.substring(fieldIndex, nextWhiteSpace); } else { return duedateDescription.substring(fieldIndex); } } return null; } private String removeValueFrom(String field, String duedateDescription) { int fieldIndex = duedateDescription.indexOf(field + ":"); if (fieldIndex > -1) { int nextWhiteSpace = duedateDescription.indexOf(" ", fieldIndex); if (nextWhiteSpace > -1) { return duedateDescription.replace(duedateDescription.substring(fieldIndex, nextWhiteSpace), ""); } else { return duedateDescription.substring(0, fieldIndex); } } return duedateDescription; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\AdvancedCycleBusinessCalendar.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); @RequestMapping(value="/", method=RequestMethod.GET) public List<User> getUserList() { // 处理"/users/"的GET请求,用来获取用户列表 // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 List<User> r = new ArrayList<User>(users.values()); return r; } @RequestMapping(value="/", method=RequestMethod.POST) public String postUser(@ModelAttribute User user) { // 处理"/users/"的POST请求,用来创建User // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数 users.put(user.getId(), user); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 // url中的id可通过@PathVariable绑定到函数的参数中 return users.get(id); }
@RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { // 处理"/users/{id}"的PUT请求,用来更新User信息 User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // 处理"/users/{id}"的DELETE请求,用来删除User users.remove(id); return "success"; } }
repos\SpringBoot-Learning-master\1.x\Chapter3-1-1\src\main\java\com\didispace\web\UserController.java
2
请完成以下Java代码
public void setIsDecimalPoint (boolean IsDecimalPoint) { set_Value (COLUMNNAME_IsDecimalPoint, Boolean.valueOf(IsDecimalPoint)); } /** Get Decimal Point. @return The number notation has a decimal point (no decimal comma) */ public boolean isDecimalPoint () { Object oo = get_Value(COLUMNNAME_IsDecimalPoint); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set System Language. @param IsSystemLanguage The screens, etc. are maintained in this Language */ public void setIsSystemLanguage (boolean IsSystemLanguage) { set_Value (COLUMNNAME_IsSystemLanguage, Boolean.valueOf(IsSystemLanguage)); } /** Get System Language. @return The screens, etc. are maintained in this Language */ public boolean isSystemLanguage () { Object oo = get_Value(COLUMNNAME_IsSystemLanguage); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Language Code. @param LanguageISO Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public void setLanguageISO (String LanguageISO) { set_Value (COLUMNNAME_LanguageISO, LanguageISO); } /** Get ISO Language Code. @return Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public String getLanguageISO () { return (String)get_Value(COLUMNNAME_LanguageISO); } /** 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; } /** Set Time Pattern. @param TimePattern Java Time Pattern */ public void setTimePattern (String TimePattern) { set_Value (COLUMNNAME_TimePattern, TimePattern); } /** Get Time Pattern. @return Java Time Pattern */ public String getTimePattern () { return (String)get_Value(COLUMNNAME_TimePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Language.java
1
请在Spring Boot框架中完成以下Java代码
private boolean hasConfigurationPropertySource(ConfigDataEnvironmentContributor contributor) { return contributor.getConfigurationPropertySource() != null; } @Override public Iterator<ConfigDataEnvironmentContributor> iterator() { return this.root.iterator(); } /** * {@link ConfigDataLocationResolverContext} for a contributor. */ private static class ContributorDataLoaderContext implements ConfigDataLoaderContext { private final ConfigDataEnvironmentContributors contributors; ContributorDataLoaderContext(ConfigDataEnvironmentContributors contributors) { this.contributors = contributors; } @Override public ConfigurableBootstrapContext getBootstrapContext() { return this.contributors.getBootstrapContext(); } } /** * {@link ConfigDataLocationResolverContext} for a contributor. */ private static class ContributorConfigDataLocationResolverContext implements ConfigDataLocationResolverContext { private final ConfigDataEnvironmentContributors contributors; private final ConfigDataEnvironmentContributor contributor; private final @Nullable ConfigDataActivationContext activationContext; private volatile @Nullable Binder binder; ContributorConfigDataLocationResolverContext(ConfigDataEnvironmentContributors contributors, ConfigDataEnvironmentContributor contributor, @Nullable ConfigDataActivationContext activationContext) { this.contributors = contributors; this.contributor = contributor; this.activationContext = activationContext; } @Override public Binder getBinder() { Binder binder = this.binder; if (binder == null) { binder = this.contributors.getBinder(this.activationContext); this.binder = binder; } return binder; } @Override public @Nullable ConfigDataResource getParent() { return this.contributor.getResource(); } @Override public ConfigurableBootstrapContext getBootstrapContext() { return this.contributors.getBootstrapContext();
} } private class InactiveSourceChecker implements BindHandler { private final @Nullable ConfigDataActivationContext activationContext; InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) { this.activationContext = activationContext; } @Override public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) { for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) { if (!contributor.isActive(this.activationContext)) { InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name); } } return result; } } /** * Binder options that can be used with * {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}. */ enum BinderOption { /** * Throw an exception if an inactive contributor contains a bound value. */ FAIL_ON_BIND_TO_INACTIVE_SOURCE } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java
2
请完成以下Java代码
public FormInfo execute(CommandContext commandContext) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); FormService formService = CommandContextUtil.getFormService(commandContext); if (formService == null) { throw new FlowableIllegalArgumentException("Form engine is not initialized"); } FormInfo formInfo = null; CaseDefinition caseDefinition = CaseDefinitionUtil.getCaseDefinition(caseDefinitionId); CmmnModel cmmnModel = CaseDefinitionUtil.getCmmnModel(caseDefinitionId); Case caseModel = cmmnModel.getCaseById(caseDefinition.getKey()); Stage planModel = caseModel.getPlanModel(); if (StringUtils.isNotEmpty(planModel.getFormKey())) { CmmnDeployment deployment = CommandContextUtil.getCmmnDeploymentEntityManager(commandContext).findById(caseDefinition.getDeploymentId());
formInfo = formService.getFormInstanceModelByKeyAndParentDeploymentIdAndScopeId(planModel.getFormKey(), deployment.getParentDeploymentId(), caseInstanceId, ScopeTypes.CMMN, null, caseDefinition.getTenantId(), cmmnEngineConfiguration.isFallbackToDefaultTenant()); } // If form does not exists, we don't want to leak out this info to just anyone if (formInfo == null) { throw new FlowableObjectNotFoundException("Form model for case definition " + caseDefinitionId + " cannot be found"); } FormFieldHandler formFieldHandler = cmmnEngineConfiguration.getFormFieldHandler(); formFieldHandler.enrichFormFields(formInfo); return formInfo; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetStartFormModelCmd.java
1
请完成以下Java代码
public class HistoryCleanupJobHandler implements JobHandler<HistoryCleanupJobHandlerConfiguration> { public static final String TYPE = "history-cleanup"; public void execute(HistoryCleanupJobHandlerConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { HistoryCleanupHandler cleanupHandler = initCleanupHandler(configuration, commandContext); if (configuration.isImmediatelyDue() || isWithinBatchWindow(commandContext) ) { cleanupHandler.performCleanup(); } commandContext.getTransactionContext() .addTransactionListener(TransactionState.COMMITTED, cleanupHandler); } protected HistoryCleanupRemovalTime getTimeBasedHandler() { return new HistoryCleanupRemovalTime(); } protected HistoryCleanupHandler initCleanupHandler(HistoryCleanupJobHandlerConfiguration configuration, CommandContext commandContext) { HistoryCleanupHandler cleanupHandler = null; if (isHistoryCleanupStrategyRemovalTimeBased(commandContext)) { cleanupHandler = getTimeBasedHandler(); } else { cleanupHandler = new HistoryCleanupBatch(); } CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration() .getCommandExecutorTxRequiresNew(); String jobId = commandContext.getCurrentJob().getId(); return cleanupHandler .setConfiguration(configuration) .setCommandExecutor(commandExecutor) .setJobId(jobId); } protected boolean isHistoryCleanupStrategyRemovalTimeBased(CommandContext commandContext) {
String historyRemovalTimeStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); return HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyRemovalTimeStrategy); } protected boolean isWithinBatchWindow(CommandContext commandContext) { return HistoryCleanupHelper.isWithinBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration()); } public HistoryCleanupJobHandlerConfiguration newConfiguration(String canonicalString) { JsonObject jsonObject = JsonUtil.asObject(canonicalString); return HistoryCleanupJobHandlerConfiguration.fromJson(jsonObject); } public String getType() { return TYPE; } public void onDelete(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) { } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobHandler.java
1
请完成以下Java代码
protected final Object getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName) { if (row == null) { return null; } final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return null; } if (columnIndex >= row.size()) { return null; } final Object value = row.get(columnIndex); return value; } protected final <T> T getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Class<T> valueClass) { final Object valueObj = getRowValueOrNull(metadata, row, columnName); if (valueObj == null) { return null; } if (!valueClass.isAssignableFrom(valueObj.getClass())) { return null; } final T value = valueClass.cast(valueObj); return value; }
/** * * @param calculationCtx * @param columnName * @return true if the status of current calculation is about calculating the row for "columnName" group (subtotals) */ protected final boolean isGroupBy(final RModelCalculationContext calculationCtx, final String columnName) { final int groupColumnIndex = calculationCtx.getGroupColumnIndex(); if (groupColumnIndex < 0) { // no grouping return false; } final IRModelMetadata metadata = calculationCtx.getMetadata(); final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return false; } return columnIndex == groupColumnIndex; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\AbstractRModelAggregatedValue.java
1
请在Spring Boot框架中完成以下Java代码
public class DeploymentResourceCollectionResource { @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected ContentTypeResolver contentTypeResolver; @Autowired protected RepositoryService repositoryService; @Autowired(required=false) protected BpmnRestApiInterceptor restApiInterceptor; @ApiOperation(value = "List resources in a deployment", tags = { "Deployment" }, nickname="listDeploymentResources", notes = "The dataUrl property in the resulting JSON for a single resource contains the actual URL to use for retrieving the binary resource.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the deployment was found and the resource list has been returned."), @ApiResponse(code = 404, message = "Indicates the requested deployment was not found.") }) @GetMapping(value = "/repository/deployments/{deploymentId}/resources", produces = "application/json") public List<DeploymentResourceResponse> getDeploymentResources(@ApiParam(name = "deploymentId") @PathVariable String deploymentId) {
// Check if deployment exists Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); if (deployment == null) { throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class); } if (restApiInterceptor != null) { restApiInterceptor.accessDeploymentById(deployment); } List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId); return restResponseFactory.createDeploymentResourceResponseList(deploymentId, resourceList, contentTypeResolver); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\DeploymentResourceCollectionResource.java
2
请完成以下Java代码
public Result<?> enhanceJavaListHttp(@RequestBody JSONObject params) { log.info(" --- params:" + params.toJSONString()); JSONArray dataList = params.getJSONArray("dataList"); List<DictModel> dict = virtualDictData(); for (int i = 0; i < dataList.size(); i++) { JSONObject record = dataList.getJSONObject(i); String province = record.getString("province"); if (province == null) { continue; } String text = dict.stream() .filter(p -> province.equals(p.getValue())) .map(DictModel::getText) .findAny() .orElse(province); record.put("province", text); } Result<?> res = Result.OK(dataList); res.setCode(1); return res; } /** * 模拟字典数据 * * @return */ private List<DictModel> virtualDictData() { List<DictModel> dict = new ArrayList<>(); dict.add(new DictModel("bj", "北京")); dict.add(new DictModel("sd", "山东")); dict.add(new DictModel("ah", "安徽")); return dict; } /** * Online表单 http 增强,add、edit增强示例 * @param params * @return */ @PostMapping("/enhanceJavaHttp") public Result<?> enhanceJavaHttp(@RequestBody JSONObject params) { log.info(" --- params:" + params.toJSONString()); String tableName = params.getString("tableName"); JSONObject record = params.getJSONObject("record"); /* * 业务场景一: 获取提交表单数据,进行其他业务关联操作
* (比如:根据入库单,同步更改库存) */ log.info(" --- tableName:" + tableName); log.info(" --- 行数据:" + record.toJSONString()); /* * 业务场景二: 保存数据之前进行数据的校验 * 直接返回错误状态即可 */ String phone = record.getString("phone"); if (oConvertUtils.isEmpty(phone)) { return Result.error("手机号不能为空!"); } /* * 业务场景三: 保存数据之对数据的处理 * 直接操作 record 即可 */ record.put("phone", "010-" + phone); /* 其他业务场景自行实现 */ // 返回场景一: 不对 record 做任何修改的情况下,可以直接返回 code, // 返回 0 = 丢弃当前数据 // 返回 1 = 新增当前数据 // 返回 2 = 修改当前数据 TODO(?)存疑 // return Result.OK(1); // 返回场景二: 需要对 record 做修改的情况下,需要返回一个JSONObject对象(或者Map也行) JSONObject res = new JSONObject(); res.put("code", 1); // 将 record 返回以进行修改 res.put("record", record); // TODO 不要 code 的概念 return Result.OK(res); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\online\OnlCgformDemoController.java
1
请完成以下Java代码
public static Pinyin convertSingle(String single) { Pinyin pinyin = map.get(single); if (pinyin == null) return Pinyin.none5; return pinyin; } /** * 将拼音的音调统统转为5调或者最大的音调 * @param p * @return */ public static Pinyin convert2Tone5(Pinyin p) { return tone2tone5[p.ordinal()]; }
/** * 将所有音调都转为1 * @param pinyinList * @return */ public static List<Pinyin> makeToneToTheSame(List<Pinyin> pinyinList) { ListIterator<Pinyin> listIterator = pinyinList.listIterator(); while (listIterator.hasNext()) { listIterator.set(convert2Tone5(listIterator.next())); } return pinyinList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\String2PinyinConverter.java
1
请完成以下Java代码
public String getEvtTp() { return evtTp; } /** * Sets the value of the evtTp property. * * @param value * allowed object is * {@link String } * */ public void setEvtTp(String value) { this.evtTp = value; } /** * Gets the value of the evtId property. * * @return * possible object is * {@link String } * */
public String getEvtId() { return evtId; } /** * Sets the value of the evtId property. * * @param value * allowed object is * {@link String } * */ public void setEvtId(String value) { this.evtId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CorporateAction9.java
1
请完成以下Java代码
public void setM_ProductOperation_ID (int M_ProductOperation_ID) { if (M_ProductOperation_ID < 1) set_Value (COLUMNNAME_M_ProductOperation_ID, null); else set_Value (COLUMNNAME_M_ProductOperation_ID, Integer.valueOf(M_ProductOperation_ID)); } /** Get Product Operation. @return Product Manufacturing Operation */ public int getM_ProductOperation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first
*/ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMProduct.java
1
请完成以下Java代码
public void onAfterCreated(final MatchInv matchInv) { unpostInvoiceIfNeeded(ImmutableList.of(matchInv)); postIt(matchInv); } @Override public void onAfterDeleted(final List<MatchInv> matchInvs) { deleteFactAcct(matchInvs); unpostInvoiceIfNeeded(matchInvs); } private void postIt(final MatchInv matchInv) { postingService.schedule( DocumentPostRequest.builder() .record(toTableRecordReference(matchInv)) .clientId(matchInv.getClientId()) .onErrorNotifyUserId(matchInv.getUpdatedByUserId()) .build() ); } @NonNull private static TableRecordReference toTableRecordReference(final MatchInv matchInv) { return TableRecordReference.of(I_M_MatchInv.Table_Name, matchInv.getId()); } private void deleteFactAcct(final List<MatchInv> matchInvs) { for (final MatchInv matchInv : matchInvs) { if (matchInv.isPosted()) { MPeriod.testPeriodOpen(Env.getCtx(), Timestamp.from(matchInv.getDateAcct()), DocBaseType.MatchInvoice, matchInv.getOrgId().getRepoId()); factAcctDAO.deleteForRecordRef(toTableRecordReference(matchInv)); }
} } private void unpostInvoiceIfNeeded(final List<MatchInv> matchInvs) { final HashSet<InvoiceId> invoiceIds = new HashSet<>(); for (final MatchInv matchInv : matchInvs) { // Reposting is required if a M_MatchInv was created for a purchase invoice. // ... because we book the matched quantity on InventoryClearing and on Expense the not matched quantity if (matchInv.getSoTrx().isPurchase()) { costDetailService.voidAndDeleteForDocument(CostingDocumentRef.ofMatchInvoiceId(matchInv.getId())); invoiceIds.add(matchInv.getInvoiceId()); } } invoiceBL.getByIds(invoiceIds) .forEach(Doc_Invoice::unpostIfNeeded); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\AcctMatchInvListener.java
1
请完成以下Java代码
public String getNamespace() { return namespace; } /** * Returns the {@link SparkplugDescriptor} * * @return the SparkplugDescriptor */ public SparkplugDescriptor getSparkplugDescriptor() { return sparkplugDescriptor; } /** * Returns the {@link EdgeNodeDescriptor} * * @return the EdgeNodeDescriptor */ public EdgeNodeDescriptor getEdgeNodeDescriptor() { return edgeNodeDescriptor; } /** * Returns the ID of the logical grouping of Edge of Network (EoN) Nodes and devices. * * @return the group ID */ public String getGroupId() { return groupId; } /** * Returns the ID of the Edge of Network (EoN) Node. * * @return the edge node ID */ public String getEdgeNodeId() { return edgeNodeId; } /** * Returns the ID of the device. * * @return the device ID */ public String getDeviceId() { return deviceId; } public void updateDeviceIdPlus(String deviceIdNew) { this.deviceId = this.deviceId.equals("+") ? deviceIdNew : this.deviceId; } /** * Returns the Host Application ID if this is a Host topic * * @return the Host Application ID */ public String getHostApplicationId() { return hostApplicationId; } /** * Returns the message type. * * @return the message type */ public SparkplugMessageType getType() { return type;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); if (hostApplicationId == null) { sb.append(getNamespace()).append("/").append(getGroupId()).append("/").append(getType()).append("/") .append(getEdgeNodeId()); if (getDeviceId() != null) { sb.append("/").append(getDeviceId()); } } else { sb.append(getNamespace()).append("/").append(getType()).append("/").append(hostApplicationId); } return sb.toString(); } /** * @param type the type to check * @return true if this topic's type matches the passes in type, false otherwise */ public boolean isType(SparkplugMessageType type) { return this.type != null && this.type.equals(type); } public boolean isNode() { return this.deviceId == null; } public String getNodeDeviceName() { return isNode() ? edgeNodeId : deviceId; } public static boolean isValidIdElementToUTF8(String deviceIdElement) { if (deviceIdElement == null) { return false; } String regex = "^(?!.*//)[^+#]*$"; return deviceIdElement.matches(regex); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugTopic.java
1
请完成以下Java代码
public int getAD_Error_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Error_ID); if (ii == null) return 0; return ii.intValue(); } /** AD_Language AD_Reference_ID=106 */ public static final int AD_LANGUAGE_AD_Reference_ID=106; /** Set Language. @param AD_Language Language for this entity */ public void setAD_Language (String AD_Language) { set_Value (COLUMNNAME_AD_Language, AD_Language); } /** Get Language. @return Language for this entity */ public String getAD_Language () { return (String)get_Value(COLUMNNAME_AD_Language); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); }
/** 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Error.java
1
请完成以下Java代码
public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } /** Get Warehouse. @return Storage Warehouse and Service Point */ public int getM_Warehouse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Expense Report. @param S_TimeExpense_ID Time and Expense Report */ public void setS_TimeExpense_ID (int S_TimeExpense_ID) { if (S_TimeExpense_ID < 1) set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, null); else set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, Integer.valueOf(S_TimeExpense_ID)); } /** Get Expense Report. @return Time and Expense Report */ public int getS_TimeExpense_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpense_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_S_TimeExpense.java
1
请完成以下Java代码
public boolean isPartUniqueIndex() { return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex); } @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 setPosition (final int Position) { set_Value (COLUMNNAME_Position, Position); } @Override public int getPosition() { return get_ValueAsInt(COLUMNNAME_Position); } /** * Type AD_Reference_ID=53241 * Reference name: EXP_Line_Type */
public static final int TYPE_AD_Reference_ID=53241; /** XML Element = E */ public static final String TYPE_XMLElement = "E"; /** XML Attribute = A */ public static final String TYPE_XMLAttribute = "A"; /** Embedded EXP Format = M */ public static final String TYPE_EmbeddedEXPFormat = "M"; /** Referenced EXP Format = R */ public static final String TYPE_ReferencedEXPFormat = "R"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
1
请完成以下Java代码
public String getValueSql(Object value, List<Object> params) { final String valueSql; if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; valueSql = modelValue.getColumnName(); } else { valueSql = "?"; params.add(value); } return buildSql(valueSql); }
@Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return null; } final String str = (String)value; // implementation detail: we use `subSequence` because we want to match the Postgres LPAD implementation. The returned string is of the EXACT required length, even if that means the string will be shortened. return StringUtils.leftPad(str.trim(), size, padStr).subSequence(0, size); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\LpadQueryFilterModifier.java
1
请完成以下Java代码
public static void refCountAndSubscribe() throws InterruptedException { Observable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish().refCount(); LOGGER.info("refcount()"); Thread.sleep(1000); LOGGER.info("subscribing #1"); Subscription subscription1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i)); Thread.sleep(1000); LOGGER.info("subscribing #2"); Subscription subscription2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i)); Thread.sleep(1000); LOGGER.info("unsubscribe#1"); subscription1.unsubscribe(); Thread.sleep(1000); LOGGER.info("unsubscribe#2"); subscription2.unsubscribe(); }
private static Observable getObservable() { return Observable.create(subscriber -> { frame.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { subscriber.onNext(e.getX()); } }); subscriber.add(Subscriptions.create(() -> { LOGGER.info("Clear resources"); for (MouseListener listener : frame.getListeners(MouseListener.class)) { frame.removeMouseListener(listener); } })); }); } }
repos\tutorials-master\rxjava-modules\rxjava-observables\src\main\java\com\baeldung\rxjava\MultipleSubscribersHotObs.java
1
请完成以下Java代码
public void setQualityAdj_Amt_Per_UOM (java.math.BigDecimal QualityAdj_Amt_Per_UOM) { set_Value (COLUMNNAME_QualityAdj_Amt_Per_UOM, QualityAdj_Amt_Per_UOM); } /** Get Ausgleichsbetrag. @return Ausgleichsbetrag */ @Override public java.math.BigDecimal getQualityAdj_Amt_Per_UOM () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QualityAdj_Amt_Per_UOM); if (bd == null) return Env.ZERO; return bd; } /** * QualityAdjustmentMonth AD_Reference_ID=540507 * Reference name: QualityAdjustmentMonth */ public static final int QUALITYADJUSTMENTMONTH_AD_Reference_ID=540507; /** Jan = Jan */ public static final String QUALITYADJUSTMENTMONTH_Jan = "Jan"; /** Feb = Feb */ public static final String QUALITYADJUSTMENTMONTH_Feb = "Feb"; /** Mar = Mar */ public static final String QUALITYADJUSTMENTMONTH_Mar = "Mar"; /** Apr = Apr */ public static final String QUALITYADJUSTMENTMONTH_Apr = "Apr"; /** May = May */ public static final String QUALITYADJUSTMENTMONTH_May = "May"; /** Jun = Jun */
public static final String QUALITYADJUSTMENTMONTH_Jun = "Jun"; /** Jul = Jul */ public static final String QUALITYADJUSTMENTMONTH_Jul = "Jul"; /** Aug = Aug */ public static final String QUALITYADJUSTMENTMONTH_Aug = "Aug"; /** Sep = Sep */ public static final String QUALITYADJUSTMENTMONTH_Sep = "Sep"; /** Oct = Oct */ public static final String QUALITYADJUSTMENTMONTH_Oct = "Oct"; /** Nov = Nov */ public static final String QUALITYADJUSTMENTMONTH_Nov = "Nov"; /** Dec = Dec */ public static final String QUALITYADJUSTMENTMONTH_Dec = "Dec"; /** Set Monat. @param QualityAdjustmentMonth Monat */ @Override public void setQualityAdjustmentMonth (java.lang.String QualityAdjustmentMonth) { set_Value (COLUMNNAME_QualityAdjustmentMonth, QualityAdjustmentMonth); } /** Get Monat. @return Monat */ @Override public java.lang.String getQualityAdjustmentMonth () { return (java.lang.String)get_Value(COLUMNNAME_QualityAdjustmentMonth); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_Month_Adj.java
1
请完成以下Java代码
public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override public LookupValuesPage getFieldTypeahead(final RowEditingContext ctx, final String fieldName, final String query) { throw new UnsupportedOperationException(); } @Override public LookupValuesList getFieldDropdown(final RowEditingContext ctx, final String fieldName) { throw new UnsupportedOperationException(); } @Override public ViewHeaderProperties getHeaderProperties() { return rowsData.getHeaderProperties(); } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return processes; } public ViewId getInitialViewId() { return initialViewId != null ? initialViewId : getViewId(); } @Override public ViewId getParentViewId() { return initialViewId; } public Optional<OrderId> getOrderId() { return rowsData.getOrder().map(Order::getOrderId); } public Optional<BPartnerId> getBpartnerId() { return rowsData.getBpartnerId(); } public SOTrx getSoTrx() { return rowsData.getSoTrx(); } public CurrencyId getCurrencyId() { return rowsData.getCurrencyId(); } public Set<ProductId> getProductIds() { return rowsData.getProductIds(); } public Optional<PriceListVersionId> getSinglePriceListVersionId() { return rowsData.getSinglePriceListVersionId(); } public Optional<PriceListVersionId> getBasePriceListVersionId()
{ return rowsData.getBasePriceListVersionId(); } public PriceListVersionId getBasePriceListVersionIdOrFail() { return rowsData.getBasePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_Pricelist_Version_Base_ID@")); } public List<ProductsProposalRow> getAllRows() { return ImmutableList.copyOf(getRows()); } public void addOrUpdateRows(@NonNull final List<ProductsProposalRowAddRequest> requests) { rowsData.addOrUpdateRows(requests); invalidateAll(); } public void patchViewRow(@NonNull final DocumentId rowId, @NonNull final ProductsProposalRowChangeRequest request) { rowsData.patchRow(rowId, request); } public void removeRowsByIds(final Set<DocumentId> rowIds) { rowsData.removeRowsByIds(rowIds); invalidateAll(); } public ProductsProposalView filter(final ProductsProposalViewFilter filter) { rowsData.filter(filter); return this; } @Override public DocumentFilterList getFilters() { return ProductsProposalViewFilters.toDocumentFilters(rowsData.getFilter()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalView.java
1
请完成以下Java代码
public boolean containsContext(HttpServletRequest request) { return getContext(request) != null; } /** * @deprecated please see {@link SecurityContextRepository#loadContext} */ @Override @Deprecated public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { return loadDeferredContext(requestResponseHolder.getRequest()).get(); } @Override public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) { Supplier<SecurityContext> supplier = () -> getContext(request); return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy); } private SecurityContext getContext(HttpServletRequest request) { return (SecurityContext) request.getAttribute(this.requestAttributeName); } @Override public void saveContext(SecurityContext context, HttpServletRequest request,
@Nullable HttpServletResponse response) { request.setAttribute(this.requestAttributeName, context); } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\RequestAttributeSecurityContextRepository.java
1
请完成以下Java代码
protected PageData<Device> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return deviceDao.findDevicesByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, Device device) { deleteDevice(tenantId, device); } }; private final PaginatedRemover<CustomerId, Device> customerDevicesRemover = new PaginatedRemover<>() { @Override protected PageData<Device> findEntities(TenantId tenantId, CustomerId id, PageLink pageLink) { return deviceDao.findDevicesByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, Device entity) { unassignDeviceFromCustomer(tenantId, new DeviceId(entity.getUuidId())); } }; @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findDeviceById(tenantId, new DeviceId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.DEVICE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\device\DeviceServiceImpl.java
1
请完成以下Java代码
public Builder withEventName(String eventName) { this.eventName = eventName; return this; } /** * Builder method for executionId parameter. * @param executionId field to set * @return builder */ public Builder withExecutionId(String executionId) { this.executionId = executionId; return this; } /** * Builder method for processInstanceId parameter. * @param processInstanceId field to set * @return builder */ public Builder withProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; return this; } /** * Builder method for processDefinitionId parameter. * @param processDefinitionId field to set * @return builder */ public Builder withProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } /** * Builder method for businessKey parameter. * @param businessKey field to set * @return builder */ public Builder withBusinessKey(String businessKey) { this.businessKey = businessKey; return this; }
/** * Builder method for configuration parameter. * @param configuration field to set * @return builder */ public Builder withConfiguration(String configuration) { this.configuration = configuration; return this; } /** * Builder method for activityId parameter. * @param activityId field to set * @return builder */ public Builder withActivityId(String activityId) { this.activityId = activityId; return this; } /** * Builder method for created parameter. * @param created field to set * @return builder */ public Builder withCreated(Date created) { this.created = created; return this; } /** * Builder method of the builder. * @return built class */ public MessageSubscriptionImpl build() { return new MessageSubscriptionImpl(this); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\MessageSubscriptionImpl.java
1
请完成以下Java代码
public final void bindFieldAndLabel(final JPanel panel, final JComponent field, final JLabel label, final String columnName) { bindFieldAndLabel(panel, field, DEFAULT_FIELD_CONSTRAINTS, label, DEFAULT_LABEL_CONSTRAINTS, columnName); } @Override public final void bindFieldAndLabel(final JPanel panel, final JComponent field, final String fieldConstraints, final JLabel label, final String labelConstraints, final String columnName) { final Properties ctx = Env.getCtx(); final String labelText = Services.get(IMsgBL.class).translate(ctx, columnName); label.setText(labelText); label.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(label, labelConstraints); panel.add(field, fieldConstraints); } @Override public final VLookup getVLookup(final int windowNo, final int tabNo, final int displayType, final String tableName, final String columnName, final boolean mandatory, final boolean autocomplete) { final Properties ctx = Env.getCtx(); final I_AD_Column column = Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName); final Lookup lookup = MLookupFactory.newInstance().get(ctx, windowNo, tabNo, column.getAD_Column_ID(), displayType); lookup.setMandatory(mandatory); final VLookup lookupField = new VLookup(columnName, mandatory, // mandatory false, // isReadOnly true, // isUpdateable lookup); if (autocomplete) { lookupField.enableLookupAutocomplete(); } // // For firing validation rules lookupField.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Object value = lookupField.getValue(); Env.setContext(ctx, windowNo, columnName, value == null ? "" : value.toString()); }
}); return lookupField; } @Override public final VNumber getVNumber(final String columnName, final boolean mandatory) { final Properties ctx = Env.getCtx(); final String title = Services.get(IMsgBL.class).translate(ctx, columnName); return new VNumber(columnName, mandatory, false, // isReadOnly true, // isUpdateable DisplayType.Number, // displayType title); } @Override public final void disposeDialogForColumnData(final int windowNo, final JDialog dialog, final List<String> columnNames) { if (columnNames == null || columnNames.isEmpty()) { return; } final StringBuilder missingColumnsBuilder = new StringBuilder(); final Iterator<String> columnNamesIt = columnNames.iterator(); while (columnNamesIt.hasNext()) { final String columnName = columnNamesIt.next(); missingColumnsBuilder.append("@").append(columnName).append("@"); if (columnNamesIt.hasNext()) { missingColumnsBuilder.append(", "); } } final Exception ex = new AdempiereException("@NotFound@ " + missingColumnsBuilder.toString()); ADialog.error(windowNo, dialog.getContentPane(), ex.getLocalizedMessage()); dialog.dispose(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\api\impl\SwingEditorFactory.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * OutputType AD_Reference_ID=540632 * Reference name: OutputType */ public static final int OUTPUTTYPE_AD_Reference_ID=540632; /** Attach = Attach */ public static final String OUTPUTTYPE_Attach = "Attach";
/** Store = Store */ public static final String OUTPUTTYPE_Store = "Store"; /** Queue = Queue */ public static final String OUTPUTTYPE_Queue = "Queue"; /** Frontend = Frontend */ public static final String OUTPUTTYPE_Frontend = "Frontend"; @Override public void setOutputType (final java.lang.String OutputType) { set_Value (COLUMNNAME_OutputType, OutputType); } @Override public java.lang.String getOutputType() { return get_ValueAsString(COLUMNNAME_OutputType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW.java
1
请完成以下Java代码
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) { CommandContext commandContext = Context.getCommandContext(); ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); ExecutionEntity executionEntity = (ExecutionEntity) execution; StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement(); if (startEvent.isInterrupting()) { List<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByParentExecutionId( executionEntity.getParentId() ); for (ExecutionEntity childExecution : childExecutions) { if (!childExecution.getId().equals(executionEntity.getId())) { executionEntityManager.cancelExecutionAndRelatedData( childExecution, DeleteReason.EVENT_SUBPROCESS_INTERRUPTING + "(" + startEvent.getId() + ")" ); } } } // Should we use triggerName and triggerData, because message name expression can change? String messageName = messageExecutionContext.getMessageName(execution); EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager(); List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if ( eventSubscription instanceof MessageEventSubscriptionEntity && eventSubscription.getEventName().equals(messageName) ) {
eventSubscriptionEntityManager.delete(eventSubscription); } } executionEntity.setCurrentFlowElement( (SubProcess) executionEntity.getCurrentFlowElement().getParentContainer() ); executionEntity.setScope(true); ExecutionEntity outgoingFlowExecution = executionEntityManager.createChildExecution(executionEntity); outgoingFlowExecution.setCurrentFlowElement(startEvent); leave(outgoingFlowExecution); } protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) { Map<String, Object> variablesMap = new HashMap<>(); // convert data objects to process variables if (dataObjects != null) { for (ValuedDataObject dataObject : dataObjects) { variablesMap.put(dataObject.getName(), dataObject.getValue()); } } return variablesMap; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\EventSubProcessMessageStartEventActivityBehavior.java
1
请完成以下Java代码
public boolean isAllowAnonymousLogin() { return allowAnonymousLogin; } public void setAllowAnonymousLogin(boolean allowAnonymousLogin) { this.allowAnonymousLogin = allowAnonymousLogin; } public boolean isAuthorizationCheckEnabled() { return authorizationCheckEnabled; } public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) { this.authorizationCheckEnabled = authorizationCheckEnabled; } public Integer getPageSize() {
return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public boolean isPasswordCheckCatchAuthenticationException() { return passwordCheckCatchAuthenticationException; } public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) { this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java
1
请完成以下Java代码
public void setM_TU_HU_PI_ID (final int M_TU_HU_PI_ID) { if (M_TU_HU_PI_ID < 1) set_Value (COLUMNNAME_M_TU_HU_PI_ID, null); else set_Value (COLUMNNAME_M_TU_HU_PI_ID, M_TU_HU_PI_ID); } @Override public int getM_TU_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_TU_HU_PI_ID); } @Override public de.metas.handlingunits.model.I_M_HU getPickFrom_HU() { return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU) { set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU); } @Override public void setPickFrom_HU_ID (final int PickFrom_HU_ID) { if (PickFrom_HU_ID < 1) set_Value (COLUMNNAME_PickFrom_HU_ID, null); else set_Value (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID); } @Override public int getPickFrom_HU_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID); } @Override public void setPickFrom_HUQRCode (final @Nullable java.lang.String PickFrom_HUQRCode) { set_Value (COLUMNNAME_PickFrom_HUQRCode, PickFrom_HUQRCode); } @Override public java.lang.String getPickFrom_HUQRCode() { return get_ValueAsString(COLUMNNAME_PickFrom_HUQRCode); } /** * PickingJobAggregationType AD_Reference_ID=541931 * Reference name: PickingJobAggregationType */ public static final int PICKINGJOBAGGREGATIONTYPE_AD_Reference_ID=541931; /** sales_order = sales_order */ public static final String PICKINGJOBAGGREGATIONTYPE_Sales_order = "sales_order"; /** product = product */ public static final String PICKINGJOBAGGREGATIONTYPE_Product = "product"; /** delivery_location = delivery_location */ public static final String PICKINGJOBAGGREGATIONTYPE_Delivery_location = "delivery_location"; @Override public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType) { set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType); } @Override
public java.lang.String getPickingJobAggregationType() { return get_ValueAsString(COLUMNNAME_PickingJobAggregationType); } @Override public void setPicking_User_ID (final int Picking_User_ID) { if (Picking_User_ID < 1) set_Value (COLUMNNAME_Picking_User_ID, null); else set_Value (COLUMNNAME_Picking_User_ID, Picking_User_ID); } @Override public int getPicking_User_ID() { return get_ValueAsInt(COLUMNNAME_Picking_User_ID); } @Override public void setPreparationDate (final @Nullable java.sql.Timestamp PreparationDate) { set_Value (COLUMNNAME_PreparationDate, PreparationDate); } @Override public java.sql.Timestamp getPreparationDate() { return get_ValueAsTimestamp(COLUMNNAME_PreparationDate); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job.java
1
请完成以下Java代码
public static void sortVariablesByCounter(List<VariableInstance> variableInstances, List<VariableInstance> counterVariableInstances) { if (counterVariableInstances == null || counterVariableInstances.isEmpty()) { return; } Map<String, Integer> sortOrder = new HashMap<>(); for (VariableInstance counterVariable : counterVariableInstances) { Object value = counterVariable.getValue(); String[] values = value.toString().split(COUNTER_VAR_VALUE_SEPARATOR); String variableInstanceId = values[0]; int order = Integer.parseInt(values[1]); sortOrder.put(variableInstanceId, order); } variableInstances.sort(Comparator.comparingInt(o -> sortOrder.getOrDefault(o.getId(), 0))); } public static Map<String, VariableAggregationDefinition> groupAggregationsByTarget(VariableScope scope, Collection<VariableAggregationDefinition> aggregations, CmmnEngineConfiguration cmmnEngineConfiguration) { Map<String, VariableAggregationDefinition> aggregationsByTarget = new HashMap<>(); for (VariableAggregationDefinition aggregation : aggregations) { String targetVarName = getAggregationTargetVarName(aggregation, scope, cmmnEngineConfiguration);
aggregationsByTarget.put(targetVarName, aggregation); } return aggregationsByTarget; } public static String getAggregationTargetVarName(VariableAggregationDefinition aggregation, VariableScope parentScope, CmmnEngineConfiguration cmmnEngineConfiguration) { String targetVarName = null; if (StringUtils.isNotEmpty(aggregation.getTargetExpression())) { Object value = cmmnEngineConfiguration.getExpressionManager() .createExpression(aggregation.getTargetExpression()) .getValue(parentScope); if (value != null) { targetVarName = value.toString(); } } else if (StringUtils.isNotEmpty(aggregation.getTarget())) { targetVarName = aggregation.getTarget(); } return targetVarName; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\variable\CmmnAggregation.java
1
请完成以下Java代码
public Boolean isFcstInd() { return fcstInd; } /** * Sets the value of the fcstInd property. * * @param value * allowed object is * {@link Boolean } * */ public void setFcstInd(Boolean value) { this.fcstInd = value; } /** * Gets the value of the bkTxCd property. * * @return * possible object is * {@link BankTransactionCodeStructure4 } * */ public BankTransactionCodeStructure4 getBkTxCd() { return bkTxCd; } /** * Sets the value of the bkTxCd property. * * @param value * allowed object is * {@link BankTransactionCodeStructure4 } *
*/ public void setBkTxCd(BankTransactionCodeStructure4 value) { this.bkTxCd = value; } /** * Gets the value of the avlbty 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 avlbty property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAvlbty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CashBalanceAvailability2 } * * */ public List<CashBalanceAvailability2> getAvlbty() { if (avlbty == null) { avlbty = new ArrayList<CashBalanceAvailability2>(); } return this.avlbty; } }
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\TotalsPerBankTransactionCode2.java
1
请完成以下Java代码
public List<MaturingConfigLine> getByMaturedProductId(@NonNull final ProductId maturedProductId) { return getMaturingConfigMap().getByMaturedProductId(maturedProductId); } @NonNull public List<MaturingConfigLine> getByFromProductId(@NonNull final ProductId maturedProductId) { return getMaturingConfigMap().getByFromProductId(maturedProductId); } final MaturingConfigMap getMaturingConfigMap() { return cache.getOrLoad(0, this::retrieveMaturingConfigMap); } private MaturingConfigMap retrieveMaturingConfigMap() { final ImmutableList<MaturingConfigLine> configs = queryBL .createQueryBuilderOutOfTrx(I_M_Maturing_Configuration_Line.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(MaturingConfigRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new MaturingConfigMap(configs); } private static MaturingConfigLine fromRecord(@NonNull final I_M_Maturing_Configuration_Line record) { return MaturingConfigLine.builder() .id(MaturingConfigLineId.ofRepoIdOrNull(record.getM_Maturing_Configuration_Line_ID())) // accept not saved records .maturingConfigId(MaturingConfigId.ofRepoIdOrNull(record.getM_Maturing_Configuration_ID())) .fromProductId((ProductId.ofRepoIdOrNull(record.getFrom_Product_ID()))) .maturedProductId(ProductId.ofRepoIdOrNull(record.getMatured_Product_ID())) .orgId(OrgId.ofRepoIdOrAny(record.getAD_Org_ID())) .maturityAge(Integer.valueOf(record.getMaturityAge())) .build(); } public MaturingConfigLine save(@NonNull final MaturingConfigLine maturingConfigLine) {
final I_M_Maturing_Configuration_Line record = InterfaceWrapperHelper.loadOrNew(maturingConfigLine.getId(), I_M_Maturing_Configuration_Line.class); updateRecord(record, maturingConfigLine); save(record); return fromRecord(record); } private static void updateRecord(@NonNull final I_M_Maturing_Configuration_Line record, @NonNull final MaturingConfigLine from) { record.setM_Maturing_Configuration_ID(from.getMaturingConfigId().getRepoId()); record.setFrom_Product_ID(ProductId.toRepoId(from.getFromProductId())); record.setMatured_Product_ID(ProductId.toRepoId(from.getMaturedProductId())); record.setAD_Org_ID(from.getOrgId().getRepoId()); record.setMaturityAge(from.getMaturityAge()); } private static void save(@NonNull final I_M_Maturing_Configuration_Line record) { saveRecord(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\maturing\MaturingConfigRepository.java
1
请完成以下Java代码
public void setC_Invoice_Candidate_ID (final int C_Invoice_Candidate_ID) { if (C_Invoice_Candidate_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_ID, C_Invoice_Candidate_ID); } @Override public int getC_Invoice_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_ID); } @Override public void setC_Invoice_Candidate_Recompute_ID (final int C_Invoice_Candidate_Recompute_ID) { if (C_Invoice_Candidate_Recompute_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Recompute_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Recompute_ID, C_Invoice_Candidate_Recompute_ID); }
@Override public int getC_Invoice_Candidate_Recompute_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_Recompute_ID); } @Override public void setChunkUUID (final @Nullable String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID); } @Override public String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_Recompute.java
1
请完成以下Java代码
public Criteria andOrderSnNotIn(List<String> values) { addCriterion("order_sn not in", values, "orderSn"); return (Criteria) this; } public Criteria andOrderSnBetween(String value1, String value2) { addCriterion("order_sn between", value1, value2, "orderSn"); return (Criteria) this; } public Criteria andOrderSnNotBetween(String value1, String value2) { addCriterion("order_sn not between", value1, value2, "orderSn"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } 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\SmsCouponHistoryExample.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Contact {" + "id=" + id + ", name='" + name + "'" + ", email='" + email + "'" + ", phone='" + phone + "'" + " }"; } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\data\Contact.java
1
请完成以下Java代码
public java.math.BigDecimal getQtyOrdered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ausliefermenge. @param QtyToDeliver Ausliefermenge */ @Override public void setQtyToDeliver (java.math.BigDecimal QtyToDeliver) { set_Value (COLUMNNAME_QtyToDeliver, QtyToDeliver); } /** Get Ausliefermenge. @return Ausliefermenge */ @Override public java.math.BigDecimal getQtyToDeliver () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID)
{ if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_DeliveryDay_Alloc.java
1
请完成以下Java代码
public class ScylladbApplication { private String keySpaceName; private String tableName; public ScylladbApplication(String keySpaceName, String tableName) { this.keySpaceName = keySpaceName; this.tableName = tableName; CreateKeyspaceStart createKeyspace = createKeyspace(keySpaceName); SimpleStatement keypaceStatement = createKeyspace.ifNotExists() .withSimpleStrategy(3) .build(); CreateTableStart createTable = createTable(keySpaceName, tableName); SimpleStatement tableStatement = createTable.ifNotExists() .withPartitionKey("id", DataTypes.BIGINT) .withColumn("name", DataTypes.TEXT) .build(); try (CqlSession session = CqlSession.builder().build()) { ResultSet rs = session.execute(keypaceStatement); if (null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty()) { rs = session.execute(tableStatement); } } } public List<String> getAllUserNames() { List<String> userNames = new ArrayList<>(); try (CqlSession session = CqlSession.builder().build()) { String query = String.format("select * from %s.%s",keySpaceName,tableName); ResultSet rs = session.execute(query); for (Row r : rs.all()) userNames.add(r.getString("name")); } return userNames; } public List<User> getUsersByUserName(String userName) {
List<User> userList = new ArrayList<>(); try (CqlSession session = CqlSession.builder().build()) { Select query = selectFrom(keySpaceName, tableName).all() .whereColumn("name") .isEqualTo(literal(userName)) .allowFiltering(); SimpleStatement statement = query.build(); ResultSet rs = session.execute(statement); for (Row r : rs) userList.add(new User(r.getLong("id"), r.getString("name"))); } return userList; } public boolean addNewUser(User user) { boolean response = false; try (CqlSession session = CqlSession.builder().build()) { InsertInto insert = insertInto(keySpaceName, tableName); SimpleStatement statement = insert.value("id", literal(user.getId())) .value("name", literal(user.getName())) .build(); ResultSet rs = session.execute(statement); response = null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty(); } return response; } }
repos\tutorials-master\persistence-modules\scylladb\src\main\java\com\baeldung\scylladb\ScylladbApplication.java
1
请完成以下Java代码
private static GS1Element readElement(@NonNull final GS1SequenceReader reader) { final int identifierPosition = reader.getPosition(); GS1ApplicationIdentifier identifier = null; String key = null; Object data = null; // Standard AIs defined in ApplicationIdentifier for (GS1ApplicationIdentifier candidate : GS1ApplicationIdentifier.values()) { if (reader.startsWith(candidate.getKey())) { identifier = candidate; key = reader.read(identifier.getKey().length()); if (identifier.getFormat() == GS1ApplicationIdentifierFormat.CUSTOM) { data = reader.readDataFieldInCustomFormat(identifier); } else { data = reader.readDataFieldInStandardFormat(identifier); } break; } } // Support for AIs 703s Number of processor with three-digit ISO country code if (key == null && reader.remainingLength() >= 4 && reader.startsWith("703")) { String start = reader.peek(4); if (start.charAt(3) >= '0' && start.charAt(3) <= '9') { key = reader.read(4); data = Arrays.asList(reader.readFixedLengthNumeric(3), reader.readVariableLengthAlphanumeric(1, 27)); } } // Support for AIs 710-719 National Healthcare Reimbursement Number (NHRN) if (key == null && reader.remainingLength() >= 3 && reader.startsWith("71")) { String start = reader.peek(3); if (start.charAt(2) >= '0' && start.charAt(2) <= '9') { key = reader.read(3);
data = reader.readVariableLengthAlphanumeric(1, 20); } } // Support for AIs 91-99 Company internal information if (key == null && reader.remainingLength() >= 2 && reader.startsWith("9")) { String start = reader.peek(2); if (start.charAt(1) >= '1' && start.charAt(1) <= '9') { key = reader.read(2); data = reader.readVariableLengthAlphanumeric(1, 30); } } // // // if (key == null) { throw new AdempiereException("Unrecognized AI at position " + identifierPosition); } if (data == null) { throw new AdempiereException("Error parsing data field for AI " + key + " at position " + identifierPosition); } return GS1Element.builder() .identifier(identifier) .key(key) .value(data) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1Parser.java
1
请完成以下Java代码
public List<FilterDefinition> getFilters() { return filters; } public void setFilters(List<FilterDefinition> filters) { this.filters = filters; } public @Nullable URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteDefinition that = (RouteDefinition) o; return this.order == that.order && Objects.equals(this.id, that.id) && Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters) && Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata) && Objects.equals(this.enabled, that.enabled); } @Override public int hashCode() { return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order, this.enabled); } @Override public String toString() { return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters + ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + ", enabled=" + enabled + '}'; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RouteDefinition.java
1
请完成以下Java代码
public void setSysAdmin(final boolean sysAdmin) { setProperty("#SysAdmin", sysAdmin); } public void setRole( final RoleId roleId, final String roleName) { setProperty(Env.CTXNAME_AD_Role_ID, RoleId.toRepoId(roleId)); setProperty(Env.CTXNAME_AD_Role_Name, roleName); Ini.setProperty(Ini.P_ROLE, roleName); } public void setRoleUserLevel(final TableAccessLevel roleUserLevel) { setProperty(Env.CTXNAME_AD_Role_UserLevel, roleUserLevel.getUserLevelString()); // Format 'SCO' } public void setAllowLoginDateOverride(final boolean allowLoginDateOverride) { setProperty(Env.CTXNAME_IsAllowLoginDateOverride, allowLoginDateOverride); } public boolean isAllowLoginDateOverride() { return getPropertyAsBoolean(Env.CTXNAME_IsAllowLoginDateOverride); } public RoleId getRoleId() { return RoleId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Role_ID)); } public void setClient(final ClientId clientId, final String clientName) { setProperty(Env.CTXNAME_AD_Client_ID, ClientId.toRepoId(clientId)); setProperty(Env.CTXNAME_AD_Client_Name, clientName); Ini.setProperty(Ini.P_CLIENT, clientName); } public ClientId getClientId() { return ClientId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Client_ID)); } public LocalDate getLoginDate() { return getPropertyAsLocalDate(Env.CTXNAME_Date); } public void setLoginDate(final LocalDate date) { setProperty(Env.CTXNAME_Date, date); } public void setOrg(final OrgId orgId, final String orgName) { setProperty(Env.CTXNAME_AD_Org_ID, OrgId.toRepoId(orgId)); setProperty(Env.CTXNAME_AD_Org_Name, orgName); Ini.setProperty(Ini.P_ORG, orgName); } public void setUserOrgs(final String userOrgs) { setProperty(Env.CTXNAME_User_Org, userOrgs); } public OrgId getOrgId() { return OrgId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Org_ID)); }
public void setWarehouse(final WarehouseId warehouseId, final String warehouseName) { setProperty(Env.CTXNAME_M_Warehouse_ID, WarehouseId.toRepoId(warehouseId)); Ini.setProperty(Ini.P_WAREHOUSE, warehouseName); } @Nullable public WarehouseId getWarehouseId() { return WarehouseId.ofRepoIdOrNull(getPropertyAsInt(Env.CTXNAME_M_Warehouse_ID)); } public void setPrinterName(final String printerName) { setProperty(Env.CTXNAME_Printer, printerName == null ? "" : printerName); Ini.setProperty(Ini.P_PRINTER, printerName); } public void setAcctSchema(final AcctSchema acctSchema) { setProperty("$C_AcctSchema_ID", acctSchema.getId().getRepoId()); setProperty("$C_Currency_ID", acctSchema.getCurrencyId().getRepoId()); setProperty("$HasAlias", acctSchema.getValidCombinationOptions().isUseAccountAlias()); } @Nullable public AcctSchemaId getAcctSchemaId() { return AcctSchemaId.ofRepoIdOrNull(getPropertyAsInt("$C_AcctSchema_ID")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\LoginContext.java
1
请完成以下Java代码
final class OAuth2PushedAuthorizationRequestUri { private static final String REQUEST_URI_PREFIX = "urn:ietf:params:oauth:request_uri:"; private static final String REQUEST_URI_DELIMITER = "___"; private static final StringKeyGenerator DEFAULT_STATE_GENERATOR = new Base64StringKeyGenerator( Base64.getUrlEncoder()); private String requestUri; private String state; private Instant expiresAt; static OAuth2PushedAuthorizationRequestUri create() { return create(Instant.now().plusSeconds(300)); } static OAuth2PushedAuthorizationRequestUri create(Instant expiresAt) { String state = DEFAULT_STATE_GENERATOR.generateKey(); OAuth2PushedAuthorizationRequestUri pushedAuthorizationRequestUri = new OAuth2PushedAuthorizationRequestUri(); pushedAuthorizationRequestUri.requestUri = REQUEST_URI_PREFIX + state + REQUEST_URI_DELIMITER + expiresAt.toEpochMilli(); pushedAuthorizationRequestUri.state = state + REQUEST_URI_DELIMITER + expiresAt.toEpochMilli(); pushedAuthorizationRequestUri.expiresAt = expiresAt; return pushedAuthorizationRequestUri; } static OAuth2PushedAuthorizationRequestUri parse(String requestUri) { int stateStartIndex = REQUEST_URI_PREFIX.length(); int expiresAtStartIndex = requestUri.indexOf(REQUEST_URI_DELIMITER) + REQUEST_URI_DELIMITER.length(); OAuth2PushedAuthorizationRequestUri pushedAuthorizationRequestUri = new OAuth2PushedAuthorizationRequestUri(); pushedAuthorizationRequestUri.requestUri = requestUri; pushedAuthorizationRequestUri.state = requestUri.substring(stateStartIndex); pushedAuthorizationRequestUri.expiresAt = Instant
.ofEpochMilli(Long.parseLong(requestUri.substring(expiresAtStartIndex))); return pushedAuthorizationRequestUri; } String getRequestUri() { return this.requestUri; } String getState() { return this.state; } Instant getExpiresAt() { return this.expiresAt; } private OAuth2PushedAuthorizationRequestUri() { } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2PushedAuthorizationRequestUri.java
1
请完成以下Java代码
public String getName() { return name; } @Schema(description = "JSON object with the Rule Node Id. " + "Specify this field to update the Rule Node. " + "Referencing non-existing Rule Node Id will cause error. " + "Omit this field to create new rule node.") @Override public RuleNodeId getId() { return super.getId(); } @Schema(description = "Timestamp of the rule node creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @Schema(description = "Additional parameters of the rule node. Contains 'layoutX' and 'layoutY' properties for visualization.", implementation = JsonNode.class) @Override
public JsonNode getAdditionalInfo() { return super.getAdditionalInfo(); } // Getter is ignored for serialization @JsonIgnore public boolean isDebugMode() { return debugMode; } // Setter is annotated for deserialization @JsonSetter public void setDebugMode(boolean debugMode) { this.debugMode = debugMode; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\rule\RuleNode.java
1
请完成以下Java代码
public class TokenDto { @JsonProperty("raw") private String raw; @Schema(name = "raw", example = "app token") public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw; } @Override public String toString() { return "TokenDto [raw=" + raw + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((raw == null) ? 0 : raw.hashCode()); return result;
} @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TokenDto other = (TokenDto) obj; if (raw == null) { if (other.raw != null) return false; } else if (!raw.equals(other.raw)) return false; return true; } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\TokenDto.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getCalledFromActivityIds() { return this.calledFromActivityIds; } public void addCallingCallActivity(String activityId) { this.calledFromActivityIds.add(activityId); } @Override public String getId() { return id; } @Override public String getKey() { return key; } @Override public String getCategory() { return category; } @Override public String getDescription() { return description; } @Override public boolean hasStartFormKey() { return hasStartFormKey; } @Override public String getName() { return name; } @Override public int getVersion() { return version; } @Override public String getResourceName() { return resourceName;
} @Override public String getDeploymentId() { return deploymentId; } @Override public String getDiagramResourceName() { return diagramResourceName; } @Override public boolean isSuspended() { return suspended; } @Override public String getTenantId() { return tenantId; } @Override public String getVersionTag() { return versionTag; } @Override public Integer getHistoryTimeToLive() { return historyTimeToLive; } @Override public boolean isStartableInTasklist() { return isStartableInTasklist; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\CalledProcessDefinitionImpl.java
2
请在Spring Boot框架中完成以下Java代码
public R save(@Valid @RequestBody Post post) { return R.status(postService.save(post)); } /** * 修改 岗位表 */ @PostMapping("/update") @ApiOperationSupport(order = 5) @Operation(summary = "修改", description = "传入post") public R update(@Valid @RequestBody Post post) { return R.status(postService.updateById(post)); } /** * 新增或修改 岗位表 */ @PostMapping("/submit") @ApiOperationSupport(order = 6) @Operation(summary = "新增或修改", description = "传入post") public R submit(@Valid @RequestBody Post post) { post.setTenantId(SecureUtil.getTenantId()); return R.status(postService.saveOrUpdate(post)); } /** * 删除 岗位表 */ @PostMapping("/remove") @ApiOperationSupport(order = 7) @Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(postService.deleteLogic(Func.toLongList(ids))); } /** * 下拉数据源 */ @GetMapping("/select") @ApiOperationSupport(order = 8) @Operation(summary = "下拉数据源", description = "传入post") public R<List<Post>> select(String tenantId, BladeUser bladeUser) { List<Post> list = postService.list(Wrappers.<Post>query().lambda().eq(Post::getTenantId, Func.toStr(tenantId, bladeUser.getTenantId()))); return R.data(list); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\PostController.java
2
请完成以下Java代码
public class InvoiceCandidate_Constants { public static final String LOGGERNAME_ROOT = InvoiceCandidate_Constants.class.getPackage().getName(); public static Logger getLogger(final Class<?> clazz) { return LogManager.getLogger(clazz); } public static final String ENTITY_TYPE = "de.metas.invoicecandidate"; public static final String JMX_BASE_NAME = ENTITY_TYPE; /** * Internal name of the AD_Input_Data destination for invoice candidates candidates. *
* @see de.metas.impex.api.IInputDataSourceDAO#retrieveInputDataSource(java.util.Properties, String, boolean, String) */ public static final String DATA_DESTINATION_INTERNAL_NAME = "DEST.de.metas.invoicecandidate"; /** * Internal Name for invoice candidate asycn batch */ public static final String C_Async_Batch_InternalName_InvoiceCandidate = "InvoiceCandidate"; /** * Internal Name voiding and recreating async batch */ public static final String C_Async_Batch_InternalName_VoidAndRecreateInvoice = "VoidAndRecreateInvoice"; public static final String C_Async_Batch_InternalName_TriggerVoidAndRecreateInvoice = "TriggerVoidAndRecreateInvoice"; }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\InvoiceCandidate_Constants.java
1
请完成以下Java代码
public PageData<DashboardInfo> findDashboardsByTenantIdAndEdgeId(UUID tenantId, UUID edgeId, PageLink pageLink) { log.debug("Try to find dashboards by tenantId [{}], edgeId [{}] and pageLink [{}]", tenantId, edgeId, pageLink); return DaoUtil.toPageData(dashboardInfoRepository .findByTenantIdAndEdgeId( tenantId, edgeId, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public DashboardInfo findFirstByTenantIdAndName(UUID tenantId, String name) { return DaoUtil.getData(dashboardInfoRepository.findFirstByTenantIdAndTitle(tenantId, name)); } @Override public String findTitleById(UUID tenantId, UUID dashboardId) { return dashboardInfoRepository.findTitleByTenantIdAndId(tenantId, dashboardId); } @Override public List<DashboardInfo> findDashboardsByIds(UUID tenantId, List<UUID> dashboardIds) { return DaoUtil.convertDataList(dashboardInfoRepository.findByIdIn(dashboardIds)); } @Override public List<DashboardInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) {
return DaoUtil.convertDataList(dashboardInfoRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, limit)); } @Override public List<DashboardInfo> findByImageLink(String imageLink, int limit) { return DaoUtil.convertDataList(dashboardInfoRepository.findByImageLink(imageLink, limit)); } @Override public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) { return dashboardInfoRepository.findDashboardInfosByTenantIdAndResourceLink(tenantId.getId(), reference, PageRequest.of(0, limit)); } @Override public List<EntityInfo> findByResource(String reference, int limit) { return dashboardInfoRepository.findDashboardInfosByResourceLink(reference, PageRequest.of(0, limit)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\dashboard\JpaDashboardInfoDao.java
1
请完成以下Java代码
public void setAD_Org_Mapping_ID (final int AD_Org_Mapping_ID) { if (AD_Org_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Org_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Org_Mapping_ID, AD_Org_Mapping_ID); } @Override public int getAD_Org_Mapping_ID() { return get_ValueAsInt(COLUMNNAME_AD_Org_Mapping_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
} @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setValue (final @Nullable 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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org_Mapping.java
1
请在Spring Boot框架中完成以下Java代码
private void recurseForwardViaSourceVhuLink(@NonNull final HuId vhuId, final int depth) { final IQueryBuilder<I_M_HU_Trace> sqlQueryBuilder = createQueryBuilderOrNull(HUTraceEventQuery.builder().vhuSourceId(vhuId).recursionMode(RecursionMode.NONE).build()); if (sqlQueryBuilder == null) { return; } final Collection<HuId> directFollowupVhuIds = sqlQueryBuilder.create().listDistinct(I_M_HU_Trace.COLUMNNAME_VHU_ID, HuId.class); for (final HuId directFollowupVhuId : directFollowupVhuIds) { load(HUTraceEventQuery.builder().vhuId(directFollowupVhuId).recursionMode(RecursionMode.FORWARD).build(), depth); } } } /** * Return all records; this makes absolutely no sense in production; Intended to be used only use for testing.
*/ @VisibleForTesting public List<HUTraceEvent> queryAll() { Adempiere.assertUnitTestMode(); final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_M_HU_Trace> queryBuilder = queryBL.createQueryBuilder(I_M_HU_Trace.class) .orderBy().addColumn(I_M_HU_Trace.COLUMN_M_HU_Trace_ID).endOrderBy(); return queryBuilder.create() .stream() .map(HuTraceEventToDbRecordUtil::fromDbRecord) .collect(Collectors.toList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\repository\RetrieveDbRecordsUtil.java
2
请完成以下Java代码
public int get(String suffix) { suffix = reverse(suffix); Integer length = trie.get(suffix); if (length == null) return 0; return length; } /** * 词语是否以该词典中的某个单词结尾 * @param word * @return */ public boolean endsWith(String word) { word = reverse(word); return trie.commonPrefixSearchWithValue(word).size() > 0; } /** * 获取最长的后缀 * @param word * @return */ public int getLongestSuffixLength(String word) { word = reverse(word); LinkedList<Map.Entry<String, Integer>> suffixList = trie.commonPrefixSearchWithValue(word); if (suffixList.size() == 0) return 0; return suffixList.getLast().getValue(); } private static String reverse(String word) { return new StringBuilder(word).reverse().toString(); }
/** * 键值对 * @return */ public Set<Map.Entry<String, Integer>> entrySet() { Set<Map.Entry<String, Integer>> treeSet = new LinkedHashSet<Map.Entry<String, Integer>>(); for (Map.Entry<String, Integer> entry : trie.entrySet()) { treeSet.add(new AbstractMap.SimpleEntry<String, Integer>(reverse(entry.getKey()), entry.getValue())); } return treeSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SuffixDictionary.java
1
请完成以下Java代码
public String createBankAccountName(@NonNull final BankAccountId bankAccountId) { final BankAccount bankAccount = getById(bankAccountId); final CurrencyCode currencyCode = currencyRepo.getCurrencyCodeById(bankAccount.getCurrencyId()); final BankId bankId = bankAccount.getBankId(); if (bankId != null) { final Bank bank = bankRepo.getById(bankId); return bank.getBankName() + "_" + currencyCode.toThreeLetterCode(); } return currencyCode.toThreeLetterCode(); } public DataImportConfigId getDataImportConfigIdForBankAccount(@NonNull final BankAccountId bankAccountId) { final BankId bankId = bankAccountDAO.getBankId(bankAccountId); return bankRepo.retrieveDataImportConfigIdForBank(bankId); } public boolean isImportAsSingleSummaryLine(@NonNull final BankAccountId bankAccountId) { final BankId bankId = bankAccountDAO.getBankId(bankAccountId); return bankRepo.isImportAsSingleSummaryLine(bankId); } @NonNull public Optional<BankId> getBankIdBySwiftCode(@NonNull final String swiftCode) { return bankRepo.getBankIdBySwiftCode(swiftCode);
} @NonNull public Optional<BankAccountId> getBankAccountId( @NonNull final BankId bankId, @NonNull final String accountNo) { return bankAccountDAO.getBankAccountId(bankId, accountNo); } @NonNull public Optional<BankAccountId> getBankAccountIdByIBAN(@NonNull final String iban) { return bankAccountDAO.getBankAccountIdByIBAN(iban); } @NonNull public Optional<String> getBankName(@NonNull final BankAccountId bankAccountId) { return Optional.of(bankAccountDAO.getById(bankAccountId)) .map(BankAccount::getBankId) .map(bankRepo::getById) .map(Bank::getBankName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\api\BankAccountService.java
1
请完成以下Java代码
public void setPolicy(CrossOriginEmbedderPolicy embedderPolicy) { Assert.notNull(embedderPolicy, "embedderPolicy cannot be null"); this.delegate = createDelegate(embedderPolicy); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(CrossOriginEmbedderPolicy embedderPolicy) { StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(EMBEDDER_POLICY, embedderPolicy.getPolicy()); return builder.build(); } public enum CrossOriginEmbedderPolicy { UNSAFE_NONE("unsafe-none"), REQUIRE_CORP("require-corp"),
CREDENTIALLESS("credentialless"); private final String policy; CrossOriginEmbedderPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\CrossOriginEmbedderPolicyServerHttpHeadersWriter.java
1
请完成以下Java代码
public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHomeTown() { return homeTown; } public void setHomeTown(String homeTown) { this.homeTown = homeTown; } public static class Builder {
private String id; private String type; private String name; private String homeTown; public static Builder newInstance() { return new Builder(); } public Person build() { return new Person(this); } public Builder id(String id) { this.id = id; return this; } public Builder type(String type) { this.type = type; return this; } public Builder name(String name) { this.name = name; return this; } public Builder homeTown(String homeTown) { this.homeTown = homeTown; return this; } } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\async\person\Person.java
1
请完成以下Java代码
public BaseResp<List<Address>> getAddressList(@RequestParam(value = "province") String province, @RequestParam(value = "area") String area, @RequestParam(value = "street") String street, @RequestParam(value = "num") String num) { if (StringUtils.isEmpty(province) || StringUtils.isEmpty(area) || StringUtils.isEmpty(street) || StringUtils .isEmpty(num)) { return new BaseResp(ResultStatus.error_invalid_argument); } Address address = new Address(); address.setProvince(province); address.setArea(area); address.setStreet(street); address.setNum(num); List<Address> lists = new ArrayList<>(); lists.add(address); lists.add(address); lists.add(address); return new BaseResp(ResultStatus.SUCCESS, lists); } @ApiOperation("获取地址信息(参数体)") @ApiResponses({@ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")}) @RequestMapping(value = "/address/area/list", method = RequestMethod.POST)
public BaseResp<String> getAddressList(@RequestBody ParaModel paraModel) { return new BaseResp(ResultStatus.SUCCESS, paraModel.toString()); } @ApiOperation("获取地址信息(路径传参)") @ApiImplicitParams({ @ApiImplicitParam(paramType = "path", name = "area", dataType = "String", required = true, value = "区域", defaultValue = "南山区"), @ApiImplicitParam(paramType = "path", name = "number", dataType = "String", required = true, value = "门牌号", defaultValue = "9527")}) @ApiResponses({@ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")}) @RequestMapping(value = "/address/{area}/{number}", method = RequestMethod.GET) public BaseResp<String> getAddress(@PathVariable("area") String area, @PathVariable("number") String number) { Address address = new Address(); address.setProvince("广东省"); address.setArea(area); address.setStreet("桃园街道"); address.setNum(number); return new BaseResp(ResultStatus.SUCCESS, address.toString()); } }
repos\spring-boot-quick-master\quick-swagger\src\main\java\com\quick\api\WebController.java
1
请完成以下Java代码
public class NotOperator { public static void ifElseStatementExample() { boolean isValid = true; if (isValid) { System.out.println("Valid"); } else { System.out.println("Invalid"); } } public static void checkIsValidIsFalseWithEmptyIfBlock() { boolean isValid = true; if (isValid) { } else { System.out.println("Invalid"); } } public static void checkIsValidIsFalseWithJustTheIfBlock() { boolean isValid = true; if (isValid == false) { System.out.println("Invalid"); } } public static void checkIsValidIsFalseWithTheNotOperator() { boolean isValid = true; if (!isValid) { System.out.println("Invalid"); } } public static void notOperatorWithBooleanValueAsOperand() { System.out.println(!true); // prints false System.out.println(!false); // prints true System.out.println(!!false); // prints false } public static void applyNotOperatorToAnExpression_example1() { int count = 2; System.out.println(!(count > 2)); // prints true System.out.println(!(count <= 2)); // prints false } public static void applyNotOperatorToAnExpression_LogicalOperators() { boolean x = true; boolean y = false; System.out.println(!(x && y)); // prints true System.out.println(!(x || y)); // prints false } public static void precedence_example() { boolean x = true; boolean y = false; System.out.println(!x && y); // prints false System.out.println(!(x && y)); // prints true
} public static void pitfalls_ComplexConditionsExample() { int count = 9; int total = 100; if (!(count >= 10 || total >= 1000)) { System.out.println("Some more work to do"); } } public static void pitfalls_simplifyComplexConditionsByReversingLogicExample() { int count = 9; int total = 100; if (count < 10 && total < 1000) { System.out.println("Some more work to do"); } } public static void exitEarlyExample() { boolean isValid = false; if(!isValid) { throw new IllegalArgumentException("Invalid input"); } // Code to execute when isValid == true goes here } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-2\src\main\java\com\baeldung\core\operators\notoperator\NotOperator.java
1
请完成以下Java代码
protected String doIt() throws Exception { final WindowUIElementsGenerator generator = WindowUIElementsGenerator.forConsumer(new IWindowUIElementsGeneratorConsumer() { @Override public void consume(final I_AD_UI_Section uiSection, final I_AD_Tab parent) { saveRecord(uiSection); addLog("Created {} for {}", uiSection, parent); } @Override public void consume(final I_AD_UI_Column uiColumn, final I_AD_UI_Section parent) { saveRecord(uiColumn); addLog("Created {} (SeqNo={}) for {}", uiColumn, uiColumn.getSeqNo(), parent); } @Override public void consume(final I_AD_UI_ElementGroup uiElementGroup, final I_AD_UI_Column parent) { saveRecord(uiElementGroup); addLog("Created {} for {}", uiElementGroup, parent); } @Override public void consume(final I_AD_UI_Element uiElement, final I_AD_UI_ElementGroup parent)
{ saveRecord(uiElement); addLog("Created {} (AD_Field={}, seqNo={}) for {}", uiElement, uiElement.getAD_Field(), uiElement.getSeqNo(), parent); } @Override public void consume(final I_AD_UI_ElementField uiElementField, final I_AD_UI_Element parent) { saveRecord(uiElementField); addLog("Created {} (AD_Field={}) for {}", uiElementField, uiElementField.getAD_Field(), parent); } }); final I_AD_Window adWindow = getRecord(I_AD_Window.class); generator.generate(adWindow); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\process\AD_Window_CreateUIElements.java
1
请完成以下Java代码
public class C_Flatrate_Term_Create_From_OLCand extends JavaProcess implements IProcessPrecondition { @Override protected void prepare() { // nothing to do } @Override protected String doIt() throws Exception { final ISubscriptionBL subscriptionBL = Services.get(ISubscriptionBL.class); if (getRecord_ID() > 0) { Check.assume(getTable_ID() == MTable.getTable_ID(I_C_OLCand.Table_Name), "Process is called for C_OLCands"); final I_C_OLCand olCand = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_C_OLCand.class, get_TrxName()); subscriptionBL.createTermForOLCand(getCtx(), olCand, getPinstanceId(), true, get_TrxName()); addLog("@C_OLCand_ID@ " + olCand.getC_OLCand_ID() + " @Processed@"); } else { final int counter = subscriptionBL.createMissingTermsForOLCands(getCtx(), true, getPinstanceId(), get_TrxName()); addLog("@Processed@ " + counter + " @C_OLCand_ID@"); } return "@Success@"; } /** * Method returns true if the given gridTab is a {@link I_C_OLCand} with the correct data destination. * * @param gridTab */ @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (!I_C_OLCand.Table_Name.equals(context.getTableName())) { return ProcessPreconditionsResolution.reject(); } if(context.isNoSelection()) {
return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } final I_C_OLCand olCand = context.getSelectedModel(I_C_OLCand.class); if(olCand.isError()) { return ProcessPreconditionsResolution.reject("line has errors"); } final IInputDataSourceDAO inputDataSourceDAO = Services.get(IInputDataSourceDAO.class); final I_AD_InputDataSource dest = inputDataSourceDAO.retrieveInputDataSource(Env.getCtx(), Contracts_Constants.DATA_DESTINATION_INTERNAL_NAME, false, get_TrxName()); if (dest == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("no input data source found"); } if (dest.getAD_InputDataSource_ID() != olCand.getAD_DataDestination_ID()) { return ProcessPreconditionsResolution.rejectWithInternalReason("input data source not matching"); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Create_From_OLCand.java
1
请完成以下Java代码
public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setStocked(final Boolean stocked) { this.stocked = stocked; this.stockedSet = true; } public void setProductCategoryIdentifier(final String productCategoryIdentifier) { this.productCategoryIdentifier = productCategoryIdentifier; this.productCategoryIdentifierSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise;
} public void setBpartnerProductItems(final List<JsonRequestBPartnerProductUpsert> bpartnerProductItems) { this.bpartnerProductItems = bpartnerProductItems; } public void setProductTaxCategories(final List<JsonRequestProductTaxCategoryUpsert> productTaxCategories) { this.productTaxCategories = productTaxCategories; } public void setUomConversions(final List<JsonRequestUOMConversionUpsert> uomConversions) { this.uomConversions = uomConversions; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProduct.java
1
请完成以下Java代码
public void setStatementDate (final @Nullable java.sql.Timestamp StatementDate) { set_Value (COLUMNNAME_StatementDate, StatementDate); } @Override public java.sql.Timestamp getStatementDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementDate); } @Override public void setStatementLineDate (final @Nullable java.sql.Timestamp StatementLineDate) { set_Value (COLUMNNAME_StatementLineDate, StatementLineDate); } @Override public java.sql.Timestamp getStatementLineDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate); } @Override public void setStmtAmt (final @Nullable BigDecimal StmtAmt) { set_Value (COLUMNNAME_StmtAmt, StmtAmt); } @Override public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTrxAmt (final @Nullable BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO;
} /** * TrxType AD_Reference_ID=215 * Reference name: C_Payment Trx Type */ public static final int TRXTYPE_AD_Reference_ID=215; /** Sales = S */ public static final String TRXTYPE_Sales = "S"; /** DelayedCapture = D */ public static final String TRXTYPE_DelayedCapture = "D"; /** CreditPayment = C */ public static final String TRXTYPE_CreditPayment = "C"; /** VoiceAuthorization = F */ public static final String TRXTYPE_VoiceAuthorization = "F"; /** Authorization = A */ public static final String TRXTYPE_Authorization = "A"; /** Void = V */ public static final String TRXTYPE_Void = "V"; /** Rückzahlung = R */ public static final String TRXTYPE_Rueckzahlung = "R"; @Override public void setTrxType (final @Nullable java.lang.String TrxType) { set_Value (COLUMNNAME_TrxType, TrxType); } @Override public java.lang.String getTrxType() { return get_ValueAsString(COLUMNNAME_TrxType); } @Override public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java
1
请完成以下Java代码
private Object getFrom() { Check.assumeNotNull(_fromModel, "_fromModel not null"); return _fromModel; } @Override public IModelCopyHelper setTo(final Object toModel) { this._toModel = toModel; this._toModelAccessor = null; return this; } private final IModelInternalAccessor getToAccessor() { if (_toModelAccessor == null) { Check.assumeNotNull(_toModel, "_toModel not null"); _toModelAccessor = InterfaceWrapperHelper.getModelInternalAccessor(_toModel); } return _toModelAccessor; }
public final boolean isSkipCalculatedColumns() { return _skipCalculatedColumns; } @Override public IModelCopyHelper setSkipCalculatedColumns(boolean skipCalculatedColumns) { this._skipCalculatedColumns = skipCalculatedColumns; return this; } @Override public IModelCopyHelper addTargetColumnNameToSkip(final String columnName) { targetColumnNamesToSkip.add(columnName); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\model\util\ModelCopyHelper.java
1
请完成以下Java代码
public DocumentId getId() { return id; } @Override public AttachmentEntryType getType() { return entry.getType(); } @Override public String getFilename() { return entry.getFilename(); } @Override public byte[] getData() { final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class); return attachmentEntryService.retrieveData(entry.getId()); }
@Override public String getContentType() { return entry.getMimeType(); } @Override public URI getUrl() { return entry.getUrl(); } @Override public Instant getCreated() { return entry.getCreatedUpdatedInfo().getCreated().toInstant(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentEntry.java
1
请在Spring Boot框架中完成以下Java代码
public class RecordAccessId implements RepoIdAware { @JsonCreator public static RecordAccessId ofRepoId(final int repoId) { return new RecordAccessId(repoId); } public static RecordAccessId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new RecordAccessId(repoId) : null; } int repoId; private RecordAccessId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "AD_User_Record_Access"); } @JsonValue @Override public int getRepoId() { return repoId; } public static int toRepoId(final RecordAccessId id) { return id != null ? id.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessId.java
2
请完成以下Java代码
public ActivitiStateHandlerRegistration findRegistrationForProcessAndState(String processName, String stateName) { ActivitiStateHandlerRegistration r = null; String key = registrationKey(processName, stateName); Collection<ActivitiStateHandlerRegistration> rs = this.findRegistrationsForProcessAndState( processName, stateName); for (ActivitiStateHandlerRegistration sr : rs) { String kName = registrationKey(sr.getProcessName(), sr.getStateName()); if (key.equalsIgnoreCase(kName)) { r = sr; break; } } for (ActivitiStateHandlerRegistration sr : rs) { String kName = registrationKey(null, sr.getStateName()); if (key.equalsIgnoreCase(kName)) { r = sr; break; } } if ((r == null) && (rs.size() > 0)) { r = rs.iterator().next(); }
return r; } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public void setBeanName(String name) { this.beanName = name; } public void afterPropertiesSet() throws Exception { Assert.notNull(this.processEngine, "the 'processEngine' can't be null"); logger.info( "this bean contains a processEngine reference. "+ this.processEngine); logger.info("starting " + getClass().getName()); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\registry\ActivitiStateHandlerRegistry.java
1
请完成以下Java代码
public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } /** * Status AD_Reference_ID=541435 * Reference name: DD_OrderLine_Schedule_Status */ public static final int STATUS_AD_Reference_ID=541435; /** NotStarted = NS */ public static final String STATUS_NotStarted = "NS"; /** InProgress = IP */
public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java
1
请完成以下Java代码
public int getCaseDefinitionVersion() { return caseDefinitionVersion; } public void setCaseDefinitionVersion(int caseDefinitionVersion) { this.caseDefinitionVersion = caseDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedCaseInstanceCount() { return finishedCaseInstanceCount; } public void setFinishedCaseInstanceCount(Long finishedCaseInstanceCount) { this.finishedCaseInstanceCount = finishedCaseInstanceCount; } public long getCleanableCaseInstanceCount() { return cleanableCaseInstanceCount; }
public void setCleanableCaseInstanceCount(Long cleanableCaseInstanceCount) { this.cleanableCaseInstanceCount = cleanableCaseInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[caseDefinitionId = " + caseDefinitionId + ", caseDefinitionKey = " + caseDefinitionKey + ", caseDefinitionName = " + caseDefinitionName + ", caseDefinitionVersion = " + caseDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedCaseInstanceCount = " + finishedCaseInstanceCount + ", cleanableCaseInstanceCount = " + cleanableCaseInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricCaseInstanceReportResultEntity.java
1
请完成以下Java代码
public class SubProcessActivityBehavior extends AbstractBpmnActivityBehavior { private static final long serialVersionUID = 1L; public void execute(DelegateExecution execution) { SubProcess subProcess = getSubProcessFromExecution(execution); FlowElement startElement = null; if (CollectionUtil.isNotEmpty(subProcess.getFlowElements())) { for (FlowElement subElement : subProcess.getFlowElements()) { if (subElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) subElement; // start none event if (CollectionUtil.isEmpty(startEvent.getEventDefinitions())) { startElement = startEvent; break; } } } } if (startElement == null) { throw new ActivitiException("No initial activity found for subprocess " + subProcess.getId()); } ExecutionEntity executionEntity = (ExecutionEntity) execution; executionEntity.setScope(true); // initialize the template-defined data objects as variables Map<String, Object> dataObjectVars = processDataObjects(subProcess.getDataObjects()); if (dataObjectVars != null) { executionEntity.setVariablesLocal(dataObjectVars); }
ExecutionEntity startSubProcessExecution = Context.getCommandContext() .getExecutionEntityManager() .createChildExecution(executionEntity); startSubProcessExecution.setCurrentFlowElement(startElement); Context.getAgenda().planContinueProcessOperation(startSubProcessExecution); } protected SubProcess getSubProcessFromExecution(DelegateExecution execution) { FlowElement flowElement = execution.getCurrentFlowElement(); SubProcess subProcess = null; if (flowElement instanceof SubProcess) { subProcess = (SubProcess) flowElement; } else { throw new ActivitiException( "Programmatic error: sub process behaviour can only be applied" + " to a SubProcess instance, but got an instance of " + flowElement ); } return subProcess; } protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) { Map<String, Object> variablesMap = new HashMap<String, Object>(); // convert data objects to process variables if (dataObjects != null) { for (ValuedDataObject dataObject : dataObjects) { variablesMap.put(dataObject.getName(), dataObject.getValue()); } } return variablesMap; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\SubProcessActivityBehavior.java
1
请完成以下Java代码
public ValueReference getValueReference(Bindings bindings, ELContext context) { return null; } @Override public Object eval(Bindings bindings, ELContext context) { return value; } public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return null; } public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues ) { return returnType == null ? value : bindings.convert(value, returnType); } @Override public String toString() { return "\"" + value + "\""; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { int end = value.length() - 1;
for (int i = 0; i < end; i++) { char c = value.charAt(i); if ((c == '#' || c == '$') && value.charAt(i + 1) == '{') { b.append('\\'); } b.append(c); } if (end >= 0) { b.append(value.charAt(end)); } } public int getCardinality() { return 0; } public AstNode getChild(int i) { return null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstText.java
1
请完成以下Java代码
public PvmAtomicOperation findMatchingAtomicOperation(String operationName) { if (operationName == null) { // default operation for backwards compatibility return PvmAtomicOperation.TRANSITION_CREATE_SCOPE; } else { return supportedOperations.get(operationName); } } protected boolean isSupported(PvmAtomicOperation atomicOperation) { return supportedOperations.containsKey(atomicOperation.getCanonicalName()); } @Override public AsyncContinuationConfiguration newConfiguration(String canonicalString) { String[] configParts = tokenizeJobConfiguration(canonicalString); AsyncContinuationConfiguration configuration = new AsyncContinuationConfiguration(); configuration.setAtomicOperation(configParts[0]); configuration.setTransitionId(configParts[1]); return configuration; } /** * @return an array of length two with the following contents: * <ul><li>First element: pvm atomic operation name * <li>Second element: transition id (may be null) */ protected String[] tokenizeJobConfiguration(String jobConfiguration) { String[] configuration = new String[2]; if (jobConfiguration != null ) { String[] configParts = jobConfiguration.split("\\$"); if (configuration.length > 2) { throw new ProcessEngineException("Illegal async continuation job handler configuration: '" + jobConfiguration + "': exprecting one part or two parts seperated by '$'."); } configuration[0] = configParts[0]; if (configParts.length == 2) { configuration[1] = configParts[1]; } } return configuration; } public static class AsyncContinuationConfiguration implements JobHandlerConfiguration {
protected String atomicOperation; protected String transitionId; public String getAtomicOperation() { return atomicOperation; } public void setAtomicOperation(String atomicOperation) { this.atomicOperation = atomicOperation; } public String getTransitionId() { return transitionId; } public void setTransitionId(String transitionId) { this.transitionId = transitionId; } @Override public String toCanonicalString() { String configuration = atomicOperation; if(transitionId != null) { // store id of selected transition in case this is async after. // id is not serialized with the execution -> we need to remember it as // job handler configuration. configuration += "$" + transitionId; } return configuration; } } public void onDelete(AsyncContinuationConfiguration configuration, JobEntity jobEntity) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\AsyncContinuationJobHandler.java
1
请完成以下Java代码
public FetchAndLockBuilderImpl maxTasks(int maxTasks) { this.maxTasks = maxTasks; return this; } public FetchAndLockBuilderImpl usePriority(boolean usePriority) { this.usePriority = usePriority; return this; } public FetchAndLockBuilderImpl orderByCreateTime() { orderingProperties.add(new QueryOrderingProperty(CREATE_TIME, null)); return this; } public FetchAndLockBuilderImpl asc() throws NotValidException { configureLastOrderingPropertyDirection(ASCENDING); return this; } public FetchAndLockBuilderImpl desc() throws NotValidException { configureLastOrderingPropertyDirection(DESCENDING); return this; } @Override public ExternalTaskQueryTopicBuilder subscribe() { checkQueryOk(); return new ExternalTaskQueryTopicBuilderImpl(commandExecutor, workerId, maxTasks, usePriority, orderingProperties); }
protected void configureLastOrderingPropertyDirection(Direction direction) { QueryOrderingProperty lastProperty = !orderingProperties.isEmpty() ? getLastElement(orderingProperties) : null; ensureNotNull(NotValidException.class, "You should call any of the orderBy methods first before specifying a direction", "currentOrderingProperty", lastProperty); if (lastProperty.getDirection() != null) { ensureNull(NotValidException.class, "Invalid query: can specify only one direction desc() or asc() for an ordering constraint", "direction", direction); } lastProperty.setDirection(direction); } protected void checkQueryOk() { for (QueryOrderingProperty orderingProperty : orderingProperties) { ensureNotNull(NotValidException.class, "Invalid query: call asc() or desc() after using orderByXX()", "direction", orderingProperty.getDirection()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\FetchAndLockBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Account { @Id private Long id; @NotNull private String name; private Long branchId; private Long customerId; /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the branchId */ public Long getBranchId() { return branchId; } /** * @param branchId the branchId to set */ public void setBranchId(Long branchId) { this.branchId = branchId; } /** * @return the customerId */ public Long getCustomerId() { return customerId; } /** * @param customerId the customerId to set */ public void setCustomerId(Long customerId) { this.customerId = customerId;
} /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((branchId == null) ? 0 : branchId.hashCode()); result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.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; Account other = (Account) obj; if (branchId == null) { if (other.branchId != null) return false; } else if (!branchId.equals(other.branchId)) return false; if (customerId == null) { if (other.customerId != null) return false; } else if (!customerId.equals(other.customerId)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-vault\src\main\java\com\baeldung\spring\cloud\vaultsample\domain\Account.java
2
请完成以下Java代码
public String getTempleNumber() { return TempleNumber; } public void setTempleNumber(String templeNumber) { TempleNumber = templeNumber; } public String getPosthumousTitle() { return posthumousTitle; } public void setPosthumousTitle(String posthumousTitle) { this.posthumousTitle = posthumousTitle; } public String getSon() { return son; } public void setSon(String son) { this.son = son; }
public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public King getKing() { return king; } public void setKing(King king) { this.king = king; } }
repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\Queen.java
1
请在Spring Boot框架中完成以下Java代码
public class Address { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String street; private int houseNumber; private String city; private int zipCode; @ManyToOne(fetch = FetchType.LAZY) private Person person; public int getId() { return id; } public void setId(int id) { this.id = id; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getStreet() { return street; } public int getHouseNumber() { return houseNumber; } public void setHouseNumber(int houseNumber) { this.houseNumber = houseNumber; } public String getCity() {
return city; } public void setCity(String city) { this.city = city; } public int getZipCode() { return zipCode; } public void setZipCode(int zipCode) { this.zipCode = zipCode; } public void setStreet(String street) { this.street = street; } }
repos\tutorials-master\persistence-modules\jpa-hibernate-cascade-type\src\main\java\com\baeldung\cascading\domain\Address.java
2
请完成以下Java代码
public void addEventListener(FlowableEventListener listenerToAdd, FlowableEngineEventType... types) { commandExecutor.execute(new AddEventListenerCommand(listenerToAdd, types)); } @Override public void removeEventListener(FlowableEventListener listenerToRemove) { commandExecutor.execute(new RemoveEventListenerCommand(listenerToRemove)); } @Override public void dispatchEvent(FlowableEvent event) { commandExecutor.execute(new DispatchEventCommand(event)); } @Override public void setProcessInstanceName(String processInstanceId, String name) { commandExecutor.execute(new SetProcessInstanceNameCmd(processInstanceId, name)); } @Override public List<Event> getProcessInstanceEvents(String processInstanceId) { return commandExecutor.execute(new GetProcessInstanceEventsCmd(processInstanceId)); }
@Override public ProcessInstanceBuilder createProcessInstanceBuilder() { return new ProcessInstanceBuilderImpl(this); } public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) { if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) { return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder)); } else if (processInstanceBuilder.getMessageName() != null) { return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder)); } else { throw new ActivitiIllegalArgumentException( "No processDefinitionId, processDefinitionKey nor messageName provided"); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\RuntimeServiceImpl.java
1
请完成以下Java代码
public class Car { private boolean diesel; private boolean manual; public Car(boolean diesel, boolean manual) { this.diesel = diesel; this.manual = manual; } public boolean isDiesel() { return diesel; } public boolean isManual() { return manual; } static Car dieselAndManualCar() {
return new Car(true, true); } static Car dieselAndAutomaticCar() { return new Car(true, false); } static Car oilAndManualCar() { return new Car(false, true); } static Car oilAndAutomaticCar() { return new Car(false, false); } }
repos\tutorials-master\core-java-modules\core-java-lang-operators\src\main\java\com\baeldung\booleanoperators\Car.java
1
请完成以下Java代码
public Authentication readAuthentication(final ServerCall<?, ?> call, final Metadata headers) throws AuthenticationException { final String header = headers.get(AUTHORIZATION_HEADER); if (header == null || !header.toLowerCase().startsWith(PREFIX)) { log.debug("No basic auth header found"); return null; } final String[] decoded = extractAndDecodeHeader(header); return new UsernamePasswordAuthenticationToken(decoded[0], decoded[1]); } /** * Decodes the header into a username and password. * * @param header The authorization header. * @return The decoded username and password. * @throws BadCredentialsException If the Basic header is not valid Base64 or is missing the {@code ':'} separator. * @see <a href= * "https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java">BasicAuthenticationFilter</a> */ private String[] extractAndDecodeHeader(final String header) { final byte[] base64Token = header.substring(PREFIX_LENGTH).getBytes(UTF_8);
byte[] decoded; try { decoded = Base64.getDecoder().decode(base64Token); } catch (final IllegalArgumentException e) { throw new BadCredentialsException("Failed to decode basic authentication token", e); } final String token = new String(decoded, UTF_8); final int delim = token.indexOf(':'); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } return new String[] {token.substring(0, delim), token.substring(delim + 1)}; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\authentication\BasicGrpcAuthenticationReader.java
1
请完成以下Java代码
public class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { try { Properties properties = getProperties(); Configuration configuration = new Configuration(); configuration.setProperties(properties); configuration.addAnnotatedClass(Person.class); configuration.addAnnotatedClass(Address.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (IOException e) { e.printStackTrace();
} return sessionFactory; } private static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource("hibernate.properties"); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\jpa-hibernate-cascade-type\src\main\java\com\baeldung\cascading\HibernateUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, AuthenticationWebFilter webFilter, EndpointsSecurityConfig endpointsConfig) { var authorizeExchange = http.authorizeExchange(); return endpointsConfig.apply(authorizeExchange) .and() .addFilterAt(webFilter, SecurityWebFiltersOrder.AUTHENTICATION) .httpBasic().disable() .cors().disable() .csrf().disable() .formLogin().disable() .logout().disable() .build(); } /**
* Moving endpoints config to particular interface allow to change endpoints in tests. */ @Bean EndpointsSecurityConfig endpointsConfig() { return http -> http .pathMatchers(HttpMethod.POST, "/api/users", "/api/users/login").permitAll() .pathMatchers(HttpMethod.GET, "/api/profiles/**").permitAll() .pathMatchers(HttpMethod.GET, "/api/articles/**").permitAll() .pathMatchers(HttpMethod.GET, "/api/tags/**").permitAll() .anyExchange().authenticated(); } @FunctionalInterface public interface EndpointsSecurityConfig { AuthorizeExchangeSpec apply(AuthorizeExchangeSpec http); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\security\SecurityConfig.java
2
请完成以下Java代码
public class ForkJoinSearchFileTask extends RecursiveAction { /** * 指定目录 */ private File file; /** * 文件后缀 */ private String suffix; public ForkJoinSearchFileTask(File file, String suffix) { this.file = file; this.suffix = suffix; } @Override protected void compute() { if (Objects.isNull(file)) { return; } File[] files = file.listFiles(); List<ForkJoinSearchFileTask> fileTasks = new ArrayList<>(); if (Objects.nonNull(files)) { for (File f : files) { // 拆分任务 if (f.isDirectory()) { fileTasks.add(new ForkJoinSearchFileTask(f, suffix)); } else { if (f.getAbsolutePath().endsWith(suffix)) { System.out.println(Thread.currentThread().getName() + " 文件: " + f.getAbsolutePath());
} } } // 提交并执行任务 invokeAll(fileTasks); for (ForkJoinSearchFileTask fileTask : fileTasks) { // 等待任务执行完成 fileTask.join(); } } } public static void main(String[] args) throws Exception { File file = new File("d:/"); ForkJoinPool pool = new ForkJoinPool(); // 生成一个计算任务,负责查找指定木目录 ForkJoinSearchFileTask searchFileTask = new ForkJoinSearchFileTask(file, ".txt"); // 异步执行一个任务 pool.execute(searchFileTask); Thread.sleep(10); // 做另外的事情 int count = 0; for (int i = 0; i < 1000; i++) { count += i; } System.out.println("计算任务:" + count); // join方法是一个阻塞方法,会等待任务执行完成 searchFileTask.join(); } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ForkJoinSearchFileTask.java
1
请完成以下Java代码
public CreditLine2 getCdtLine() { return cdtLine; } /** * Sets the value of the cdtLine property. * * @param value * allowed object is * {@link CreditLine2 } * */ public void setCdtLine(CreditLine2 value) { this.cdtLine = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the dt property. * * @return * possible object is * {@link DateAndDateTimeChoice } * */ public DateAndDateTimeChoice getDt() { return dt; }
/** * Sets the value of the dt property. * * @param value * allowed object is * {@link DateAndDateTimeChoice } * */ public void setDt(DateAndDateTimeChoice value) { this.dt = value; } /** * Gets the value of the avlbty 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 avlbty property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAvlbty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CashBalanceAvailability2 } * * */ public List<CashBalanceAvailability2> getAvlbty() { if (avlbty == null) { avlbty = new ArrayList<CashBalanceAvailability2>(); } return this.avlbty; } }
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\CashBalance3.java
1
请完成以下Java代码
public I_PP_Order_Qty retrieveOrderQtyForCostCollector( @NonNull final PPOrderId ppOrderId, @NonNull final PPCostCollectorId costCollectorId) { return retrieveOrderQtys(ppOrderId) .stream() .filter(cand -> cand.getPP_Cost_Collector_ID() == costCollectorId.getRepoId()) // .peek(cand -> Check.assume(cand.isProcessed(), "Candidate was expected to be processed: {}", cand)) .reduce((cand1, cand2) -> { throw new HUException("Expected only one candidate but got: " + cand1 + ", " + cand2); }) .orElse(null); } @Override public List<I_PP_Order_Qty> retrieveOrderQtyForFinishedGoodsReceive(@NonNull final PPOrderId ppOrderId) { return retrieveOrderQtys(ppOrderId) .stream() .filter(cand -> cand.getPP_Order_BOMLine_ID() <= 0) .collect(ImmutableList.toImmutableList()); }
@Override public Optional<I_PP_Order_Qty> retrieveOrderQtyForHu( @NonNull final PPOrderId ppOrderId, @NonNull final HuId huId) { return retrieveOrderQtys(ppOrderId) .stream() .filter(cand -> cand.getM_HU_ID() == huId.getRepoId()) .reduce((cand1, cand2) -> { throw new HUException("Expected only one candidate but got: " + cand1 + ", " + cand2); }); } @Override public boolean hasUnprocessedOrderQty(@NonNull final PPOrderId ppOrderId) { return streamOrderQtys(ppOrderId) .anyMatch(candidate -> !candidate.isProcessed()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPOrderQtyDAO.java
1
请完成以下Java代码
public Mono<CommentView> addComment(String slug, CreateCommentRequest request, User currentUser) { return articleRepository.findBySlugOrFail(slug) .flatMap(article -> addComment(request, currentUser, article)); } public Mono<Void> deleteComment(String commentId, String slug, User user) { return articleRepository.findBySlugOrFail(slug) .flatMap(article -> article.getCommentById(commentId) .map(comment -> deleteComment(article, comment, user)) .orElse(Mono.empty()) ); } public Mono<MultipleCommentsView> getComments(String slug, Optional<User> user) { return articleRepository.findBySlug(slug) .zipWhen(article -> userRepository.findById(article.getAuthorId())) .map(tuple -> { var article = tuple.getT1(); var author = tuple.getT2(); return getComments(user, article, author); }); } private Mono<Void> deleteComment(Article article, Comment comment, User user) { if (!comment.isAuthor(user)) { return Mono.error(new InvalidRequestException("Comment", "only author can delete comment")); } article.deleteComment(comment); return articleRepository.save(article).then();
} private Mono<CommentView> addComment(CreateCommentRequest request, User currentUser, Article article) { var comment = request.toComment(UUID.randomUUID().toString(), currentUser.getId()); article.addComment(comment); var profileView = CommentView.toCommentView(comment, ProfileView.toOwnProfile(currentUser)); return articleRepository.save(article).thenReturn(profileView); } private MultipleCommentsView getComments(Optional<User> user, Article article, User author) { var comments = article.getComments(); var authorProfile = user .map(viewer -> toProfileViewForViewer(author, viewer)) .orElse(toUnfollowedProfileView(author)); var commentViews = comments.stream() .map(comment -> CommentView.toCommentView(comment, authorProfile)) .toList(); return MultipleCommentsView.of(commentViews); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\CommentService.java
1
请完成以下Java代码
public Builder withRefreshButton() { return withRefreshButton(true); } public Builder withRefreshButton(final boolean withRefreshButton) { this.withRefreshButton = withRefreshButton; return this; } public Builder withResetButton(final boolean withResetButton) { this.withResetButton = withResetButton; return this; } public Builder withCustomizeButton(final boolean withCustomizeButton) { this.withCustomizeButton = withCustomizeButton; return this; } public Builder withHistoryButton(final boolean withHistoryButton) { this.withHistoryButton = withHistoryButton; return this; } public Builder withZoomButton(final boolean withZoomButton) { this.withZoomButton = withZoomButton; return this; }
/** * Advice builder to create the buttons with text on them. */ public Builder withText() { return withText(true); } /** * Advice builder to create the buttons without any text on them. * * NOTE: this is the default option anyway. You can call it just to explicitly state the obvious. */ public Builder withoutText() { return withText(false); } /** * Advice builder to create the buttons with or without text on them. * * @param withText true if buttons shall have text on them */ public Builder withText(final boolean withText) { this.withText = withText; return this; } public Builder withSmallButtons(final boolean withSmallButtons) { smallButtons = withSmallButtons; return this; } } } // ConfirmPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ConfirmPanel.java
1
请完成以下Java代码
public class Customer { private String name; private int points; private String profilePhotoUrl; public Customer(String name, int points) { this(name, points, ""); } public Customer(String name, int points, String profilePhotoUrl) { this.name = name; this.points = points; this.profilePhotoUrl = profilePhotoUrl; } public String getName() { return name; } public int getPoints() { return points; } public boolean hasOver(int points) { return this.points > points;
} public boolean hasOverHundredPoints() { return this.points > 100; } public boolean hasValidProfilePhoto() throws Exception { URL url = new URI(this.profilePhotoUrl).toURL(); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); return connection.getResponseCode() == HttpURLConnection.HTTP_OK; } public boolean hasValidProfilePhotoWithoutCheckedException() { try { URL url = new URI(this.profilePhotoUrl).toURL(); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); return connection.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (Exception e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-streams-3\src\main\java\com\baeldung\streams\filter\Customer.java
1
请完成以下Java代码
public class GraphLoader { public JavaSparkContext getSparkContext() throws IOException { Path temp = Files.createTempDirectory("sparkGraphFrames"); SparkConf sparkConf = new SparkConf().setAppName("SparkGraphX").setMaster("local[*]"); JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf); javaSparkContext.setCheckpointDir(temp.toString()); return javaSparkContext; } public GraphFrame getGraphFrameUserRelationship() throws IOException { Path temp = Files.createTempDirectory("sparkGraphFrames"); SparkSession session = SparkSession.builder() .appName("SparkGraphFrameSample") .config("spark.sql.warehouse.dir", temp.toString()) .sparkContext(getSparkContext().sc()) .master("local[*]") .getOrCreate(); List<User> users = loadUsers(); Dataset<Row> userDataset = session.createDataFrame(users, User.class); List<Relationship> relationshipsList = getRelations(); Dataset<Row> relationshipDataset = session.createDataFrame(relationshipsList, Relationship.class); GraphFrame graphFrame = new GraphFrame(userDataset, relationshipDataset); return graphFrame; } public List<Relationship> getRelations() {
List<Relationship> relationships = new ArrayList<>(); relationships.add(new Relationship("Friend", "1", "2")); relationships.add(new Relationship("Following", "1", "4")); relationships.add(new Relationship("Friend", "2", "4")); relationships.add(new Relationship("Relative", "3", "1")); relationships.add(new Relationship("Relative", "3", "4")); return relationships; } private List<User> loadUsers() { User john = new User(1L, "John"); User martin = new User(2L, "Martin"); User peter = new User(3L, "Peter"); User alicia = new User(4L, "Alicia"); List<User> users = new ArrayList<>(); users.add(new User(1L, "John")); users.add(new User(2L, "Martin")); users.add(new User(3L, "Peter")); users.add(new User(4L, "Alicia")); return users; } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\graphframes\GraphLoader.java
1
请完成以下Java代码
public void disableCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).disable(); } public void disableCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).disable(); } public void reenableCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).reenable(); } public void reenableCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).reenable(); } public void completeCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).complete();
} public void completeCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).complete(); } public void closeCaseInstance(String caseInstanceId) { withCaseExecution(caseInstanceId).close(); } public void terminateCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).terminate(); } public void terminateCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).terminate(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
static ToCoreNotificationMsg toProto(boolean timeSeries, String scope, EntityId entityId, List<TsKvEntry> updates) { TransportProtos.TbSubUpdateProto.Builder builder = TransportProtos.TbSubUpdateProto.newBuilder(); builder.setEntityIdMSB(entityId.getId().getMostSignificantBits()); builder.setEntityIdLSB(entityId.getId().getLeastSignificantBits()); Map<String, List<TransportProtos.TsValueProto>> data = new TreeMap<>(); for (TsKvEntry tsEntry : updates) { data.computeIfAbsent(tsEntry.getKey(), k -> new ArrayList<>()).add(toTsValueProto(tsEntry.getTs(), tsEntry)); } data.forEach((key, value) -> { TransportProtos.TsValueListProto.Builder dataBuilder = TransportProtos.TsValueListProto.newBuilder(); dataBuilder.setKey(key);
dataBuilder.addAllTsValue(value); builder.addData(dataBuilder.build()); }); var result = TransportProtos.LocalSubscriptionServiceMsgProto.newBuilder(); if (timeSeries) { result.setTsUpdate(builder); } else { builder.setScope(scope); result.setAttrUpdate(builder); } return ToCoreNotificationMsg.newBuilder().setToLocalSubscriptionServiceMsg(result).build(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbSubscriptionUtils.java
2
请完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; }
public List<SysPermission> getPermissions() { return permissions; } public void setPermissions(List<SysPermission> permissions) { this.permissions = permissions; } public List<UserInfo> getUserInfos() { return userInfos; } public void setUserInfos(List<UserInfo> userInfos) { this.userInfos = userInfos; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysRole.java
1
请完成以下Java代码
public Timestamp getStatementDate () { return (Timestamp)get_Value(COLUMNNAME_StatementDate); } /** Set Statement difference. @param StatementDifference Difference between statement ending balance and actual ending balance */ public void setStatementDifference (BigDecimal StatementDifference) { set_Value (COLUMNNAME_StatementDifference, StatementDifference); } /** Get Statement difference. @return Difference between statement ending balance and actual ending balance */ public BigDecimal getStatementDifference () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_StatementDifference); if (bd == null) return Env.ZERO; return bd; } public I_C_ElementValue getUser1() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser1_ID(), get_TrxName()); } /** Set User List 1. @param User1_ID User defined list element #1 */ public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get User List 1. @return User defined list element #1 */ public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null)
return 0; return ii.intValue(); } public I_C_ElementValue getUser2() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser2_ID(), get_TrxName()); } /** Set User List 2. @param User2_ID User defined list element #2 */ public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get User List 2. @return User defined list element #2 */ public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cash.java
1
请完成以下Java代码
private List<ToUsageStatsServiceMsg> toMsgPack(List<UsageStatsServiceMsg> list) { return Lists.partition(list, packSize) .stream() .map(partition -> ToUsageStatsServiceMsg.newBuilder() .addAllMsgs(partition) .setServiceId(serviceInfoProvider.getServiceId()) .build()) .toList(); } @Override public void report(TenantId tenantId, CustomerId customerId, ApiUsageRecordKey key, long value) { if (!enabled) return; ReportLevel[] reportLevels = new ReportLevel[3]; reportLevels[0] = ReportLevel.of(tenantId); if (key.isCounter()) { reportLevels[1] = ReportLevel.of(TenantId.SYS_TENANT_ID); } if (enabledPerCustomer && customerId != null && !customerId.isNullUid()) { reportLevels[2] = ReportLevel.of(tenantId, customerId); } report(key, value, reportLevels); } @Override public void report(TenantId tenantId, CustomerId customerId, ApiUsageRecordKey key) { report(tenantId, customerId, key, 1); } private void report(ApiUsageRecordKey key, long value, ReportLevel... levels) { ConcurrentMap<ReportLevel, AtomicLong> statsForKey = stats.get(key); for (ReportLevel level : levels) { if (level == null) continue; AtomicLong n = statsForKey.computeIfAbsent(level, k -> new AtomicLong()); if (key.isCounter()) { n.addAndGet(value); } else { n.set(value); } } }
@Data private static class ReportLevel { private final TenantId tenantId; private final CustomerId customerId; public static ReportLevel of(TenantId tenantId) { return new ReportLevel(tenantId, null); } public static ReportLevel of(TenantId tenantId, CustomerId customerId) { return new ReportLevel(tenantId, customerId); } public ParentEntity getParentEntity() { return new ParentEntity(tenantId, customerId); } } @Data private static class ParentEntity { private final TenantId tenantId; private final CustomerId customerId; public EntityId getId() { return customerId != null ? customerId : tenantId; } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\usagestats\DefaultTbApiUsageReportClient.java
1
请在Spring Boot框架中完成以下Java代码
public RepositoryService getRepositoryService() { return processEngine.getRepositoryService(); } @Bean(name = "formService") @Override public FormService getFormService() { return processEngine.getFormService(); } @Bean(name = "taskService") @Override public TaskService getTaskService() { return processEngine.getTaskService(); } @Bean(name = "historyService") @Override public HistoryService getHistoryService() { return processEngine.getHistoryService(); } @Bean(name = "identityService") @Override public IdentityService getIdentityService() { return processEngine.getIdentityService(); } @Bean(name = "managementService") @Override public ManagementService getManagementService() { return processEngine.getManagementService(); } @Bean(name = "authorizationService") @Override public AuthorizationService getAuthorizationService() { return processEngine.getAuthorizationService(); } @Bean(name = "caseService") @Override public CaseService getCaseService() { return processEngine.getCaseService();
} @Bean(name = "filterService") @Override public FilterService getFilterService() { return processEngine.getFilterService(); } @Bean(name = "externalTaskService") @Override public ExternalTaskService getExternalTaskService() { return processEngine.getExternalTaskService(); } @Bean(name = "decisionService") @Override public DecisionService getDecisionService() { return processEngine.getDecisionService(); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringProcessEngineServicesConfiguration.java
2
请完成以下Java代码
public List<SortingDto> toSortingDtos() { return orderingProperties.stream() .map(SortingDto::fromOrderingProperty) .collect(Collectors.toList()); } /** * Returns the last configured field in this {@link OrderingConfig}. */ protected OrderingProperty getLastConfiguredProperty() { return !orderingProperties.isEmpty() ? orderingProperties.get(orderingProperties.size() - 1) : null; } /** * The field to sort by. */ public enum SortingField { CREATE_TIME("createTime"); private final String name; SortingField(String name) { this.name = name; } public String getName() { return this.name; } } /** * The direction of createTime. */ public enum Direction { ASC, DESC; public String asString() { return super.name().toLowerCase(); } } /** * Static Class that encapsulates an ordering property with a field and its direction.
*/ public static class OrderingProperty { protected SortingField field; protected Direction direction; /** * Static factory method to create {@link OrderingProperty} out of a field and its corresponding {@link Direction}. */ public static OrderingProperty of(SortingField field, Direction direction) { OrderingProperty result = new OrderingProperty(); result.setField(field); result.setDirection(direction); return result; } public void setField(SortingField field) { this.field = field; } public SortingField getField() { return this.field; } public void setDirection(Direction direction) { this.direction = direction; } public Direction getDirection() { return this.direction; } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\OrderingConfig.java
1