instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void afterPropertiesSet() { Assert.notNull(this.securityMetadataSource, "securityMetadataSource must be specified"); Assert.notNull(this.channelDecisionManager, "channelDecisionManager must be specified"); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAllConfigAttributes(); if (attributes == null) { this.logger.warn("Could not validate configuration attributes as the " + "FilterInvocationSecurityMetadataSource did not return any attributes"); return; } Set<ConfigAttribute> unsupportedAttributes = getUnsupportedAttributes(attributes); Assert.isTrue(unsupportedAttributes.isEmpty(), () -> "Unsupported configuration attributes: " + unsupportedAttributes); this.logger.info("Validated configuration attributes"); } private Set<ConfigAttribute> getUnsupportedAttributes(Collection<ConfigAttribute> attrDefs) { Set<ConfigAttribute> unsupportedAttributes = new HashSet<>(); for (ConfigAttribute attr : attrDefs) { if (!this.channelDecisionManager.supports(attr)) { unsupportedAttributes.add(attr); } } return unsupportedAttributes; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; FilterInvocation filterInvocation = new FilterInvocation(request, response, chain); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAttributes(filterInvocation); if (attributes != null) { this.logger.debug(LogMessage.format("Request: %s; ConfigAttributes: %s", filterInvocation, attributes)); this.channelDecisionManager.decide(filterInvocation, attributes); @Nullable HttpServletResponse channelResponse = filterInvocation.getResponse(); Assert.notNull(channelResponse, "HttpServletResponse is required"); if (channelResponse.isCommitted()) { return; }
} chain.doFilter(request, response); } protected @Nullable ChannelDecisionManager getChannelDecisionManager() { return this.channelDecisionManager; } protected FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public void setChannelDecisionManager(ChannelDecisionManager channelDecisionManager) { this.channelDecisionManager = channelDecisionManager; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource) { this.securityMetadataSource = filterInvocationSecurityMetadataSource; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\ChannelProcessingFilter.java
1
请完成以下Java代码
public class TitleCaseConverter { private static final String WORD_SEPARATOR = " "; public static String convertToTitleCaseIteratingChars(String text) { if (text == null || text.isEmpty()) { return text; } StringBuilder converted = new StringBuilder(); boolean convertNext = true; for (char ch : text.toCharArray()) { if (Character.isSpaceChar(ch)) { convertNext = true; } else if (convertNext) { ch = Character.toTitleCase(ch); convertNext = false; } else { ch = Character.toLowerCase(ch); } converted.append(ch); } return converted.toString(); } public static String convertToTitleCaseSplitting(String text) { if (text == null || text.isEmpty()) { return text; } return Arrays .stream(text.split(WORD_SEPARATOR)) .map(word -> word.isEmpty() ? word : Character.toTitleCase(word.charAt(0)) + word .substring(1) .toLowerCase())
.collect(Collectors.joining(WORD_SEPARATOR)); } public static String convertToTitleCaseIcu4j(String text) { if (text == null || text.isEmpty()) { return text; } return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance()); } public static String convertToTileCaseWordUtilsFull(String text) { return WordUtils.capitalizeFully(text); } public static String convertToTileCaseWordUtils(String text) { return WordUtils.capitalize(text); } }
repos\tutorials-master\core-java-modules\core-java-string-conversions-4\src\main\java\com\baeldung\titlecase\TitleCaseConverter.java
1
请在Spring Boot框架中完成以下Java代码
public void evict(TenantId tenantId, AssetProfileId profileId) { AssetProfile oldProfile = assetProfilesMap.remove(profileId); log.debug("[{}] evict asset profile from cache: {}", profileId, oldProfile); AssetProfile newProfile = get(tenantId, profileId); if (newProfile != null) { notifyProfileListeners(newProfile); } } @Override public void evict(TenantId tenantId, AssetId assetId) { AssetProfileId old = assetsMap.remove(assetId); if (old != null) { AssetProfile newProfile = get(tenantId, assetId); if (newProfile == null || !old.equals(newProfile.getId())) { notifyAssetListeners(tenantId, assetId, newProfile); } } } @Override public void addListener(TenantId tenantId, EntityId listenerId, Consumer<AssetProfile> profileListener, BiConsumer<AssetId, AssetProfile> assetListener) { if (profileListener != null) { profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener); } if (assetListener != null) { assetProfileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, assetListener); } } @Override public AssetProfile find(AssetProfileId assetProfileId) { return assetProfileService.findAssetProfileById(TenantId.SYS_TENANT_ID, assetProfileId); } @Override public AssetProfile findOrCreateAssetProfile(TenantId tenantId, String profileName) { return assetProfileService.findOrCreateAssetProfile(tenantId, profileName); } @Override public void removeListener(TenantId tenantId, EntityId listenerId) {
ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.remove(listenerId); } ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> assetListeners = assetProfileListeners.get(tenantId); if (assetListeners != null) { assetListeners.remove(listenerId); } } private void notifyProfileListeners(AssetProfile profile) { ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(profile.getTenantId()); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(profile)); } } private void notifyAssetListeners(TenantId tenantId, AssetId assetId, AssetProfile profile) { if (profile != null) { ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> tenantListeners = assetProfileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(assetId, profile)); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbAssetProfileCache.java
2
请完成以下Java代码
protected void configureQuery(HistoricActivityInstanceQueryImpl query) { getAuthorizationManager().configureHistoricActivityInstanceQuery(query); getTenantManager().configureQuery(query); } public DbOperation addRemovalTimeToActivityInstancesByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricActivityInstanceEventEntity.class, "updateHistoricActivityInstancesByRootProcessInstanceId", parameters); } public DbOperation addRemovalTimeToActivityInstancesByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager()
.updatePreserveOrder(HistoricActivityInstanceEventEntity.class, "updateHistoricActivityInstancesByProcessInstanceId", parameters); } public DbOperation deleteHistoricActivityInstancesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricActivityInstanceEntity.class, "deleteHistoricActivityInstancesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricActivityInstanceManager.java
1
请完成以下Java代码
public class CamundaFieldImpl extends BpmnModelElementInstanceImpl implements CamundaField { protected static Attribute<String> camundaNameAttribute; protected static Attribute<String> camundaExpressionAttribute; protected static Attribute<String> camundaStringValueAttribute; protected static ChildElement<CamundaExpression> camundaExpressionChild; protected static ChildElement<CamundaString> camundaStringChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaField.class, CAMUNDA_ELEMENT_FIELD) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaField>() { public CamundaField newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaFieldImpl(instanceContext); } }); camundaNameAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_NAME) .namespace(CAMUNDA_NS) .build(); camundaExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EXPRESSION) .namespace(CAMUNDA_NS) .build(); camundaStringValueAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_STRING_VALUE) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); camundaExpressionChild = sequenceBuilder.element(CamundaExpression.class) .build(); camundaStringChild = sequenceBuilder.element(CamundaString.class) .build(); typeBuilder.build(); } public CamundaFieldImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getCamundaName() { return camundaNameAttribute.getValue(this); } public void setCamundaName(String camundaName) { camundaNameAttribute.setValue(this, camundaName); } public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaStringValue() { return camundaStringValueAttribute.getValue(this); } public void setCamundaStringValue(String camundaStringValue) { camundaStringValueAttribute.setValue(this, camundaStringValue); } public CamundaString getCamundaString() { return camundaStringChild.getChild(this); } public void setCamundaString(CamundaString camundaString) { camundaStringChild.setChild(this, camundaString); } public CamundaExpression getCamundaExpressionChild() { return camundaExpressionChild.getChild(this); } public void setCamundaExpressionChild(CamundaExpression camundaExpression) { camundaExpressionChild.setChild(this, camundaExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFieldImpl.java
1
请完成以下Java代码
public String get(String key) { try { readLock.lock(); logger.info(Thread.currentThread().getName() + " reading"); return syncHashMap.get(key); } finally { readLock.unlock(); } } public String remove(String key) { try { writeLock.lock(); return syncHashMap.remove(key); } finally { writeLock.unlock(); } } public boolean containsKey(String key) { try { readLock.lock(); return syncHashMap.containsKey(key); } finally { readLock.unlock(); } } boolean isReadLockAvailable() { return readLock.tryLock(); } public static void main(String[] args) throws InterruptedException { final int threadCount = 3; final ExecutorService service = Executors.newFixedThreadPool(threadCount); SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock(); service.execute(new Thread(new Writer(object), "Writer")); service.execute(new Thread(new Reader(object), "Reader1")); service.execute(new Thread(new Reader(object), "Reader2")); service.shutdown(); } private static class Reader implements Runnable { SynchronizedHashMapWithRWLock object;
Reader(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { object.get("key" + i); } } } private static class Writer implements Runnable { SynchronizedHashMapWithRWLock object; public Writer(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { try { object.put("key" + i, "value" + i); sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SynchronizedHashMapWithRWLock.java
1
请完成以下Java代码
public boolean isFulfilled(PvmExecutionImpl element) { return element == null || CompensationBehavior.isCompensationThrowing(element); } }); return walker.getCurrentElement(); } /** * See #CAM-10978 * Use case process instance with <code>asyncBefore</code> startEvent * After unifying the history variable's creation<br> * The following changed:<br> * * variables will receive the <code>processInstanceId</code> as <code>activityInstanceId</code> in such cases (previously was the startEvent id)<br> * * historic details have new <code>initial</code> property to track initial variables that process is started with<br> * The jobs created prior <code>7.13</code> and not executed before do not have historic information of variables. * This method takes care of that. */
public static void createMissingHistoricVariables(PvmExecutionImpl execution) { Collection<VariableInstanceEntity> variables = ((ExecutionEntity) execution).getVariablesInternal(); if (variables != null && variables.size() > 0) { // trigger historic creation if the history is not presented already for (VariableInstanceEntity variable : variables) { if (variable.wasCreatedBefore713()) { VariableInstanceHistoryListener.INSTANCE.onCreate(variable, variable.getExecution()); } } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\LegacyBehavior.java
1
请完成以下Java代码
private static OIRowUserInputParts extractInitialUserInput(final @NonNull CreateViewRequest request) { final OIRowUserInputParts initialUserInput = request.getParameterAs(VIEW_PARAM_InitialUserInput, OIRowUserInputParts.class); return initialUserInput != null ? initialUserInput : OIRowUserInputParts.EMPTY; } @NonNull private static SAPGLJournalId extractSAPGLJournalId(final @NonNull CreateViewRequest request) { return Check.assumeNotNull(request.getParameterAs(VIEW_PARAM_SAP_GLJournal_ID, SAPGLJournalId.class), "No {} parameter provided", VIEW_PARAM_SAP_GLJournal_ID); } @Nullable private DocumentFilter getEffectiveFilter(final @NonNull CreateViewRequest request) { return request.getFiltersUnwrapped(getFilterDescriptor()) .getFilterById(OIViewFilterHelper.FILTER_ID) .orElse(null);
} private DocumentFilterDescriptor getFilterDescriptor() { DocumentFilterDescriptor filterDescriptor = this._filterDescriptor; if (filterDescriptor == null) { final AcctSchema primaryAcctSchema = acctSchemaBL.getPrimaryAcctSchema(ClientId.METASFRESH); final LookupDescriptorProviders lookupDescriptorProviders = lookupDataSourceFactory.getLookupDescriptorProviders(); filterDescriptor = this._filterDescriptor = OIViewFilterHelper.createFilterDescriptor(lookupDescriptorProviders, elementValueService, primaryAcctSchema); } return filterDescriptor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
public DataSource ordersDataSource() { DataSourceProperties primaryDataSourceProperties = ordersDataSourceProperties(); return DataSourceBuilder.create() .driverClassName(primaryDataSourceProperties.getDriverClassName()) .url(primaryDataSourceProperties.getUrl()) .username(primaryDataSourceProperties.getUsername()) .password(primaryDataSourceProperties.getPassword()) .build(); } @Bean public PlatformTransactionManager ordersTransactionManager() { EntityManagerFactory factory = ordersEntityManagerFactory().getObject(); return new JpaTransactionManager(factory); } @Bean public LocalContainerEntityManagerFactoryBean ordersEntityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(ordersDataSource()); factory.setPackagesToScan(new String[]{"net.alanbinu.springboot.springbootmultipledatasources.orders.entities"}); factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto")); jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql")); factory.setJpaProperties(jpaProperties);
return factory; } @Bean public DataSourceInitializer ordersDataSourceInitializer() { DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(ordersDataSource()); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("orders-data.sql")); dataSourceInitializer.setDatabasePopulator(databasePopulator); dataSourceInitializer.setEnabled(env.getProperty("datasource.orders.initialize", Boolean.class, false)); return dataSourceInitializer; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\config\OrdersDataSourceConfig.java
2
请完成以下Java代码
private TableRecordReference getTableRecordReferenceFromEventDescriptor(final SupplyRequiredDescriptor descriptor) { final TableRecordReference recordReference = TableRecordReference.ofNullable(I_C_Order.Table_Name, descriptor.getOrderId()); if (recordReference == null) { Loggables.withLogger(log, Level.ERROR).addLog("Could not trigger notification for event descriptor {}. Could not identify a DB record to reference.", descriptor); return null; } return recordReference; } private Set<UserId> getRecipients(@Nullable final MaterialPlanningContext context, @NonNull final SupplyRequiredDescriptor descriptor) { final Set<UserId> userIds = new HashSet<>(); final UserId plannerId = context == null ? null : context.getProductPlanning().getPlannerId(); if (plannerId != null && plannerId.isRegularUser()) { userIds.add(plannerId); } final OrderId orderId = OrderId.ofRepoIdOrNull(descriptor.getOrderId()); if (orderId != null) { final I_C_Order order = orderBL.getById(orderId); final UserId salesRepUserId = UserId.ofRepoIdOrNull(order.getSalesRep_ID()); if (salesRepUserId != null && salesRepUserId.isRegularUser()) { userIds.add(salesRepUserId); }
final UserId updatedByUserId = UserId.ofRepoIdOrNull(InterfaceWrapperHelper.getPO(order).getUpdatedBy()); if (updatedByUserId != null && updatedByUserId.isRegularUser()) { userIds.add(updatedByUserId); } } //deadletter recipient if (userIds.isEmpty()) { final UserId supervisorId = orgDAO.getOrgInfoById(descriptor.getOrgId()).getSupervisorId(); if (supervisorId != null && supervisorId.isRegularUser()) { userIds.add(supervisorId); } } return userIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredDecreasedNotificationProducer.java
1
请完成以下Java代码
public class BaseAuthor implements Serializable { private static final long serialVersionUID = 1L; @Id private Long id; private int age; private String name; private String genre; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre;
} public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Author{" + "name=" + name + "}"; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSubentities\src\main\java\com\bookstore\entity\BaseAuthor.java
1
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String userName; private String password; private String email; private String nickname; private String regTime; public User() { super(); } public User(String email, String nickname, String password, String userName, String regTime) { super(); this.email = email; this.nickname = nickname; this.password = password; this.userName = userName; this.regTime = regTime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getRegTime() { return regTime; } public void setRegTime(String regTime) { this.regTime = regTime; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\java\com\neo\domain\User.java
1
请完成以下Java代码
public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Ratio getPA_Ratio() throws RuntimeException { return (I_PA_Ratio)MTable.get(getCtx(), I_PA_Ratio.Table_Name) .getPO(getPA_Ratio_ID(), get_TrxName()); } /** Set Ratio. @param PA_Ratio_ID Performace Ratio */ public void setPA_Ratio_ID (int PA_Ratio_ID) { if (PA_Ratio_ID < 1) set_Value (COLUMNNAME_PA_Ratio_ID, null); else set_Value (COLUMNNAME_PA_Ratio_ID, Integer.valueOf(PA_Ratio_ID)); } /** Get Ratio.
@return Performace Ratio */ public int getPA_Ratio_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_PA_Measure.java
1
请完成以下Java代码
public abstract class Processor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** 业务组件列表(当前处理器需要处理的组件列表) */ protected List<BaseComponent> componentList; /** * 处理函数 * @param orderProcessContext */ public void handle(OrderProcessContext orderProcessContext) { overrideSuperComponentList(); // componentList为空
if (CollectionUtils.isEmpty(componentList)) { logger.error(this.getClass().getSimpleName() + "中componentList为空!"); throw new CommonSysException(ExpCodeEnum.COMPONENT_NULL); } // 依次执行所有业务组件 for (BaseComponent component : componentList) { component.handle(orderProcessContext); // 终止 if (orderProcessContext.isStop()) { break; } } } protected abstract void overrideSuperComponentList(); }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\processor\Processor.java
1
请完成以下Java代码
public static String moveDown(XMLStreamReader xtr) { try { while (xtr.hasNext()) { int event = xtr.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: return null; case XMLStreamConstants.START_ELEMENT: return xtr.getLocalName(); case XMLStreamConstants.END_ELEMENT: return null; } } } catch (Exception e) { LOGGER.warn("Error while moving down in XML document", e); } return null; }
public static boolean moveToEndOfElement(XMLStreamReader xtr, String elementName) { try { while (xtr.hasNext()) { int event = xtr.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: return false; case XMLStreamConstants.END_ELEMENT: if (xtr.getLocalName().equals(elementName)) return true; break; } } } catch (Exception e) { LOGGER.warn("Error while moving to end of element {}", elementName, e); } return false; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\XMLStreamReaderUtil.java
1
请完成以下Java代码
public Optional<ProductPlanning> retrieveActiveProductPlanningByProductAndSchemaId( @NonNull final ProductId productId, @NonNull final ProductPlanningSchemaId schemaId) { return queryBL.createQueryBuilder(I_PP_Product_Planning.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_M_Product_ID, productId) .addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_M_Product_PlanningSchema_ID, schemaId) .orderBy(I_PP_Product_Planning.COLUMN_SeqNo) .create() .firstOptional(I_PP_Product_Planning.class) .map(ProductPlanningDAO::fromRecord); } @Override public Stream<I_M_Product> streamProductsWithNoProductPlanningButWithSchemaSelector() { final IQuery<I_PP_Product_Planning> existentProductPlanning = queryBL.createQueryBuilder(I_PP_Product_Planning.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .create(); // TODO move it to ProductDAO return queryBL.createQueryBuilder(I_M_Product.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addNotInSubQueryFilter(I_M_Product.COLUMNNAME_M_Product_ID, I_PP_Product_Planning.COLUMNNAME_M_Product_ID, existentProductPlanning) .addNotNull(I_M_Product.COLUMN_M_ProductPlanningSchema_Selector) .create() .iterateAndStream(); } @Override public Optional<ProductPlanning> retrieveManufacturingOrTradingPlanning(@NonNull final ProductId productId, @NonNull final OrgId orgId) { final ICompositeQueryFilter<I_PP_Product_Planning> manufacturedOrTraded = queryBL.createCompositeQueryFilter(I_PP_Product_Planning.class) .setJoinOr() .addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_IsManufactured, X_PP_Product_Planning.ISMANUFACTURED_Yes)
.addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_IsTraded, X_PP_Product_Planning.ISTRADED_Yes); final I_PP_Product_Planning record = queryBL.createQueryBuilder(I_PP_Product_Planning.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_M_Product_ID, productId) .addInArrayOrAllFilter(I_PP_Product_Planning.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY) .filter(manufacturedOrTraded) .orderBy() .addColumn(I_PP_Product_Planning.COLUMNNAME_AD_Org_ID, Direction.Descending, Nulls.Last) // specific org first .addColumn(I_PP_Product_Planning.COLUMNNAME_IsManufactured, Direction.Descending, Nulls.Last) // 'Y' first, NULL last .addColumn(I_PP_Product_Planning.COLUMNNAME_IsTraded, Direction.Descending, Nulls.Last) // 'Y' first, NULL last .addColumn(I_PP_Product_Planning.COLUMNNAME_M_Warehouse_ID, Direction.Descending, Nulls.Last) .endOrderBy() .create() .first(); return record != null ? Optional.of(ProductPlanningDAO.fromRecord(record)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\planning\impl\ProductPlanningDAO.java
1
请完成以下Java代码
public CustomPropertiesResolver createExpressionCustomPropertiesResolver(ActivitiListener activitiListener) { return new ExpressionCustomPropertiesResolver( expressionManager.createExpression(activitiListener.getCustomPropertiesResolverImplementation()) ); } @Override public CustomPropertiesResolver createDelegateExpressionCustomPropertiesResolver( ActivitiListener activitiListener ) { return new DelegateExpressionCustomPropertiesResolver( expressionManager.createExpression(activitiListener.getCustomPropertiesResolverImplementation()) ); } /** * @param entityType * the name of the entity
* @return * @throws ActivitiIllegalArgumentException * when the given entity name */ protected Class<?> getEntityType(String entityType) { if (entityType != null) { Class<?> entityClass = ENTITY_MAPPING.get(entityType.trim()); if (entityClass == null) { throw new ActivitiIllegalArgumentException( "Unsupported entity-type for an ActivitiEventListener: " + entityType ); } return entityClass; } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultListenerFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class ConfigProperties { @Validated public static class Credentials { @Length(max = 4, min = 1) private String authMethod; private String username; private String password; public String getAuthMethod() { return authMethod; } public void setAuthMethod(String authMethod) { this.authMethod = authMethod; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } @NotBlank private String hostName; @Min(1025) @Max(65536) private int port; @Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$") private String from; private Credentials credentials; private List<String> defaultRecipients; private Map<String, String> additionalHeaders; public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public int getPort() { return port; } public void setPort(int port) { this.port = port; }
public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Credentials getCredentials() { return credentials; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } public List<String> getDefaultRecipients() { return defaultRecipients; } public void setDefaultRecipients(List<String> defaultRecipients) { this.defaultRecipients = defaultRecipients; } public Map<String, String> getAdditionalHeaders() { return additionalHeaders; } public void setAdditionalHeaders(Map<String, String> additionalHeaders) { this.additionalHeaders = additionalHeaders; } @Bean @ConfigurationProperties(prefix = "item") public Item item(){ return new Item(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\ConfigProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class PmsOperator extends PermissionBaseEntity { /** * */ private static final long serialVersionUID = 1L; private String loginName;// 登录名 private String loginPwd; // 登录密码 private String realName; // 姓名 private String mobileNo; // 手机号 private String type; // 操作员类型(admin:超级管理员,common:普通操作员),超级管理员由系统初始化时添加,不能删除 private String salt;// 盐 /** * 登录名 * * @return */ public String getLoginName() { return loginName; } /** * 登录名 * * @return */ public void setLoginName(String loginName) { this.loginName = loginName; } /** * 登录密码 * * @return */ public String getLoginPwd() { return loginPwd; } /** * 登录密码 * * @return */ public void setLoginPwd(String loginPwd) { this.loginPwd = loginPwd; } /** * 姓名 * * @return */ public String getRealName() { return realName; } /** * 姓名 * * @return */ public void setRealName(String realName) { this.realName = realName; } /** * 手机号 * * @return */ public String getMobileNo() { return mobileNo; } /** * 手机号 * * @return
*/ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } /** * 操作员类型 * * @return */ public String getType() { return type; } /** * 操作员类型 * * @return */ public void setType(String type) { this.type = type; } /** * 盐 * * @return */ public String getsalt() { return salt; } /** * 盐 * * @param salt */ public void setsalt(String salt) { this.salt = salt; } /** * 认证加密的盐 * * @return */ public String getCredentialsSalt() { return loginName + salt; } public PmsOperator() { } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperator.java
2
请完成以下Java代码
default IEditablePricingContext setQty(@NonNull final Quantity qty) { setQty(qty.toBigDecimal()); setUomId(qty.getUomId()); return this; } IEditablePricingContext setBPartnerId(BPartnerId bpartnerId); IEditablePricingContext setCurrencyId(@Nullable CurrencyId currencyId); IEditablePricingContext setPriceDate(LocalDate priceDate); IEditablePricingContext setPricingSystemId(PricingSystemId pricingSystemId); IEditablePricingContext setPriceListId(@Nullable PriceListId priceListId); IEditablePricingContext setPriceListVersionId(@Nullable PriceListVersionId priceListVersionId); IEditablePricingContext setProductId(ProductId productId); /** * Set this to <code>true</code> to indicate to the pricing engine that discounts shall <b>not</b> be computed and applied to the result. */ IEditablePricingContext setDisallowDiscount(boolean disallowDiscount); IEditablePricingContext setForcePricingConditionsBreak(PricingConditionsBreak forcePricingConditionsBreak); IEditablePricingContext setTrxName(String trxName); /**
* @see IPricingContext#isConvertPriceToContextUOM() */ IEditablePricingContext setConvertPriceToContextUOM(boolean convertPriceToContextUOM); IEditablePricingContext setProperty(String propertyName, Object value); default IEditablePricingContext setProperty(final String propertyName) { return setProperty(propertyName, Boolean.TRUE); } IEditablePricingContext setManualPriceEnabled(boolean manualPriceEnabled); /** * Note that either countryId or priceListId need to be provided. */ IEditablePricingContext setCountryId(@Nullable CountryId countryId); IEditablePricingContext setFailIfNotCalculated(); IEditablePricingContext setSkipCheckingPriceListSOTrxFlag(boolean skipCheckingPriceListSOTrxFlag); IEditablePricingContext setManualPrice(@Nullable final BigDecimal manualPrice); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\IEditablePricingContext.java
1
请完成以下Java代码
public class TbNodeUpgradeUtils { public static void upgradeConfigurationAndVersion(RuleNode node, RuleNodeClassInfo nodeInfo) { JsonNode oldConfiguration = node.getConfiguration(); int configurationVersion = node.getConfigurationVersion(); int currentVersion = nodeInfo.getCurrentVersion(); var configClass = nodeInfo.getAnnotation().configClazz(); if (oldConfiguration == null || !oldConfiguration.isObject()) { log.warn("Failed to upgrade rule node with id: {} type: {} fromVersion: {} toVersion: {}. " + "Current configuration is null or not a json object. " + "Going to set default configuration ... ", node.getId(), node.getType(), configurationVersion, currentVersion); node.setConfiguration(getDefaultConfig(configClass)); } else { var tbVersionedNode = getTbVersionedNode(nodeInfo); try { JsonNode queueName = oldConfiguration.get(QUEUE_NAME); TbPair<Boolean, JsonNode> upgradeResult = tbVersionedNode.upgrade(configurationVersion, oldConfiguration); if (upgradeResult.getFirst()) { node.setConfiguration(upgradeResult.getSecond()); if (nodeInfo.getAnnotation().hasQueueName() && queueName != null && queueName.isTextual()) { node.setQueueName(queueName.asText()); }
} } catch (Exception e) { try { JacksonUtil.treeToValue(oldConfiguration, configClass); } catch (Exception ex) { log.warn("Failed to upgrade rule node with id: {} type: {} fromVersion: {} toVersion: {}. " + "Going to set default configuration ... ", node.getId(), node.getType(), configurationVersion, currentVersion, e); node.setConfiguration(getDefaultConfig(configClass)); } } } node.setConfigurationVersion(currentVersion); } @SneakyThrows private static TbNode getTbVersionedNode(RuleNodeClassInfo nodeInfo) { return (TbNode) nodeInfo.getClazz().getDeclaredConstructor().newInstance(); } @SneakyThrows private static JsonNode getDefaultConfig(Class<? extends NodeConfiguration> configClass) { return JacksonUtil.valueToTree(configClass.getDeclaredConstructor().newInstance().defaultConfiguration()); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\utils\TbNodeUpgradeUtils.java
1
请在Spring Boot框架中完成以下Java代码
public RpUserPayConfig checkParamAndGetUserPayConfig(Object object, BindingResult bindingResult, HttpServletRequest httpServletRequest)throws BizException{ validator.validate(object, bindingResult); if (bindingResult.hasErrors()) {// 校验银行卡信息是否完整 String errorResponse = getErrorResponse(bindingResult); LOG.info("请求参数异常:{}", errorResponse); throw new PayBizException(PayBizException.REQUEST_PARAM_ERR, errorResponse); } Object jsonObject = JSONObject.toJSON(object); Map<String, Object> jsonParamMap = JSONObject.parseObject(jsonObject.toString(), Map.class); LOG.info("parseObject:" + jsonParamMap); String payKey = String.valueOf(jsonParamMap.get("payKey")); RpUserPayConfig rpUserPayConfig = rpUserPayConfigService.getByPayKey(payKey); if (rpUserPayConfig == null) { LOG.info("payKey[{}]的商户不存在", payKey); throw new PayBizException(PayBizException.USER_PAY_CONFIG_IS_NOT_EXIST, "用户异常"); } checkIp(rpUserPayConfig, httpServletRequest );// ip校验 String sign = String.valueOf(jsonParamMap.get("sign")); if (!MerchantApiUtil.isRightSign(jsonParamMap, rpUserPayConfig.getPaySecret(), sign)) { LOG.info("参数[{}],MD5签名验证异常sign:{}", jsonParamMap, sign);
throw new TradeBizException(TradeBizException.TRADE_ORDER_ERROR, "订单签名异常"); } return rpUserPayConfig; } /** * 获取错误返回信息 * * @param bindingResult * @return */ public String getErrorResponse(BindingResult bindingResult) { StringBuffer sb = new StringBuffer(); for (ObjectError objectError : bindingResult.getAllErrors()) { sb.append(objectError.getDefaultMessage()).append(","); } sb.delete(sb.length() - 1, sb.length()); return sb.toString(); } }
repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\service\CnpPayService.java
2
请完成以下Java代码
public class C_Invoice_Candidate_ApproveForInvoicing extends C_Invoice_Candidate_ProcessHelper { @Override protected boolean isApproveForInvoicing() { return true; } /** * Implementation detail: during `checkPreconditionsApplicable` `getProcessInfo` throws exception because it is not configured for the Process, so we ignore it. */ @Override protected IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters) { final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_C_Invoice_Candidate.class); if (includeProcessInfoFilters) { queryBuilder.filter(getProcessInfo().getQueryFilterOrElseFalse()); } queryBuilder.addFilter(getSelectionFilter()); queryBuilder.addOnlyActiveRecordsFilter() .addNotNull(I_C_Invoice_Candidate.COLUMNNAME_C_Currency_ID) .addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, true) // not processed .addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_ApprovalForInvoicing, true) // not already approved ; // Only selected rows final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (!selectedRowIds.isAll()) { final Set<Integer> invoiceCandidateIds = selectedRowIds.toIntSet(); if (invoiceCandidateIds.isEmpty()) { // shall not happen throw new AdempiereException("@NoSelection@"); } queryBuilder.addInArrayFilter(I_C_Invoice_Candidate.COLUMN_C_Invoice_Candidate_ID, invoiceCandidateIds); } return queryBuilder.create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_ApproveForInvoicing.java
1
请完成以下Java代码
public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) { this.currentProcessDefinition = currentProcessDefinition; } public FlowElement getCurrentFlowElement() { return currentFlowElement; } public void setCurrentFlowElement(FlowElement currentFlowElement) { this.currentFlowElement = currentFlowElement; } public ActivityImpl getCurrentActivity() { return currentActivity; } public void setCurrentActivity(ActivityImpl currentActivity) { this.currentActivity = currentActivity; } public void setCurrentSubProcess(SubProcess subProcess) { currentSubprocessStack.push(subProcess); } public SubProcess getCurrentSubProcess() { return currentSubprocessStack.peek(); } public void removeCurrentSubProcess() { currentSubprocessStack.pop(); } public void setCurrentScope(ScopeImpl scope) { currentScopeStack.push(scope); }
public ScopeImpl getCurrentScope() { return currentScopeStack.peek(); } public void removeCurrentScope() { currentScopeStack.pop(); } public BpmnParse setSourceSystemId(String systemId) { sourceSystemId = systemId; return this; } public String getSourceSystemId() { return this.sourceSystemId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
1
请完成以下Java代码
public ServerResponse.BodyBuilder varyBy(String... requestHeaders) { this.headers.setVary(Arrays.asList(requestHeaders)); return this; } @Override public ServerResponse build() { return build((request, response) -> null); } @Override public ServerResponse build(WriteFunction writeFunction) { return new WriteFunctionResponse(this.statusCode, this.headers, this.cookies, writeFunction); } @Override public ServerResponse body(Object body) { return GatewayEntityResponseBuilder.fromObject(body) .status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .build(); } @Override public <T> ServerResponse body(T body, ParameterizedTypeReference<T> bodyType) { return GatewayEntityResponseBuilder.fromObject(body, bodyType) .status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .build(); } @Override public ServerResponse render(String name, Object... modelAttributes) { return new GatewayRenderingResponseBuilder(name).status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .modelAttributes(modelAttributes) .build();
} @Override public ServerResponse render(String name, Map<String, ?> model) { return new GatewayRenderingResponseBuilder(name).status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .modelAttributes(model) .build(); } @Override public ServerResponse stream(Consumer<ServerResponse.StreamBuilder> streamConsumer) { return GatewayStreamingServerResponse.create(this.statusCode, this.headers, this.cookies, streamConsumer, null); } private static class WriteFunctionResponse extends AbstractGatewayServerResponse { private final WriteFunction writeFunction; WriteFunctionResponse(HttpStatusCode statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies, WriteFunction writeFunction) { super(statusCode, headers, cookies); Objects.requireNonNull(writeFunction, "WriteFunction must not be null"); this.writeFunction = writeFunction; } @Override protected @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { return this.writeFunction.write(request, response); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponseBuilder.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WeakPropertyChangeListener other = (WeakPropertyChangeListener)obj; final PropertyChangeListener thisDelegate = getDelegate(); final PropertyChangeListener otherDelegate = other.getDelegate(); if (thisDelegate == null) { if (otherDelegate != null) { return false; } } else if (!thisDelegate.equals(otherDelegate)) { return false; } return true; } public boolean isWeak() { return delegate == null; } public PropertyChangeListener getDelegate() { if (delegate != null) { return delegate; } final PropertyChangeListener delegate = delegateRef.get(); return delegate; } @Override public void propertyChange(final PropertyChangeEvent evt) { final boolean DEBUG = false;
final PropertyChangeListener delegate = getDelegate(); if (delegate == null) { // delegate reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("delegate of {0} is expired", this)); } return; } final Object source = evt.getSource(); final PropertyChangeEvent evtNew; if (source instanceof Reference) { final Reference<?> sourceRef = (Reference<?>)source; final Object sourceObj = sourceRef.get(); if (sourceObj == null) { // reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("sourceObj of {0} is expired", this)); } return; } evtNew = new PropertyChangeEvent(sourceObj, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); evtNew.setPropagationId(evt.getPropagationId()); } else { evtNew = evt; } delegate.propertyChange(evtNew); } @Override public String toString() { return "WeakPropertyChangeListener [delegate=" + delegate + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\WeakPropertyChangeListener.java
1
请在Spring Boot框架中完成以下Java代码
private List<String> processIgnoreAuthMethod(Class<?> clazz, Method method) { RequestMapping base = clazz.getAnnotation(RequestMapping.class); String[] baseUrl = Objects.nonNull(base) ? base.value() : new String[]{}; String[] uri = null; if (method.isAnnotationPresent(RequestMapping.class)) { uri = method.getAnnotation(RequestMapping.class).value(); } else if (method.isAnnotationPresent(GetMapping.class)) { uri = method.getAnnotation(GetMapping.class).value(); } else if (method.isAnnotationPresent(PostMapping.class)) { uri = method.getAnnotation(PostMapping.class).value(); } else if (method.isAnnotationPresent(PutMapping.class)) { uri = method.getAnnotation(PutMapping.class).value(); } else if (method.isAnnotationPresent(DeleteMapping.class)) { uri = method.getAnnotation(DeleteMapping.class).value(); } else if (method.isAnnotationPresent(PatchMapping.class)) { uri = method.getAnnotation(PatchMapping.class).value(); } return uri != null ? rebuildUrl(baseUrl, uri) : Collections.emptyList(); } private List<String> rebuildUrl(String[] bases, String[] uris) { List<String> urls = new ArrayList<>(); if (bases.length > 0) { for (String base : bases) { for (String uri : uris) { // 如果uri包含路径占位符, 则需要将其替换为* if (uri.matches(".*\\{.*}.*")) { uri = uri.replaceAll("\\{.*?}", "*"); }
urls.add(prefix(base) + prefix(uri)); } } } else { Arrays.stream(uris).forEach(uri -> { urls.add(prefix(uri)); }); } return urls; } private String prefix(String seg) { return seg.startsWith("/") ? seg : "/"+seg; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\ignore\IgnoreAuthPostProcessor.java
2
请完成以下Java代码
ClientGraphQlRequest getRequest() { return this.request; } Encoder<?> getEncoder() { return this.encoder; } Decoder<?> getDecoder() { return this.decoder; } @Override public ClientResponseField field(String path) { return new DefaultClientResponseField(this, super.field(path)); } @Override public <D> D toEntity(Class<D> type) { ClientResponseField field = field(""); D entity = field.toEntity(type); // should never happen because toEntity checks response.isValid if (entity == null) {
throw new FieldAccessException(getRequest(), this, field); } return entity; } @Override public <D> D toEntity(ParameterizedTypeReference<D> type) { ClientResponseField field = field(""); D entity = field.toEntity(type); // should never happen because toEntity checks response.isValid if (entity == null) { throw new FieldAccessException(getRequest(), this, field); } return entity; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultClientGraphQlResponse.java
1
请完成以下Java代码
public DeploymentCache<Object> getKnowledgeBaseCache() { return knowledgeBaseCache; } public void setKnowledgeBaseCache(DeploymentCache<Object> knowledgeBaseCache) { this.knowledgeBaseCache = knowledgeBaseCache; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; }
public ProcessDefinitionEntityManager getProcessDefinitionEntityManager() { return processDefinitionEntityManager; } public void setProcessDefinitionEntityManager(ProcessDefinitionEntityManager processDefinitionEntityManager) { this.processDefinitionEntityManager = processDefinitionEntityManager; } public DeploymentEntityManager getDeploymentEntityManager() { return deploymentEntityManager; } public void setDeploymentEntityManager(DeploymentEntityManager deploymentEntityManager) { this.deploymentEntityManager = deploymentEntityManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\DeploymentManager.java
1
请完成以下Java代码
public final LUTUAssignBuilder setHUPlanningReceiptOwnerPM(final boolean isHUPlanningReceiptOwnerPM) { assertConfigurable(); _isHUPlanningReceiptOwnerPM = isHUPlanningReceiptOwnerPM; return this; } private final boolean isHUPlanningReceiptOwnerPM() { return _isHUPlanningReceiptOwnerPM; } public LUTUAssignBuilder setDocumentLine(final IHUDocumentLine documentLine) { assertConfigurable(); _documentLine = documentLine; return this; } private IHUDocumentLine getDocumentLine() { return _documentLine; // null is ok } public LUTUAssignBuilder setC_BPartner(final I_C_BPartner bpartner) { assertConfigurable(); this._bpartnerId = bpartner != null ? BPartnerId.ofRepoId(bpartner.getC_BPartner_ID()) : null; return this; } private final BPartnerId getBPartnerId() { return _bpartnerId; } public LUTUAssignBuilder setC_BPartner_Location_ID(final int bpartnerLocationId) { assertConfigurable(); _bpLocationId = bpartnerLocationId; return this;
} private final int getC_BPartner_Location_ID() { return _bpLocationId; } public LUTUAssignBuilder setM_Locator(final I_M_Locator locator) { assertConfigurable(); _locatorId = LocatorId.ofRecordOrNull(locator); return this; } private LocatorId getLocatorId() { Check.assumeNotNull(_locatorId, "_locatorId not null"); return _locatorId; } public LUTUAssignBuilder setHUStatus(final String huStatus) { assertConfigurable(); _huStatus = huStatus; return this; } private String getHUStatus() { Check.assumeNotEmpty(_huStatus, "_huStatus not empty"); return _huStatus; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUAssignBuilder.java
1
请完成以下Java代码
public List<OrderCost> getByOrderId(@NonNull final OrderId orderId) { return newSession().getByOrderId(orderId); } public List<OrderCost> getByOrderIds(@NonNull final Set<OrderId> orderIds) { return newSession().getByOrderIds(orderIds); } public List<OrderCost> getByOrderLineIds(@NonNull final Set<OrderLineId> orderLineIds) { return newSession().getByOrderLineIds(orderLineIds); } public OrderCost getById(@NonNull final OrderCostId orderCostId) { return CollectionUtils.singleElement(getByIds(ImmutableSet.of(orderCostId))); } public List<OrderCost> getByIds(@NonNull final Collection<OrderCostId> orderCostIds) { return newSession().getByIds(orderCostIds); } public void saveAll(final Collection<OrderCost> orderCostsList) { newSession().saveAll(orderCostsList); } public void save(final OrderCost orderCost) { newSession().save(orderCost); } public void changeByOrderLineId(@NonNull final OrderLineId orderLineId, @NonNull final Consumer<OrderCost> consumer) { newSession().changeByOrderLineId(orderLineId, consumer); }
public void deleteDetails(@NonNull final OrderCostId orderCostId) { queryBL.createQueryBuilder(I_C_Order_Cost_Detail.class) .addEqualsFilter(I_C_Order_Cost_Detail.COLUMNNAME_C_Order_Cost_ID, orderCostId) .create() .delete(); } public boolean hasCostsByCreatedOrderLineIds(final ImmutableSet<OrderLineId> orderLineIds) { if (orderLineIds.isEmpty()) { return false; } return queryBL.createQueryBuilder(I_C_Order_Cost.class) .addInArrayFilter(I_C_Order_Cost.COLUMNNAME_Created_OrderLine_ID, orderLineIds) .create() .anyMatch(); } public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { final I_C_Order_Cost orderCostRecord = queryBL.createQueryBuilder(I_C_Order_Cost.class) .addEqualsFilter(I_C_Order_Cost.COLUMNNAME_C_Order_ID, createdOrderLineId.getOrderId()) .addEqualsFilter(I_C_Order_Cost.COLUMNNAME_Created_OrderLine_ID, createdOrderLineId.getOrderLineId()) .create() .firstOnly(); if (orderCostRecord == null) { return; } final OrderCostId orderCostId = OrderCostId.ofRepoId(orderCostRecord.getC_Order_Cost_ID()); deleteDetails(orderCostId); InterfaceWrapperHelper.delete(orderCostRecord, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepository.java
1
请完成以下Java代码
public class ResourceBundleELResolver extends ELResolver { public ResourceBundleELResolver() { super(); } @Override public Object getValue(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base instanceof ResourceBundle) { context.setPropertyResolved(base, property); if (property != null) { try { return ((ResourceBundle) base).getObject(property.toString()); } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; } @Override public Class<?> getType(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base instanceof ResourceBundle) { context.setPropertyResolved(base, property); /* * ResourceBundles are always read-only so fall-through to return null */ } return null; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { Objects.requireNonNull(context); if (base instanceof ResourceBundle) { context.setPropertyResolved(base, property); throw new PropertyNotWritableException("ELResolver not writable for type '" + base.getClass().getName() + "'");
} } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base instanceof ResourceBundle) { context.setPropertyResolved(base, property); return true; } return false; } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (base instanceof ResourceBundle) { return String.class; } return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ResourceBundleELResolver.java
1
请在Spring Boot框架中完成以下Java代码
JvmInfoMetrics jvmInfoMetrics() { return new JvmInfoMetrics(); } @Bean @ConditionalOnMissingBean JvmCompilationMetrics jvmCompilationMetrics() { return new JvmCompilationMetrics(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = VIRTUAL_THREAD_METRICS_CLASS) static class VirtualThreadMetricsConfiguration { @Bean @ConditionalOnMissingBean(type = VIRTUAL_THREAD_METRICS_CLASS) @ImportRuntimeHints(VirtualThreadMetricsRuntimeHintsRegistrar.class) MeterBinder virtualThreadMetrics() throws ClassNotFoundException { Class<?> virtualThreadMetricsClass = ClassUtils.forName(VIRTUAL_THREAD_METRICS_CLASS, getClass().getClassLoader()); return (MeterBinder) BeanUtils.instantiateClass(virtualThreadMetricsClass); }
} static final class VirtualThreadMetricsRuntimeHintsRegistrar implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection() .registerTypeIfPresent(classLoader, VIRTUAL_THREAD_METRICS_CLASS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\jvm\JvmMetricsAutoConfiguration.java
2
请完成以下Java代码
public class RuleChainEntity extends BaseVersionedEntity<RuleChain> { @Column(name = ModelConstants.RULE_CHAIN_TENANT_ID_PROPERTY) private UUID tenantId; @Column(name = ModelConstants.RULE_CHAIN_NAME_PROPERTY) private String name; @Enumerated(EnumType.STRING) @Column(name = ModelConstants.RULE_CHAIN_TYPE_PROPERTY) private RuleChainType type; @Column(name = ModelConstants.RULE_CHAIN_FIRST_RULE_NODE_ID_PROPERTY) private UUID firstRuleNodeId; @Column(name = ModelConstants.RULE_CHAIN_ROOT_PROPERTY) private boolean root; @Column(name = ModelConstants.DEBUG_MODE) private boolean debugMode; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.RULE_CHAIN_CONFIGURATION_PROPERTY) private JsonNode configuration; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.ADDITIONAL_INFO_PROPERTY) private JsonNode additionalInfo; @Column(name = ModelConstants.EXTERNAL_ID_PROPERTY) private UUID externalId; public RuleChainEntity() { } public RuleChainEntity(RuleChain ruleChain) { super(ruleChain); this.tenantId = DaoUtil.getId(ruleChain.getTenantId()); this.name = ruleChain.getName(); this.type = ruleChain.getType(); if (ruleChain.getFirstRuleNodeId() != null) { this.firstRuleNodeId = ruleChain.getFirstRuleNodeId().getId(); } this.root = ruleChain.isRoot();
this.debugMode = ruleChain.isDebugMode(); this.configuration = ruleChain.getConfiguration(); this.additionalInfo = ruleChain.getAdditionalInfo(); if (ruleChain.getExternalId() != null) { this.externalId = ruleChain.getExternalId().getId(); } } @Override public RuleChain toData() { RuleChain ruleChain = new RuleChain(new RuleChainId(this.getUuid())); ruleChain.setCreatedTime(createdTime); ruleChain.setVersion(version); ruleChain.setTenantId(TenantId.fromUUID(tenantId)); ruleChain.setName(name); ruleChain.setType(type); if (firstRuleNodeId != null) { ruleChain.setFirstRuleNodeId(new RuleNodeId(firstRuleNodeId)); } ruleChain.setRoot(root); ruleChain.setDebugMode(debugMode); ruleChain.setConfiguration(configuration); ruleChain.setAdditionalInfo(additionalInfo); if (externalId != null) { ruleChain.setExternalId(new RuleChainId(externalId)); } return ruleChain; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\RuleChainEntity.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Externe Datensatz-ID. @param RemoteRecordId Externe Datensatz-ID */ @Override public void setRemoteRecordId (java.lang.String RemoteRecordId) { set_Value (COLUMNNAME_RemoteRecordId, RemoteRecordId); } /** Get Externe Datensatz-ID. @return Externe Datensatz-ID */ @Override public java.lang.String getRemoteRecordId () { return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId); } /** Set Anfangsdatum. @param StartDate First effective day (inclusive)
*/ @Override public void setStartDate (java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Anfangsdatum. @return First effective day (inclusive) */ @Override public java.sql.Timestamp getStartDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Campaign.java
1
请完成以下Java代码
public PickingSlotRow getById(@NonNull final DocumentId id) throws EntityNotFoundException { return rows.getById(id); } @Override public LookupValuesPage getFilterParameterDropdown(final String filterId, final String filterParameterName, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public DocumentFilterList getStickyFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentFilterList getFilters() { return filters; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override
public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请在Spring Boot框架中完成以下Java代码
private Map<String,Object> getCpuInfo(CentralProcessor processor) { Map<String,Object> cpuInfo = new LinkedHashMap<>(); cpuInfo.put("name", processor.getProcessorIdentifier().getName()); cpuInfo.put("package", processor.getPhysicalPackageCount() + "个物理CPU"); cpuInfo.put("core", processor.getPhysicalProcessorCount() + "个物理核心"); cpuInfo.put("coreNumber", processor.getPhysicalProcessorCount()); cpuInfo.put("logic", processor.getLogicalProcessorCount() + "个逻辑CPU"); // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); // 默认等待300毫秒... long time = 300; Util.sleep(time); long[] ticks = processor.getSystemCpuLoadTicks(); while (Arrays.toString(prevTicks).equals(Arrays.toString(ticks)) && time < 1000){ time += 25; Util.sleep(25); ticks = processor.getSystemCpuLoadTicks(); } long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()]; long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal; cpuInfo.put("used", df.format(100d * user / totalCpu + 100d * sys / totalCpu)); cpuInfo.put("idle", df.format(100d * idle / totalCpu)); return cpuInfo; }
/** * 获取系统相关信息,系统、运行天数、系统IP * @param os / * @return / */ private Map<String,Object> getSystemInfo(OperatingSystem os){ Map<String,Object> systemInfo = new LinkedHashMap<>(); // jvm 运行时间 long time = ManagementFactory.getRuntimeMXBean().getStartTime(); Date date = new Date(time); // 计算项目运行时间 String formatBetween = DateUtil.formatBetween(date, new Date(), Level.HOUR); // 系统信息 systemInfo.put("os", os.toString()); systemInfo.put("day", formatBetween); systemInfo.put("ip", StringUtils.getLocalIp()); return systemInfo; } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\MonitorServiceImpl.java
2
请完成以下Java代码
public int getPP_Order_Receipt_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Receipt_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQualityInspectionCycle (final @Nullable java.lang.String QualityInspectionCycle) { set_ValueNoCheck (COLUMNNAME_QualityInspectionCycle, QualityInspectionCycle); } @Override public java.lang.String getQualityInspectionCycle() { return get_ValueAsString(COLUMNNAME_QualityInspectionCycle); }
@Override public void setRV_M_Material_Tracking_HU_Details_ID (final int RV_M_Material_Tracking_HU_Details_ID) { if (RV_M_Material_Tracking_HU_Details_ID < 1) set_ValueNoCheck (COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID, null); else set_ValueNoCheck (COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID, RV_M_Material_Tracking_HU_Details_ID); } @Override public int getRV_M_Material_Tracking_HU_Details_ID() { return get_ValueAsInt(COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_M_Material_Tracking_HU_Details.java
1
请完成以下Java代码
protected static EntityLinkEntity copyAndCreateEntityLink(String subScopeId, String parentElementId, String referenceScopeId, String referenceScopeType, String hierarchyType, EntityLink parentEntityLink, EntityLinkService entityLinkService, CmmnHistoryManager historyManager) { EntityLinkEntity newEntityLink = (EntityLinkEntity) entityLinkService.createEntityLink(); newEntityLink.setLinkType(EntityLinkType.CHILD); newEntityLink.setScopeId(parentEntityLink.getScopeId()); newEntityLink.setSubScopeId(subScopeId); newEntityLink.setScopeType(parentEntityLink.getScopeType()); newEntityLink.setScopeDefinitionId(parentEntityLink.getScopeDefinitionId()); newEntityLink.setParentElementId(parentElementId); newEntityLink.setReferenceScopeId(referenceScopeId); newEntityLink.setReferenceScopeType(referenceScopeType); newEntityLink.setHierarchyType(hierarchyType); newEntityLink.setRootScopeId(parentEntityLink.getRootScopeId()); newEntityLink.setRootScopeType(parentEntityLink.getRootScopeType()); entityLinkService.insertEntityLink(newEntityLink); historyManager.recordEntityLinkCreated(newEntityLink); return newEntityLink; } protected static EntityLinkEntity createEntityLink(String scopeId, String subScopeId, String parentElementId, String referenceScopeId, String referenceScopeType, String hierarchyType, String rootScopeId, String rootScopeType, EntityLinkService entityLinkService, CmmnHistoryManager historyManager) {
EntityLinkEntity newEntityLink = (EntityLinkEntity) entityLinkService.createEntityLink(); newEntityLink.setLinkType(EntityLinkType.CHILD); newEntityLink.setScopeId(scopeId); newEntityLink.setSubScopeId(subScopeId); newEntityLink.setScopeType(ScopeTypes.CMMN); newEntityLink.setParentElementId(parentElementId); newEntityLink.setReferenceScopeId(referenceScopeId); newEntityLink.setReferenceScopeType(referenceScopeType); newEntityLink.setHierarchyType(hierarchyType); newEntityLink.setRootScopeId(rootScopeId); newEntityLink.setRootScopeType(rootScopeType); entityLinkService.insertEntityLink(newEntityLink); historyManager.recordEntityLinkCreated(newEntityLink); return newEntityLink; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\EntityLinkUtil.java
1
请完成以下Java代码
public class MUserDefTab extends X_AD_UserDef_Tab { /** * */ private static final long serialVersionUID = -1211944378938157092L; @SuppressWarnings("unused") public MUserDefTab(Properties ctx, int AD_UserDef_Tab_ID, String trxName) { super(ctx, AD_UserDef_Tab_ID, trxName); } @SuppressWarnings("unused") public MUserDefTab(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } private MUserDefField[] getFields() { if (m_fields != null) { return m_fields; } final String whereClause = MUserDefField.COLUMNNAME_AD_UserDef_Tab_ID+"=?"; final List<MUserDefField> list = new Query(getCtx(), MUserDefField.Table_Name, whereClause, get_TrxName()) .setParameters(get_ID()) .setOnlyActiveRecords(true) .setOrderBy(MUserDefField.COLUMNNAME_AD_Field_ID) .list(MUserDefField.class); // m_fields = list.toArray(new MUserDefField[0]); return m_fields; } private MUserDefField[] m_fields = null; public MUserDefField getField(AdFieldId AD_Field_ID) { if (AD_Field_ID == null) { return null; } for (MUserDefField field : getFields()) { if (AD_Field_ID.getRepoId() == field.getAD_Field_ID()) { return field;
} } return null; } public void apply(GridTabVO vo) { final String name = getName(); if (!Check.isEmpty(name) && name.length() > 1) vo.setName(name); if (!Check.isEmpty(getDescription())) vo.setDescription(getDescription()); if (!Check.isEmpty(getHelp())) vo.setHelp(getHelp()); // vo.IsSingleRow = this.isSingleRow(); vo.setReadOnly(this.isReadOnly()); // vo.IsDeleteable // vo.IsHighVolume // vo.IsInsertRecord } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MUserDefTab.java
1
请完成以下Java代码
public Builder appendAllJoining(final String separator, final List<IStringExpression> expressionsToAppend) { if (expressionsToAppend.isEmpty()) { return this; } final IStringExpression separatorExpr = Check.isEmpty(separator) ? null : createConstantExpression(separator); boolean isFirstExpr = true; for (final IStringExpression expr : expressionsToAppend) { if (expr == null || expr.isNullExpression()) { continue; } if (separatorExpr != null && !isFirstExpr) { append(separatorExpr); } append(expr); isFirstExpr = false; } return this; } public Builder appendIfNotEmpty(@Nullable final String string) { if (isEmpty()) { return this; } return append(string); } public Builder append(final StringBuilder constant) { if (constant == null || constant.length() <= 0) { return this; } append(constant.toString()); return this; } public Builder append(final Builder otherBuilder) { for (final IStringExpression expr : otherBuilder.expressions) { append(expr); } if (otherBuilder._lastConstantBuffer != null && otherBuilder._lastConstantBuffer.length() > 0) { appendToLastConstantBuffer(otherBuilder._lastConstantBuffer.toString()); } return this; } public Builder append(final CtxName name) { append(new SingleParameterStringExpression(name.toStringWithMarkers(), name));
return this; } /** * Wraps the entire content of this builder using given wrapper. * After this method invocation the builder will contain only the wrapped expression. */ public Builder wrap(final IStringExpressionWrapper wrapper) { Check.assumeNotNull(wrapper, "Parameter wrapper is not null"); final IStringExpression expression = build(); final IStringExpression expressionWrapped = wrapper.wrap(expression); expressions.clear(); append(expressionWrapped); return this; } /** * If the {@link Condition} is <code>true</code> then it wraps the entire content of this builder using given wrapper. * After this method invocation the builder will contain only the wrapped expression. */ public Builder wrapIfTrue(final boolean condition, final IStringExpressionWrapper wrapper) { if (!condition) { return this; } return wrap(wrapper); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CompositeStringExpression.java
1
请完成以下Java代码
public int hashCode() { return 1; } @Override public boolean equals(final Object other) { if (other instanceof AttachmentEntryDataResource) { return Arrays.equals(source, ((AttachmentEntryDataResource)other).source); } else { return false; } } @Override @NonNull public String getFilename() {
return filename; } @Override public String getDescription() { return description; } @Override public long contentLength() { return source.length; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(source); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryDataResource.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiAuditConfig { @NonNull ApiAuditConfigId apiAuditConfigId; boolean active; @NonNull OrgId orgId; int seqNo; boolean isBypassAudit; boolean forceProcessedAsync; int keepRequestDays; int keepRequestBodyDays; int keepResponseDays; int keepResponseBodyDays; int keepErroredRequestDays; @Nullable HttpMethod method; @Nullable String pathPrefix; @Nullable NotificationTriggerType notifyUserInCharge; @Nullable UserGroupId userGroupInChargeId; /** * If true, then still both {@link org.compiere.model.I_API_Request_Audit} and {@link org.compiere.model.I_API_Response_Audit} records are written for the request, but in an asynchrounous way, while the actual requests might already have been performed. * This implies better performance for the caller, but: * <li>no {@link org.compiere.model.I_API_Request_Audit_Log} records will be created</li> * <li>Creating those audit reocrds might fail without the API caller noticing it</li> */ boolean performAuditAsync; /** * If true, the API response shall be wrapped into a {@link JsonApiResponse} * If false, it shall be communicated via a http response header. * Note that if {@link #performAuditAsync} is {@code true}, then the API response is never wrapped. */
boolean wrapApiResponse; @NonNull @Builder.Default @JsonIgnore // not needed in snapshot-testing AntPathMatcher antPathMatcher = new AntPathMatcher(); public boolean matchesRequest(@NonNull final String requestPath, @NonNull final String httpMethod) { final boolean isPathMatching = this.pathPrefix == null || requestPath.contains(this.pathPrefix) || antPathMatcher.match(pathPrefix, requestPath); final boolean isMethodMatching = this.method == null || httpMethod.equalsIgnoreCase(method.getCode()); return isMethodMatching && isPathMatching; } @NonNull public Optional<UserGroupId> getUserGroupToNotify(final boolean isError) { if (this.userGroupInChargeId == null || this.notifyUserInCharge == null || this.notifyUserInCharge.equals(NotificationTriggerType.NEVER) || (NotificationTriggerType.ONLY_ON_ERROR.equals(this.notifyUserInCharge) && !isError)) { return Optional.empty(); } return Optional.of(userGroupInChargeId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\config\ApiAuditConfig.java
2
请在Spring Boot框架中完成以下Java代码
public NursingHome email(String email) { this.email = email; return this; } /** * Get email * @return email **/ @Schema(example = "wagemann@berliner-stadtmission.de", description = "") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public NursingHome timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NursingHome nursingHome = (NursingHome) o; return Objects.equals(this._id, nursingHome._id) && Objects.equals(this.name, nursingHome.name) && Objects.equals(this.address, nursingHome.address) && Objects.equals(this.postalCode, nursingHome.postalCode) && Objects.equals(this.city, nursingHome.city) && Objects.equals(this.phone, nursingHome.phone) && Objects.equals(this.fax, nursingHome.fax) &&
Objects.equals(this.email, nursingHome.email) && Objects.equals(this.timestamp, nursingHome.timestamp); } @Override public int hashCode() { return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class NursingHome {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\NursingHome.java
2
请完成以下Java代码
public void setHR_Department_ID (int HR_Department_ID) { if (HR_Department_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Department_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Department_ID, Integer.valueOf(HR_Department_ID)); } /** Get Payroll Department. @return Payroll Department */ public int getHR_Department_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Department_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); }
/** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Department.java
1
请完成以下Java代码
default Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return ImmutableMap.of(); } // // Included documents (children) // @formatter:off default Collection<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); } // @formatter:on // // Attributes // @formatter:off default boolean hasAttributes() { return false; } default IViewRowAttributes getAttributes() { throw new EntityNotFoundException("Row does not support attributes"); } // @formatter:on // // IncludedView // @formatter:off default ViewId getIncludedViewId() { return null; } // @formatter:on //
// Single column row // @formatter:off /** @return true if frontend shall display one single column */ default boolean isSingleColumn() { return false; } /** @return text to be displayed if {@link #isSingleColumn()} */ default ITranslatableString getSingleColumnCaption() { return TranslatableStrings.empty(); } // @formatter:on /** * @return a stream of given row and all it's included rows recursively */ default Stream<IViewRow> streamRecursive() { return this.getIncludedRows() .stream() .map(IViewRow::streamRecursive) .reduce(Stream.of(this), Stream::concat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewRow.java
1
请完成以下Java代码
public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setM_MatchInv_ID (final int M_MatchInv_ID) { if (M_MatchInv_ID < 1) set_ValueNoCheck (COLUMNNAME_M_MatchInv_ID, null); else set_ValueNoCheck (COLUMNNAME_M_MatchInv_ID, M_MatchInv_ID); } @Override public int getM_MatchInv_ID() { return get_ValueAsInt(COLUMNNAME_M_MatchInv_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPosted (final boolean Posted) { set_ValueNoCheck (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override
public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setQty (final BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInUOM (final @Nullable BigDecimal QtyInUOM) { set_Value (COLUMNNAME_QtyInUOM, QtyInUOM); } @Override public BigDecimal getQtyInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInUOM); return bd != null ? bd : BigDecimal.ZERO; } /** * Type AD_Reference_ID=541716 * Reference name: M_MatchInv_Type */ public static final int TYPE_AD_Reference_ID=541716; /** Material = M */ public static final String TYPE_Material = "M"; /** Cost = C */ public static final String TYPE_Cost = "C"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchInv.java
1
请完成以下Java代码
public int retrieveTopLevelHuId(@NonNull final I_M_HU hu) { if (huStatusBL.isPhysicalHU(hu) || huStatusBL.isStatusShipped(hu)) { return handlingUnitsBL.getTopLevelParent(hu).getM_HU_ID(); } return -1; } public Optional<IPair<ProductId, Quantity>> retrieveProductAndQty(@NonNull final I_M_HU vhu) { final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); final IHUStorage vhuStorage = storageFactory.getStorage(vhu); if (vhuStorage == null) { return Optional.empty(); } final ProductId vhuProductId = vhuStorage.getSingleProductIdOrNull(); if (vhuProductId == null)
{ return Optional.empty(); } final I_C_UOM stockingUOM = productBL.getStockUOM(vhuProductId); final Quantity qty = vhuStorage.getQuantity(vhuProductId, stockingUOM); return Optional.of(ImmutablePair.of(vhuProductId, qty)); } public Optional<Quantity> retrieveProductQty(final HuId huId, final ProductId productId) { return retrieveProductAndQty(handlingUnitsBL.getById(huId)) .filter(productAndQty -> ProductId.equals(productAndQty.getLeft(), productId)) .map(IPair::getRight); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\HUAccessService.java
1
请完成以下Java代码
public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Binärwert. @param BinaryData Binary Data */ @Override public void setBinaryData (byte[] BinaryData) { set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData); } /** Get Binärwert. @return Binary Data */ @Override public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** Set Migriert am. @param MigrationDate Migriert am */ @Override public void setMigrationDate (java.sql.Timestamp MigrationDate) { set_Value (COLUMNNAME_MigrationDate, MigrationDate); } /** Get Migriert am. @return Migriert am */ @Override public java.sql.Timestamp getMigrationDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Mitteilung. @param TextMsg Text Message */ @Override
public void setTextMsg (java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Mitteilung. @return Text Message */ @Override public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java
1
请在Spring Boot框架中完成以下Java代码
public final class TransactionDescriptor { EventDescriptor eventDescriptor; int transactionId; ProductId productId; WarehouseId warehouseId; LocatorId locatorId; PPCostCollectorId costCollectorId; InOutLineId inoutLineId; MovementLineId movementLineId; InventoryLineId inventoryLineId; Instant transactionDate; BigDecimal movementQty; String movementType; List<HUDescriptor> huDescriptors; @Builder private TransactionDescriptor( final EventDescriptor eventDescriptor, final int transactionId, final ProductId productId, final WarehouseId warehouseId,
final LocatorId locatorId, final Instant transactionDate, final BigDecimal movementQty, // final PPCostCollectorId costCollectorId, final InOutLineId inoutLineId, final MovementLineId movementLineId, final InventoryLineId inventoryLineId, // final String movementType, @Singular final List<HUDescriptor> huDescriptors) { this.eventDescriptor = eventDescriptor; this.transactionId = transactionId; this.productId = productId; this.warehouseId = warehouseId; this.locatorId = locatorId; this.transactionDate = transactionDate; this.movementQty = movementQty; this.costCollectorId = costCollectorId; this.inoutLineId = inoutLineId; this.movementLineId = movementLineId; this.inventoryLineId = inventoryLineId; this.movementType = movementType; this.huDescriptors = huDescriptors; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\TransactionDescriptor.java
2
请完成以下Java代码
protected void dispatchExecutionCancelled(EventSubscriptionEntity eventSubscription, ExecutionEntity execution, CommandContext commandContext) { // subprocesses for (ExecutionEntity subExecution : execution.getExecutions()) { dispatchExecutionCancelled(eventSubscription, subExecution, commandContext); } // call activities ExecutionEntity subProcessInstance = commandContext.getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId()); if (subProcessInstance != null) { dispatchExecutionCancelled(eventSubscription, subProcessInstance, commandContext); } // activity with message/signal boundary events ActivityImpl activity = execution.getActivity(); if (activity != null && activity.getActivityBehavior() != null) { dispatchActivityCancelled(eventSubscription, execution, activity, commandContext); }
} protected void dispatchActivityCancelled(EventSubscriptionEntity eventSubscription, ExecutionEntity execution, ActivityImpl activity, CommandContext commandContext) { commandContext.getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createActivityCancelledEvent(activity.getId(), (String) activity.getProperties().get("name"), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), (String) activity.getProperties().get("type"), activity.getActivityBehavior().getClass().getCanonicalName(), eventSubscription), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\event\AbstractEventHandler.java
1
请完成以下Java代码
private RevolutPaymentExport toRevolutExport(@NonNull final I_Revolut_Payment_Export record) { final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID()); final CurrencyCode currencyCode = currencyDAO.getCurrencyCodeById(currencyId); final Amount amount = Amount.of(record.getAmount(), currencyCode); final TableRecordReference recordRef = TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()); return RevolutPaymentExport.builder() .revolutPaymentExportId(RevolutPaymentExportId.ofRepoId(record.getRevolut_Payment_Export_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .recordReference(recordRef) .name(record.getName()) .recipientType(RecipientType.ofCode(record.getRecipientType())) .accountNo(record.getAccountNo())
.routingNo(record.getRoutingNo()) .IBAN(record.getIBAN()) .SwiftCode(record.getSwiftCode()) .amount(amount) .recipientBankCountryId(CountryId.ofRepoIdOrNull(record.getRecipientBankCountryId())) .paymentReference(record.getPaymentReference()) .recipientCountryId(CountryId.ofRepoIdOrNull(record.getRecipientCountryId())) .regionName(record.getRegionName()) .addressLine1(record.getAddressLine1()) .addressLine2(record.getAddressLine2()) .city(record.getCity()) .postalCode(record.getPostalCode()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\RevolutExportRepo.java
1
请完成以下Java代码
public boolean isHandled(final Object model) { for (final IAttributeStorageFactory factory : factories) { if (factory.isHandled(model)) { return true; } } return false; } @Override public IAttributeStorage getAttributeStorage(@NonNull final Object model) { final IAttributeStorage storage = getAttributeStorageIfHandled(model); if (storage == null) { throw new AdempiereException("None of the registered factories can handle the given model") .appendParametersToMessage() .setParameter("model", model) .setParameter("this instance", this); } return storage; } @Override public IAttributeStorage getAttributeStorageIfHandled(final Object model) { for (final IAttributeStorageFactory factory : factories) { final IAttributeStorage storage = factory.getAttributeStorageIfHandled(model); if (storage != null) { return storage; } } return null; } @Override public final IHUAttributesDAO getHUAttributesDAO() { Check.assumeNotNull(huAttributesDAO, "huAttributesDAO not null"); return huAttributesDAO; }
@Override public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO) { this.huAttributesDAO = huAttributesDAO; for (final IAttributeStorageFactory factory : factories) { factory.setHUAttributesDAO(huAttributesDAO); } } @Override public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO(); } @Override public IHUStorageFactory getHUStorageFactory() { return huStorageFactory; } @Override public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory; for (final IAttributeStorageFactory factory : factories) { factory.setHUStorageFactory(huStorageFactory); } } @Override public void flush() { for (final IAttributeStorageFactory factory : factories) { factory.flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageFactory.java
1
请完成以下Java代码
public class X_C_JobCategory extends PO implements I_C_JobCategory, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_C_JobCategory (Properties ctx, int C_JobCategory_ID, String trxName) { super (ctx, C_JobCategory_ID, trxName); /** if (C_JobCategory_ID == 0) { setC_JobCategory_ID (0); setName (null); } */ } /** Load Constructor */ public X_C_JobCategory (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 2 - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_JobCategory[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Position Category. @param C_JobCategory_ID Job Position Category */ public void setC_JobCategory_ID (int C_JobCategory_ID) { if (C_JobCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_C_JobCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_C_JobCategory_ID, Integer.valueOf(C_JobCategory_ID)); } /** Get Position Category. @return Job Position Category */ public int getC_JobCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_JobCategory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobCategory.java
1
请完成以下Java代码
private static ClientRegistration.Builder withProviderConfiguration(AuthorizationServerMetadata metadata, String issuer) { String metadataIssuer = metadata.getIssuer().getValue(); Assert.state(issuer.equals(metadataIssuer), () -> "The Issuer \"" + metadataIssuer + "\" provided in the configuration metadata did " + "not match the requested issuer \"" + issuer + "\""); String name = URI.create(issuer).getHost(); ClientAuthenticationMethod method = getClientAuthenticationMethod(metadata.getTokenEndpointAuthMethods()); Map<String, Object> configurationMetadata = new LinkedHashMap<>(metadata.toJSONObject()); // @formatter:off return ClientRegistration.withRegistrationId(name) .userNameAttributeName(IdTokenClaimNames.SUB) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(method) .redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}") .authorizationUri((metadata.getAuthorizationEndpointURI() != null) ? metadata.getAuthorizationEndpointURI().toASCIIString() : null) .providerConfigurationMetadata(configurationMetadata) .tokenUri(metadata.getTokenEndpointURI().toASCIIString()) .issuerUri(issuer) .clientName(issuer); // @formatter:on } private static ClientAuthenticationMethod getClientAuthenticationMethod( List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
if (metadataAuthMethods == null || metadataAuthMethods .contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) { // If null, the default includes client_secret_basic return ClientAuthenticationMethod.CLIENT_SECRET_BASIC; } if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_POST)) { return ClientAuthenticationMethod.CLIENT_SECRET_POST; } if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.NONE)) { return ClientAuthenticationMethod.NONE; } return null; } private interface ThrowingFunction<S, T, E extends Throwable> { T apply(S src) throws E; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\registration\ClientRegistrations.java
1
请完成以下Java代码
public Long getId() { return this.id; } public String getContent() { return this.content; } public User getAuthor() { return this.author; } public void setId(Long id) { this.id = id; } public void setContent(String content) { this.content = content; } public void setAuthor(User author) { this.author = author; } @Override public boolean equals(Object o) { if (this == o) { return true;
} if (o == null || getClass() != o.getClass()) { return false; } Post post = (Post) o; return Objects.equals(id, post.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Post(id=" + this.getId() + ", content=" + this.getContent() + ", author=" + this.getAuthor() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\Post.java
1
请完成以下Java代码
protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.error("prepare - Unknown Parameter: " + name); } m_C_ProjectLine_ID = getRecord_ID(); } // prepare /** * Perform process. * @return Message (clear text) * @throws Exception if not successful */ protected String doIt() throws Exception { if (m_C_ProjectLine_ID == 0) throw new IllegalArgumentException("No Project Line"); MProjectLine projectLine = new MProjectLine (getCtx(), m_C_ProjectLine_ID, get_TrxName()); log.info("doIt - " + projectLine); if (projectLine.getM_Product_ID() == 0) throw new IllegalArgumentException("No Product"); // MProject project = new MProject (getCtx(), projectLine.getC_Project_ID(), get_TrxName()); if (project.getM_PriceList_ID() == 0) { throw new IllegalArgumentException("No PriceList"); } //
boolean isSOTrx = true; MProductPricing pp = new MProductPricing ( OrgId.ofRepoId(project.getAD_Org_ID()), projectLine.getM_Product_ID(), project.getC_BPartner_ID(), null, /* countryId */ projectLine.getPlannedQty(), isSOTrx); pp.setM_PriceList_ID(project.getM_PriceList_ID()); pp.setPriceDate(project.getDateContract()); // projectLine.setPlannedPrice(pp.getPriceStd()); projectLine.setPlannedMarginAmt(pp.getPriceStd().subtract(pp.getPriceLimit())); projectLine.save(); // String retValue = Msg.getElement(getCtx(), "PriceList") + pp.getPriceList() + " - " + Msg.getElement(getCtx(), "PriceStd") + pp.getPriceStd() + " - " + Msg.getElement(getCtx(), "PriceLimit") + pp.getPriceLimit(); return retValue; } // doIt } // ProjectLinePricing
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectLinePricing.java
1
请完成以下Spring Boot application配置
spring.application.name=Eurekaserver eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false server.port=8761 eureka.instance.hostname=localhost eureka.server.expected-client-renewal-interval-seconds=30 eureka.instance.lease-expiration-duration-in-seconds=90 eureka.server.eviction-interval-timer-in-ms=60000 eure
ka.server.renewal-percent-threshold=0.85 eureka.server.renewal-threshold-update-interval-ms=900000 eureka.server.enable-self-preservation=true
repos\tutorials-master\spring-cloud-modules\spring-cloud-eureka-self-preservation\spring-cloud-eureka-server\src\main\resources\application.properties
2
请完成以下Java代码
public void setAuthorizationEventPublisher(AuthorizationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "eventPublisher cannot be null"); this.eventPublisher = eventPublisher; } /** * Gets the {@link AuthorizationManager} used by this filter * @return the {@link AuthorizationManager} */ public AuthorizationManager<HttpServletRequest> getAuthorizationManager() { return this.authorizationManager; } public boolean isObserveOncePerRequest() { return this.observeOncePerRequest; } /** * Sets whether this filter apply only once per request. By default, this is * <code>false</code>, meaning the filter will execute on every request. Sometimes * users may wish it to execute more than once per request, such as when JSP forwards * are being used and filter security is desired on each included fragment of the HTTP * request. * @param observeOncePerRequest whether the filter should only be applied once per * request */ public void setObserveOncePerRequest(boolean observeOncePerRequest) { this.observeOncePerRequest = observeOncePerRequest; } /** * If set to true, the filter will be applied to error dispatcher. Defaults to * {@code true}. * @param filterErrorDispatch whether the filter should be applied to error dispatcher */ public void setFilterErrorDispatch(boolean filterErrorDispatch) { this.filterErrorDispatch = filterErrorDispatch;
} /** * If set to true, the filter will be applied to the async dispatcher. Defaults to * {@code true}. * @param filterAsyncDispatch whether the filter should be applied to async dispatch */ public void setFilterAsyncDispatch(boolean filterAsyncDispatch) { this.filterAsyncDispatch = filterAsyncDispatch; } private static class NoopAuthorizationEventPublisher implements AuthorizationEventPublisher { @Override public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication, T object, @Nullable AuthorizationResult result) { } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\intercept\AuthorizationFilter.java
1
请完成以下Java代码
public class C_RecurrentPaymentCreateInvoice extends JavaProcess { /** * Prepare - e.g., get Parameters. */ @Override protected void prepare() { // nothing to do } /** * Perform process. * * @return Message (clear text) * @throws Exception * if not successful */
@Override protected String doIt() throws Exception { final Timestamp startTime = SystemTime.asTimestamp(); final IBankingBL bankingBL = Services.get(IBankingBL.class); final List<I_C_Invoice> invoices = bankingBL.createInvoicesForRecurrentPayments(get_TrxName()); addLog("Created " + invoices.size() + " invoices in " + TimeUtil.formatElapsed(startTime)); return "@Success@"; } } // PaySelectionCreateCheck
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\C_RecurrentPaymentCreateInvoice.java
1
请完成以下Java代码
public boolean existsByTenantIdAndTypeAndStatusOneOf(TenantId tenantId, JobType type, JobStatus... statuses) { return jobRepository.existsByTenantIdAndTypeAndStatusIn(tenantId.getId(), type, Arrays.stream(statuses).toList()); } @Override public boolean existsByTenantIdAndEntityIdAndStatusOneOf(TenantId tenantId, EntityId entityId, JobStatus... statuses) { return jobRepository.existsByTenantIdAndEntityIdAndStatusIn(tenantId.getId(), entityId.getId(), Arrays.stream(statuses).toList()); } @Override public Job findOldestByTenantIdAndTypeAndStatusForUpdate(TenantId tenantId, JobType type, JobStatus status) { return DaoUtil.getData(jobRepository.findOldestByTenantIdAndTypeAndStatusForUpdate(tenantId.getId(), type.name(), status.name())); } @Override public void removeByTenantId(TenantId tenantId) { jobRepository.deleteByTenantId(tenantId.getId()); } @Override public int removeByEntityId(TenantId tenantId, EntityId entityId) { return jobRepository.deleteByEntityId(entityId.getId());
} @Override public EntityType getEntityType() { return EntityType.JOB; } @Override protected Class<JobEntity> getEntityClass() { return JobEntity.class; } @Override protected JpaRepository<JobEntity, UUID> getRepository() { return jobRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\job\JpaJobDao.java
1
请完成以下Java代码
private static String extractUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder, @NonNull final String rel) { for (final LinkDescription link : apiOrder.links()) { if (rel.contentEquals(link.rel())) { return link.href(); } } return null; } private static String toJson(final com.paypal.orders.Order apiOrder) { if (apiOrder == null) { return ""; } try { // IMPORTANT: we shall use paypal's JSON serializer, else we won't get any result return new com.braintreepayments.http.serializer.Json().serialize(apiOrder); } catch (final Exception ex)
{ logger.warn("Failed converting {} to JSON. Returning toString()", apiOrder, ex); return apiOrder.toString(); } } public PayPalOrder markRemoteDeleted(@NonNull final PayPalOrderId id) { final I_PayPal_Order existingRecord = getRecordById(id); final PayPalOrder order = toPayPalOrder(existingRecord) .toBuilder() .status(PayPalOrderStatus.REMOTE_DELETED) .build(); updateRecord(existingRecord, order); saveRecord(existingRecord); return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderRepository.java
1
请完成以下Java代码
public IView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = request.getViewId(); viewId.assertWindowId(WINDOW_ID); return OIView.builder() .viewId(viewId) .rowsData(getViewData(request)) .filterDescriptor(getFilterDescriptor()) .sapglJournalId(extractSAPGLJournalId(request)) .relatedProcess(createProcessDescriptor(10, OIView_Select.class)) .relatedProcess(createProcessDescriptor(20, OIView_AddToJournal.class)) .build(); } private RelatedProcessDescriptor createProcessDescriptor(final int sortNo, @NonNull final Class<?> processClass) { final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass); return RelatedProcessDescriptor.builder() .processId(processId) .anyTable().anyWindow() .displayPlace(RelatedProcessDescriptor.DisplayPlace.ViewQuickActions) .sortNo(sortNo) .build(); } private OIViewData getViewData(final @NonNull CreateViewRequest request) { final SAPGLJournalId sapglJournalId = extractSAPGLJournalId(request); final DocumentFilter effectiveFilter = getEffectiveFilter(request); final OIRowUserInputParts initialUserInput = extractInitialUserInput(request); return viewDataService.getData(sapglJournalId, effectiveFilter, initialUserInput); } @NonNull
private static OIRowUserInputParts extractInitialUserInput(final @NonNull CreateViewRequest request) { final OIRowUserInputParts initialUserInput = request.getParameterAs(VIEW_PARAM_InitialUserInput, OIRowUserInputParts.class); return initialUserInput != null ? initialUserInput : OIRowUserInputParts.EMPTY; } @NonNull private static SAPGLJournalId extractSAPGLJournalId(final @NonNull CreateViewRequest request) { return Check.assumeNotNull(request.getParameterAs(VIEW_PARAM_SAP_GLJournal_ID, SAPGLJournalId.class), "No {} parameter provided", VIEW_PARAM_SAP_GLJournal_ID); } @Nullable private DocumentFilter getEffectiveFilter(final @NonNull CreateViewRequest request) { return request.getFiltersUnwrapped(getFilterDescriptor()) .getFilterById(OIViewFilterHelper.FILTER_ID) .orElse(null); } private DocumentFilterDescriptor getFilterDescriptor() { DocumentFilterDescriptor filterDescriptor = this._filterDescriptor; if (filterDescriptor == null) { final AcctSchema primaryAcctSchema = acctSchemaBL.getPrimaryAcctSchema(ClientId.METASFRESH); final LookupDescriptorProviders lookupDescriptorProviders = lookupDataSourceFactory.getLookupDescriptorProviders(); filterDescriptor = this._filterDescriptor = OIViewFilterHelper.createFilterDescriptor(lookupDescriptorProviders, elementValueService, primaryAcctSchema); } return filterDescriptor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIViewFactory.java
1
请完成以下Java代码
public static MixedMoney sumOf(@NonNull final Collection<Money> collection) { if (collection.isEmpty()) { return MixedMoney.EMPTY; } final HashMap<CurrencyId, Money> map = new HashMap<>(); for (final Money money : collection) { map.compute(money.getCurrencyId(), (currencyId, currentMoney) -> currentMoney == null ? money : currentMoney.add(money)); } return new MixedMoney(map); } public String toString() { return MoreObjects.toStringHelper(this) .addValue(map.values()) .toString();
} public Optional<Money> toNoneOrSingleValue() { if (map.isEmpty()) { return Optional.empty(); } else if (map.size() == 1) { return map.values().stream().findFirst(); } else { throw new AdempiereException("Expected none or single value but got many: " + map.values()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\MixedMoney.java
1
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Window getAD_Window() throws RuntimeException { return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name) .getPO(getAD_Window_ID(), get_TrxName()); } /** Set Window. @param AD_Window_ID Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_Value (COLUMNNAME_AD_Window_ID, null); else set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Window. @return Data entry or display window */ public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribute. @param Attribute Attribute */
public void setAttribute (String Attribute) { set_Value (COLUMNNAME_Attribute, Attribute); } /** Get Attribute. @return Attribute */ public String getAttribute () { return (String)get_Value(COLUMNNAME_Attribute); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getAttribute()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Preference.java
1
请在Spring Boot框架中完成以下Java代码
public final class DataNeo4jAutoConfiguration { @Bean @ConditionalOnMissingBean Neo4jConversions neo4jConversions() { return new Neo4jConversions(); } @Bean @ConditionalOnMissingBean Neo4jManagedTypes neo4jManagedTypes(ApplicationContext applicationContext) throws ClassNotFoundException { Set<Class<?>> initialEntityClasses = new EntityScanner(applicationContext).scan(Node.class, RelationshipProperties.class); return Neo4jManagedTypes.fromIterable(initialEntityClasses); } @Bean @ConditionalOnMissingBean Neo4jMappingContext neo4jMappingContext(Neo4jManagedTypes managedTypes, Neo4jConversions neo4jConversions) { Neo4jMappingContext context = new Neo4jMappingContext(neo4jConversions); context.setManagedTypes(managedTypes); return context; } @Bean @ConditionalOnMissingBean DatabaseSelectionProvider databaseSelectionProvider(DataNeo4jProperties properties) { String database = properties.getDatabase(); return (database != null) ? DatabaseSelectionProvider.createStaticDatabaseSelectionProvider(database) : DatabaseSelectionProvider.getDefaultSelectionProvider(); } @Bean(Neo4jRepositoryConfigurationExtension.DEFAULT_NEO4J_CLIENT_BEAN_NAME) @ConditionalOnMissingBean Neo4jClient neo4jClient(Driver driver, DatabaseSelectionProvider databaseNameProvider) {
return Neo4jClient.create(driver, databaseNameProvider); } @Bean(Neo4jRepositoryConfigurationExtension.DEFAULT_NEO4J_TEMPLATE_BEAN_NAME) @ConditionalOnMissingBean(Neo4jOperations.class) Neo4jTemplate neo4jTemplate(Neo4jClient neo4jClient, Neo4jMappingContext neo4jMappingContext) { return new Neo4jTemplate(neo4jClient, neo4jMappingContext); } @Bean(Neo4jRepositoryConfigurationExtension.DEFAULT_TRANSACTION_MANAGER_BEAN_NAME) @ConditionalOnMissingBean(TransactionManager.class) Neo4jTransactionManager transactionManager(Driver driver, DatabaseSelectionProvider databaseNameProvider, ObjectProvider<TransactionManagerCustomizers> optionalCustomizers) { Neo4jTransactionManager transactionManager = new Neo4jTransactionManager(driver, databaseNameProvider); optionalCustomizers.ifAvailable((customizer) -> customizer.customize(transactionManager)); return transactionManager; } }
repos\spring-boot-4.0.1\module\spring-boot-data-neo4j\src\main\java\org\springframework\boot\data\neo4j\autoconfigure\DataNeo4jAutoConfiguration.java
2
请完成以下Java代码
protected PeriodUnit getPeriodUnit() { return periodUnit; } public String getReportType() { return reportType; } @CamundaQueryParam("reportType") public void setReportType(String reportType) { if (!VALID_REPORT_TYPE_VALUES.contains(reportType)) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "reportType parameter has invalid value: " + reportType); } this.reportType = reportType; } @CamundaQueryParam(value = "periodUnit", converter = PeriodUnitConverter.class) public void setPeriodUnit(PeriodUnit periodUnit) { this.periodUnit = periodUnit; }
protected List<? extends ReportResult> executeReportQuery(T report) { return report.duration(periodUnit); } public List<? extends ReportResult> executeReport(ProcessEngine engine) { T reportQuery = createNewReportQuery(engine); applyFilters(reportQuery); try { return executeReportQuery(reportQuery); } catch (NotValidException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); } } protected abstract T createNewReportQuery(ProcessEngine engine); protected abstract void applyFilters(T reportQuery); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AbstractReportDto.java
1
请在Spring Boot框架中完成以下Java代码
public User getUserDefault2(Long id, Throwable e) { System.out.println(e.getMessage()); User user = new User(); user.setId(-2L); user.setUsername("defaultUser2"); user.setPassword("123456"); return user; } public List<User> getUsers() { return this.restTemplate.getForObject("http://Server-Provider/user", List.class); } public String addUser() { User user = new User(1L, "mrbird", "123456"); HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode(); if (status.is2xxSuccessful()) { return "新增用户成功";
} else { return "新增用户失败"; } } @CacheRemove(commandKey = "getUserById") @HystrixCommand public void updateUser(@CacheKey("id") User user) { this.restTemplate.put("http://Server-Provider/user", user); } public void deleteUser(@PathVariable Long id) { this.restTemplate.delete("http://Server-Provider/user/{1}", id); } }
repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\Service\UserService.java
2
请完成以下Java代码
public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Container URL. @param CM_Container_URL_ID Contains info on used URLs */ public void setCM_Container_URL_ID (int CM_Container_URL_ID) { if (CM_Container_URL_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, Integer.valueOf(CM_Container_URL_ID)); } /** Get Container URL. @return Contains info on used URLs */ public int getCM_Container_URL_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_URL_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Last Result. @param Last_Result Contains data on the last check result */ public void setLast_Result (String Last_Result) { set_Value (COLUMNNAME_Last_Result, Last_Result);
} /** Get Last Result. @return Contains data on the last check result */ public String getLast_Result () { return (String)get_Value(COLUMNNAME_Last_Result); } /** Set Status. @param Status Status of the currently running check */ public void setStatus (String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ public String getStatus () { return (String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_URL.java
1
请完成以下Java代码
public CustomValueMapper createInstance() { Class<?> valueMapperClass = lookupClass(); CustomValueMapper valueMapper = null; if (valueMapperClass != null) { valueMapper = newInstance(valueMapperClass); if (valueMapper != null) { LOGGER.logSpinValueMapperDetected(); } } // else: engine plugin is not on classpath return valueMapper; } protected CustomValueMapper newInstance(Class<?> valueMapperClass) { try { return (CustomValueMapper) valueMapperClass.newInstance(); } catch (InstantiationException e) { throw LOGGER.spinValueMapperInstantiationException(e); } catch (IllegalAccessException e) { throw LOGGER.spinValueMapperAccessException(e); } catch (ClassCastException e) { throw LOGGER.spinValueMapperCastException(e, CustomValueMapper.class.getName()); } catch (Throwable e) { throw LOGGER.spinValueMapperException(e);
} } protected Class<?> lookupClass() { try { return Class.forName(SPIN_VALUE_MAPPER_CLASS_NAME); } catch (ClassNotFoundException ignored) { // engine plugin is not on class path => ignore } catch (Throwable e) { throw LOGGER.spinValueMapperException(e); } return null; } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\spin\SpinValueMapperFactory.java
1
请完成以下Java代码
String toString(int indentFactor, int indent) throws JSONException { int len = length(); if (len == 0) { return "[]"; } int i; StringBuilder sb = new StringBuilder("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); } /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. * <p>
* Warning: This method assumes that the signalData structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject) v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray) v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONArray.java
1
请完成以下Java代码
public void dispose() { final CacheMgt cacheManager = CacheMgt.get(); CACHE_RESET_TABLE_NAMES.forEach(tableName -> cacheManager.removeCacheResetListener(tableName, this)); } @Override public long reset(final CacheInvalidateMultiRequest multiRequest) { doConvert("cache reset on " + multiRequest); return 1; } private final Properties getCtx() { return Env.getCtx(); } @Override public void vetoableChange(final PropertyChangeEvent evt) throws PropertyVetoException { // Try apply UOM conversion doConvert("" + evt.getPropertyName() + " field changed"); } private I_M_Product getM_Product() { return toModel(I_M_Product.class, fieldProduct.getValue()); } private I_C_UOM getC_UOM() { return toModel(I_C_UOM.class, fieldUOM.getValue()); } private I_C_UOM getC_UOM_To() { return toModel(I_C_UOM.class, fieldUOMTo.getValue()); } private BigDecimal getQty() { final BigDecimal qty = (BigDecimal)fieldQty.getValue(); return qty == null ? BigDecimal.ZERO : qty; } private void setQtyConv(final BigDecimal qtyConv) { fieldQtyConv.setValue(qtyConv, true); } private void setDescription(final String description) { fieldDescription.setValue(description, true); } private <T> T toModel(final Class<T> modelClass, final Object idObj) { final int id = toID(idObj); if (id <= 0) { return null; } return InterfaceWrapperHelper.create(getCtx(), id, modelClass, ITrx.TRXNAME_None); } private static final int toID(final Object idObj) { if (idObj == null) { return -1; } else if (idObj instanceof Number) { return ((Number)idObj).intValue(); } else { return -1; } } private void doConvert(final String reason) { // Reset setDescription(null);
setQtyConv(null); final I_C_UOM uomFrom = getC_UOM(); final I_C_UOM uomTo = getC_UOM_To(); if (uomFrom == null || uomTo == null) { return; } final I_M_Product product = getM_Product(); final BigDecimal qty = getQty(); try { final BigDecimal qtyConv; if (product != null) { final UOMConversionContext conversionCtx = UOMConversionContext.of(product); qtyConv = uomConversionBL.convertQty(conversionCtx, qty, uomFrom, uomTo); } else { qtyConv = uomConversionBL.convert(uomFrom, uomTo, qty).orElse(null); } setQtyConv(qtyConv); setDescription("Converted " + NumberUtils.stripTrailingDecimalZeros(qty) + " " + uomFrom.getUOMSymbol() + " to " + NumberUtils.stripTrailingDecimalZeros(qtyConv) + " " + uomTo.getUOMSymbol() + "<br>Product: " + (product == null ? "-" : product.getName()) + "<br>Reason: " + reason); } catch (final Exception e) { setDescription(e.getLocalizedMessage()); // because this is a test form, printing the exception directly to console it's totally fine. // More, if we would log it as WARNING/SEVERE, an AD_Issue would be created, but we don't want that. e.printStackTrace(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\uom\form\UOMConversionCheckFormPanel.java
1
请完成以下Java代码
public void deleteDeployment(String deploymentId) { deleteEventDefinitionsForDeployment(deploymentId); deleteChannelDefinitionsForDeployment(deploymentId); getResourceEntityManager().deleteResourcesByDeploymentId(deploymentId); delete(findById(deploymentId)); } protected void deleteEventDefinitionsForDeployment(String deploymentId) { getEventDefinitionEntityManager().deleteEventDefinitionsByDeploymentId(deploymentId); } protected void deleteChannelDefinitionsForDeployment(String deploymentId) { getChannelDefinitionEntityManager().deleteChannelDefinitionsByDeploymentId(deploymentId); } @Override public long findDeploymentCountByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentCountByQueryCriteria(deploymentQuery); } @Override public List<EventDeployment> findDeploymentsByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentsByQueryCriteria(deploymentQuery); } @Override public List<String> getDeploymentResourceNames(String deploymentId) { return dataManager.getDeploymentResourceNames(deploymentId); } @Override public List<EventDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentsByNativeQuery(parameterMap); }
@Override public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentCountByNativeQuery(parameterMap); } protected EventResourceEntityManager getResourceEntityManager() { return engineConfiguration.getResourceEntityManager(); } protected EventDefinitionEntityManager getEventDefinitionEntityManager() { return engineConfiguration.getEventDefinitionEntityManager(); } protected ChannelDefinitionEntityManager getChannelDefinitionEntityManager() { return engineConfiguration.getChannelDefinitionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDeploymentEntityManagerImpl.java
1
请完成以下Java代码
public void setCategory(String category) { this.category = category; } public String getTaskIdVariableName() { return taskIdVariableName; } public void setTaskIdVariableName(String taskIdVariableName) { this.taskIdVariableName = taskIdVariableName; } public String getTaskCompleterVariableName() { return taskCompleterVariableName; } public void setTaskCompleterVariableName(String taskCompleterVariableName) { this.taskCompleterVariableName = taskCompleterVariableName; } public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } public List<FlowableListener> getTaskListeners() { return taskListeners; }
public void setTaskListeners(List<FlowableListener> taskListeners) { this.taskListeners = taskListeners; } @Override public HumanTask clone() { HumanTask clone = new HumanTask(); clone.setValues(this); return clone; } public void setValues(HumanTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setSameDeployment(otherElement.isSameDeployment()); setValidateFormFields(otherElement.getValidateFormFields()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setTaskIdVariableName(otherElement.getTaskIdVariableName()); setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName()); setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers())); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\HumanTask.java
1
请完成以下Java代码
private InvoiceChangedEvent createInvoiceChangedEvent(final I_C_Invoice invoice, final boolean reversal) { return InvoiceChangedEvent.builder() .invoiceId(InvoiceId.ofRepoId(invoice.getC_Invoice_ID())) .invoiceDate(TimeUtil.asLocalDate(invoice.getDateInvoiced())) .bpartnerId(BPartnerId.ofRepoId(invoice.getC_BPartner_ID())) .soTrx(SOTrx.ofBoolean(invoice.isSOTrx())) .reversal(reversal) .productPrices(extractProductPrices(invoice)) .build(); } private ImmutableList<ProductPrice> extractProductPrices(final I_C_Invoice invoice) { final IInvoiceDAO invoicesRepo = Services.get(IInvoiceDAO.class); final CurrencyId currencyId = CurrencyId.ofRepoId(invoice.getC_Currency_ID()); final ImmutableMap<ProductId, Money> pricesByProductId = invoicesRepo.retrieveLines(invoice) .stream() .filter(invoiceLine -> invoiceLine.getM_Product_ID() > 0) .collect(ImmutableMap.toImmutableMap( invoiceLine -> ProductId.ofRepoId(invoiceLine.getM_Product_ID()), // keyMapper invoiceLine -> Money.of(invoiceLine.getPriceActual(), currencyId), // valueMapper Money::max)); // mergeFunction
return pricesByProductId.keySet() .stream() .map(productId -> ProductPrice.builder() .productId(productId) .price(pricesByProductId.get(productId)) .build()) .collect(ImmutableList.toImmutableList()); } private boolean isCreditMemo(final I_C_Invoice invoice) { final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); return invoiceBL.isCreditMemo(invoice); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\interceptor\C_Invoice.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthResource { private final Logger log = LoggerFactory.getLogger(AuthResource.class); private OAuth2AuthenticationService authenticationService; public AuthResource(OAuth2AuthenticationService authenticationService) { this.authenticationService = authenticationService; } /** * Authenticates a user setting the access and refresh token cookies. * * @param request the HttpServletRequest holding - among others - the headers passed from the client. * @param response the HttpServletResponse getting the cookies set upon successful authentication. * @param params the login params (username, password, rememberMe). * @return the access token of the authenticated user. Will return an error code if it fails to authenticate the user. */ @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType .APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, String> params) {
return authenticationService.authenticate(request, response, params); } /** * Logout current user deleting his cookies. * * @param request the HttpServletRequest holding - among others - the headers passed from the client. * @param response the HttpServletResponse getting the cookies set upon successful authentication. * @return an empty response entity. */ @RequestMapping(value = "/logout", method = RequestMethod.POST) @Timed public ResponseEntity<?> logout(HttpServletRequest request, HttpServletResponse response) { log.info("logging out user {}", SecurityContextHolder.getContext().getAuthentication().getName()); authenticationService.logout(request, response); return ResponseEntity.noContent().build(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\web\rest\AuthResource.java
2
请在Spring Boot框架中完成以下Java代码
public Amount getTotalDueSeller() { return totalDueSeller; } public void setTotalDueSeller(Amount totalDueSeller) { this.totalDueSeller = totalDueSeller; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentSummary paymentSummary = (PaymentSummary)o; return Objects.equals(this.payments, paymentSummary.payments) && Objects.equals(this.refunds, paymentSummary.refunds) && Objects.equals(this.totalDueSeller, paymentSummary.totalDueSeller); } @Override public int hashCode() { return Objects.hash(payments, refunds, totalDueSeller); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentSummary {\n"); sb.append(" payments: ").append(toIndentedString(payments)).append("\n");
sb.append(" refunds: ").append(toIndentedString(refunds)).append("\n"); sb.append(" totalDueSeller: ").append(toIndentedString(totalDueSeller)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PaymentSummary.java
2
请完成以下Java代码
public Object execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); AttachmentEntity updateAttachment = processEngineConfiguration.getAttachmentEntityManager().findById(attachment.getId()); String processInstanceId = updateAttachment.getProcessInstanceId(); String processDefinitionId = null; if (updateAttachment.getProcessInstanceId() != null) { ExecutionEntity process = processEngineConfiguration.getExecutionEntityManager().findById(processInstanceId); if (process != null) { processDefinitionId = process.getProcessDefinitionId(); if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, process.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.saveAttachment(attachment); return null; } }
} updateAttachment.setName(attachment.getName()); updateAttachment.setDescription(attachment.getDescription()); FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, attachment, processInstanceId, processInstanceId, processDefinitionId), processEngineConfiguration.getEngineCfgKey()); } return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SaveAttachmentCmd.java
1
请完成以下Java代码
public class ExpressionCaseLifecycleListener implements CaseInstanceLifecycleListener { protected String sourceState; protected String targetState; protected Expression expression; public ExpressionCaseLifecycleListener(String sourceState, String targetState, Expression expression) { this.sourceState = sourceState; this.targetState = targetState; this.expression = expression; } @Override public String getSourceState() { return sourceState; } @Override public String getTargetState() {
return targetState; } @Override public void stateChanged(CaseInstance caseInstance, String oldState, String newState) { expression.getValue((CaseInstanceEntity) caseInstance); } /** * returns the expression text for this case instance lifecycle listener. */ public String getExpressionText() { return expression.getExpressionText(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\listener\ExpressionCaseLifecycleListener.java
1
请完成以下Java代码
public String getLoopDataOutputRef() { return loopDataOutputRef; } public void setLoopDataOutputRef(String loopDataOutputRef) { this.loopDataOutputRef = loopDataOutputRef; } public String getOutputDataItem() { return outputDataItem; } public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; }
public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; } public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setLoopDataOutputRef(otherLoopCharacteristics.getLoopDataOutputRef()); setOutputDataItem(otherLoopCharacteristics.getOutputDataItem()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请完成以下Java代码
public void validateSOTrx(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { validatePositiveAmountDocType(docTypeInvoicingPoolRecord); validateNegativeAmountDocType(docTypeInvoicingPoolRecord); } @ModelChange( timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_DocType_Invoicing_Pool.COLUMNNAME_IsActive) public void validateInactivation(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { if (docTypeInvoicingPoolRecord.isActive()) { return; } final ImmutableSet<DocTypeId> referencingDocTypeIds = docTypeBL .getDocTypeIdsByInvoicingPoolId(DocTypeInvoicingPoolId.ofRepoId(docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID())); if (!referencingDocTypeIds.isEmpty()) { throw new AdempiereException(MSG_REFERENCED_INVOICING_POOL) .markAsUserValidationError() .appendParametersToMessage() .setParameter("DocTypeIds", referencingDocTypeIds) .setParameter("DocTypeInvoicingPoolId", docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID()); } } private void validatePositiveAmountDocType(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { final DocTypeId positiveAmountDocTypeId = DocTypeId.ofRepoId(docTypeInvoicingPoolRecord.getPositive_Amt_C_DocType_ID()); validateDocType(positiveAmountDocTypeId, docTypeInvoicingPoolRecord); } private void validateNegativeAmountDocType(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord)
{ final DocTypeId negativeAmountDocTypeId = DocTypeId.ofRepoId(docTypeInvoicingPoolRecord.getNegative_Amt_C_DocType_ID()); validateDocType(negativeAmountDocTypeId, docTypeInvoicingPoolRecord); } private void validateDocType( @NonNull final DocTypeId docTypeId, @NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { final I_C_DocType docTypeRecord = docTypeBL.getById(docTypeId); if (docTypeRecord.isSOTrx() != docTypeInvoicingPoolRecord.isSOTrx()) { throw new AdempiereException(MSG_DIFFERENT_SO_TRX_INVOICING_POOL_DOCUMENT_TYPE) .markAsUserValidationError() .appendParametersToMessage() .setParameter("DocType.Name", docTypeRecord.getName()) .setParameter("DocTypeInvoicingPoolId", docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\invoicingpool\C_DocType_Invoicing_Pool.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; private int price; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id") private Author author; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; }
public void setIsbn(String isbn) { this.isbn = isbn; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Book)) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaFullJoins\src\main\java\com\bookstore\entity\Book.java
2
请在Spring Boot框架中完成以下Java代码
public class ShipperTransportationDocActionCustomizer implements IDocActionOptionsCustomizer { @Override public String getAppliesToTableName() { return I_M_ShipperTransportation.Table_Name; } @Override public void customizeValidActions(final DocActionOptionsContext optionsCtx) { final Set<String> docActions = new LinkedHashSet<>(optionsCtx.getDocActions()); final String docStatus = optionsCtx.getDocStatus(); if (IDocument.STATUS_Drafted.equals(docStatus)) {
// remove the void option when Drafted docActions.remove(IDocument.ACTION_Void); } // Complete .. CO else if (IDocument.STATUS_Completed.equals(docStatus)) { docActions.add(IDocument.ACTION_ReActivate); } // // Correct options optionsCtx.setDocActions(ImmutableSet.copyOf(docActions)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\ShipperTransportationDocActionCustomizer.java
2
请完成以下Java代码
public void beforeComplete(final I_C_Flatrate_Conditions cond) { final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class); final boolean matchingsAreRequired = X_C_Flatrate_Conditions.TYPE_CONDITIONS_HoldingFee.equals(cond.getType_Conditions()) || X_C_Flatrate_Conditions.TYPE_CONDITIONS_Refundable.equals(cond.getType_Conditions()) || X_C_Flatrate_Conditions.TYPE_CONDITIONS_FlatFee.equals(cond.getType_Conditions()) || X_C_Flatrate_Conditions.TYPE_CONDITIONS_QualityBasedInvoicing.equals(cond.getType_Conditions()); if (matchingsAreRequired) { // 03660 for subscriptions, we don't strictly require mappings anymore, // because it's simply impractical for multi-org-setups final List<I_C_Flatrate_Matching> matchings = flatrateDB.retrieveFlatrateMatchings(cond); if (matchings.isEmpty()) { throw new AdempiereException(MSG_CONDITIONS_ERROR_MATCHING_MISSING_0P); } } final boolean hasHoCompletedTransition = cond.getC_Flatrate_Transition_ID() <= 0 || !X_C_Flatrate_Transition.DOCSTATUS_Completed.equals(cond.getC_Flatrate_Transition().getDocStatus());
if (hasHoCompletedTransition) { throw new AdempiereException(MSG_CONDITIONS_ERROR_TRANSITION_NOT_CO_0P); } } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE }) public void beforeReactivate(final I_C_Flatrate_Conditions cond) { // check if the conditions are already used somewhere final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class); final List<I_C_Flatrate_Term> terms = flatrateDB.retrieveTerms(cond); if (!terms.isEmpty()) { throw new AdempiereException(MSG_CONDITIONS_ERROR_ALREADY_IN_USE_0P); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_Conditions.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean SecurityWebFilterChain filterChain(ServerHttpSecurity http) { // @formatter:off return http .authorizeExchange(exchanges -> exchanges .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() .anyExchange().authenticated()) .formLogin(Customizer.withDefaults()) .sessionManagement((sessions) -> sessions .concurrentSessions((concurrency) -> concurrency .maximumSessions((authentication) -> { if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_UNLIMITED_SESSIONS"))) { return Mono.empty(); } return Mono.just(1); }) .maximumSessionsExceededHandler(new PreventLoginServerMaximumSessionsExceededHandler()) ) ) .build(); // @formatter:on }
@Bean <S extends Session> SpringSessionBackedReactiveSessionRegistry<S> sessionRegistry( ReactiveSessionRepository<S> sessionRepository, ReactiveFindByIndexNameSessionRepository<S> indexedSessionRepository) { return new SpringSessionBackedReactiveSessionRegistry<>(sessionRepository, indexedSessionRepository); } @Bean MapReactiveUserDetailsService reactiveUserDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails unlimited = User.withDefaultPasswordEncoder() .username("unlimited") .password("password") .roles("USER", "UNLIMITED_SESSIONS") .build(); return new MapReactiveUserDetailsService(user, unlimited); } }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-reactive-max-sessions\src\main\java\com\example\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class JasperExecuteReportStrategy implements ExecuteReportStrategy { private static final String SYS_CONFIG_MOCK_REPORT_SERVICE = "de.metas.report.jasper.IsMockReportService"; private static final String MOCK_CUCUMBER_REPORT_FILENAME = "test_filename.pdf"; private static final String MOCK_CUCUMBER_REPORT_DATA = "dGVzdA=="; @Override public ExecuteReportResult executeReport( @NonNull final ProcessInfo processInfo, @Nullable final OutputType outputType) { final OutputType outputTypeEffective = Check.assumeNotNull( CoalesceUtil.coalesce( outputType, processInfo.getJRDesiredOutputType()), "From the given parameters, either outputType or processInfo.getJRDesiredOutputType() need to be non-null; processInfo={}", processInfo); final ReportResult reportResult = getReportResult(processInfo, outputTypeEffective); final byte[] reportData = reportResult.getReportContent(); final String reportFilename = reportResult.getReportFilename(); if (Check.isBlank(reportFilename)) // if the report returns some blanks, we ignore them { return ExecuteReportResult.of(outputTypeEffective, new ByteArrayResource(reportData)); } else { return ExecuteReportResult.of(reportFilename, outputTypeEffective, new ByteArrayResource(reportData)); } } private ReportResult getReportResult( @NonNull final ProcessInfo processInfo, @NonNull final OutputType outputType) {
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); //dev-note: workaround to mock jasper reports during cucumber tests if (sysConfigBL.getBooleanValue(SYS_CONFIG_MOCK_REPORT_SERVICE, false)) { return ReportResult.builder() .outputType(outputType) .reportFilename(MOCK_CUCUMBER_REPORT_FILENAME) .reportContentBase64(MOCK_CUCUMBER_REPORT_DATA) .build(); } final ReportsClient reportsClient = ReportsClient.get(); return reportsClient.report(processInfo, outputType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\de.metas.report.jasper.client\src\main\java\de\metas\report\jasper\client\process\JasperExecuteReportStrategy.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getSystemHost() { return systemHost; } public void setSystemHost(String systemHost) { this.systemHost = systemHost; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status;
} public Date getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(Date startTimestamp) { this.startTimestamp = startTimestamp; } public Date getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(Date lastAccessTime) { this.lastAccessTime = lastAccessTime; } public Long getTimeout() { return timeout; } public void setTimeout(Long timeout) { this.timeout = timeout; } }
repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\pojo\UserOnline.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomIpAuthenticationProvider implements AuthenticationProvider { Set<String> whitelist = new HashSet<>(); public CustomIpAuthenticationProvider() { whitelist.add("11.11.11.11"); whitelist.add("127.0.0.1"); } @Override public Authentication authenticate(Authentication auth) throws AuthenticationException { WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); String userIp = details.getRemoteAddress(); if (!whitelist.contains(userIp)) { throw new BadCredentialsException("Invalid IP Address"); }
final String name = auth.getName(); final String password = auth.getCredentials().toString(); if (name.equals("john") && password.equals("123")) { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); return new UsernamePasswordAuthenticationToken(name, password, authorities); } else { throw new BadCredentialsException("Invalid username or password"); } } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\roles\ip\config\CustomIpAuthenticationProvider.java
2
请完成以下Java代码
public String getRequestType () { return (String)get_Value(COLUMNNAME_RequestType); } /** Set Status Code. @param StatusCode Status Code */ public void setStatusCode (int StatusCode) { set_Value (COLUMNNAME_StatusCode, Integer.valueOf(StatusCode)); } /** Get Status Code. @return Status Code */ public int getStatusCode () { Integer ii = (Integer)get_Value(COLUMNNAME_StatusCode); if (ii == null) return 0; return ii.intValue(); } /** Set User Agent. @param UserAgent Browser Used */ public void setUserAgent (String UserAgent) {
set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } /** Set Web Session. @param WebSession Web Session ID */ public void setWebSession (String WebSession) { set_Value (COLUMNNAME_WebSession, WebSession); } /** Get Web Session. @return Web Session ID */ public String getWebSession () { return (String)get_Value(COLUMNNAME_WebSession); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebAccessLog.java
1
请完成以下Java代码
public void addSentence(String sentence) { T key = generateKey(sentence); if (key == null) return; Set<String> set = storage.get(key); if (set == null) { set = new TreeSet<String>(); storage.put(key, set); } set.add(sentence); } /** * 生成能够代表这个句子的键 * @param sentence * @return */ protected abstract T generateKey(String sentence); @Override public Map<String, Double> computeScore(String outerSentence) { TreeMap<String, Double> result = new TreeMap<String, Double>(Collections.reverseOrder()); T keyOuter = generateKey(outerSentence); if (keyOuter == null) return result; for (Map.Entry<T, Set<String>> entry : storage.entrySet()) { T key = entry.getKey();
Double score = keyOuter.similarity(key); for (String sentence : entry.getValue()) { result.put(sentence, score); } } return result; } @Override public void removeAllSentences() { storage.clear(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\suggest\scorer\BaseScorer.java
1
请完成以下Java代码
public ReviewStatus getStatus() { return status; } public void setStatus(ReviewStatus status) { this.status = status; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true;
} if (!(obj instanceof BookReview)) { return false; } return id != null && id.equals(((BookReview) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\entity\BookReview.java
1
请完成以下Java代码
public ProcessEngineException parseProcessException(String name, Throwable cause) { return new ProcessEngineException(exceptionMessage("002", "Error while parsing process of resource '{}'.", name), cause); } public void ignoredSentryWithMissingCondition(String id) { logInfo( "003", "Sentry with id '{}' will be ignored. Reason: Neither ifPart nor onParts are defined with a condition.", id ); } public void ignoredSentryWithInvalidParts(String id) { logInfo("004", "Sentry with id '{}' will be ignored. Reason: ifPart and all onParts are not valid.", id); } public void ignoredUnsupportedAttribute(String attribute, String element, String id) { logInfo( "005", "The attribute '{}' based on the element '{}' of the sentry with id '{}' is not supported and will be ignored.", attribute, element, id ); } public void multipleIgnoredConditions(String id) { logInfo( "006", "The ifPart of the sentry with id '{}' has more than one condition. " + "Only the first one will be used and the other conditions will be ignored.",
id ); } public CmmnTransformException nonMatchingVariableEvents(String id) { return new CmmnTransformException(exceptionMessage( "007", "The variableOnPart of the sentry with id '{}' must have one valid variable event. ", id )); } public CmmnTransformException emptyVariableName(String id) { return new CmmnTransformException(exceptionMessage( "008", "The variableOnPart of the sentry with id '{}' must have variable name. ", id )); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransformerLogger.java
1
请完成以下Java代码
public class TaskReportResourceImpl implements TaskReportResource { public static final MediaType APPLICATION_CSV_TYPE = new MediaType("application", "csv"); public static final MediaType TEXT_CSV_TYPE = new MediaType("text", "csv"); public static final List<Variant> VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, APPLICATION_CSV_TYPE, TEXT_CSV_TYPE).add().build(); protected ProcessEngine engine; public TaskReportResourceImpl(ProcessEngine engine) { this.engine = engine; } public Response getTaskCountByCandidateGroupReport(Request request) { Variant variant = request.selectVariant(VARIANTS); if (variant != null) { MediaType mediaType = variant.getMediaType(); if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { List<TaskCountByCandidateGroupResultDto> result = getTaskCountByCandidateGroupResultAsJson(); return Response.ok(result, mediaType).build(); } else if (APPLICATION_CSV_TYPE.equals(mediaType) || TEXT_CSV_TYPE.equals(mediaType)) { String csv = getReportResultAsCsv(); return Response .ok(csv, mediaType) .header("Content-Disposition", URLEncodingUtil.buildAttachmentValue("task-count-by-candidate-group.csv"))
.build(); } } throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); } @SuppressWarnings("unchecked") protected List<TaskCountByCandidateGroupResult> queryTaskCountByCandidateGroupReport() { TaskCountByCandidateGroupResultDto reportDto = new TaskCountByCandidateGroupResultDto(); return (List<TaskCountByCandidateGroupResult>) reportDto.executeTaskCountByCandidateGroupReport(engine); } protected List<TaskCountByCandidateGroupResultDto> getTaskCountByCandidateGroupResultAsJson() { List<TaskCountByCandidateGroupResult> reports = queryTaskCountByCandidateGroupReport(); List<TaskCountByCandidateGroupResultDto> result = new ArrayList<TaskCountByCandidateGroupResultDto>(); for (TaskCountByCandidateGroupResult report : reports) { result.add(TaskCountByCandidateGroupResultDto.fromTaskCountByCandidateGroupResultDto(report)); } return result; } protected String getReportResultAsCsv() { List<TaskCountByCandidateGroupResult> reports = queryTaskCountByCandidateGroupReport(); return TaskReportResultToCsvConverter.convertCandidateGroupReportResult(reports); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\task\impl\TaskReportResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringQrtzScheduler { Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ApplicationContext applicationContext; @PostConstruct public void init() { logger.info("Hello world from Spring..."); } @Bean public SpringBeanJobFactory springBeanJobFactory() { AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory(); logger.debug("Configuring Job factory"); jobFactory.setApplicationContext(applicationContext); return jobFactory; } @Bean public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job, DataSource quartzDataSource) { SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean(); schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties")); logger.debug("Setting the Scheduler up"); schedulerFactory.setJobFactory(springBeanJobFactory()); schedulerFactory.setJobDetails(job); schedulerFactory.setTriggers(trigger); // Comment the following line to use the default Quartz job store. schedulerFactory.setDataSource(quartzDataSource); return schedulerFactory; } @Bean
public JobDetailFactoryBean jobDetail() { JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean(); jobDetailFactory.setJobClass(SampleJob.class); jobDetailFactory.setName("Qrtz_Job_Detail"); jobDetailFactory.setDescription("Invoke Sample Job service..."); jobDetailFactory.setDurability(true); return jobDetailFactory; } @Bean public SimpleTriggerFactoryBean trigger(JobDetail job) { SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean(); trigger.setJobDetail(job); int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); trigger.setRepeatInterval(frequencyInSec * 1000); trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); trigger.setName("Qrtz_Trigger"); return trigger; } @Bean @QuartzDataSource @ConfigurationProperties(prefix = "spring.datasource") public DataSource quartzDataSource() { return DataSourceBuilder.create().build(); } }
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\springquartz\basics\scheduler\SpringQrtzScheduler.java
2
请完成以下Java代码
public class CameraStream extends Application { private VideoCapture capture; public void start(Stage stage) throws Exception { OpenCV.loadShared(); capture = new VideoCapture(0); // The number is the ID of the camera ImageView imageView = new ImageView(); HBox hbox = new HBox(imageView); Scene scene = new Scene(hbox); stage.setScene(scene); stage.show(); new AnimationTimer() { @Override public void handle(long l) { imageView.setImage(getCapture()); } }.start(); } public Image getCapture() { Mat mat = new Mat(); capture.read(mat); return mat2Img(mat); } public Image getCaptureWithFaceDetection() { Mat mat = new Mat(); capture.read(mat); Mat haarClassifiedImg = detectFace(mat); return mat2Img(haarClassifiedImg); } public Image mat2Img(Mat mat) { MatOfByte bytes = new MatOfByte(); Imgcodecs.imencode("img", mat, bytes); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray()); Image img = new Image(inputStream); return img; }
public static void main(String[] args) { Application.launch(args); } public static Mat detectFace(Mat inputImage) { MatOfRect facesDetected = new MatOfRect(); CascadeClassifier cascadeClassifier = new CascadeClassifier(); int minFaceSize = Math.round(inputImage.rows() * 0.1f); cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml"); cascadeClassifier.detectMultiScale(inputImage, facesDetected, 1.1, 3, Objdetect.CASCADE_SCALE_IMAGE, new Size(minFaceSize, minFaceSize), new Size()); Rect[] facesArray = facesDetected.toArray(); for (Rect face : facesArray) { Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3); } return inputImage; } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imageprocessing\opencv\CameraStream.java
1
请完成以下Java代码
public String getGroupId() { return groupId; } public String getEdgeNodeId() { return edgeNodeId; } /** * Returns a {@link String} representing the Edge Node's Descriptor of the form: "<groupId>/<edgeNodeId>". * * @return a {@link String} representing the Edge Node's Descriptor. */ @Override public String getDescriptorString() { return descriptorString; } @Override
public int hashCode() { return this.getDescriptorString().hashCode(); } @Override public boolean equals(Object object) { if (object instanceof EdgeNodeDescriptor) { return this.getDescriptorString().equals(((EdgeNodeDescriptor) object).getDescriptorString()); } return this.getDescriptorString().equals(object); } @Override @JsonValue public String toString() { return getDescriptorString(); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\EdgeNodeDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public class BankStatementImportFileId implements RepoIdAware { @NonNull @JsonCreator public static BankStatementImportFileId ofRepoId(final int repoId) { return new BankStatementImportFileId(repoId); } @Nullable public static BankStatementImportFileId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final BankStatementImportFileId bankStatementImportFileId) { return bankStatementImportFileId != null ? bankStatementImportFileId.getRepoId() : 0; }
int repoId; private BankStatementImportFileId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_BankStatement_Import_File_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\BankStatementImportFileId.java
2
请完成以下Java代码
public int getLevelHierarchy() { return get_ValueAsInt(COLUMNNAME_LevelHierarchy); } @Override public void setPointsSum_Forecasted (final BigDecimal PointsSum_Forecasted) { set_Value (COLUMNNAME_PointsSum_Forecasted, PointsSum_Forecasted); } @Override public BigDecimal getPointsSum_Forecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Forecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Invoiceable (final BigDecimal PointsSum_Invoiceable) { set_ValueNoCheck (COLUMNNAME_PointsSum_Invoiceable, PointsSum_Invoiceable); } @Override public BigDecimal getPointsSum_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Invoiced (final BigDecimal PointsSum_Invoiced) { set_Value (COLUMNNAME_PointsSum_Invoiced, PointsSum_Invoiced); }
@Override public BigDecimal getPointsSum_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Settled (final BigDecimal PointsSum_Settled) { set_Value (COLUMNNAME_PointsSum_Settled, PointsSum_Settled); } @Override public BigDecimal getPointsSum_Settled() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_ToSettle (final BigDecimal PointsSum_ToSettle) { set_Value (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle); } @Override public BigDecimal getPointsSum_ToSettle() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Share.java
1
请完成以下Java代码
public void setBill_User_ID(final int Bill_User_ID) { delegate.setBill_User_ID(Bill_User_ID); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } @Override public I_C_Flatrate_Term getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); }
@Override public ContractBillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new ContractBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class)); } public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId, final @Nullable BPartnerContactId billToContactId) { setBill_BPartner_ID(billToLocationId.getBpartnerRepoId()); setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId()); setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId()); setBill_User_ID(billToContactId == null ? -1 : billToContactId.getRepoId()); } public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId) { setBill_BPartner_ID(billToLocationId.getBpartnerRepoId()); setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId()); setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractBillLocationAdapter.java
1
请完成以下Java代码
public class FixedOrderByKeyComparator<V, K> implements Comparator<V> { public static <V, K> FixedOrderByKeyComparator<V, K> of(final K notMatchedMarker, final List<K> fixedOrderList, final Function<V, K> keyMapper) { final int notMatchedMarkerIndex = fixedOrderList.indexOf(notMatchedMarker); final int notMatchedMarkerIndexEffective = notMatchedMarkerIndex >= 0 ? notMatchedMarkerIndex : Integer.MAX_VALUE; return new FixedOrderByKeyComparator<>(fixedOrderList, notMatchedMarkerIndexEffective, keyMapper); } public static <V, K> FixedOrderByKeyComparator<V, K> notMatchedAtTheEnd(final List<K> fixedOrderList, final Function<V, K> keyMapper) { final int notMatchedMarkerIndex = Integer.MAX_VALUE; return new FixedOrderByKeyComparator<>(fixedOrderList, notMatchedMarkerIndex, keyMapper); } private final List<K> fixedOrderKeys; private final int notMatchedMarkerIndex; private final Function<V, K> keyMapper; @Builder private FixedOrderByKeyComparator( @NonNull @Singular final List<K> fixedOrderKeys, final int notMatchedMarkerIndex, @NonNull final Function<V, K> keyMapper) { // Check.assume(!fixedOrderKeys.isEmpty(), "fixedOrderList not empty"); // empty list shall be OK this.fixedOrderKeys = fixedOrderKeys;
this.notMatchedMarkerIndex = notMatchedMarkerIndex; this.keyMapper = keyMapper; } @Override public int compare(final V o1, final V o2) { final int idx1 = getIndexOf(o1); final int idx2 = getIndexOf(o2); return idx1 - idx2; } private int getIndexOf(final V obj) { final K key = keyMapper.apply(obj); int idx = fixedOrderKeys.indexOf(key); if (idx < 0) { idx = notMatchedMarkerIndex; } return idx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\FixedOrderByKeyComparator.java
1