instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class PersonServiceImpl implements PersonService { private final PersonRepository personRepository; /** * 登录 * * @param request {@link LoginRequest} * @return {@link Result} */ @Override public Result login(LoginRequest request) { log.info("IN LDAP auth"); Person user = personRepository.findByUid(request.getUsername()); try { if (ObjectUtils.isEmpty(user)) { throw new ServiceException("用户名或密码错误,请重新尝试"); } else { user.setUserPassword(LdapUtils.asciiToString(user.getUserPassword())); if (!LdapUtils.verify(user.getUserPassword(), request.getPassword())) { throw new ServiceException("用户名或密码错误,请重新尝试"); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } log.info("user info:{}", user); return Result.success(user); } /**
* 查询全部 * * @return {@link Result} */ @Override public Result listAllPerson() { Iterable<Person> personList = personRepository.findAll(); personList.forEach(person -> person.setUserPassword(LdapUtils.asciiToString(person.getUserPassword()))); return Result.success(personList); } /** * 保存 * * @param person {@link Person} */ @Override public void save(Person person) { Person p = personRepository.save(person); log.info("用户{}保存成功", p.getUid()); } /** * 删除 * * @param person {@link Person} */ @Override public void delete(Person person) { personRepository.delete(person); log.info("删除用户{}成功", person.getUid()); } }
repos\spring-boot-demo-master\demo-ldap\src\main\java\com\xkcoding\ldap\service\impl\PersonServiceImpl.java
1
请完成以下Java代码
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { /* * A plan fragment does NOT have a runtime state, even though it has an associated plan item. * * From the CMMN spec: "Unlike other PlanItemDefinitions, a PlanFragment does not have a representation in run-time, * i.e., there is no notion of lifecycle tracking of a PlanFragment (not being a Stage) in the context of a Case instance. * Just the PlanItems that are contained in it are instantiated and have their lifecyles that are tracked. * * Do note that a Stage is a subclass of a PlanFragment (but this is only for plan item / sentry containment). */ PlanFragment planFragment = new PlanFragment(); planFragment.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); planFragment.setCase(conversionHelper.getCurrentCase());
planFragment.setParent(conversionHelper.getCurrentPlanFragment()); conversionHelper.setCurrentPlanFragment(planFragment); conversionHelper.addPlanFragment(planFragment); return planFragment; } @Override protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) { super.elementEnd(xtr, conversionHelper); conversionHelper.removeCurrentPlanFragment(); } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\PlanFragmentXmlConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class Payment { @Id @GeneratedValue private Long id; private Long amount; @Column(unique = true) private String referenceNumber; @Enumerated(EnumType.STRING) private State state; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public String getReferenceNumber() { return referenceNumber; }
public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } public State getState() { return state; } public void setState(State state) { this.state = state; } public enum State { STARTED, FAILED, SUCCESSFUL } }
repos\tutorials-master\persistence-modules\spring-data-jpa-annotations\src\main\java\com\baeldung\tx\model\Payment.java
2
请完成以下Java代码
public Segment getSegment() { return segment; } public void setSegment(Segment segment) { this.segment = segment; } /** * 是否激活了停用词过滤器 * * @return */
public boolean isFilterEnabled() { return filter; } /** * 激活/关闭停用词过滤器 * * @param filter */ public void enableFilter(boolean filter) { this.filter = filter; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\DocVectorModel.java
1
请完成以下Java代码
public Object getObject(Object key) { try { if (key != null) { Object obj = redisTemplate.opsForValue().get(key.toString()); return obj; } } catch (Exception e) { logger.error("redis "); } return null; } @Override public Object removeObject(Object key) { try { if (key != null) { redisTemplate.delete(key.toString()); } } catch (Exception e) { } return null; } @Override public void clear() { logger.debug("清空缓存"); try {
Set<String> keys = redisTemplate.keys("*:" + this.id + "*"); if (!CollectionUtils.isEmpty(keys)) { redisTemplate.delete(keys); } } catch (Exception e) { } } @Override public int getSize() { Long size = (Long) redisTemplate.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.dbSize(); } }); return size.intValue(); } @Override public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } }
repos\spring-boot-student-master\spring-boot-student-mybatis-redis\src\main\java\com\xiaolyuh\redis\cache\MybatisRedisCache.java
1
请在Spring Boot框架中完成以下Java代码
public class SysAnnouncementSendServiceImpl extends ServiceImpl<SysAnnouncementSendMapper, SysAnnouncementSend> implements ISysAnnouncementSendService { @Resource private SysAnnouncementSendMapper sysAnnouncementSendMapper; @Autowired private SysAnnouncementMapper sysAnnouncementMapper; @Override public Page<AnnouncementSendModel> getMyAnnouncementSendPage(Page<AnnouncementSendModel> page, AnnouncementSendModel announcementSendModel) { return page.setRecords(sysAnnouncementSendMapper.getMyAnnouncementSendList(page, announcementSendModel)); } @Override public AnnouncementSendModel getOne(String sendId) { return sysAnnouncementSendMapper.getOne(sendId); } /** * 获取当前用户已阅读数量 * * @param id * @return */ @Override public long getReadCountByUserId(String id) { LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); return sysAnnouncementSendMapper.getReadCountByUserId(id, sysUser.getId()); } /** * 根据多个id批量删除已阅读的数量 * * @param ids */ @Override public void deleteBatchByIds(String ids) { LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); //根据用户id和阅读表的id获取所有阅读的数据 List<String> sendIds = sysAnnouncementSendMapper.getReadAnnSendByUserId(Arrays.asList(ids.split(SymbolConstant.COMMA)),sysUser.getId());
if(CollectionUtil.isNotEmpty(sendIds)){ this.removeByIds(sendIds); } } /** * 根据busId更新阅读状态 * @param busId * @param busType */ @Override public void updateReadFlagByBusId(String busId, String busType) { SysAnnouncement announcement = sysAnnouncementMapper.selectOne(new QueryWrapper<SysAnnouncement>().eq("bus_type",busType).eq("bus_id",busId)); if(oConvertUtils.isNotEmpty(announcement)){ LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal(); String userId = sysUser.getId(); LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda(); updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG); updateWrapper.set(SysAnnouncementSend::getReadTime, new Date()); updateWrapper.eq(SysAnnouncementSend::getAnntId,announcement.getId()); updateWrapper.eq(SysAnnouncementSend::getUserId,userId); SysAnnouncementSend announcementSend = new SysAnnouncementSend(); sysAnnouncementSendMapper.update(announcementSend, updateWrapper); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysAnnouncementSendServiceImpl.java
2
请完成以下Java代码
public int getC_BPartner_ID() { if (m_partner == null) { return 0; } return m_partner.getC_BPartner_ID(); } // getBPartner_ID /** * @return Template Business Partner or null */ private static I_C_BPartner createNewTemplateBPartner(final int clientId) { final I_C_BPartner bpartner = InterfaceWrapperHelper.newInstanceOutOfTrx(I_C_BPartner.class); final I_C_BPartner template = getBPartnerCashTrx(clientId); if (template != null) { InterfaceWrapperHelper.copyValues(bpartner, bpartner); } // Reset bpartner.setValue(""); bpartner.setName(""); bpartner.setName2(null); bpartner.setDUNS(""); bpartner.setFirstSale(null); // bpartner.setPotentialLifeTimeValue(BigDecimal.ZERO); bpartner.setAcqusitionCost(BigDecimal.ZERO); bpartner.setShareOfCustomer(0); bpartner.setSalesVolume(0); return bpartner; } // getTemplate
/** * @return Cash Trx Business Partner or null */ private static I_C_BPartner getBPartnerCashTrx(final int clientId) { final IClientDAO clientDAO = Services.get(IClientDAO.class); final I_AD_ClientInfo clientInfo = clientDAO.retrieveClientInfo(Env.getCtx(), clientId); final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(clientInfo.getC_BPartnerCashTrx_ID()); if(bpartnerId == null) { return null; } return Services.get(IBPartnerDAO.class).getById(bpartnerId); } // getBPartnerCashTrx } // VBPartner
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VBPartner.java
1
请完成以下Java代码
public class CalloutAttributeStorageListener implements IAttributeStorageListener { private final AttributeSetCalloutExecutor calloutExecutor = new AttributeSetCalloutExecutor(); @Override public void onAttributeValueCreated(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); final Object valueOld = null; final Object valueNew = attributeValue.getValue(); calloutExecutor.executeCallout(attributeValueContext, storage, attribute, valueOld, valueNew); } @Override public void onAttributeValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); final Object valueNew = attributeValue.getValue(); calloutExecutor.executeCallout(attributeValueContext, storage, attribute, valueOld, valueNew); }
@Override public void onAttributeValueDeleted(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); final Object valueOld = attributeValue.getValue(); final Object valueNew = null; calloutExecutor.executeCallout(attributeValueContext, storage, attribute, valueOld, valueNew); } @Override public String toString() { return "CalloutAttributeStorageListener [calloutExecutor=" + calloutExecutor + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CalloutAttributeStorageListener.java
1
请完成以下Java代码
public static boolean checkIfSortedUsingRecursion(List<String> listOfStrings) { return isSortedRecursive(listOfStrings, listOfStrings.size()); } public static boolean isSortedRecursive(List<String> listOfStrings, int index) { if (index < 2) { return true; } else if (listOfStrings.get(index - 2) .compareTo(listOfStrings.get(index - 1)) > 0) { return false; } else { return isSortedRecursive(listOfStrings, index - 1); } } public static boolean checkIfSortedUsingOrderingClass(List<String> listOfStrings) { return Ordering.<String> natural() .isOrdered(listOfStrings);
} public static boolean checkIfSortedUsingOrderingClass(List<Employee> employees, Comparator<Employee> employeeComparator) { return Ordering.from(employeeComparator) .isOrdered(employees); } public static boolean checkIfSortedUsingOrderingClassHandlingNull(List<String> listOfStrings) { return Ordering.<String> natural() .nullsLast() .isOrdered(listOfStrings); } public static boolean checkIfSortedUsingComparators(List<String> listOfStrings) { return Comparators.isInOrder(listOfStrings, Comparator.<String> naturalOrder()); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\checksortedlist\SortedListChecker.java
1
请完成以下Java代码
public void initialize(VariableSerializers serializers, String dbType) { if (value.getType() != null && value.getType().isAbstract()) { valueCondition = new CompositeQueryVariableValueCondition(this); } else { valueCondition = new SingleQueryVariableValueCondition(this); } valueCondition.initializeValue(serializers, dbType); } public List<SingleQueryVariableValueCondition> getValueConditions() { return valueCondition.getDisjunctiveConditions(); } public String getName() { return name; } public QueryOperator getOperator() { if(operator != null) { return operator; } return QueryOperator.EQUALS; } public String getOperatorName() { return getOperator().toString(); } public Object getValue() { return value.getValue(); } public TypedValue getTypedValue() { return value; } public boolean isLocal() { return local; } public boolean isVariableNameIgnoreCase() { return variableNameIgnoreCase; } public void setVariableNameIgnoreCase(boolean variableNameIgnoreCase) { this.variableNameIgnoreCase = variableNameIgnoreCase; } public boolean isVariableValueIgnoreCase() {
return variableValueIgnoreCase; } public void setVariableValueIgnoreCase(boolean variableValueIgnoreCase) { this.variableValueIgnoreCase = variableValueIgnoreCase; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryVariableValue that = (QueryVariableValue) o; return local == that.local && variableNameIgnoreCase == that.variableNameIgnoreCase && variableValueIgnoreCase == that.variableValueIgnoreCase && name.equals(that.name) && value.equals(that.value) && operator == that.operator && Objects.equals(valueCondition, that.valueCondition); } @Override public int hashCode() { return Objects.hash(name, value, operator, local, valueCondition, variableNameIgnoreCase, variableValueIgnoreCase); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryVariableValue.java
1
请完成以下Java代码
public class PropertiesPropertySourceLoader implements PropertySourceLoader { private static final String XML_FILE_EXTENSION = ".xml"; @Override public String[] getFileExtensions() { return new String[] { "properties", "xml" }; } @Override public List<PropertySource<?>> load(String name, Resource resource) throws IOException { List<Map<String, ?>> properties = loadProperties(resource); if (properties.isEmpty()) { return Collections.emptyList(); } List<PropertySource<?>> propertySources = new ArrayList<>(properties.size()); for (int i = 0; i < properties.size(); i++) { String documentNumber = (properties.size() != 1) ? " (document #" + i + ")" : ""; propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber, Collections.unmodifiableMap(properties.get(i)), true)); }
return propertySources; } @SuppressWarnings({ "unchecked", "rawtypes" }) private List<Map<String, ?>> loadProperties(Resource resource) throws IOException { String filename = resource.getFilename(); List<Map<String, ?>> result = new ArrayList<>(); if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { result.add((Map) PropertiesLoaderUtils.loadProperties(resource)); } else { List<Document> documents = new OriginTrackedPropertiesLoader(resource).load(); documents.forEach((document) -> result.add(document.asMap())); } return result; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\PropertiesPropertySourceLoader.java
1
请完成以下Java代码
public class DokumentAbfragenAntwort { @XmlElement(name = "Data", required = true) protected byte[] data; @XmlAttribute(name = "DokumentId", required = true) protected String dokumentId; /** * Gets the value of the data property. * * @return * possible object is * byte[] */ public byte[] getData() { return data; } /** * Sets the value of the data property. * * @param value * allowed object is * byte[] */ public void setData(byte[] value) { this.data = value; } /** * Gets the value of the dokumentId property. * * @return * possible object is * {@link String } * */
public String getDokumentId() { return dokumentId; } /** * Sets the value of the dokumentId property. * * @param value * allowed object is * {@link String } * */ public void setDokumentId(String value) { this.dokumentId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\DokumentAbfragenAntwort.java
1
请在Spring Boot框架中完成以下Java代码
private static CandidatesQuery createPreExistingCandidatesQuery( @NonNull final PPOrder ppOrder, @NonNull final PPOrderLine ppOrderLine) { final MaterialDispoGroupId groupId = ppOrder.getPpOrderData().getMaterialDispoGroupId(); if (groupId == null) { // return false, but don't write another log message; we already logged in the other createQuery() method return CandidatesQuery.FALSE; } return CandidatesQuery.builder() .type(PPOrderHandlerUtils.extractCandidateType(ppOrderLine)) .businessCase(CandidateBusinessCase.PRODUCTION) .groupId(groupId) .materialDescriptorQuery(PPOrderHandlerUtils.createMaterialDescriptorQuery(ppOrderLine.getPpOrderLineData().getProductDescriptor())) .build(); } private MaterialDescriptor createMaterialDescriptor(@NonNull final PPOrderLine ppOrderLine) { return MaterialDescriptor.builder() .date(ppOrderLine.getPpOrderLineData().getIssueOrReceiveDate()) .productDescriptor(ppOrderLine.getPpOrderLineData().getProductDescriptor()) .quantity(ppOrderLine.getPpOrderLineData().getQtyOpenNegateIfReceipt())
.warehouseId(ppOrder.getPpOrderData().getWarehouseId()) // .customerId(ppOrder.getBPartnerId()) not 100% sure if the ppOrder's bPartner is the customer this is made for .build(); } private ProductionDetail createProductionDetail(@NonNull final PPOrderLine ppOrderLine) { return ProductionDetail.builder() .advised(advised) .pickDirectlyIfFeasible(pickDirectlyIfFeasible) .plantId(ppOrder.getPpOrderData().getPlantId()) .workstationId(ppOrder.getPpOrderData().getWorkstationId()) .qty(ppOrderLine.getPpOrderLineData().getQtyOpenNegateIfReceipt()) .productPlanningId(ppOrder.getPpOrderData().getProductPlanningId()) .productBomLineId(ppOrderLine.getPpOrderLineData().getProductBomLineId()) .description(ppOrderLine.getPpOrderLineData().getDescription()) .ppOrderRef(PPOrderRef.ofPPOrderBOMLineId(ppOrder.getPpOrderId(), ppOrderLine.getPpOrderLineId())) .ppOrderDocStatus(ppOrder.getDocStatus()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\pporder\PPOrderLineCandidatesCreateCommand.java
2
请完成以下Java代码
public Result processWorkPackage(final I_C_Queue_WorkPackage workpackage, final String localTrxName) { final IQueueDAO queueDAO = Services.get(IQueueDAO.class); final IESRImportBL esrImportBL = Services.get(IESRImportBL.class); final List<I_ESR_Import> records = queueDAO.retrieveAllItems(workpackage, I_ESR_Import.class); for (final I_ESR_Import esrImport : records) { // the esr can not have the file twice; is restricted before in the process so we are not overlapping // we can load the file twice if (esrImport.isProcessed() || !esrImport.isActive() || esrImport.isValid()) { // already processed => do nothing // already imported continue; } // esrImportBL.loadESRImportFile(esrImport); // import is done, so we can process and create payments
processESRImportFile(esrImport); } return Result.SUCCESS; } private void processESRImportFile(final I_ESR_Import esrImport) { Services.get(IESRImportBL.class).process(esrImport); } @Override public boolean isRunInTransaction() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\processor\impl\LoadESRImportFileWorkpackageProcessor.java
1
请完成以下Java代码
private List<IProductionMaterial> getProductionMaterials(final ProductionMaterialType type, final I_M_Product product) { Check.assumeNotNull(type, "type not null"); final int productId = product == null ? -1 : product.getM_Product_ID(); final List<IProductionMaterial> result = new ArrayList<IProductionMaterial>(); for (final IProductionMaterial productionMaterial : getProductionMaterials()) { if (productionMaterial.getType() != type) { continue; } if (productId > 0) { final I_M_Product productionMaterialProduct = productionMaterial.getM_Product(); final int productionMaterialProductId = productionMaterialProduct.getM_Product_ID(); if (productionMaterialProductId != productId) { continue; } } result.add(productionMaterial); } return result; } protected void setAllOrders(final List<IQualityInspectionOrder> allOrders) { assumeQualityInspection(); Check.assumeNotNull(allOrders, "allOrders not null"); this.allOrders = Collections.unmodifiableList(new ArrayList<>(allOrders)); } @Override public List<IQualityInspectionOrder> getAllOrders() { return allOrders; } @Override public BigDecimal getAlreadyInvoicedNetSum() { if (_alreadyInvoicedSum == null) { final IInvoicedSumProvider invoicedSumProvider = qualityBasedConfigProviderService.getInvoicedSumProvider(); _alreadyInvoicedSum = invoicedSumProvider.getAlreadyInvoicedNetSum(_materialTracking); } if (_alreadyInvoicedSum == null) { _alreadyInvoicedSum = BigDecimal.ZERO; }
return _alreadyInvoicedSum; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("QualityInspectionOrder [_ppOrder="); builder.append(_ppOrder); builder.append(", _qualityInspection="); builder.append(_qualityInspection); builder.append(", _materialTracking="); builder.append(_materialTracking); builder.append(", _qualityBasedConfig="); builder.append(_qualityBasedConfig); builder.append(", _inspectionNumber="); builder.append(_inspectionNumber); builder.append(", _productionMaterials="); builder.append(_productionMaterials); builder.append(", _productionMaterial_Raw="); builder.append(_productionMaterial_Raw); builder.append(", _productionMaterial_Main="); builder.append(_productionMaterial_Main); builder.append(", _productionMaterial_Scrap="); builder.append(_productionMaterial_Scrap); builder.append(", _alreadyInvoicedSum="); builder.append(_alreadyInvoicedSum); // builder.append(", preceedingOrders="); // builder.append(preceedingOrders); builder.append("]"); return builder.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionOrder.java
1
请完成以下Java代码
public ChannelDefinitionParse sourceUrl(String url) { try { return sourceUrl(new URL(url)); } catch (MalformedURLException e) { throw new FlowableException("malformed url: " + url, e); } } public ChannelDefinitionParse sourceResource(String resource) { if (name == null) { name(resource); } setStreamSource(new ResourceStreamSource(resource)); return this; } public ChannelDefinitionParse sourceString(String string) { if (name == null) { name("string"); } setStreamSource(new StringStreamSource(string)); return this; } protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } /* * ------------------- GETTERS AND SETTERS ------------------- */ public List<ChannelDefinitionEntity> getChannelDefinitions() { return channelDefinitions; }
public EventDeploymentEntity getDeployment() { return deployment; } public void setDeployment(EventDeploymentEntity deployment) { this.deployment = deployment; } public ChannelModel getChannelModel() { return channelModel; } public void setChannelModel(ChannelModel channelModel) { this.channelModel = channelModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\parser\ChannelDefinitionParse.java
1
请在Spring Boot框架中完成以下Java代码
private String createSamlPostRequestFormData(Saml2PostAuthenticationRequest authenticationRequest) { String authenticationRequestUri = authenticationRequest.getAuthenticationRequestUri(); String relayState = authenticationRequest.getRelayState(); String samlRequest = authenticationRequest.getSamlRequest(); StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>\n"); html.append("<html>\n").append(" <head>\n"); html.append(" <meta http-equiv=\"Content-Security-Policy\" ") .append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n"); html.append(" <meta charset=\"utf-8\" />\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <noscript>\n"); html.append(" <p>\n"); html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n"); html.append(" you must press the Continue button once to proceed.\n"); html.append(" </p>\n"); html.append(" </noscript>\n"); html.append(" \n"); html.append(" <form action=\""); html.append(authenticationRequestUri); html.append("\" method=\"post\">\n"); html.append(" <div>\n"); html.append(" <input type=\"hidden\" name=\"SAMLRequest\" value=\""); html.append(HtmlUtils.htmlEscape(samlRequest)); html.append("\"/>\n"); if (StringUtils.hasText(relayState)) { html.append(" <input type=\"hidden\" name=\"RelayState\" value=\""); html.append(HtmlUtils.htmlEscape(relayState)); html.append("\"/>\n"); }
html.append(" </div>\n"); html.append(" <noscript>\n"); html.append(" <div>\n"); html.append(" <input type=\"submit\" value=\"Continue\"/>\n"); html.append(" </div>\n"); html.append(" </noscript>\n"); html.append(" </form>\n"); html.append(" \n"); html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n"); html.append(" </body>\n"); html.append("</html>"); return html.toString(); } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2WebSsoAuthenticationRequestFilter.java
2
请在Spring Boot框架中完成以下Java代码
static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor) { ConfigurationPropertySource propertySource = contributor.getConfigurationPropertySource(); if (propertySource != null) { ERRORS.forEach((name, replacement) -> { ConfigurationProperty property = propertySource.getConfigurationProperty(name); if (property != null) { throw new InvalidConfigDataPropertyException(property, false, replacement, contributor.getResource()); } }); if (contributor.isFromProfileSpecificImport() && !contributor.hasConfigDataOption(ConfigData.Option.IGNORE_PROFILES)) { PROFILE_SPECIFIC_ERRORS.forEach((name) -> { ConfigurationProperty property = propertySource.getConfigurationProperty(name); if (property != null) { throw new InvalidConfigDataPropertyException(property, true, null, contributor.getResource()); } }); } } } private static String getMessage(ConfigurationProperty property, boolean profileSpecific, @Nullable ConfigurationPropertyName replacement, @Nullable ConfigDataResource location) { StringBuilder message = new StringBuilder("Property '"); message.append(property.getName()); if (location != null) {
message.append("' imported from location '"); message.append(location); } message.append("' is invalid"); if (profileSpecific) { message.append(" in a profile specific resource"); } if (replacement != null) { message.append(" and should be replaced with '"); message.append(replacement); message.append("'"); } if (property.getOrigin() != null) { message.append(" [origin: "); message.append(property.getOrigin()); message.append("]"); } return message.toString(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InvalidConfigDataPropertyException.java
2
请完成以下Java代码
private final class CacheInvalidateMultiRequestsCollector { private final String name; // used for debugging @Nullable private DocumentToInvalidateMap documents = new DocumentToInvalidateMap(); private CacheInvalidateMultiRequestsCollector(final String name) { this.name = name; } public CacheInvalidateMultiRequestsCollector collect(@NonNull final CacheInvalidateMultiRequest multiRequest) { multiRequest.getRequests().forEach(this::collect); return this; } private void collect(@NonNull final CacheInvalidateRequest request) { logger.trace("Collecting request on `{}`: {}", name, request); final TableRecordReference rootDocumentRef = request.getRootRecordOrNull(); if (rootDocumentRef == null) { return; } // // If we are still collecting document, we will collect this event. // If not, we will have to fire this event directly. final DocumentToInvalidateMap documentsToCollect = this.documents; final DocumentToInvalidateMap documents; final boolean autoflush; if (documentsToCollect != null) { documents = documentsToCollect; autoflush = false; } else { // Basically this shall not happen, but for some reason it's happening. // So, for that case, instead of just ignoring event, better to fire it directly. documents = new DocumentToInvalidateMap(); autoflush = true; } // final DocumentToInvalidate documentToInvalidate = documents.getDocumentToInvalidate(rootDocumentRef); final String childTableName = request.getChildTableName(); if (childTableName == null) { documentToInvalidate.invalidateDocument(); } else if (request.isAllRecords()) { documentToInvalidate.invalidateAllIncludedDocuments(childTableName); // NOTE: as a workaround to solve the problem of https://github.com/metasfresh/metasfresh-webui-api/issues/851, // we are invalidating the whole root document to make sure that in case there were any virtual columns on header,
// those get refreshed too. documentToInvalidate.invalidateDocument(); } else { final int childRecordId = request.getChildRecordId(); documentToInvalidate.addIncludedDocument(childTableName, childRecordId); } // if (autoflush && !documents.isEmpty()) { logger.trace("Auto-flushing {} collected requests for on `{}`", documents.size(), name); DocumentCacheInvalidationDispatcher.this.resetAsync(documents); } } public void resetAsync() { final DocumentToInvalidateMap documents = this.documents; this.documents = null; // just to prevent adding more events if (documents == null) { // it was already executed return; } logger.trace("Flushing {} collected requests for on `{}`", documents.size(), name); if (documents.isEmpty()) { return; } DocumentCacheInvalidationDispatcher.this.resetAsync(documents); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentCacheInvalidationDispatcher.java
1
请在Spring Boot框架中完成以下Java代码
public void setInternational(International value) { this.international = value; } /** * Gets the value of the hazardous property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the hazardous property. * * <p> * For example, to add a new item, do as follows: * <pre> * getHazardous().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Hazardous } * * */ public List<Hazardous> getHazardous() { if (hazardous == null) { hazardous = new ArrayList<Hazardous>(); } return this.hazardous; } /** * Gets the value of the printInfo1OnParcelLabel property. * * @return * possible object is * {@link Boolean } * */ public Boolean isPrintInfo1OnParcelLabel() { return printInfo1OnParcelLabel; } /** * Sets the value of the printInfo1OnParcelLabel property. * * @param value * allowed object is * {@link Boolean } * */ public void setPrintInfo1OnParcelLabel(Boolean value) { this.printInfo1OnParcelLabel = value; } /** * Gets the value of the info1 property. * * @return * possible object is * {@link String } * */ public String getInfo1() { return info1; } /** * Sets the value of the info1 property. * * @param value * allowed object is * {@link String } * */ public void setInfo1(String value) { this.info1 = value; } /** * Gets the value of the info2 property. * * @return * possible object is * {@link String } * */ public String getInfo2() { return info2;
} /** * Sets the value of the info2 property. * * @param value * allowed object is * {@link String } * */ public void setInfo2(String value) { this.info2 = value; } /** * Gets the value of the returns property. * * @return * possible object is * {@link Boolean } * */ public Boolean isReturns() { return returns; } /** * Sets the value of the returns property. * * @param value * allowed object is * {@link Boolean } * */ public void setReturns(Boolean value) { this.returns = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Parcel.java
2
请完成以下Java代码
public class ErrorDeclarationForProcessInstanceFinder implements TreeVisitor<PvmScope> { protected Exception exception; protected String errorCode; protected PvmActivity errorHandlerActivity; protected ErrorEventDefinition errorEventDefinition; protected PvmActivity currentActivity; public ErrorDeclarationForProcessInstanceFinder(Exception exception, String errorCode, PvmActivity currentActivity) { this.exception = exception; this.errorCode = errorCode; this.currentActivity = currentActivity; } @Override public void visit(PvmScope scope) { List<ErrorEventDefinition> errorEventDefinitions = scope.getProperties().get(BpmnProperties.ERROR_EVENT_DEFINITIONS); for (ErrorEventDefinition errorEventDefinition : errorEventDefinitions) { PvmActivity activityHandler = scope.getProcessDefinition().findActivity(errorEventDefinition.getHandlerActivityId()); if ((!isReThrowingErrorEventSubprocess(activityHandler)) && ((exception != null && errorEventDefinition.catchesException(exception)) || (exception == null && errorEventDefinition.catchesError(errorCode)))) { errorHandlerActivity = activityHandler; this.errorEventDefinition = errorEventDefinition;
break; } } } protected boolean isReThrowingErrorEventSubprocess(PvmActivity activityHandler) { ScopeImpl activityHandlerScope = (ScopeImpl)activityHandler; return activityHandlerScope.isAncestorFlowScopeOf((ScopeImpl)currentActivity); } public PvmActivity getErrorHandlerActivity() { return errorHandlerActivity; } public ErrorEventDefinition getErrorEventDefinition() { return errorEventDefinition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\ErrorDeclarationForProcessInstanceFinder.java
1
请完成以下Java代码
public boolean isSuspended() { return Suspended.equals(this); } public boolean isCompleted() { return Completed.equals(this); } public boolean isError() { return isAborted() || isTerminated(); } /** * @return true if state is Aborted (Environment/Setup issue) */ public boolean isAborted() { return Aborted.equals(this); } /** * @return true if state is Terminated (Execution issue) */ public boolean isTerminated() { return Terminated.equals(this); } /** * Get New State Options based on current State */ private WFState[] getNewStateOptions() { if (isNotStarted()) return new WFState[] { Running, Aborted, Terminated }; else if (isRunning()) return new WFState[] { Suspended, Completed, Aborted, Terminated }; else if (isSuspended()) return new WFState[] { Running, Aborted, Terminated }; else return new WFState[] {}; } /** * Is the new State valid based on current state * * @param newState new state * @return true valid new state */ public boolean isValidNewState(final WFState newState)
{ final WFState[] options = getNewStateOptions(); for (final WFState option : options) { if (option.equals(newState)) return true; } return false; } /** * @return true if the action is valid based on current state */ public boolean isValidAction(final WFAction action) { final WFAction[] options = getActionOptions(); for (final WFAction option : options) { if (option.equals(action)) { return true; } } return false; } /** * @return valid actions based on current State */ private WFAction[] getActionOptions() { if (isNotStarted()) return new WFAction[] { WFAction.Start, WFAction.Abort, WFAction.Terminate }; if (isRunning()) return new WFAction[] { WFAction.Suspend, WFAction.Complete, WFAction.Abort, WFAction.Terminate }; if (isSuspended()) return new WFAction[] { WFAction.Resume, WFAction.Abort, WFAction.Terminate }; else return new WFAction[] {}; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFState.java
1
请完成以下Java代码
public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } @Override public void setWF_Initial_User_ID (final int WF_Initial_User_ID) { if (WF_Initial_User_ID < 1) set_Value (COLUMNNAME_WF_Initial_User_ID, null); else set_Value (COLUMNNAME_WF_Initial_User_ID, WF_Initial_User_ID); } @Override public int getWF_Initial_User_ID() { return get_ValueAsInt(COLUMNNAME_WF_Initial_User_ID); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Process.java
1
请完成以下Java代码
public void setBinaryData (byte[] BinaryData) { set_Value (COLUMNNAME_BinaryData, BinaryData); } /** Get BinaryData. @return Binary Data */ public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** 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 Error. @param IsError An Error occured in the execution */ public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Error. @return An Error occured in the execution */ public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reference. @param Reference Reference for this record */ public void setReference (String Reference) {
set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference); } /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessorLog.java
1
请完成以下Java代码
public Map<String, String[]> getParameterMap() { return this.parameters; } public void setRedirectUrl(String redirectUrl) { Assert.notNull(redirectUrl, "redirectUrl cannot be null"); this.redirectUrl = redirectUrl; } public void setCookies(List<Cookie> cookies) { Assert.notNull(cookies, "cookies cannot be null"); this.cookies = cookies; } public void setMethod(String method) { Assert.notNull(method, "method cannot be null"); this.method = method; }
public void setHeaders(Map<String, List<String>> headers) { Assert.notNull(headers, "headers cannot be null"); this.headers = headers; } public void setLocales(List<Locale> locales) { Assert.notNull(locales, "locales cannot be null"); this.locales = locales; } public void setParameters(Map<String, String[]> parameters) { Assert.notNull(parameters, "parameters cannot be null"); this.parameters = parameters; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SimpleSavedRequest.java
1
请完成以下Java代码
private long getPreloadSecondTime(String[] cacheParams) { // 自动刷新时间,默认是0 Long preloadSecondTime = 0L; // 设置自动刷新时间 if (cacheParams.length > 2) { String preloadStr = cacheParams[2]; if (!StringUtils.isEmpty(preloadStr)) { // 支持配置刷新时间使用EL表达式读取配置文件时间 if (preloadStr.contains(MARK)) { preloadStr = beanFactory.resolveEmbeddedValue(preloadStr); } preloadSecondTime = Long.parseLong(preloadStr); } } return preloadSecondTime < 0 ? 0 : preloadSecondTime; } /** * 重写父类的getCache方法,增加了三个参数 * * @param cacheName 缓存名称 * @param expirationSecondTime 过期时间 * @param preloadSecondTime 自动刷新时间 * @param cacheMap 通过反射获取的父类的cacheMap对象 * @return Cache */ public Cache getCache(String cacheName, long expirationSecondTime, long preloadSecondTime, ConcurrentHashMap<String, Cache> cacheMap) { Cache cache = cacheMap.get(cacheName); if (cache != null) { return cache; } else { // Fully synchronize now for missing cache creation... synchronized (cacheMap) { cache = cacheMap.get(cacheName); if (cache == null) { // 调用我们自己的getMissingCache方法创建自己的cache cache = getMissingCache(cacheName, expirationSecondTime, preloadSecondTime); if (cache != null) { cache = decorateCache(cache); cacheMap.put(cacheName, cache); // 反射去执行父类的updateCacheNames(cacheName)方法
Class<?>[] parameterTypes = {String.class}; Object[] parameters = {cacheName}; ReflectionUtils.invokeMethod(getInstance(), SUPER_METHOD_UPDATECACHENAMES, parameterTypes, parameters); } } return cache; } } } /** * 创建缓存 * * @param cacheName 缓存名称 * @param expirationSecondTime 过期时间 * @param preloadSecondTime 制动刷新时间 * @return */ public CustomizedRedisCache getMissingCache(String cacheName, long expirationSecondTime, long preloadSecondTime) { logger.info("缓存 cacheName:{},过期时间:{}, 自动刷新时间:{}", cacheName, expirationSecondTime, preloadSecondTime); Boolean dynamic = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_DYNAMIC); Boolean cacheNullValues = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_CACHENULLVALUES); return dynamic ? new CustomizedRedisCache(cacheName, (this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null), this.getRedisOperations(), expirationSecondTime, preloadSecondTime, cacheNullValues) : null; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CustomizedRedisCacheManager.java
1
请完成以下Java代码
/* package */class AllocationResult extends AbstractAllocationResult { private final BigDecimal qtyToAllocate; private final BigDecimal qtyAllocated; private final boolean completed; private final List<IHUTransactionCandidate> transactions; private final List<IHUTransactionAttribute> attributeTransactions; public AllocationResult(final BigDecimal qtyToAllocate, final BigDecimal qtyAllocated, final List<IHUTransactionCandidate> trxs, final List<IHUTransactionAttribute> attributeTrxs) { this.qtyToAllocate = qtyToAllocate; this.qtyAllocated = qtyAllocated; this.completed = qtyToAllocate.compareTo(qtyAllocated) == 0; this.attributeTransactions = Collections.unmodifiableList(new ArrayList<>(attributeTrxs)); this.transactions = Collections.unmodifiableList(new ArrayList<>(trxs)); } @Override public String toString() { return "AllocationResult [" + "completed=" + completed + ", qtyToAllocate=" + qtyToAllocate + ", qtyAllocated=" + qtyAllocated + ", transactions(" + transactions.size() + ")=" + transactions + ", attribute transactions(" + attributeTransactions.size() + ")=" + attributeTransactions + "]"; } @Override public boolean isCompleted() { return completed; }
@Override public BigDecimal getQtyToAllocate() { return qtyToAllocate; } @Override public BigDecimal getQtyAllocated() { return qtyAllocated; } @Override public List<IHUTransactionCandidate> getTransactions() { return ImmutableList.copyOf(transactions); } @Override public List<IHUTransactionAttribute> getAttributeTransactions() { return ImmutableList.copyOf(attributeTransactions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationResult.java
1
请完成以下Java代码
public void performIgnoreConditionsOutgoingBehavior(ActivityExecution activityExecution) { performOutgoingBehavior(activityExecution, false); } /** * Actual implementation of leaving an activity. * * @param execution * The current execution context * @param checkConditions * Whether or not to check conditions before determining whether or * not to take a transition. */ protected void performOutgoingBehavior(ActivityExecution execution, boolean checkConditions) { LOG.leavingActivity(execution.getActivity().getId()); String defaultSequenceFlow = (String) execution.getActivity().getProperty("default"); List<PvmTransition> transitionsToTake = new ArrayList<>(); List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions(); for (PvmTransition outgoingTransition : outgoingTransitions) { if (defaultSequenceFlow == null || !outgoingTransition.getId().equals(defaultSequenceFlow)) { Condition condition = (Condition) outgoingTransition.getProperty(BpmnParse.PROPERTYNAME_CONDITION); if (condition == null || !checkConditions || condition.evaluate(execution)) { transitionsToTake.add(outgoingTransition); } } } if (transitionsToTake.size() == 1) { execution.leaveActivityViaTransition(transitionsToTake.get(0)); } else if (transitionsToTake.size() >= 1) { execution.leaveActivityViaTransitions(transitionsToTake, Arrays.asList(execution)); } else { if (defaultSequenceFlow != null) { PvmTransition defaultTransition = execution.getActivity().findOutgoingTransition(defaultSequenceFlow); if (defaultTransition != null) { execution.leaveActivityViaTransition(defaultTransition); } else { throw LOG.missingDefaultFlowException(execution.getActivity().getId(), defaultSequenceFlow); } } else if (!outgoingTransitions.isEmpty()) {
throw LOG.missingConditionalFlowException(execution.getActivity().getId()); } else { if (((ActivityImpl) execution.getActivity()).isCompensationHandler() && isAncestorCompensationThrowing(execution)) { execution.endCompensation(); } else { LOG.missingOutgoingSequenceFlow(execution.getActivity().getId()); execution.end(true); } } } } protected boolean isAncestorCompensationThrowing(ActivityExecution execution) { ActivityExecution parent = execution.getParent(); while (parent != null) { if (CompensationBehavior.isCompensationThrowing((PvmExecutionImpl) parent)) { return true; } parent = parent.getParent(); } return false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnActivityBehavior.java
1
请完成以下Java代码
protected final ProcessPreconditionsResolution acceptIfDraft(final @NonNull IProcessPreconditionsContext context) { final CostRevaluationId costRevaluationId = getCostRevaluationId(context); return costRevaluationService.isDraftedDocument(costRevaluationId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("Already in progress/finished."); } protected final ProcessPreconditionsResolution acceptIfHasActiveLines(final @NonNull IProcessPreconditionsContext context) { final CostRevaluationId costRevaluationId = getCostRevaluationId(context); return costRevaluationService.hasActiveLines(costRevaluationId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("No active lines found"); } protected final ProcessPreconditionsResolution acceptIfDoesNotHaveActiveLines(final @NonNull IProcessPreconditionsContext context) {
final CostRevaluationId costRevaluationId = getCostRevaluationId(context); return !costRevaluationService.hasActiveLines(costRevaluationId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("Active lines found"); } protected final CostRevaluationId getCostRevaluationId() { return CostRevaluationId.ofRepoId(getRecord_ID()); } @NonNull private static CostRevaluationId getCostRevaluationId(final @NonNull IProcessPreconditionsContext context) { return CostRevaluationId.ofRepoId(context.getSingleSelectedRecordId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\process\M_CostRevaluation_ProcessTemplate.java
1
请在Spring Boot框架中完成以下Java代码
private StreamsBuilder createStreamBuilder() { if (this.properties == null) { return new StreamsBuilder(); } else { StreamsConfig streamsConfig = new StreamsConfig(this.properties); TopologyConfig topologyConfig = new TopologyConfig(streamsConfig); return new StreamsBuilder(topologyConfig); } } /** * Called whenever a {@link KafkaStreams} is added or removed. * * @since 2.5.3 * */ public interface Listener { /**
* A new {@link KafkaStreams} was created. * @param id the streams id (factory bean name). * @param streams the streams; */ default void streamsAdded(String id, KafkaStreams streams) { } /** * An existing {@link KafkaStreams} was removed. * @param id the streams id (factory bean name). * @param streams the streams; */ default void streamsRemoved(String id, KafkaStreams streams) { } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\StreamsBuilderFactoryBean.java
2
请完成以下Java代码
private void checkAvailabilityAsync(@NonNull final AvailabilityRequest request, @NonNull final AvailabilityCheckCallback callback) { final Properties localCtx = Env.copyCtx(Env.getCtx()); CompletableFuture .supplyAsync(() -> { try (final IAutoCloseable ctxWithinAsyncThread = Env.switchContext(localCtx)) { return checkAvailabilityAndConvertThrowable(request); } }) .whenComplete((result, throwable) -> { final boolean resultWasFound = result != null && !result.isEmpty(); final boolean errorOccured = throwable != null; if (resultWasFound || errorOccured) { callback.onResult(result, throwable); } }); } private AvailabilityMultiResult checkAvailabilityAndConvertThrowable(final AvailabilityRequest request) { if (!vendorProvidesAvailabilityCheck(request.getVendorId())) { return AvailabilityMultiResult.EMPTY; } try { return checkAvailability0(request); } catch (final Throwable t) { throw convertThrowable(t); } } private AvailabilityMultiResult checkAvailability0(@NonNull final AvailabilityRequest request) { final VendorGatewayService vendorGatewayService = vendorGatewayRegistry .getSingleVendorGatewayService(request.getVendorId()) .orElse(null); if (vendorGatewayService == null) { // shall not happen because we already checked that return AvailabilityMultiResult.EMPTY; } final AvailabilityResponse availabilityResponse = vendorGatewayService.retrieveAvailability(request); final ImmutableList.Builder<AvailabilityResult> result = ImmutableList.builder(); for (final AvailabilityResponseItem responseItem : availabilityResponse.getAvailabilityResponseItems()) {
final I_C_UOM uom = uomsRepo.getById(responseItem.getUomId()); final AvailabilityResult availabilityResult = AvailabilityResult .prepareBuilderFor(responseItem, uom) .build(); result.add(availabilityResult); } return AvailabilityMultiResult.of(result.build()); } private AdempiereException convertThrowable(@NonNull final Throwable throwable) { final boolean isAvailabilityRequestException = throwable instanceof AvailabilityRequestException; if (!isAvailabilityRequestException) { return AdempiereException.wrapIfNeeded(throwable); } final AvailabilityRequestException availabilityRequestException = AvailabilityRequestException.cast(throwable); final ImmutableList<AvailabilityException.ErrorItem> errorItems = availabilityRequestException .getRequestItem2Exception() .entrySet() .stream() .map(entry -> AvailabilityException.ErrorItem.builder() .trackingId(entry.getKey().getTrackingId()) .error(entry.getValue()) .build()) .collect(ImmutableList.toImmutableList()); return new AvailabilityException(errorItems); } private boolean vendorProvidesAvailabilityCheck(final int vendorBPartnerId) { return vendorGatewayRegistry.getSingleVendorGatewayService(vendorBPartnerId).isPresent(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityCheckCommand.java
1
请完成以下Java代码
public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } @Override public I_AD_Reference getAD_Reference() throws RuntimeException { return (I_AD_Reference)MTable.get(getCtx(), I_AD_Reference.Table_Name) .getPO(getAD_Reference_ID(), get_TrxName()); }
@Override public int getAD_Reference_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Reference_ID); if (ii == null) return 0; return ii.intValue(); } @Override public void setAD_Reference_ID(int AD_Reference_ID) { if (AD_Reference_ID < 1) set_Value (COLUMNNAME_AD_Reference_ID, null); else set_Value (COLUMNNAME_AD_Reference_ID, Integer.valueOf(AD_Reference_ID)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POSKey.java
1
请完成以下Java代码
public void setCurrentLUTUConfiguration(final I_M_InOutLine documentLine, final I_M_HU_LUTU_Configuration lutuConfiguration) { documentLine.setM_HU_LUTU_Configuration(lutuConfiguration); } @Override public I_M_HU_LUTU_Configuration createNewLUTUConfiguration(final I_M_InOutLine documentLine) { final I_M_HU_PI_Item_Product tuPIItemProduct = getM_HU_PI_Item_Product(documentLine); final ProductId cuProductId = ProductId.ofRepoId(documentLine.getM_Product_ID()); final UomId cuUOMId = UomId.ofRepoId(documentLine.getC_UOM_ID()); final BPartnerId bpartnerId = BPartnerId.ofRepoId(documentLine.getM_InOut().getC_BPartner_ID()); final I_M_HU_LUTU_Configuration lutuConfiguration = lutuFactory.createLUTUConfiguration( tuPIItemProduct, cuProductId, cuUOMId, bpartnerId, false); // noLUForVirtualTU == false => allow placing the CU (e.g. a packing material product) directly on the LU // // Update LU/TU configuration updateLUTUConfigurationFromDocumentLine(lutuConfiguration, documentLine); // NOTE: don't save it return lutuConfiguration; } @Override public void updateLUTUConfigurationFromDocumentLine(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration, @NonNull final I_M_InOutLine documentLine) { final I_M_InOut customerReturn = documentLine.getM_InOut(); // // Set BPartner / Location to be used final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(customerReturn.getC_BPartner_ID()); final int bpartnerLocationId = customerReturn.getC_BPartner_Location_ID(); lutuConfiguration.setC_BPartner_ID(BPartnerId.toRepoId(bpartnerId)); lutuConfiguration.setC_BPartner_Location_ID(bpartnerLocationId);
// // Set Locator final WarehouseId warehouseId = WarehouseId.ofRepoId(customerReturn.getM_Warehouse_ID()); final LocatorId locatorId = warehouseBL.getOrCreateDefaultLocatorId(warehouseId); lutuConfiguration.setM_Locator_ID(locatorId.getRepoId()); // // Set HUStatus=Planning because receipt schedules are always about planning lutuConfiguration.setHUStatus(X_M_HU.HUSTATUS_Planning); lutuConfiguration.setQtyLU(BigDecimal.ONE); lutuConfiguration.setIsInfiniteQtyLU(false); lutuConfiguration.setQtyTU(documentLine.getQtyEnteredTU().signum() == 0 ? BigDecimal.ONE: documentLine.getQtyEnteredTU()); lutuConfiguration.setIsInfiniteQtyTU(false); lutuConfiguration.setQtyCUsPerTU(documentLine.getMovementQty()); lutuConfiguration.setIsInfiniteQtyCU(false); } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product(@NonNull final I_M_InOutLine inOutLine) { final HUPIItemProductId piItemProductId = HUPIItemProductId.ofRepoIdOrNone(inOutLine.getM_HU_PI_Item_Product_ID()); return piItemProductBL.getRecordById(piItemProductId); } @Override public void save(@NonNull final I_M_InOutLine documentLine) { inOutDAO.save(documentLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnLUTUConfigurationHandler.java
1
请完成以下Java代码
public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getParentId() { return parentId; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() {
return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalReferenceRestController { public static final String EXTERNAL_REFERENCE_REST_CONTROLLER_PATH_V2 = MetasfreshRestAPIConstants.ENDPOINT_API_V2 + "/externalRefs"; private final ExternalReferenceRestControllerService externalReferenceRestControllerService; public ExternalReferenceRestController(@NonNull final ExternalReferenceRestControllerService externalReferenceRestControllerService) { this.externalReferenceRestControllerService = externalReferenceRestControllerService; } // we actually ask for info and don't change anything in metasfresh...that's why would have a GET...despite a GET shouldn't have a request body @PutMapping("{orgCode}") public JsonExternalReferenceLookupResponse lookup( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are looking for") // @PathVariable("orgCode") // @NonNull final String orgCode, @RequestBody @NonNull final JsonExternalReferenceLookupRequest request) { return externalReferenceRestControllerService.performLookup(orgCode, request); } // note that we are not going to update references because they are not supposed to change @PostMapping("{orgCode}") public ResponseEntity<?> insert(
@ApiParam(required = true, value = "`AD_Org.Value` of the external references we are inserting") // @PathVariable("orgCode") // @NonNull final String orgCode, @RequestBody @NonNull final JsonExternalReferenceCreateRequest request) { externalReferenceRestControllerService.performInsert(orgCode, request); return ResponseEntity.ok().build(); } @PutMapping("/upsert/{orgCode}") public ResponseEntity<?> upsert( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are upserting") // @PathVariable("orgCode") // @Nullable final String orgCode, @RequestBody @NonNull final JsonRequestExternalReferenceUpsert request) { externalReferenceRestControllerService.performUpsert(request, orgCode); return ResponseEntity.ok().build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\v2\ExternalReferenceRestController.java
2
请完成以下Java代码
public void setIsSOTrx (java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public java.lang.String getIsSOTrx () { return (java.lang.String)get_Value(COLUMNNAME_IsSOTrx); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); }
/** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set VAT Code. @param VATCode VAT Code */ @Override public void setVATCode (java.lang.String VATCode) { set_Value (COLUMNNAME_VATCode, VATCode); } /** Get VAT Code. @return VAT Code */ @Override public java.lang.String getVATCode () { return (java.lang.String)get_Value(COLUMNNAME_VATCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_C_VAT_Code.java
1
请完成以下Java代码
protected Collection<String> collectProcessInstanceIds() { Set<String> collectedProcessInstanceIds = new HashSet<String>(); List<String> processInstanceIds = builder.getProcessInstanceIds(); if (processInstanceIds != null) { collectedProcessInstanceIds.addAll(processInstanceIds); } final HistoricProcessInstanceQueryImpl historicProcessInstanceQuery = (HistoricProcessInstanceQueryImpl) builder.getHistoricProcessInstanceQuery(); if (historicProcessInstanceQuery != null) { collectedProcessInstanceIds.addAll(historicProcessInstanceQuery.listIds()); } EnsureUtil.ensureNotEmpty(BadUserRequestException.class, "processInstanceIds", collectedProcessInstanceIds); return collectedProcessInstanceIds; } protected void writeUserOperationLog(CommandContext commandContext, ProcessDefinition processDefinition, int numInstances, boolean async) { List<PropertyChange> propertyChanges = new ArrayList<PropertyChange>(); propertyChanges.add(new PropertyChange("nrOfInstances", null,
numInstances)); propertyChanges.add(new PropertyChange("async", null, async)); commandContext.getOperationLogManager() .logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_RESTART_PROCESS_INSTANCE, null, processDefinition.getId(), processDefinition.getKey(), propertyChanges); } protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) { return commandContext .getProcessEngineConfiguration() .getDeploymentCache() .findDeployedProcessDefinitionById(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractRestartProcessInstanceCmd.java
1
请完成以下Java代码
protected Object deserializeFromByteArray(byte[] bytes, String objectTypeName) throws Exception { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); DataFormatMapper mapper = dataFormat.getMapper(); DataFormatReader reader = dataFormat.getReader(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); InputStreamReader inReader = new InputStreamReader(bais, processEngineConfiguration.getDefaultCharset()); BufferedReader bufferedReader = new BufferedReader(inReader); try { Object mappedObject = reader.readInput(bufferedReader); return mapper.mapInternalToJava(mappedObject, objectTypeName, getValidator(processEngineConfiguration)); } finally{ IoUtil.closeSilently(bais); IoUtil.closeSilently(inReader); IoUtil.closeSilently(bufferedReader); }
} protected boolean canSerializeValue(Object value) { return dataFormat.getMapper().canMap(value); } protected DeserializationTypeValidator getValidator(final ProcessEngineConfigurationImpl processEngineConfiguration) { if (validator == null && processEngineConfiguration.isDeserializationTypeValidationEnabled()) { validator = new DeserializationTypeValidator() { @Override public boolean validate(String type) { return processEngineConfiguration.getDeserializationTypeValidator().validate(type); } }; } return validator; } }
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinObjectValueSerializer.java
1
请完成以下Java代码
public Collection<Object> values() { return new AbstractCollection<>() { @Override @NonNull public Iterator<Object> iterator() { return new DecoratingEntryValueIterator(delegate.entrySet().iterator()); } @Override public int size() { return delegate.size(); } }; } @Override @NonNull public Set<Entry<String, Object>> entrySet() { return new AbstractSet<>() { @Override @NonNull public Iterator<Entry<String, Object>> iterator() { return new DecoratingEntryIterator(delegate.entrySet().iterator()); } @Override public int size() { return delegate.size(); } }; } private class DecoratingEntryIterator implements Iterator<Entry<String, Object>> { private final Iterator<Entry<String, Object>> delegate; DecoratingEntryIterator(Iterator<Entry<String, Object>> delegate) { this.delegate = delegate; } @Override public boolean hasNext() { return delegate.hasNext(); }
@Override public Entry<String, Object> next() { Entry<String, Object> entry = delegate.next(); return new AbstractMap.SimpleEntry<>(entry.getKey(), cachingResolver.resolveProperty(entry.getKey())); } } @Override public void forEach(BiConsumer<? super String, ? super Object> action) { delegate.forEach((k, v) -> action.accept(k, cachingResolver.resolveProperty(k))); } private class DecoratingEntryValueIterator implements Iterator<Object> { private final Iterator<Entry<String, Object>> entryIterator; DecoratingEntryValueIterator(Iterator<Entry<String, Object>> entryIterator) { this.entryIterator = entryIterator; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public Object next() { Entry<String, Object> entry = entryIterator.next(); return cachingResolver.resolveProperty(entry.getKey()); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\EncryptableMapWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } public Optional<Student> findOne(String id) { return Optional.of(template.findById(Student.class).one(id)); } public List<Student> findAll() { return template.findByQuery(Student.class).all(); } public List<Student> findByFirstName(String firstName) { return template.findByQuery(Student.class).matching(where("firstName").is(firstName)).all(); } public List<Student> findByLastName(String lastName) {
return template.findByQuery(Student.class).matching(where("lastName").is(lastName)).all(); } public void create(Student student) { student.setCreated(DateTime.now()); template.insertById(Student.class).one(student); } public void update(Student student) { student.setUpdated(DateTime.now()); template.upsertById(Student.class).one(student); } public void delete(Student student) { template.removeById(Student.class).oneEntity(student); } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\StudentTemplateService.java
2
请完成以下Java代码
public class M_HU_PI { private transient static final Logger logger = LogManager.getLogger(M_HU_PI.class); private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void onDeleteMHUPI(final I_M_HU_PI pi) { final List<I_M_HU_PI_Version> piVersions = handlingUnitsDAO.retrieveAllPIVersions(pi); for (final I_M_HU_PI_Version version : piVersions) { InterfaceWrapperHelper.delete(version); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_M_HU_PI.COLUMNNAME_IsDefaultForPicking ) public void ensureOnlyOneDefaultForPicking(@NonNull final I_M_HU_PI newDefault) { try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(newDefault))
{ if (!newDefault.isDefaultForPicking()) { return; } final I_M_HU_PI previousDefault = handlingUnitsDAO.retrievePIDefaultForPicking(); if (previousDefault != null) { logger.debug("M_HU_PI={} is now IsDefaultForPicking; -> Change previousDefault M_HU_PI={} to IsDefaultForPicking='N'", newDefault.getM_HU_PI_ID(), previousDefault.getM_HU_PI_ID()); previousDefault.setIsDefaultForPicking(false); handlingUnitsDAO.save(previousDefault); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU_PI.java
1
请完成以下Java代码
public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public String getBootVersion() { return this.bootVersion; } public void setBootVersion(String bootVersion) { this.bootVersion = bootVersion; } public String getPackaging() { return this.packaging; } public void setPackaging(String packaging) { this.packaging = packaging; } public String getApplicationName() { return this.applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getConfigurationFileFormat() { return this.configurationFileFormat; } public void setConfigurationFileFormat(String configurationFileFormat) { this.configurationFileFormat = configurationFileFormat; } public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return getGroupId() + "." + getArtifactId();
} return null; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getJavaVersion() { return this.javaVersion; } public void setJavaVersion(String javaVersion) { this.javaVersion = javaVersion; } public String getBaseDir() { return this.baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectRequest.java
1
请完成以下Java代码
public CC createFieldLabelConstraints(final boolean sameLine) { final CC constraints = new CC() .alignX("trailing") // align label to right, near the editor field ; if (!sameLine) { constraints.newline(); } return constraints; } public CC createFieldEditorConstraints(final GridFieldLayoutConstraints gridFieldConstraints) { final CC constraints = new CC() .alignX("leading")
.pushX() .growX(); if (gridFieldConstraints.getSpanX() > 1) { final int spanX = gridFieldConstraints.getSpanX() * 2 - 1; constraints.setSpanX(spanX); } if (gridFieldConstraints.getSpanY() > 1) { constraints.setSpanY(gridFieldConstraints.getSpanY()); } return constraints; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelLayoutFactory.java
1
请在Spring Boot框架中完成以下Java代码
public Result<IPage<SysUser>> queryDepartPostUserPageList( @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, @RequestParam(name = "departId", required = false) String departId, @RequestParam(name="realname",required=false) String realname, @RequestParam(name="username",required=false) String username, @RequestParam(name="isMultiTranslate",required=false) String isMultiTranslate, @RequestParam(name="id",required = false) String id){ String[] arr = new String[]{departId, realname, username, id}; SqlInjectionUtil.filterContent(arr, SymbolConstant.SINGLE_QUOTATION_MARK); IPage<SysUser> pageList = sysUserDepartService.queryDepartPostUserPageList(departId, username, realname, pageSize, pageNo,id,isMultiTranslate); return Result.OK(pageList); } /** * 获取上传文件的进度 * * @param fileKey * @param type * @return */ @GetMapping("/getUploadFileProgress") public Result<Double> getUploadFileProgress(@RequestParam(name = "fileKey") String fileKey, @RequestParam("type") String type){ Double progress = ImportSysUserCache.getImportSysUserMap(fileKey, type); if(progress == 100){ ImportSysUserCache.removeImportLowAppMap(fileKey); } return Result.ok(progress);
} /** * 验证当前登录用户是否仍使用系统默认初始密码。 * 返回值说明: * yes_{URL编码后的默认密码} -> 用户当前密码为默认初始密码,前端需弹出强制修改提示 * no -> 用户密码不是默认密码,或未开启默认密码检测开关 */ @GetMapping("/verifyIzDefaultPwd") public Result<String> verifyIzDefaultPwd() throws UnsupportedEncodingException { // 未配置 Firewall 或已关闭默认密码检测开关 (enableDefaultPwdCheck=false) 时,直接返回 "no" 表示无需提示 if (jeecgBaseConfig.getFirewall() == null || Boolean.FALSE.equals((jeecgBaseConfig.getFirewall().getEnableDefaultPwdCheck()))) { return Result.OK("no"); } LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); SysUser user = sysUserService.getById(sysUser.getId()); String passwordEncode = PasswordUtil.encrypt(user.getUsername(), PasswordConstant.DEFAULT_PASSWORD, user.getSalt()); if(passwordEncode.equals(user.getPassword())){ String encode = URLEncoder.encode(PasswordConstant.DEFAULT_PASSWORD, "UTF-8"); return Result.OK("yes_" + encode); } return Result.OK("no"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysUserController.java
2
请完成以下Java代码
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 UUID. @param UUID UUID */ @Override public void setUUID (java.lang.String UUID) { set_ValueNoCheck (COLUMNNAME_UUID, UUID); } /** Get UUID. @return UUID */ @Override public java.lang.String getUUID () { return (java.lang.String)get_Value(COLUMNNAME_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection.java
1
请完成以下Java代码
public Builder withFirstName(String firstName) { this.firstName = firstName; return this; } public Builder withLastName(String lastName) { this.lastName = lastName; return this; } public Builder withEmail(String email) { this.email = email; return this; } public Builder withUsername(String username) { this.username = username; return this; }
public Builder withPassword(String password) { this.password = password; return this; } public Builder withAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; return this; } public CustomUserDetails build() { return new CustomUserDetails(this); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-thymeleaf\src\main\java\com\baeldung\customuserdetails\CustomUserDetails.java
1
请完成以下Java代码
private void preUpdate() { logger.info("@PreUpdate callback ..."); } @PreRemove private void preRemove() { logger.info("@PreRemove callback ..."); } @PostLoad private void postLoad() { logger.info("@PostLoad callback ..."); } @PostPersist private void postPersist() { logger.info("@PostPersist callback ..."); }
@PostUpdate private void postUpdate() { logger.info("@PostUpdate callback ..."); } @PostRemove private void postRemove() { logger.info("@PostRemove callback ..."); } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJpaCallbacks\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
protected void registerCallouts(@NonNull final IProgramaticCalloutProvider calloutsRegistry) { // nothing on this level } private void setupEventBus() { final List<Topic> userNotificationsTopics = getAvailableUserNotificationsTopics(); if (userNotificationsTopics != null && !userNotificationsTopics.isEmpty()) { final IEventBusFactory eventBusFactory = Services.get(IEventBusFactory.class); for (final Topic topic : userNotificationsTopics) { eventBusFactory.addAvailableUserNotificationsTopic(topic); } } } /** * @return available user notifications topics to listen */ protected List<Topic> getAvailableUserNotificationsTopics() { return ImmutableList.of(); } private void setupMigrationScriptsLogger() { final Set<String> tableNames = getTableNamesToSkipOnMigrationScriptsLogging(); if (tableNames != null && !tableNames.isEmpty()) { final IMigrationLogger migrationLogger = Services.get(IMigrationLogger.class); migrationLogger.addTablesToIgnoreList(tableNames); } } protected Set<String> getTableNamesToSkipOnMigrationScriptsLogging() {return ImmutableSet.of();} @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) {
// nothing } /** * Does nothing. Module interceptors are not allowed to intercept models or documents */ @Override public final void onModelChange(final Object model, final ModelChangeType changeType) { // nothing } /** * Does nothing. Module interceptors are not allowed to intercept models or documents */ @Override public final void onDocValidate(final Object model, final DocTimingType timing) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AbstractModuleInterceptor.java
1
请完成以下Java代码
public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO: notifyRecordsChanged: // get M_HU_IDs from recordRefs, // find the top level records from this view which contain our HUs // invalidate those top levels only final Set<HuId> huIdsToCheck = recordRefs .streamIds(I_M_HU.Table_Name, HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (huIdsToCheck.isEmpty()) { return; } final boolean containsSomeRecords = rowsBuffer.containsAnyOfHUIds(huIdsToCheck); if (!containsSomeRecords) { return; } invalidateAll(); } @Override public Stream<HUEditorRow> streamByIds(final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return Stream.empty(); } return streamByIds(HUEditorRowFilter.onlyRowIds(rowIds)); } public Stream<HUEditorRow> streamByIds(final HUEditorRowFilter filter) { return rowsBuffer.streamByIdsExcludingIncludedRows(filter); } /** * @return top level rows and included rows recursive stream which are matching the given filter */
public Stream<HUEditorRow> streamAllRecursive(final HUEditorRowFilter filter) { return rowsBuffer.streamAllRecursive(filter); } /** * @return true if there is any top level or included row which is matching given filter */ public boolean matchesAnyRowRecursive(final HUEditorRowFilter filter) { return rowsBuffer.matchesAnyRowRecursive(filter); } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { final Set<HuId> huIds = streamByIds(rowIds) .filter(HUEditorRow::isPureHU) .map(HUEditorRow::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (huIds.isEmpty()) { return ImmutableList.of(); } final List<I_M_HU> hus = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class) .addInArrayFilter(I_M_HU.COLUMN_M_HU_ID, huIds) .create() .list(I_M_HU.class); return InterfaceWrapperHelper.createList(hus, modelClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorView.java
1
请完成以下Java代码
public int getM_Warehouse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_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 Number of Inventory counts. @param NoInventoryCount Frequency of inventory counts per year */ public void setNoInventoryCount (int NoInventoryCount) { set_Value (COLUMNNAME_NoInventoryCount, Integer.valueOf(NoInventoryCount)); } /** Get Number of Inventory counts. @return Frequency of inventory counts per year */ public int getNoInventoryCount () { Integer ii = (Integer)get_Value(COLUMNNAME_NoInventoryCount); if (ii == null) return 0; return ii.intValue(); } /** Set Number of Product counts. @param NoProductCount Frequency of product counts per year */ public void setNoProductCount (int NoProductCount) { set_Value (COLUMNNAME_NoProductCount, Integer.valueOf(NoProductCount)); }
/** Get Number of Product counts. @return Frequency of product counts per year */ public int getNoProductCount () { Integer ii = (Integer)get_Value(COLUMNNAME_NoProductCount); if (ii == null) return 0; return ii.intValue(); } /** Set Number of runs. @param NumberOfRuns Frequency of processing Perpetual Inventory */ public void setNumberOfRuns (int NumberOfRuns) { set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns)); } /** Get Number of runs. @return Frequency of processing Perpetual Inventory */ public int getNumberOfRuns () { Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PerpetualInv.java
1
请完成以下Java代码
protected ProcessEngine lookupProcessEngine(BeanManager beanManager) { ServiceLoader<ProcessEngineLookup> processEngineServiceLoader = ServiceLoader.load(ProcessEngineLookup.class); Iterator<ProcessEngineLookup> serviceIterator = processEngineServiceLoader.iterator(); List<ProcessEngineLookup> discoveredLookups = new ArrayList<>(); while (serviceIterator.hasNext()) { ProcessEngineLookup serviceInstance = serviceIterator.next(); discoveredLookups.add(serviceInstance); } Collections.sort(discoveredLookups, new Comparator<ProcessEngineLookup>() { @Override public int compare(ProcessEngineLookup o1, ProcessEngineLookup o2) { return (-1) * ((Integer) o1.getPrecedence()).compareTo(o2.getPrecedence()); } }); ProcessEngine processEngine = null; for (ProcessEngineLookup processEngineLookup : discoveredLookups) { processEngine = processEngineLookup.getProcessEngine(); if (processEngine != null) { this.processEngineLookup = processEngineLookup; LOGGER.debug("ProcessEngineLookup service {} returned process engine.", processEngineLookup.getClass()); break; } else { LOGGER.debug("ProcessEngineLookup service {} returned 'null' value.", processEngineLookup.getClass()); } } if (processEngineLookup == null) {
throw new FlowableException("Could not find an implementation of the org.flowable.cdi.spi.ProcessEngineLookup service " + "returning a non-null processEngine. Giving up."); } FlowableServices services = ProgrammaticBeanLookup.lookup(FlowableServices.class, beanManager); services.setProcessEngine(processEngine); return processEngine; } private void deployProcesses(ProcessEngine processEngine) { new ProcessDeployer(processEngine).deployProcesses(); } public void beforeShutdown(@Observes BeforeShutdown event) { if (processEngineLookup != null) { processEngineLookup.ungetProcessEngine(); processEngineLookup = null; } LOGGER.info("Shutting down flowable-cdi"); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\FlowableExtension.java
1
请完成以下Java代码
public DmnEngineConfiguration setDecisionRequirementsDiagramGenerator(DecisionRequirementsDiagramGenerator decisionRequirementsDiagramGenerator) { this.decisionRequirementsDiagramGenerator = decisionRequirementsDiagramGenerator; return this; } public boolean isCreateDiagramOnDeploy() { return isCreateDiagramOnDeploy; } public DmnEngineConfiguration setCreateDiagramOnDeploy(boolean isCreateDiagramOnDeploy) { this.isCreateDiagramOnDeploy = isCreateDiagramOnDeploy; return this; } public String getDecisionFontName() { return decisionFontName; } public DmnEngineConfiguration setDecisionFontName(String decisionFontName) { this.decisionFontName = decisionFontName; return this; } public String getLabelFontName() { return labelFontName;
} public DmnEngineConfiguration setLabelFontName(String labelFontName) { this.labelFontName = labelFontName; return this; } public String getAnnotationFontName() { return annotationFontName; } public DmnEngineConfiguration setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; return this; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngineConfiguration.java
1
请完成以下Java代码
public class SumUpConfig { @NonNull @Getter private final SumUpConfigId id; @Getter private final boolean isActive; @NonNull @Getter private final String apiKey; @NonNull @Getter private final SumUpMerchantCode merchantCode; @Nullable @Getter private final SumUpCardReaderExternalId defaultCardReaderExternalId; @NonNull @Getter private final List<SumUpCardReader> cardReaders; @NonNull private final ImmutableMap<SumUpCardReaderExternalId, SumUpCardReader> cardReadersByExternalId; @Builder(toBuilder = true) private SumUpConfig( @NonNull final SumUpConfigId id, final boolean isActive, @NonNull final String apiKey, @NonNull final SumUpMerchantCode merchantCode, @NonNull final List<SumUpCardReader> cardReaders, @Nullable final SumUpCardReaderExternalId defaultCardReaderExternalId) { this.id = id; this.isActive = isActive; this.apiKey = apiKey; this.merchantCode = merchantCode; this.cardReaders = ImmutableList.copyOf(cardReaders); this.cardReadersByExternalId = Maps.uniqueIndex(cardReaders, SumUpCardReader::getExternalId); this.defaultCardReaderExternalId = determineDefaultCardReaderExternalId(defaultCardReaderExternalId, this.cardReadersByExternalId); } private static SumUpCardReaderExternalId determineDefaultCardReaderExternalId( @Nullable final SumUpCardReaderExternalId suggestedDefaultCardReaderExternalId, @NonNull Map<SumUpCardReaderExternalId, SumUpCardReader> cardReadersByExternalId) { SumUpCardReaderExternalId defaultCardReaderExternalId = suggestedDefaultCardReaderExternalId; if (defaultCardReaderExternalId != null) { final SumUpCardReader defaultCardReader = cardReadersByExternalId.get(defaultCardReaderExternalId); if (defaultCardReader == null || !defaultCardReader.isActive())
{ defaultCardReaderExternalId = null; } } if (defaultCardReaderExternalId == null && !cardReadersByExternalId.isEmpty()) { final List<SumUpCardReader> activeCardReaders = cardReadersByExternalId.values().stream() .filter(SumUpCardReader::isActive) .collect(Collectors.toList()); if (activeCardReaders.size() == 1) { defaultCardReaderExternalId = activeCardReaders.get(0).getExternalId(); } } return defaultCardReaderExternalId; } @NonNull public SumUpCardReaderExternalId getDefaultCardReaderExternalIdNotNull() { if (defaultCardReaderExternalId == null) { throw new AdempiereException("No default card reader was configured for " + this); } return defaultCardReaderExternalId; } public SumUpCardReader getCardReaderById(@NonNull SumUpCardReaderExternalId id) { final SumUpCardReader cardReader = cardReadersByExternalId.get(id); if (cardReader == null) { throw new AdempiereException("No card reader found for " + id); } return cardReader; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpConfig.java
1
请完成以下Java代码
protected BigDecimal getInternalValueNumber() { return valueBD; } @Override protected String getInternalValueStringInitial() { return valueInitialStr; } @Override protected BigDecimal getInternalValueNumberInitial() { return valueInitialBD; } @Override protected void setInternalValueStringInitial(final String value) { valueInitialStr = value; } @Override protected void setInternalValueNumberInitial(final BigDecimal value) { valueInitialBD = value; } @Override public String getPropagationType() { return propagationType; } @Override public IAttributeAggregationStrategy retrieveAggregationStrategy() { return aggregationStrategy; } @Override public IAttributeSplitterStrategy retrieveSplitterStrategy() { return splitterStrategy; } @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return transferStrategy; } @Override public boolean isUseInASI() { return false; } @Override public boolean isDefinedByTemplate() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public boolean isReadonlyUI() { return false; } @Override public boolean isDisplayedUI() { return true; } @Override public boolean isMandatory()
{ return false; } @Override public boolean isNew() { return isGeneratedAttribute; } @Override protected void setInternalValueDate(Date value) { this.valueDate = value; } @Override protected Date getInternalValueDate() { return valueDate; } @Override protected void setInternalValueDateInitial(Date value) { this.valueInitialDate = value; } @Override protected Date getInternalValueDateInitial() { return valueInitialDate; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\PlainAttributeValue.java
1
请完成以下Java代码
public class XLSXReader { /** * Opens an XLSX workbook. * * @param filePath the path to the XLSX file * @return a Workbook object representing the XLSX file * @throws IOException if an I/O error occurs */ public static Workbook openWorkbook(String filePath) throws IOException { try (FileInputStream fis = new FileInputStream(filePath)) { return WorkbookFactory.create(fis); } } /** * Iterates over rows and columns to output them as a list of string arrays. * * @param filePath the path to the XLSX file * @return a list of string arrays representing the data * @throws IOException if an I/O error occurs */ public static List<String[]> iterateAndPrepareData(String filePath) throws IOException { Workbook workbook = openWorkbook(filePath); Sheet sheet = workbook.getSheetAt(0); // Assuming we are reading from the first sheet
List<String[]> data = new ArrayList<>(); DataFormatter formatter = new DataFormatter(); // Iterate through each row in the sheet for (Row row : sheet) { int lastCellNum = row.getLastCellNum(); if (lastCellNum < 0) { continue; // Skip empty rows or rows with invalid data } String[] rowData = new String[lastCellNum]; // Iterate through each cell in the row for (int cn = 0; cn < lastCellNum; cn++) { Cell cell = row.getCell(cn); rowData[cn] = cell == null ? "" : formatter.formatCellValue(cell); } // Add the row data to the list data.add(rowData); } workbook.close(); return data; } }
repos\tutorials-master\core-java-modules\core-java-io-conversions-3\src\main\java\com\baeldung\xlsxtocsv\XLSXReader.java
1
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { // // Create/Update table sequences // NOTE: we shall do this only if it's a new table, else we will change the sequence's next value // which could be OK on our local development database, // but when the migration script will be executed on target customer database, their sequences will be wrongly changed (08607) if (success && newRecord) { final ISequenceDAO sequenceDAO = Services.get(ISequenceDAO.class); sequenceDAO.createTableSequenceChecker(getCtx()) .setFailOnFirstError(true) .setSequenceRangeCheck(false) .setTable(this) .setTrxName(get_TrxName()) .run(); } if (!newRecord && is_ValueChanged(COLUMNNAME_TableName)) {
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); adTableDAO.onTableNameRename(this); } return success; } // afterSave public Query createQuery(String whereClause, String trxName) { return new Query(this.getCtx(), this, whereClause, trxName); } @Override public String toString() { return "MTable[" + get_ID() + "-" + getTableName() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTable.java
1
请完成以下Java代码
protected void buildPrepare() { for (final OrgPermission perm : getPermissionsInternalMap().values()) { adClientIds.add(perm.getClientId()); adOrgIds.add(perm.getOrgId()); } } @Override protected OrgPermissions createPermissionsInstance() { return new OrgPermissions(this); } private AdTreeId getOrgTreeId() { return orgTreeId; } /** * Load Org Access Add Tree to List */ public Builder addPermissionRecursively(final OrgPermission oa) { if (hasPermission(oa)) { return this; } addPermission(oa, CollisionPolicy.Override); // Do we look for trees? final AdTreeId adTreeOrgId = getOrgTreeId(); if (adTreeOrgId == null) { return this; } final OrgResource orgResource = oa.getResource(); if (!orgResource.isGroupingOrg()) { return this; } // Summary Org - Get Dependents final MTree_Base tree = MTree_Base.getById(adTreeOrgId); final String sql = "SELECT " + " AD_Client_ID" + ", AD_Org_ID" + ", " + I_AD_Org.COLUMNNAME_IsSummary + " FROM AD_Org " + " WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + tree.getNodeTableName()
+ " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y')"; final Object[] sqlParams = new Object[] { tree.getAD_Tree_ID(), orgResource.getOrgId() }; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); while (rs.next()) { final ClientId clientId = ClientId.ofRepoId(rs.getInt(1)); final OrgId orgId = OrgId.ofRepoId(rs.getInt(2)); final boolean isGroupingOrg = StringUtils.toBoolean(rs.getString(3)); final OrgResource resource = OrgResource.of(clientId, orgId, isGroupingOrg); final OrgPermission childOrgPermission = oa.copyWithResource(resource); addPermissionRecursively(childOrgPermission); } return this; } catch (final SQLException e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermissions.java
1
请在Spring Boot框架中完成以下Java代码
public void setTERMSDATETO(String value) { this.termsdateto = value; } /** * Gets the value of the discountpercent property. * * @return * possible object is * {@link String } * */ public String getDISCOUNTPERCENT() { return discountpercent; } /** * Sets the value of the discountpercent property. * * @param value * allowed object is * {@link String } * */ public void setDISCOUNTPERCENT(String value) { this.discountpercent = value; } /** * Gets the value of the discountamount property. * * @return * possible object is * {@link String } * */ public String getDISCOUNTAMOUNT() { return discountamount; } /** * Sets the value of the discountamount property. *
* @param value * allowed object is * {@link String } * */ public void setDISCOUNTAMOUNT(String value) { this.discountamount = value; } /** * Gets the value of the paymentdesc property. * * @return * possible object is * {@link String } * */ public String getPAYMENTDESC() { return paymentdesc; } /** * Sets the value of the paymentdesc property. * * @param value * allowed object is * {@link String } * */ public void setPAYMENTDESC(String value) { this.paymentdesc = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HPAYT1.java
2
请完成以下Java代码
public String getDownloadOptions() { return downloadOptions; } public void setDownloadOptions(String downloadOptions) { this.downloadOptions = downloadOptions; } public String getPermittedCrossDomainPolicies() { return permittedCrossDomainPolicies; } public void setPermittedCrossDomainPolicies(String permittedCrossDomainPolicies) { this.permittedCrossDomainPolicies = permittedCrossDomainPolicies; } public String getPermissionsPolicy() { return permissionsPolicy; } public void setPermissionsPolicy(String permissionsPolicy) { this.permissionsPolicy = permissionsPolicy; } /** * @return the default/opt-out header names to disable */ public List<String> getDisable() { return disabledHeaders.stream().toList(); } /** * Binds the list of default/opt-out header names to disable, transforms them into a * lowercase set. This is to ensure case-insensitive comparison. * @param disable - list of default/opt-out header names to disable */ public void setDisable(List<String> disable) { if (disable != null) { disabledHeaders = disable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet()); } } /** * @return the opt-in header names to enable */ public Set<String> getEnabledHeaders() { return enabledHeaders; } /**
* Binds the list of default/opt-out header names to enable, transforms them into a * lowercase set. This is to ensure case-insensitive comparison. * @param enable - list of default/opt-out header enable */ public void setEnable(List<String> enable) { if (enable != null) { enabledHeaders = enable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet()); } } /** * @return the default/opt-out header names to disable */ public Set<String> getDisabledHeaders() { return disabledHeaders; } /** * @return the default/opt-out header names to apply */ public Set<String> getDefaultHeaders() { return defaultHeaders; } @Override public String toString() { return "SecureHeadersProperties{" + "xssProtectionHeader='" + xssProtectionHeader + '\'' + ", strictTransportSecurity='" + strictTransportSecurity + '\'' + ", frameOptions='" + frameOptions + '\'' + ", contentTypeOptions='" + contentTypeOptions + '\'' + ", referrerPolicy='" + referrerPolicy + '\'' + ", contentSecurityPolicy='" + contentSecurityPolicy + '\'' + ", downloadOptions='" + downloadOptions + '\'' + ", permittedCrossDomainPolicies='" + permittedCrossDomainPolicies + '\'' + ", permissionsPolicy='" + permissionsPolicy + '\'' + ", defaultHeaders=" + defaultHeaders + ", enable=" + enabledHeaders + ", disable=" + disabledHeaders + '}'; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersProperties.java
1
请完成以下Java代码
public String getName() { return identityId; } /** * @return the id of the identity * (userId) behind this authentication */ public String getIdentityId() { return identityId; } /** * @return return the name of the process engine for which this authentication * was established. */ public String getProcessEngineName() { return processEngineName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((identityId == null) ? 0 : identityId.hashCode()); result = prime * result + ((processEngineName == null) ? 0 : processEngineName.hashCode()); return result; } @Override public boolean equals(Object obj) {
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Authentication other = (Authentication) obj; if (identityId == null) { if (other.identityId != null) return false; } else if (!identityId.equals(other.identityId)) return false; if (processEngineName == null) { if (other.processEngineName != null) return false; } else if (!processEngineName.equals(other.processEngineName)) return false; return true; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\Authentication.java
1
请完成以下Java代码
public DetailId getTabId() { return tabId; } public void setAllowCreateNew(final boolean allowCreateNew, final String reason) { this.allowCreateNew = allowCreateNew; allowCreateNewReason = reason; } public void setAllowDelete(final boolean allowDelete, final String reason) { this.allowDelete = allowDelete; allowDeleteReason = reason; } public void markAllRowsStaled() { stale = Boolean.TRUE; } public void staleRows(@NonNull final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { // shall not happen return; } else if (rowIds.isAll()) { markAllRowsStaled(); }
else { staleRowIds.addAll(rowIds.toSet()); } } public void mergeFrom(JSONIncludedTabInfo from) { if (from.stale != null) { stale = from.stale; } staleRowIds.addAll(from.staleRowIds); if (from.allowCreateNew != null) { allowCreateNew = from.allowCreateNew; allowCreateNewReason = from.allowCreateNewReason; } if (from.allowDelete != null) { allowDelete = from.allowDelete; allowDeleteReason = from.allowDeleteReason; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONIncludedTabInfo.java
1
请完成以下Java代码
public static Date getNextWeekEndDay() { return DateUtil.endOfWeek(DateUtil.nextWeek()); } /** * 过去七天开始时间(不含今天) * * @return */ public static Date getLast7DaysStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -7); return DateUtil.beginOfDay(calendar.getTime()); } /** * 过去七天结束时间(不含今天) * * @return */ public static Date getLast7DaysEndTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getLast7DaysStartTime()); calendar.add(Calendar.DATE, 6); return DateUtil.endOfDay(calendar.getTime()); } /** * 昨天开始时间 * * @return */ public static Date getYesterdayStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -1); return DateUtil.beginOfDay(calendar.getTime()); } /** * 昨天结束时间 * * @return */ public static Date getYesterdayEndTime() { return DateUtil.endOfDay(getYesterdayStartTime());
} /** * 明天开始时间 * * @return */ public static Date getTomorrowStartTime() { return DateUtil.beginOfDay(DateUtil.tomorrow()); } /** * 明天结束时间 * * @return */ public static Date getTomorrowEndTime() { return DateUtil.endOfDay(DateUtil.tomorrow()); } /** * 今天开始时间 * * @return */ public static Date getTodayStartTime() { return DateUtil.beginOfDay(new Date()); } /** * 今天结束时间 * * @return */ public static Date getTodayEndTime() { return DateUtil.endOfDay(new Date()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateRangeUtils.java
1
请完成以下Java代码
public void addTransactionListener(TransactionState transactionState, final TransactionListener transactionListener) { CommandContext commandContext = Context.getCommandContext(); try { addTransactionListener(transactionState, transactionListener, commandContext); } catch (Exception e) { throw LOG.exceptionWhileInteractingWithTransaction("registering synchronization", e); } } public abstract static class TransactionStateSynchronization { protected final TransactionListener transactionListener; protected final TransactionState transactionState; private final CommandContext commandContext; public TransactionStateSynchronization(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) { this.transactionState = transactionState; this.transactionListener = transactionListener; this.commandContext = commandContext; } public void beforeCompletion() { if(TransactionState.COMMITTING.equals(transactionState) || TransactionState.ROLLINGBACK.equals(transactionState)) { transactionListener.execute(commandContext); } } public void afterCompletion(int status) { if(isRolledBack(status) && TransactionState.ROLLED_BACK.equals(transactionState)) {
transactionListener.execute(commandContext); } else if(isCommitted(status) && TransactionState.COMMITTED.equals(transactionState)) { transactionListener.execute(commandContext); } } protected abstract boolean isCommitted(int status); protected abstract boolean isRolledBack(int status); } @Override public boolean isTransactionActive() { try { return isTransactionActiveInternal(); } catch (Exception e) { throw LOG.exceptionWhileInteractingWithTransaction("getting transaction state", e); } } protected abstract void doRollback() throws Exception; protected abstract boolean isTransactionActiveInternal() throws Exception; protected abstract void addTransactionListener(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) throws Exception; }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\jta\AbstractTransactionContext.java
1
请完成以下Java代码
public String getLocalizedName() { return localizedName; } @Override public void setLocalizedName(String localizedName) { this.localizedName = localizedName; } @Override public boolean isPlannedForActivationInMigration() { return plannedForActivationInMigration; } @Override public void setPlannedForActivationInMigration(boolean plannedForActivationInMigration) { this.plannedForActivationInMigration = plannedForActivationInMigration; } @Override public boolean isStateChangeUnprocessed() { return stateChangeUnprocessed; } @Override public void setStateChangeUnprocessed(boolean stateChangeUnprocessed) { this.stateChangeUnprocessed = stateChangeUnprocessed; } @Override public Map<String, Object> getPlanItemInstanceLocalVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (VariableInstance variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getSubScopeId() != null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } @Override public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("PlanItemInstance with id: ") .append(id); if (getName() != null) { stringBuilder.append(", name: ").append(getName()); } stringBuilder.append(", definitionId: ") .append(planItemDefinitionId) .append(", state: ") .append(state); if (elementId != null) { stringBuilder.append(", elementId: ").append(elementId); } stringBuilder .append(", caseInstanceId: ") .append(caseInstanceId) .append(", caseDefinitionId: ") .append(caseDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { stringBuilder.append(", tenantId=").append(tenantId); } return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\PlanItemInstanceEntityImpl.java
1
请完成以下Java代码
public void attachState(MigratingTransitionInstance targetTransitionInstance) { throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this); } public void setDependentJobInstance(MigratingAsyncJobInstance jobInstance) { this.jobInstance = jobInstance; } public void addMigratingDependentInstance(MigratingInstance migratingInstance) { migratingDependentInstances.add(migratingInstance); } public List<MigratingInstance> getMigratingDependentInstances() { return migratingDependentInstances; } @Override public void migrateState() { ExecutionEntity representativeExecution = resolveRepresentativeExecution(); representativeExecution.setProcessDefinition(targetScope.getProcessDefinition()); representativeExecution.setActivity((PvmActivity) targetScope); } @Override public void migrateDependentEntities() { jobInstance.migrateState(); jobInstance.migrateDependentEntities(); for (MigratingInstance dependentInstance : migratingDependentInstances) { dependentInstance.migrateState(); dependentInstance.migrateDependentEntities(); } } public TransitionInstance getTransitionInstance() { return transitionInstance; } /** * Else asyncBefore */ public boolean isAsyncAfter() { return jobInstance.isAsyncAfter(); }
public boolean isAsyncBefore() { return jobInstance.isAsyncBefore(); } public MigratingJobInstance getJobInstance() { return jobInstance; } @Override public void setParent(MigratingScopeInstance parentInstance) { if (parentInstance != null && !(parentInstance instanceof MigratingActivityInstance)) { throw MIGRATION_LOGGER.cannotHandleChild(parentInstance, this); } MigratingActivityInstance parentActivityInstance = (MigratingActivityInstance) parentInstance; if (this.parentInstance != null) { ((MigratingActivityInstance) this.parentInstance).removeChild(this); } this.parentInstance = parentActivityInstance; if (parentInstance != null) { parentActivityInstance.addChild(this); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingTransitionInstance.java
1
请完成以下Java代码
public int getC_Period_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Period_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date. @return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Document Date. @param DateDoc Date of the Document */ public void setDateDoc (Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Document Date. @return Date of the Document */ public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) {
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Disposed.java
1
请完成以下Java代码
protected Map<Class<? extends Throwable>, Boolean> getEntries() { return this.entries; } private boolean matchInCache(@Nullable Throwable classifiable) { if (classifiable == null) { return this.defaultMatch; } Class<? extends Throwable> exceptionClass = classifiable.getClass(); if (this.entries.containsKey(exceptionClass)) { return this.entries.get(exceptionClass); } // check for subclasses Boolean value = null; for (Class<?> cls = exceptionClass.getSuperclass(); !cls.equals(Object.class) && value == null; cls = cls.getSuperclass()) { value = this.entries.get(cls); } // check for interfaces subclasses if (value == null) { for (Class<?> cls = exceptionClass; !cls.equals(Object.class) && value == null; cls = cls.getSuperclass()) { for (Class<?> ifc : cls.getInterfaces()) { value = this.entries.get(ifc); if (value != null) { break; } } } } // ConcurrentHashMap doesn't allow nulls if (value != null) { this.entries.put(exceptionClass, value); } if (value == null) { value = this.defaultMatch; } return value; } /** * Fluent API for configuring an {@link ExceptionMatcher}. */ public static class Builder { private final boolean matchIfFound; private final Set<Class<? extends Throwable>> exceptionClasses = new LinkedHashSet<>(); private boolean traverseCauses = false;
protected Builder(boolean matchIfFound) { this.matchIfFound = matchIfFound; } /** * Add an exception type. * @param exceptionType the exception type to add * @return {@code this} */ public Builder add(Class<? extends Throwable> exceptionType) { Assert.notNull(exceptionType, "Exception class can not be null"); this.exceptionClasses.add(exceptionType); return this; } /** * Add all exception types from the given collection. * @param exceptionTypes the exception types to add * @return {@code this} */ public Builder addAll(Collection<Class<? extends Throwable>> exceptionTypes) { this.exceptionClasses.addAll(exceptionTypes); return this; } /** * Specify if the matcher should traverse nested causes to check for the presence * of a matching exception. * @param traverseCauses whether to traverse causes * @return {@code this} */ public Builder traverseCauses(boolean traverseCauses) { this.traverseCauses = traverseCauses; return this; } /** * Build an {@link ExceptionMatcher}. * @return a new exception matcher */ public ExceptionMatcher build() { return new ExceptionMatcher(buildEntries(new ArrayList<>(this.exceptionClasses), this.matchIfFound), !this.matchIfFound, this.traverseCauses); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\ExceptionMatcher.java
1
请完成以下Java代码
public String getExecutionId() { return executionId; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public String getTaskId() { return taskId; } public String getJobId() { return jobId; } public String getJobDefinitionId() { return jobDefinitionId; } public String getBatchId() { return batchId; } public String getUserId() { return userId; } public Date getTimestamp() { return timestamp; } public String getOperationId() { return operationId; } public String getExternalTaskId() {
return externalTaskId; } public String getOperationType() { return operationType; } public String getEntityType() { return entityType; } public String getProperty() { return property; } public String getOrgValue() { return orgValue; } public String getNewValue() { return newValue; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getCategory() { return category; } public String getAnnotation() { return annotation; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogEntryDto.java
1
请完成以下Java代码
public void applyTo(VariableScope variableScope, VariableMap variables) { if (readLocal) { variableScope = new VariableScopeLocalAdapter(variableScope); } if (allVariables) { Map<String, Object> allVariables = variableScope.getVariables(); variables.putAll(allVariables); } else { Object value = getSource(variableScope); variables.put(target, value); } } public ParameterValueProvider getSourceValueProvider() { return sourceValueProvider; } public void setSourceValueProvider(ParameterValueProvider source) { this.sourceValueProvider = source; } // target ////////////////////////////////////////////////////////// public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } // all variables //////////////////////////////////////////////////
public boolean isAllVariables() { return allVariables; } public void setAllVariables(boolean allVariables) { this.allVariables = allVariables; } // local public void setReadLocal(boolean readLocal) { this.readLocal = readLocal; } public boolean isReadLocal() { return readLocal; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CallableElementParameter.java
1
请完成以下Java代码
@Override protected String doIt() throws Exception { final BPartnerId bPartnerId = BPartnerId.ofRepoId(getProcessInfo().getRecord_ID()); final List<TransactionResult> transactionResults = creditPassTransactionService .getAndSaveCreditScore(Optional.ofNullable(paymentRule).orElse(StringUtils.EMPTY), bPartnerId); List<Integer> tableRecordReferences = transactionResults.stream() .map(tr -> tr.getTransactionResultId().getRepoId()) .collect(Collectors.toList()); getResult().setRecordsToOpen(I_CS_Transaction_Result.Table_Name, tableRecordReferences, null); return MSG_OK; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!context.isSingleSelection())
{ return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final I_C_BPartner partner = context.getSelectedModel(I_C_BPartner.class); if (!partner.isCustomer()) { return ProcessPreconditionsResolution.rejectWithInternalReason("Business partner is not a customer"); } if (!creditPassTransactionService.hasConfigForPartnerId(BPartnerId.ofRepoId(partner.getC_BPartner_ID()))) { return ProcessPreconditionsResolution.rejectWithInternalReason("Business partner has no associated creditPass config"); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\process\CS_Creditpass_TransactionFrom_C_BPartner.java
1
请完成以下Java代码
public void assertExpectedNetAmtToInvoiceIfSet() { if (_netAmtToInvoiceExpected == null) { return; } assertExpectedNetAmtToInvoice(_netAmtToInvoiceExpected); } /** * Asserts aggregated net amount to invoice equals with given expected value. * * If it's not equal, an error message will be logged to {@link ILoggable}. * * @throws AdempiereException if the checksums are not equal and {@link #isFailIfNetAmtToInvoiceChecksumNotMatch()}. */ public void assertExpectedNetAmtToInvoice(@NonNull final BigDecimal netAmtToInvoiceExpected) { Check.assume(netAmtToInvoiceExpected.signum() != 0, "netAmtToInvoiceExpected != 0"); final BigDecimal netAmtToInvoiceActual = getValue(); if (netAmtToInvoiceExpected.compareTo(netAmtToInvoiceActual) != 0) { final String errmsg = "NetAmtToInvoice checksum not match" + "\n Expected: " + netAmtToInvoiceExpected + "\n Actual: " + netAmtToInvoiceActual
+ "\n Invoice candidates count: " + _countInvoiceCandidates; Loggables.addLog(errmsg); if (isFailIfNetAmtToInvoiceChecksumNotMatch()) { throw new AdempiereException(errmsg); } } } /** * @return true if we shall fail if the net amount to invoice checksum does not match. */ public final boolean isFailIfNetAmtToInvoiceChecksumNotMatch() { final boolean failIfNetAmtToInvoiceChecksumNotMatchDefault = true; return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_FailIfNetAmtToInvoiceChecksumNotMatch, failIfNetAmtToInvoiceChecksumNotMatchDefault); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ICNetAmtToInvoiceChecker.java
1
请在Spring Boot框架中完成以下Java代码
public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public void setParentCaseInstanceId(String parentCaseInstanceId) { this.parentCaseInstanceId = parentCaseInstanceId; } public Boolean getWithoutCallbackId() { return withoutCallbackId; } public void setWithoutCallbackId(Boolean withoutCallbackId) { this.withoutCallbackId = withoutCallbackId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } public Boolean getWithoutTenantId() { return withoutTenantId; }
public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getCallbackIds() { return callbackIds; } public void setCallbackIds(Set<String> callbackIds) { this.callbackIds = callbackIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceQueryRequest.java
2
请完成以下Java代码
public int processScheduled() { final int batchSize = getProcessingBatchSize(); final Stopwatch stopwatch = Stopwatch.createStarted(); final int count = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, "SELECT de_metas_acct.fact_acct_openItems_to_update_process(p_BatchSize:=?)", batchSize); stopwatch.stop(); logger.debug("Processed {} records in {} (batchSize={})", count, stopwatch, batchSize); return count; } private int getProcessingBatchSize() { final int batchSize = sysConfigBL.getIntValue(SYSCONFIG_ProcessingBatchSize, -1); return batchSize > 0 ? batchSize : DEFAULT_ProcessingBatchSize; } public void fireGLJournalCompleted(final SAPGLJournal glJournal) { for (SAPGLJournalLine line : glJournal.getLines()) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { continue; }
handlersByKey.values() .stream() .distinct() .forEach(handler -> handler.onGLJournalLineCompleted(line)); } } public void fireGLJournalReactivated(final SAPGLJournal glJournal) { for (SAPGLJournalLine line : glJournal.getLines()) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { continue; } handlersByKey.values().forEach(handler -> handler.onGLJournalLineReactivated(line)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\FAOpenItemsService.java
1
请完成以下Java代码
public String getConfiguration() { return configuration; } public String getHistoryConfiguration() { return historyConfiguration; } public String getIncidentMessage() { return incidentMessage; } public String getTenantId() { return tenantId; } public String getJobDefinitionId() { return jobDefinitionId; } public Boolean isOpen() { return open; } public Boolean isDeleted() { return deleted; } public Boolean isResolved() { return resolved; } public String getAnnotation() { return annotation; }
public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) { HistoricIncidentDto dto = new HistoricIncidentDto(); dto.id = historicIncident.getId(); dto.processDefinitionKey = historicIncident.getProcessDefinitionKey(); dto.processDefinitionId = historicIncident.getProcessDefinitionId(); dto.processInstanceId = historicIncident.getProcessInstanceId(); dto.executionId = historicIncident.getExecutionId(); dto.createTime = historicIncident.getCreateTime(); dto.endTime = historicIncident.getEndTime(); dto.incidentType = historicIncident.getIncidentType(); dto.failedActivityId = historicIncident.getFailedActivityId(); dto.activityId = historicIncident.getActivityId(); dto.causeIncidentId = historicIncident.getCauseIncidentId(); dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId(); dto.configuration = historicIncident.getConfiguration(); dto.historyConfiguration = historicIncident.getHistoryConfiguration(); dto.incidentMessage = historicIncident.getIncidentMessage(); dto.open = historicIncident.isOpen(); dto.deleted = historicIncident.isDeleted(); dto.resolved = historicIncident.isResolved(); dto.tenantId = historicIncident.getTenantId(); dto.jobDefinitionId = historicIncident.getJobDefinitionId(); dto.removalTime = historicIncident.getRemovalTime(); dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId(); dto.annotation = historicIncident.getAnnotation(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentDto.java
1
请完成以下Java代码
public class ReconnectStrategyExponential implements ReconnectStrategy { public static final int DEFAULT_RECONNECT_INTERVAL_SEC = 10; public static final int MAX_RECONNECT_INTERVAL_SEC = 60; public static final int EXP_MAX = 8; public static final long JITTER_MAX = 1; private final long reconnectIntervalMinSeconds; private final long reconnectIntervalMaxSeconds; private long lastDisconnectNanoTime = 0; //isotonic time private long retryCount = 0; public ReconnectStrategyExponential(long reconnectIntervalMinSeconds) { this.reconnectIntervalMaxSeconds = calculateIntervalMax(reconnectIntervalMinSeconds); this.reconnectIntervalMinSeconds = calculateIntervalMin(reconnectIntervalMinSeconds); } long calculateIntervalMax(long reconnectIntervalMinSeconds) { return reconnectIntervalMinSeconds > MAX_RECONNECT_INTERVAL_SEC ? reconnectIntervalMinSeconds : MAX_RECONNECT_INTERVAL_SEC; } long calculateIntervalMin(long reconnectIntervalMinSeconds) { return Math.min((reconnectIntervalMinSeconds > 0 ? reconnectIntervalMinSeconds : DEFAULT_RECONNECT_INTERVAL_SEC), this.reconnectIntervalMaxSeconds); } @Override synchronized public long getNextReconnectDelay() { final long currentNanoTime = getNanoTime(); final long coolDownSpentNanos = currentNanoTime - lastDisconnectNanoTime; lastDisconnectNanoTime = currentNanoTime; if (isCooledDown(coolDownSpentNanos)) {
retryCount = 0; return reconnectIntervalMinSeconds; } return calculateNextReconnectDelay() + calculateJitter(); } long calculateJitter() { return ThreadLocalRandom.current().nextInt() >= 0 ? JITTER_MAX : 0; } long calculateNextReconnectDelay() { return Math.min(reconnectIntervalMaxSeconds, reconnectIntervalMinSeconds + calculateExp(retryCount++)); } long calculateExp(long e) { return 1L << Math.min(e, EXP_MAX); } boolean isCooledDown(long coolDownSpentNanos) { return TimeUnit.NANOSECONDS.toSeconds(coolDownSpentNanos) > reconnectIntervalMaxSeconds + reconnectIntervalMinSeconds; } long getNanoTime() { return System.nanoTime(); } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\ReconnectStrategyExponential.java
1
请完成以下Java代码
public int getM_HU_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Locator_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_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 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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Stock_Detail_V.java
1
请在Spring Boot框架中完成以下Java代码
public H100 getH100() { return h100; } public List<H110> getH110Lines() { return h110Lines; } public List<H120> getH120Lines() { return h120Lines; }
public List<H130> getH130Lines() { return h130Lines; } public List<OrderLine> getOrderLines() { return orderLines; } public List<T100> getT100Lines() { return t100Lines; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\OrderHeader.java
2
请完成以下Java代码
public void setPlannedQty (final BigDecimal PlannedQty) { set_ValueNoCheck (COLUMNNAME_PlannedQty, PlannedQty); } @Override public BigDecimal getPlannedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override
public void setSKU (final @Nullable java.lang.String SKU) { set_ValueNoCheck (COLUMNNAME_SKU, SKU); } @Override public java.lang.String getSKU() { return get_ValueAsString(COLUMNNAME_SKU); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Details_v.java
1
请完成以下Java代码
public static Locator parse(String hostPort) { return Optional.ofNullable(hostPort) .filter(StringUtils::hasText) .map(it -> { String host = parseHost(it); int port = parsePort(it); return newLocator(host, port); }) .orElseThrow(() -> newIllegalArgumentException("Locator host/port [%s] is not valid", hostPort)); } private static String parseHost(String value) { int index = String.valueOf(value).trim().indexOf("["); return index > 0 ? value.trim().substring(0, index).trim() : index != 0 && StringUtils.hasText(value) ? value.trim() : DEFAULT_LOCATOR_HOST; } private static int parsePort(String value) { StringBuilder digits = new StringBuilder(); for (char chr : String.valueOf(value).toCharArray()) { if (Character.isDigit(chr)) { digits.append(chr); } } return digits.length() > 0 ? Integer.parseInt(digits.toString()) : DEFAULT_LOCATOR_PORT; } /** * Construct a new {@link Locator} initialized with the {@link String host} and {@link Integer port} * on which this {@link Locator} is running and listening for connections. * * @param host {@link String} containing the name of the host on which this {@link Locator} is running. * @param port {@link Integer} specifying the port number on which this {@link Locator} is listening. */ private Locator(String host, Integer port) { this.host = host; this.port = port; } /** * Return the {@link String name} of the host on which this {@link Locator} is running. * * Defaults to {@literal localhost}. * * @return the {@link String name} of the host on which this {@link Locator} is running. */ public String getHost() { return StringUtils.hasText(this.host) ? this.host : DEFAULT_LOCATOR_HOST; } /** * Returns the {@link Integer port} on which this {@link Locator} is listening. * * Defaults to {@literal 10334}. * * @return the {@link Integer port} on which this {@link Locator} is listening. */
public int getPort() { return this.port != null ? this.port : DEFAULT_LOCATOR_PORT; } @Override public int compareTo(Locator other) { int result = this.getHost().compareTo(other.getHost()); return result != 0 ? result : (this.getPort() - other.getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Locator)) { return false; } Locator that = (Locator) obj; return this.getHost().equals(that.getHost()) && this.getPort() == that.getPort(); } @Override public int hashCode() { int hashValue = 17; hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getHost()); hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPort()); return hashValue; } @Override public String toString() { return String.format("%s[%d]", getHost(), getPort()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\CloudCacheService.java
1
请完成以下Java代码
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = this.userRepository.findByEmail(username); if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); } return new CustomUserDetails(user); } private static final class CustomUserDetails extends User implements UserDetails { private CustomUserDetails(User user) { super(user); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return AuthorityUtils.createAuthorityList("ROLE_USER"); } @Override public String getUsername() { return getEmail(); } @Override public boolean isAccountNonExpired() { return true; }
@Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } private static final long serialVersionUID = 5639683223516504866L; } }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\security\UserRepositoryUserDetailsService.java
1
请完成以下Java代码
public class MyPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor { public MyPerformanceMonitorInterceptor() { } public MyPerformanceMonitorInterceptor(boolean useDynamicLogger) { setUseDynamicLogger(useDynamicLogger); } @Override protected Object invokeUnderTrace(MethodInvocation invocation, Log log) throws Throwable { String name = createInvocationTraceName(invocation); long start = System.currentTimeMillis(); log.info("Method "+name+" execution started at:"+new Date()); try {
return invocation.proceed(); } finally { long end = System.currentTimeMillis(); long time = end - start; log.info("Method "+name+" execution lasted:"+time+" ms"); log.info("Method "+name+" execution ended at:"+new Date()); if (time > 10){ log.warn("Method execution longer than 10 ms!"); } } } }
repos\tutorials-master\spring-aop-2\src\main\java\com\baeldung\performancemonitor\MyPerformanceMonitorInterceptor.java
1
请完成以下Java代码
protected Mono<HttpClient> getHttpClientMono(Route route, ServerWebExchange exchange) { return Mono.just(getHttpClient(route, exchange)); } /** * Creates a new HttpClient with per route timeout configuration. Sub-classes that * override, should call super.getHttpClient() if they want to honor the per route * timeout configuration. * @param route the current route. * @param exchange the current ServerWebExchange. * @return the configured HttpClient. */ protected HttpClient getHttpClient(Route route, ServerWebExchange exchange) { Object connectTimeoutAttr = route.getMetadata().get(CONNECT_TIMEOUT_ATTR) != null ? route.getMetadata().get(CONNECT_TIMEOUT_ATTR) : properties.getConnectTimeout(); if (connectTimeoutAttr != null) { Integer connectTimeout = java.util.Objects.requireNonNull(getInteger(connectTimeoutAttr), "connectTimeout must not be null"); return this.httpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); } return httpClient; } static @Nullable Integer getInteger(Object connectTimeoutAttr) { Integer connectTimeout; if (connectTimeoutAttr instanceof Integer) { connectTimeout = (Integer) connectTimeoutAttr; } else { connectTimeout = Integer.parseInt(connectTimeoutAttr.toString()); } return connectTimeout; }
private @Nullable Duration getResponseTimeout(Route route) { try { if (route.getMetadata().containsKey(RESPONSE_TIMEOUT_ATTR)) { Long routeResponseTimeout = getLong(route.getMetadata().get(RESPONSE_TIMEOUT_ATTR)); if (routeResponseTimeout != null && routeResponseTimeout >= 0) { return Duration.ofMillis(routeResponseTimeout); } else { return null; } } } catch (NumberFormatException e) { // ignore number format and use global default } return properties.getResponseTimeout(); } static @Nullable Long getLong(Object responseTimeoutAttr) { Long responseTimeout = null; if (responseTimeoutAttr instanceof Number) { responseTimeout = ((Number) responseTimeoutAttr).longValue(); } else if (responseTimeoutAttr != null) { responseTimeout = Long.parseLong(responseTimeoutAttr.toString()); } return responseTimeout; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\NettyRoutingFilter.java
1
请在Spring Boot框架中完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getSubscriptionsPerConnection() { return subscriptionsPerConnection; } public void setSubscriptionsPerConnection(int subscriptionsPerConnection) { this.subscriptionsPerConnection = subscriptionsPerConnection; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public int getSubscriptionConnectionMinimumIdleSize() { return subscriptionConnectionMinimumIdleSize; } public void setSubscriptionConnectionMinimumIdleSize(int subscriptionConnectionMinimumIdleSize) { this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize; } public int getSubscriptionConnectionPoolSize() { return subscriptionConnectionPoolSize; } public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) { this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize; } public int getConnectionMinimumIdleSize() { return connectionMinimumIdleSize; } public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) { this.connectionMinimumIdleSize = connectionMinimumIdleSize; } public int getConnectionPoolSize() { return connectionPoolSize; } public void setConnectionPoolSize(int connectionPoolSize) { this.connectionPoolSize = connectionPoolSize; } public int getDatabase() {
return database; } public void setDatabase(int database) { this.database = database; } public boolean isDnsMonitoring() { return dnsMonitoring; } public void setDnsMonitoring(boolean dnsMonitoring) { this.dnsMonitoring = dnsMonitoring; } public int getDnsMonitoringInterval() { return dnsMonitoringInterval; } public void setDnsMonitoringInterval(int dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } }
repos\kkFileView-master\server\src\main\java\cn\keking\config\RedissonConfig.java
2
请完成以下Java代码
public class StreamRetryOperationsInterceptorFactoryBean extends StatelessRetryOperationsInterceptorFactoryBean { @Override protected @Nullable Object recover(@Nullable Object[] args, Throwable cause) { StreamMessageRecoverer messageRecoverer = (StreamMessageRecoverer) getMessageRecoverer(); Object arg = args[0]; if (arg instanceof org.springframework.amqp.core.Message) { return super.recover(args, cause); } else { if (messageRecoverer == null) { this.logger.warn("Message(s) dropped on recovery: " + arg, cause); } else { Message message = (Message) arg; Context context = (Context) args[1]; Assert.notNull(message, "Message must not be null"); Assert.notNull(context, "Context must not be null"); messageRecoverer.recover(message, context, cause); } return null; } }
/** * Set a {@link StreamMessageRecoverer} to call when retries are exhausted. * @param messageRecoverer the recoverer. */ public void setStreamMessageRecoverer(StreamMessageRecoverer messageRecoverer) { super.setMessageRecoverer(messageRecoverer); } @Override public void setMessageRecoverer(MessageRecoverer messageRecoverer) { throw new UnsupportedOperationException("Use setStreamMessageRecoverer() instead"); } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\retry\StreamRetryOperationsInterceptorFactoryBean.java
1
请完成以下Java代码
public java.lang.String getShipper_EORI() { return get_ValueAsString(COLUMNNAME_Shipper_EORI); } @Override public void setShipper_Name1 (final @Nullable java.lang.String Shipper_Name1) { set_Value (COLUMNNAME_Shipper_Name1, Shipper_Name1); } @Override public java.lang.String getShipper_Name1() { return get_ValueAsString(COLUMNNAME_Shipper_Name1); } @Override public void setShipper_Name2 (final @Nullable java.lang.String Shipper_Name2) { set_Value (COLUMNNAME_Shipper_Name2, Shipper_Name2); } @Override public java.lang.String getShipper_Name2() { return get_ValueAsString(COLUMNNAME_Shipper_Name2); } @Override public void setShipper_StreetName1 (final @Nullable java.lang.String Shipper_StreetName1) { set_Value (COLUMNNAME_Shipper_StreetName1, Shipper_StreetName1); } @Override public java.lang.String getShipper_StreetName1() { return get_ValueAsString(COLUMNNAME_Shipper_StreetName1); } @Override public void setShipper_StreetName2 (final @Nullable java.lang.String Shipper_StreetName2) { set_Value (COLUMNNAME_Shipper_StreetName2, Shipper_StreetName2); } @Override public java.lang.String getShipper_StreetName2() { return get_ValueAsString(COLUMNNAME_Shipper_StreetName2);
} @Override public void setShipper_StreetNumber (final @Nullable java.lang.String Shipper_StreetNumber) { set_Value (COLUMNNAME_Shipper_StreetNumber, Shipper_StreetNumber); } @Override public java.lang.String getShipper_StreetNumber() { return get_ValueAsString(COLUMNNAME_Shipper_StreetNumber); } @Override public void setShipper_ZipCode (final @Nullable java.lang.String Shipper_ZipCode) { set_Value (COLUMNNAME_Shipper_ZipCode, Shipper_ZipCode); } @Override public java.lang.String getShipper_ZipCode() { return get_ValueAsString(COLUMNNAME_Shipper_ZipCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder.java
1
请在Spring Boot框架中完成以下Java代码
public class RoleId implements RepoIdAware { public static final RoleId SYSTEM = new RoleId(0); public static final RoleId WEBUI = new RoleId(540024); /** * Used by the reports service when it accesses the REST-API */ public static final RoleId JSON_REPORTS = new RoleId(540078); @JsonCreator public static RoleId ofRepoId(final int repoId) { final RoleId roleId = ofRepoIdOrNull(repoId); return Check.assumeNotNull(roleId, "Unable to create a roleId for repoId={}", repoId); } public static RoleId ofRepoIdOrNull(final int repoId) { if (repoId == SYSTEM.getRepoId()) { return SYSTEM; } else if (repoId == WEBUI.getRepoId()) { return WEBUI; } else if (repoId == JSON_REPORTS.getRepoId()) { return JSON_REPORTS; } else { return repoId > 0 ? new RoleId(repoId) : null; } }
public static int toRepoId(@Nullable final RoleId id) { return toRepoId(id, -1); } public static int toRepoId(@Nullable final RoleId id, final int defaultValue) { return id != null ? id.getRepoId() : defaultValue; } public static boolean equals(final RoleId id1, final RoleId id2) { return Objects.equals(id1, id2); } int repoId; private RoleId(final int repoId) { this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "AD_Role_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isSystem() {return isSystem(repoId);} public static boolean isSystem(final int repoId) {return repoId == SYSTEM.repoId;} public boolean isRegular() {return isRegular(repoId);} public static boolean isRegular(final int repoId) {return !isSystem(repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\RoleId.java
2
请完成以下Java代码
public class PrivilegeEntityManagerImpl extends AbstractIdmEngineEntityManager<PrivilegeEntity, PrivilegeDataManager> implements PrivilegeEntityManager { public PrivilegeEntityManagerImpl(IdmEngineConfiguration idmEngineConfiguration, PrivilegeDataManager privilegeDataManager) { super(idmEngineConfiguration, privilegeDataManager); } @Override public PrivilegeQuery createNewPrivilegeQuery() { return new PrivilegeQueryImpl(getCommandExecutor()); } @Override public List<Privilege> findPrivilegeByQueryCriteria(PrivilegeQueryImpl query) { return dataManager.findPrivilegeByQueryCriteria(query); } @Override
public long findPrivilegeCountByQueryCriteria(PrivilegeQueryImpl query) { return dataManager.findPrivilegeCountByQueryCriteria(query); } @Override public List<Privilege> findPrivilegeByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findPrivilegeByNativeQuery(parameterMap); } @Override public long findPrivilegeCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findPrivilegeCountByNativeQuery(parameterMap); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\PrivilegeEntityManagerImpl.java
1
请完成以下Java代码
public class ReceiptSchedule { @NonNull private final ReceiptScheduleId id; @NonNull private final OrgId orgId; @NonNull private final BPartnerId vendorId; @Nullable private final OrderId orderId; private int numberOfItemsWithSameOrderId;
@Nullable private final LocalDateTime dateOrdered; @NonNull private final ProductId productId; @NonNull private final Quantity quantityToDeliver; @Nullable private final AttributeSetInstanceId attributeSetInstanceId; @NonNull private APIExportStatus exportStatus; }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ReceiptSchedule.java
1
请完成以下Java代码
public class X_EDI_cctop_000_v extends org.compiere.model.PO implements I_EDI_cctop_000_v, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1093740575L; /** Standard Constructor */ public X_EDI_cctop_000_v (final Properties ctx, final int EDI_cctop_000_v_ID, @Nullable final String trxName) { super (ctx, EDI_cctop_000_v_ID, trxName); } /** Load Constructor */ public X_EDI_cctop_000_v (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_ID() {
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setEDI_cctop_000_v_ID (final int EDI_cctop_000_v_ID) { if (EDI_cctop_000_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_000_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_000_v_ID, EDI_cctop_000_v_ID); } @Override public int getEDI_cctop_000_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_000_v_ID); } @Override public void setEdiInvoicRecipientGLN (final @Nullable java.lang.String EdiInvoicRecipientGLN) { set_ValueNoCheck (COLUMNNAME_EdiInvoicRecipientGLN, EdiInvoicRecipientGLN); } @Override public java.lang.String getEdiInvoicRecipientGLN() { return get_ValueAsString(COLUMNNAME_EdiInvoicRecipientGLN); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_000_v.java
1
请完成以下Java代码
public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) { DeploymentMappings mappings = elementConfiguration.getMappings(); List<String> ids = elementConfiguration.getIds(); return new BatchConfiguration(ids, mappings); } protected BatchElementConfiguration collectProcessInstanceIds(CommandContext commandContext) { BatchElementConfiguration elementConfiguration = new BatchElementConfiguration(); if (!CollectionUtil.isEmpty(processInstanceIds)) { ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl(); query.processInstanceIds(new HashSet<>(processInstanceIds)); List<ImmutablePair<String, String>> mappings = commandContext.runWithoutAuthorization(query::listDeploymentIdMappings); elementConfiguration.addDeploymentMappings(mappings); } ProcessInstanceQueryImpl processInstanceQuery = (ProcessInstanceQueryImpl) this.processInstanceQuery; if (processInstanceQuery != null) {
List<ImmutablePair<String, String>> mappings = processInstanceQuery.listDeploymentIdMappings(); elementConfiguration.addDeploymentMappings(mappings); } HistoricProcessInstanceQueryImpl historicProcessInstanceQuery = (HistoricProcessInstanceQueryImpl) this.historicProcessInstanceQuery; if (historicProcessInstanceQuery != null) { historicProcessInstanceQuery.unfinished(); List<ImmutablePair<String, String>> mappings = historicProcessInstanceQuery.listDeploymentIdMappings(); elementConfiguration.addDeploymentMappings(mappings); } return elementConfiguration; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\variables\SetVariablesToProcessInstancesBatchCmd.java
1
请完成以下Java代码
private Iterator<I_C_Flatrate_Term> retrieveTermsToEvaluate() { final Iterator<I_C_Flatrate_Term> termsToEval = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Flatrate_Term.class) .addOnlyContextClient(getCtx()) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, X_C_Flatrate_Term.CONTRACTSTATUS_DeliveryPause, X_C_Flatrate_Term.CONTRACTSTATUS_Running, X_C_Flatrate_Term.CONTRACTSTATUS_Waiting, X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, IDocument.STATUS_Closed, IDocument.STATUS_Completed) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate).addColumn(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID).endOrderBy() .create() .iterate(I_C_Flatrate_Term.class); return termsToEval; } private boolean invokeEvalCurrentSPs(final I_C_Flatrate_Term flatrateTerm) { final Mutable<Boolean> success = new Mutable<>(false);
Services.get(ITrxManager.class).runInNewTrx(() -> { try { subscriptionBL.evalCurrentSPs(flatrateTerm, currentDate); success.setValue(true); } catch (final AdempiereException e) { addLog("Error updating " + flatrateTerm + ": " + e.getMessage()); } }); return success.getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\process\C_SubscriptionProgress_Evaluate.java
1
请完成以下Java代码
public String getComponentType() { return componentType; } @Override public void setComponentType(final String componentType) { this.componentType = componentType; } @Override public String getVariantGroup() { return variantGroup; } @Override public void setVariantGroup(final String variantGroup) { this.variantGroup = variantGroup; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } @Override public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{ this.handlingUnitsInfo = handlingUnitsInfo; } @Override public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { handlingUnitsInfoProjected = handlingUnitsInfo; } @Override public IHandlingUnitsInfo getHandlingUnitsInfoProjected() { return handlingUnitsInfoProjected; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java
1
请完成以下Java代码
public int getAD_Role_ID() { return get_ValueAsInt(COLUMNNAME_AD_Role_ID); } @Override public void setAD_Session_ID (final int AD_Session_ID) { if (AD_Session_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Session_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Session_ID, AD_Session_ID); } @Override public int getAD_Session_ID() { return get_ValueAsInt(COLUMNNAME_AD_Session_ID); } @Override public void setClient_Info (final @Nullable java.lang.String Client_Info) { set_Value (COLUMNNAME_Client_Info, Client_Info); } @Override public java.lang.String getClient_Info() { return get_ValueAsString(COLUMNNAME_Client_Info); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHostKey (final @Nullable java.lang.String HostKey) { set_Value (COLUMNNAME_HostKey, HostKey); } @Override public java.lang.String getHostKey() { return get_ValueAsString(COLUMNNAME_HostKey); } @Override public void setIsLoginIncorrect (final boolean IsLoginIncorrect) { set_Value (COLUMNNAME_IsLoginIncorrect, IsLoginIncorrect); } @Override public boolean isLoginIncorrect() { return get_ValueAsBoolean(COLUMNNAME_IsLoginIncorrect); } @Override public void setLoginDate (final @Nullable java.sql.Timestamp LoginDate) { set_Value (COLUMNNAME_LoginDate, LoginDate); } @Override public java.sql.Timestamp getLoginDate() { return get_ValueAsTimestamp(COLUMNNAME_LoginDate); } @Override public void setLoginUsername (final @Nullable java.lang.String LoginUsername) { set_Value (COLUMNNAME_LoginUsername, LoginUsername); } @Override public java.lang.String getLoginUsername() { return get_ValueAsString(COLUMNNAME_LoginUsername); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setRemote_Addr (final @Nullable java.lang.String Remote_Addr) { set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr); } @Override public java.lang.String getRemote_Addr() { return get_ValueAsString(COLUMNNAME_Remote_Addr); } @Override public void setRemote_Host (final @Nullable java.lang.String Remote_Host) { set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host); } @Override public java.lang.String getRemote_Host() { return get_ValueAsString(COLUMNNAME_Remote_Host); } @Override public void setWebSession (final @Nullable java.lang.String WebSession) { set_ValueNoCheck (COLUMNNAME_WebSession, WebSession); } @Override public java.lang.String getWebSession() { return get_ValueAsString(COLUMNNAME_WebSession); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Session.java
1
请完成以下Java代码
public boolean supports(ConfigAttribute attribute) { if ((attribute.getAttribute() != null) && !attribute.getAttribute().startsWith(rolePrefix)) { return true; }else { return false; } } @Override public boolean supports(Class<?> clazz) { return true; } @Override public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { if (authentication == null) { return ACCESS_DENIED;
} String name = authentication.getName(); int result = ACCESS_ABSTAIN; for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; if (attribute.getAttribute().equals(name)) { return ACCESS_GRANTED; } } } return result; } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\si\security\UsernameAccessDecisionVoter.java
1
请完成以下Java代码
public static JSONDocumentList ofDocumentsList( @NonNull final OrderedDocumentsList documents, @NonNull final JSONDocumentOptions options, @Nullable final Boolean hasComments) { return builder() .result(JSONDocument.ofDocumentsList(documents.toList(), options, hasComments)) .orderBys(JSONViewOrderBy.ofList(documents.getOrderBys())) .build(); } public List<JSONDocument> toList() {return result;} public JSONDocumentList withMissingIdsUpdatedFromExpectedRowIds(@NonNull final DocumentIdsSelection expectedRowIds) { final ImmutableSet<DocumentId> missingIdsNew = normalizeMissingIds(computeMissingIdsFromExpectedRowIds(expectedRowIds)); if (Objects.equals(this.missingIds, missingIdsNew)) { return this; } return toBuilder().missingIds(missingIdsNew).build(); } public Set<DocumentId> computeMissingIdsFromExpectedRowIds(final DocumentIdsSelection expectedRowIds) { if (expectedRowIds.isEmpty() || expectedRowIds.isAll()) {
return null; } else { final ImmutableSet<DocumentId> existingRowIds = getRowIds(); return Sets.difference(expectedRowIds.toSet(), existingRowIds); } } private ImmutableSet<DocumentId> getRowIds() { return result.stream() .map(JSONDocument::getRowId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentList.java
1
请完成以下Java代码
private ManufacturingJob issueForWhatWasReceived(@NonNull final UserConfirmationRequest request) { return jobService.autoIssueWhatWasReceived( extractManufacturingJob(request), extractIssueStrategy(request) ); } @NonNull private static RawMaterialsIssueStrategy extractIssueStrategy(@NonNull final UserConfirmationRequest request) { final ManufacturingJobActivity activity = extractManufacturingJobActivity(request); final IssueOnlyWhatWasReceivedConfig config = activity.getIssueOnlyWhatWasReceivedConfig(); return config != null ? config.getIssueStrategy() : RawMaterialsIssueStrategy.DEFAULT; } @NonNull private static ManufacturingJobActivity extractManufacturingJobActivity(final @NotNull UserConfirmationRequest request)
{ final ManufacturingJob job = extractManufacturingJob(request); final ManufacturingJobActivityId manufacturingJobActivityId = extractManufacturingJobActivityId(request); return job.getActivityById(manufacturingJobActivityId); } @NonNull private static ManufacturingJob extractManufacturingJob(final @NotNull UserConfirmationRequest request) { return ManufacturingMobileApplication.getManufacturingJob(request.getWfProcess()); } @NonNull private static ManufacturingJobActivityId extractManufacturingJobActivityId(final @NotNull UserConfirmationRequest request) { return request.getWfActivity().getId().getAsId(ManufacturingJobActivityId.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\issue\RawMaterialsIssueOnlyWhatWasReceivedActivityHandler.java
1
请完成以下Java代码
private boolean isValidPO(final PO po) { final String parentTrxName = getParentTrxName(); if (!isSameTrxName(parentTrxName, po.get_TrxName())) { return false; } final String tableName = getTableName(); if (!po.get_TableName().equals(tableName)) { logger.warn("PO " + po + " does not expected table: " + tableName); return false; } final int id = getId(); if (id < 0) { return false; } if (po.get_ID() != id) { return false; } return true; } private boolean isSameTrxName(final String trxName1, final String trxName2) { return Services.get(ITrxManager.class).isSameTrxName(trxName1, trxName2); } @Nullable private PO load(final Properties ctx, final int id, final String trxName) { if (id < 0) { return null; } // NOTE: we call MTable.getPO because we want to hit the ModelCacheService. // If we are using Query directly then cache won't be asked to retrieve (but it will just be asked to put to cache)
if (id == 0) { // FIXME: this is a special case because the system will consider we want a new record. Fix this workaround return new Query(ctx, tableName, loadWhereClause, trxName) .setParameters(id) .firstOnly(PO.class); } else { return TableModelLoader.instance.getPO(ctx, tableName, id, trxName); } } protected abstract int getId(); protected abstract boolean setId(int id); public final String getTableName() { return tableName; } protected final String getParentColumnName() { return parentColumnName; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("parentColumnName", parentColumnName) .add("tableName", tableName) .add("idColumnName", idColumnName) .add("loadWhereClause", loadWhereClause) .add("po", poRef) .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\AbstractPOCacheLocal.java
1
请完成以下Java代码
public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the rate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is
* {@link BigDecimal } * */ public void setRate(BigDecimal value) { this.rate = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxCharges2.java
1
请完成以下Java代码
public void unlockUser() { ensureNotReadOnly(); identityService.unlockUser(resourceId); } public void updateCredentials(UserCredentialsDto account) { ensureNotReadOnly(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); if(currentAuthentication != null && currentAuthentication.getUserId() != null) { if(!identityService.checkPassword(currentAuthentication.getUserId(), account.getAuthenticatedUserPassword())) { throw new InvalidRequestException(Status.BAD_REQUEST, "The given authenticated user password is not valid."); } } User dbUser = findUserObject(); if(dbUser == null) { throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); } dbUser.setPassword(account.getPassword()); identityService.saveUser(dbUser); } public void updateProfile(UserProfileDto profile) { ensureNotReadOnly(); User dbUser = findUserObject(); if(dbUser == null) { throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); }
profile.update(dbUser); identityService.saveUser(dbUser); } protected User findUserObject() { try { return identityService.createUserQuery() .userId(resourceId) .singleResult(); } catch(ProcessEngineException e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing user query: "+e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\UserResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ServletWebServerFactoryCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered { private final ServerProperties serverProperties; private final List<WebListenerRegistrar> webListenerRegistrars; private final List<CookieSameSiteSupplier> cookieSameSiteSuppliers; private final @Nullable SslBundles sslBundles; public ServletWebServerFactoryCustomizer(ServerProperties serverProperties) { this(serverProperties, Collections.emptyList(), Collections.emptyList(), null); } public ServletWebServerFactoryCustomizer(ServerProperties serverProperties, List<WebListenerRegistrar> webListenerRegistrars, List<CookieSameSiteSupplier> cookieSameSiteSuppliers, @Nullable SslBundles sslBundles) { this.serverProperties = serverProperties; this.webListenerRegistrars = webListenerRegistrars; this.cookieSameSiteSuppliers = cookieSameSiteSuppliers; this.sslBundles = sslBundles; } @Override public int getOrder() { return 0; } @Override public void customize(ConfigurableServletWebServerFactory factory) { PropertyMapper map = PropertyMapper.get(); map.from(this.serverProperties::getPort).to(factory::setPort); map.from(this.serverProperties::getAddress).to(factory::setAddress);
map.from(this.serverProperties.getServlet()::getContextPath).to(factory::setContextPath); map.from(this.serverProperties.getServlet()::getApplicationDisplayName).to(factory::setDisplayName); map.from(this.serverProperties.getServlet()::isRegisterDefaultServlet).to(factory::setRegisterDefaultServlet); map.from(this.serverProperties.getServlet()::getSession).to(factory::setSession); map.from(this.serverProperties::getSsl).to(factory::setSsl); map.from(this.serverProperties.getServlet()::getJsp).to(factory::setJsp); map.from(this.serverProperties::getCompression).to(factory::setCompression); map.from(this.serverProperties::getHttp2).to(factory::setHttp2); map.from(this.serverProperties::getServerHeader).to(factory::setServerHeader); map.from(this.serverProperties.getServlet()::getContextParameters).to(factory::setInitParameters); map.from(this.serverProperties.getShutdown()).to(factory::setShutdown); map.from(() -> this.sslBundles).to(factory::setSslBundles); map.from(() -> this.cookieSameSiteSuppliers) .whenNot(CollectionUtils::isEmpty) .to(factory::setCookieSameSiteSuppliers); map.from(this.serverProperties::getMimeMappings).to(factory::addMimeMappings); map.from(this.serverProperties.getServlet().getEncoding()::getMapping).to(factory::setLocaleCharsetMappings); this.webListenerRegistrars.forEach((registrar) -> registrar.register(factory)); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\servlet\ServletWebServerFactoryCustomizer.java
2