instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class StartProcessPayload implements Payload { private String id; private String processDefinitionId; private String processDefinitionKey; private String name; private String businessKey; private Map<String, Object> variables = new HashMap<>(); private String linkedProcessInstanceId; private String linkedProcessInstanceType; public StartProcessPayload() { this.id = UUID.randomUUID().toString(); } public StartProcessPayload( String processDefinitionId, String processDefinitionKey, String name, String businessKey, Map<String, Object> variables ) { this(); this.processDefinitionId = processDefinitionId; this.processDefinitionKey = processDefinitionKey; this.name = name; this.businessKey = businessKey; this.variables = variables; } @Override public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getBusinessKey() { return businessKey; }
public Map<String, Object> getVariables() { return variables; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLinkedProcessInstanceId() { return linkedProcessInstanceId; } public void setLinkedProcessInstanceId(String linkedProcessInstanceId) { this.linkedProcessInstanceId = linkedProcessInstanceId; } public String getLinkedProcessInstanceType() { return linkedProcessInstanceType; } public void setLinkedProcessInstanceType(String linkedProcessInstanceType) { this.linkedProcessInstanceType = linkedProcessInstanceType; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\StartProcessPayload.java
1
请完成以下Java代码
public void registerListener(final IWFExecutionListener listener) { if (listener == null) { return; } synchronized (executionListeners) { if (executionListeners.contains(listener)) { return; } executionListeners.add(listener);
} } @Override public void notifyActivityPerformed(Object fromModel, Object toModel) { synchronized (executionListeners) { for (IWFExecutionListener listener : executionListeners) { listener.onActivityPerformed(fromModel, toModel); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\workflow\api\impl\WFExecutionFactory.java
1
请完成以下Java代码
public int countByTenantIdAndNotificationTypes(TenantId tenantId, Collection<NotificationType> notificationTypes) { return notificationTemplateRepository.countByTenantIdAndNotificationTypes(tenantId.getId(), notificationTypes); } @Override public void removeByTenantId(TenantId tenantId) { notificationTemplateRepository.deleteByTenantId(tenantId.getId()); } @Override public NotificationTemplate findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public NotificationTemplate findByTenantIdAndName(UUID tenantId, String name) { return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndName(tenantId, name)); } @Override public PageData<NotificationTemplate> findByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(notificationTemplateRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink))); } @Override
public NotificationTemplateId getExternalIdByInternal(NotificationTemplateId internalId) { return DaoUtil.toEntityId(notificationTemplateRepository.getExternalIdByInternal(internalId.getId()), NotificationTemplateId::new); } @Override public PageData<NotificationTemplate> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override protected JpaRepository<NotificationTemplateEntity, UUID> getRepository() { return notificationTemplateRepository; } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_TEMPLATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationTemplateDao.java
1
请完成以下Java代码
public void setQtySupplyRequired_AtDate (final @Nullable BigDecimal QtySupplyRequired_AtDate) { set_Value (COLUMNNAME_QtySupplyRequired_AtDate, QtySupplyRequired_AtDate); } @Override public BigDecimal getQtySupplyRequired_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyRequired_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplySum_AtDate (final @Nullable BigDecimal QtySupplySum_AtDate) { set_Value (COLUMNNAME_QtySupplySum_AtDate, QtySupplySum_AtDate); } @Override
public BigDecimal getQtySupplySum_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplySum_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyToSchedule_AtDate (final @Nullable BigDecimal QtySupplyToSchedule_AtDate) { set_Value (COLUMNNAME_QtySupplyToSchedule_AtDate, QtySupplyToSchedule_AtDate); } @Override public BigDecimal getQtySupplyToSchedule_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyToSchedule_AtDate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit.java
1
请完成以下Java代码
public void setNonStdAddress (final boolean NonStdAddress) { set_Value (COLUMNNAME_NonStdAddress, NonStdAddress); } @Override public boolean isNonStdAddress() { return get_ValueAsBoolean(COLUMNNAME_NonStdAddress); } @Override public void setPostal (final @Nullable java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); } @Override public void setPostal_Add (final @Nullable java.lang.String Postal_Add) { set_Value (COLUMNNAME_Postal_Add, Postal_Add); } @Override public java.lang.String getPostal_Add() { return get_ValueAsString(COLUMNNAME_Postal_Add); } @Override public void setRegionName (final @Nullable java.lang.String RegionName) {
set_Value (COLUMNNAME_RegionName, RegionName); } @Override public java.lang.String getRegionName() { return get_ValueAsString(COLUMNNAME_RegionName); } @Override public void setTownship (final @Nullable java.lang.String Township) { set_Value (COLUMNNAME_Township, Township); } @Override public java.lang.String getTownship() { return get_ValueAsString(COLUMNNAME_Township); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Postal.java
1
请完成以下Java代码
public HistoryJobQuery createHistoryJobQuery() { return new HistoryJobQueryImpl(commandExecutor, configuration.getJobServiceConfiguration()); } @Override public ExternalWorkerJobAcquireBuilder createExternalWorkerJobAcquireBuilder() { return new ExternalWorkerJobAcquireBuilderImpl(commandExecutor, configuration.getJobServiceConfiguration()); } @Override public ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String externalJobId, String workerId) { return new ExternalWorkerJobFailureBuilderImpl(externalJobId, workerId, commandExecutor, configuration.getJobServiceConfiguration()); } @Override public CmmnExternalWorkerTransitionBuilder createCmmnExternalWorkerTransitionBuilder(String externalJobId, String workerId) { return new CmmnExternalWorkerTransitionBuilderImpl(commandExecutor, externalJobId, workerId); } @Override public void unacquireExternalWorkerJob(String jobId, String workerId) { commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration())); } @Override public void unacquireAllExternalWorkerJobsForWorker(String workerId) { commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration())); } @Override public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) { commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration())); } @Override public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) { return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager()); } public <T> T executeCommand(Command<T> command) { if (command == null) { throw new FlowableIllegalArgumentException("The command is null"); }
return commandExecutor.execute(command); } public <T> T executeCommand(CommandConfig config, Command<T> command) { if (config == null) { throw new FlowableIllegalArgumentException("The config is null"); } if (command == null) { throw new FlowableIllegalArgumentException("The command is null"); } return commandExecutor.execute(config, command); } @Override public LockManager getLockManager(String lockName) { return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnManagementServiceImpl.java
1
请完成以下Java代码
public void merge(List<DependencyGroup> otherContent) { otherContent.forEach((group) -> { if (this.content.stream() .noneMatch((it) -> group.getName() != null && group.getName().equals(it.getName()))) { this.content.add(group); } }); index(); } private void index() { this.indexedDependencies.clear(); this.content.forEach((group) -> group.content.forEach((dependency) -> { // Apply defaults if (dependency.getCompatibilityRange() == null && group.getCompatibilityRange() != null) { dependency.setCompatibilityRange(group.getCompatibilityRange()); } if (dependency.getBom() == null && group.getBom() != null) { dependency.setBom(group.getBom()); } if (dependency.getRepository() == null && group.getRepository() != null) { dependency.setRepository(group.getRepository()); } dependency.resolve(); indexDependency(dependency.getId(), dependency);
for (String alias : dependency.getAliases()) { indexDependency(alias, dependency); } })); } private void indexDependency(String id, Dependency dependency) { Dependency existing = this.indexedDependencies.get(id); if (existing != null) { throw new IllegalArgumentException("Could not register " + dependency + " another dependency " + "has also the '" + id + "' id " + existing); } this.indexedDependencies.put(id, dependency); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\DependenciesCapability.java
1
请在Spring Boot框架中完成以下Java代码
public class MSV3ConnectionFactory { public WebServiceTemplate createWebServiceTemplate(@NonNull final MSV3ClientConfig config) { final HttpComponentsMessageSender messageSender = createMessageSender(config.getAuthUsername(), config.getAuthPassword()); final Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan(config.getVersion().getJaxbPackagesToScan()); final WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setMessageSender(messageSender); webServiceTemplate.setMarshaller(marshaller); webServiceTemplate.setUnmarshaller(marshaller); try { // Using the default messageFactory, we end up with SOAP 1.1. and the following error on the server side // Content-Type: text/xml; charset=utf-8 Supported ones are: [application/soap+xml] // ..which results in a http error "Unsupported Media Type [415]" on the client side webServiceTemplate .setMessageFactory( new SaajSoapMessageFactory( MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL))); } catch (final SOAPException e) { throw AdempiereException.wrapIfNeeded(e) .setParameter("config", config); } return webServiceTemplate; } private static HttpComponentsMessageSender createMessageSender( @NonNull final String authUsername, @NonNull final String authPassword) {
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authUsername, authPassword); final HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender(); messageSender.setCredentials(credentials); try { messageSender.afterPropertiesSet(); // to make sure credentials are set to HttpClient } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex) .setParameter("username", authUsername); } return messageSender; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3ConnectionFactory.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult register(@RequestParam String username, @RequestParam String password, @RequestParam String telephone, @RequestParam String authCode) { memberService.register(username, password, telephone, authCode); return CommonResult.success(null,"注册成功"); } @ApiOperation("会员登录") @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public CommonResult login(@RequestParam String username, @RequestParam String password) { String token = memberService.login(username, password); if (token == null) { return CommonResult.validateFailed("用户名或密码错误"); } Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", token); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); } @ApiOperation("获取会员信息") @RequestMapping(value = "/info", method = RequestMethod.GET) @ResponseBody public CommonResult info(Principal principal) { if(principal==null){ return CommonResult.unauthorized(null); } UmsMember member = memberService.getCurrentMember(); return CommonResult.success(member); } @ApiOperation("获取验证码") @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET) @ResponseBody public CommonResult getAuthCode(@RequestParam String telephone) { String authCode = memberService.generateAuthCode(telephone); return CommonResult.success(authCode,"获取验证码成功"); } @ApiOperation("会员修改密码") @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) @ResponseBody public CommonResult updatePassword(@RequestParam String telephone, @RequestParam String password,
@RequestParam String authCode) { memberService.updatePassword(telephone,password,authCode); return CommonResult.success(null,"密码修改成功"); } @ApiOperation(value = "刷新token") @RequestMapping(value = "/refreshToken", method = RequestMethod.GET) @ResponseBody public CommonResult refreshToken(HttpServletRequest request) { String token = request.getHeader(tokenHeader); String refreshToken = memberService.refreshToken(token); if (refreshToken == null) { return CommonResult.failed("token已经过期!"); } Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", refreshToken); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\UmsMemberController.java
2
请完成以下Java代码
static HandlerFilterFunction<ServerResponse, ServerResponse> setPath(String path) { return ofRequestProcessor(BeforeFilterFunctions.setPath(path)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestHeader(String name, String value) { return ofRequestProcessor(BeforeFilterFunctions.setRequestHeader(name, value)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestHostHeader(String host) { return ofRequestProcessor(BeforeFilterFunctions.setRequestHostHeader(host)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setResponseHeader(String name, String value) { return ofResponseProcessor(AfterFilterFunctions.setResponseHeader(name, value)); } static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix() { return stripPrefix(1); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix(int parts) { return ofRequestProcessor(BeforeFilterFunctions.stripPrefix(parts)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(int statusCode) { return setStatus(new HttpStatusHolder(null, statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusCode statusCode) { return setStatus(new HttpStatusHolder(statusCode, null)); }
@Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusHolder statusCode) { return ofResponseProcessor(AfterFilterFunctions.setStatus(statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> uri(String uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> uri(URI uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(FilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\FilterFunctions.java
1
请在Spring Boot框架中完成以下Java代码
public class AcquireExternalWorkerJobsCmd implements Command<List<AcquiredExternalWorkerJob>> { protected final String workerId; protected final int numberOfJobs; protected final ExternalWorkerJobAcquireBuilderImpl builder; protected final JobServiceConfiguration jobServiceConfiguration; public AcquireExternalWorkerJobsCmd(String workerId, int numberOfJobs, ExternalWorkerJobAcquireBuilderImpl builder, JobServiceConfiguration jobServiceConfiguration) { this.workerId = workerId; this.numberOfJobs = numberOfJobs; this.builder = builder; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public List<AcquiredExternalWorkerJob> execute(CommandContext commandContext) { String topic = builder.getTopic(); if (StringUtils.isEmpty(topic)) { throw new FlowableIllegalArgumentException("topic must not be empty"); } if (numberOfJobs < 1) { throw new FlowableIllegalArgumentException("requested number of jobs must not be smaller than 1"); } if (StringUtils.isEmpty(workerId)) { throw new FlowableIllegalArgumentException("workerId must not be empty"); } ExternalWorkerJobEntityManager externalWorkerJobEntityManager = jobServiceConfiguration.getExternalWorkerJobEntityManager(); InternalJobManager internalJobManager = jobServiceConfiguration.getInternalJobManager(); List<ExternalWorkerJobEntity> jobs = externalWorkerJobEntityManager.findExternalJobsToExecute(builder, numberOfJobs); int lockTimeInMillis = (int) builder.getLockDuration().abs().toMillis(); List<AcquiredExternalWorkerJob> acquiredJobs = new ArrayList<>(jobs.size()); for (ExternalWorkerJobEntity job : jobs) { lockJob(commandContext, job, lockTimeInMillis); Map<String, Object> variables = null; if (internalJobManager != null) { variables = internalJobManager.resolveVariablesForExternalWorkerJob(job);
if (job.isExclusive()) { internalJobManager.lockJobScope(job); } } acquiredJobs.add(new AcquiredExternalWorkerJobImpl(job, variables)); } return acquiredJobs; } protected void lockJob(CommandContext commandContext, JobInfoEntity job, int lockTimeInMillis) { GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime()); gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis); job.setLockOwner(workerId); job.setLockExpirationTime(gregorianCalendar.getTime()); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\AcquireExternalWorkerJobsCmd.java
2
请完成以下Java代码
public QueryLimit getLaunchersLimit() { final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100); return limitInt == -100 ? Constants.DEFAULT_LaunchersLimit : QueryLimit.ofInt(limitInt); } // // // // // // @Value @Builder private static class ComputedWorkflowLaunchers { @NonNull WorkflowLaunchersList list; @NonNull WorkflowLaunchersQuery validationKey; private ComputedWorkflowLaunchers(@NonNull final WorkflowLaunchersList list, @NonNull final WorkflowLaunchersQuery validationKey) { this.list = list; this.validationKey = validationKey; } public static ComputedWorkflowLaunchers ofListAndQuery(@NonNull final WorkflowLaunchersList list, @NonNull final WorkflowLaunchersQuery query) { return new ComputedWorkflowLaunchers(list, toValidationKey(query)); }
private static WorkflowLaunchersQuery toValidationKey(@NonNull final WorkflowLaunchersQuery query) { return query.toBuilder() .maxStaleAccepted(Duration.ZERO) .build(); } public boolean matches(@NonNull final WorkflowLaunchersQuery query) { if (list.isStaled(query.getMaxStaleAccepted())) { return false; } final WorkflowLaunchersQuery validationKeyExpected = toValidationKey(query); return validationKey.equals(validationKeyExpected); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\lauchers\PickingWorkflowLaunchersProvider.java
1
请完成以下Java代码
public class ElementContainer extends ConcreteElement implements Printable { /** * */ private static final long serialVersionUID = -5023697241526677706L; /** internal use only @serial ec ec */ private Vector<Element> ec = new Vector<Element>(2); /** Basic constructor */ public ElementContainer() { } /** Basic constructor */ public ElementContainer(Element element) { addElement(element); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public ElementContainer addElement(Element element) { ec.addElement(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public ElementContainer addElement(String element) { ec.addElement(new StringElement(element)); return(this); } /** Implements the output method in Element */ public void output(OutputStream out) { Element element = null; Enumeration<Element> data = ec.elements();
while ( data.hasMoreElements() ) { element = data.nextElement(); element.output(out); } } /** Implements the output method in Element */ public void output(PrintWriter out) { Element element = null; Enumeration<Element> data = ec.elements(); while ( data.hasMoreElements() ) { element = data.nextElement(); element.output(out); } } /** returns an enumeration of the elements in this container */ public Enumeration<Element> elements() { return ec.elements(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ElementContainer.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isMember(String name) { return this.delegate.isMember(name); } @Override public boolean showComponents(SecurityContext securityContext) { return this.delegate.showComponents(securityContext); } @Override public boolean showDetails(SecurityContext securityContext) { return this.delegate.showDetails(securityContext); } @Override
public StatusAggregator getStatusAggregator() { return this.delegate.getStatusAggregator(); } @Override public HttpCodeStatusMapper getHttpCodeStatusMapper() { return this.delegate.getHttpCodeStatusMapper(); } @Override public AdditionalHealthEndpointPath getAdditionalPath() { return this.additionalPath; } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\DelegatingAvailabilityProbesHealthEndpointGroup.java
2
请完成以下Java代码
public class DiscountAmountAndType1 { @XmlElement(name = "Tp") protected DiscountAmountType1Choice tp; @XmlElement(name = "Amt", required = true) protected ActiveOrHistoricCurrencyAndAmount amt; /** * Gets the value of the tp property. * * @return * possible object is * {@link DiscountAmountType1Choice } * */ public DiscountAmountType1Choice getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link DiscountAmountType1Choice } * */ public void setTp(DiscountAmountType1Choice value) {
this.tp = 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_04\DiscountAmountAndType1.java
1
请完成以下Java代码
void set(int id, boolean bit) { if (bit) { _units.set(id / UNIT_SIZE, _units.get(id / UNIT_SIZE) | 1 << (id % UNIT_SIZE)); } } /** * * @param id * @return */ int rank(int id) { int unit_id = id / UNIT_SIZE; return _ranks[unit_id] + popCount(_units.get(unit_id) & (~0 >>> (UNIT_SIZE - (id % UNIT_SIZE) - 1))); } /** * 是否为空 * @return */ boolean empty() { return _units.empty(); } /** * 1的数量 * @return */ int numOnes() { return _numOnes; } /** * 大小 * @return */ int size() { return _size; } /** * 在末尾追加 */ void append() { if ((_size % UNIT_SIZE) == 0) { _units.add(0); } ++_size; } /** * 构建 */ void build() { _ranks = new int[_units.size()]; _numOnes = 0; for (int i = 0; i < _units.size(); ++i) { _ranks[i] = _numOnes; _numOnes += popCount(_units.get(i)); } } /** * 清空 */ void clear() { _units.clear(); _ranks = null;
} /** * 整型大小 */ private static final int UNIT_SIZE = 32; // sizeof(int) * 8 /** * 1的数量 * @param unit * @return */ private static int popCount(int unit) { unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555); unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333); unit = ((unit >>> 4) + unit) & 0x0F0F0F0F; unit += unit >>> 8; unit += unit >>> 16; return unit & 0xFF; } /** * 储存空间 */ private AutoIntPool _units = new AutoIntPool(); /** * 是每个元素的1的个数的累加 */ private int[] _ranks; /** * 1的数量 */ private int _numOnes; /** * 大小 */ private int _size; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
1
请完成以下Java代码
public boolean save(String path) { try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8")); for (Map.Entry<String, String> entry : trie.entrySet()) { bw.write(entry.getKey()); bw.write(separator); bw.write(entry.getValue()); bw.newLine(); } bw.close(); } catch (Exception e) { Predefine.logger.warning("保存词典到" + path + "失败"); return true;
} return false; } /** * 将自己逆转过来返回 * @return */ public StringDictionary reverse() { StringDictionary dictionary = new StringDictionary(separator); for (Map.Entry<String, String> entry : entrySet()) { dictionary.trie.put(entry.getValue(), entry.getKey()); } return dictionary; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\StringDictionary.java
1
请完成以下Java代码
public static void clear() { ProcessEngineContextImpl.clear(); } /** * <p>Takes a callable and executes all engine API invocations * within that callable in a new Process Engine Context. Please * see the {@link ProcessEngineContext} class documentation for * a more detailed description on the purpose of this method.</p> * * An alternative to calling: * * <code> * try { * requiresNew(); * callable.call(); * } finally {
* clear(); * } * </code> * * @param callable the callable to execute * @return what is defined by the callable passed to the method * @throws Exception */ public static <T> T withNewProcessEngineContext(Callable<T> callable) throws Exception { try { requiresNew(); return callable.call(); } finally { clear(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\context\ProcessEngineContext.java
1
请完成以下Java代码
public boolean isMandatory () { Object oo = get_Value(COLUMNNAME_IsMandatory); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * PersonalDataCategory AD_Reference_ID=540857 * Reference name: PersonalDataCategory */ public static final int PERSONALDATACATEGORY_AD_Reference_ID=540857; /** NotPersonal = NP */ public static final String PERSONALDATACATEGORY_NotPersonal = "NP"; /** Personal = P */ public static final String PERSONALDATACATEGORY_Personal = "P"; /** SensitivePersonal = SP */ public static final String PERSONALDATACATEGORY_SensitivePersonal = "SP"; /** Set Datenschutz-Kategorie. @param PersonalDataCategory Datenschutz-Kategorie */ @Override public void setPersonalDataCategory (java.lang.String PersonalDataCategory) { set_Value (COLUMNNAME_PersonalDataCategory, PersonalDataCategory); }
/** Get Datenschutz-Kategorie. @return Datenschutz-Kategorie */ @Override public java.lang.String getPersonalDataCategory () { return (java.lang.String)get_Value(COLUMNNAME_PersonalDataCategory); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Field.java
1
请完成以下Java代码
public ProducerFactory<Object, Object> getProducerFactory() { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public ProducerFactory<Object, Object> getProducerFactory(String topic) { ProducerFactory<Object, Object> producerFactory = this.factoryMap.computeIfAbsent(topic, key -> { for (Entry<Pattern, ProducerFactory<Object, Object>> entry : this.factoryMatchers.entrySet()) { if (entry.getKey().matcher(topic).matches()) { return entry.getValue(); } } return null; }); Assert.state(producerFactory != null, "No producer factory found for topic: " + topic); return producerFactory; } @Override public <T> T execute(ProducerCallback<Object, Object, T> callback) { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); }
@Override public <T> T executeInTransaction(OperationsCallback<Object, Object, T> callback) { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, ConsumerGroupMetadata groupMetadata) { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public Map<MetricName, ? extends Metric> metrics() { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public void flush() { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\RoutingKafkaTemplate.java
1
请完成以下Java代码
public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom ()
{ return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Movement.java
1
请完成以下Java代码
public List<WidgetTypeInfo> findByTenantAndImageLink(TenantId tenantId, String imageUrl, int limit) { return DaoUtil.convertDataList(widgetTypeInfoRepository.findByTenantAndImageUrl(tenantId.getId(), imageUrl, limit)); } @Override public List<WidgetTypeInfo> findByImageLink(String imageUrl, int limit) { return DaoUtil.convertDataList(widgetTypeInfoRepository.findByImageUrl(imageUrl, limit)); } @Override public PageData<WidgetTypeDetails> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<WidgetTypeFields> findNextBatch(UUID id, int batchSize) { return widgetTypeRepository.findNextBatch(id, Limit.of(batchSize)); } @Override
public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) { return widgetTypeInfoRepository.findWidgetTypeInfosByTenantIdAndResourceLink(tenantId.getId(), reference, PageRequest.of(0, limit)); } @Override public List<EntityInfo> findByResource(String reference, int limit) { return widgetTypeInfoRepository.findWidgetTypeInfosByResourceLink(reference, PageRequest.of(0, limit)); } @Override public EntityType getEntityType() { return EntityType.WIDGET_TYPE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\widget\JpaWidgetTypeDao.java
1
请完成以下Java代码
private boolean checkInterrupted() { if (isInterrupted()) { log.info("interrupted"); // interrupt child processes if (m_child != null) m_child.destroy(); m_child = null; if (m_outReader != null && m_outReader.isAlive()) m_outReader.interrupt(); m_outReader = null; if (m_errReader != null && m_errReader.isAlive()) m_errReader.interrupt(); m_errReader = null; // close Streams if (m_inStream != null) try { m_inStream.close(); } catch (Exception e) {} m_inStream = null; if (m_outStream != null) try { m_outStream.close(); } catch (Exception e) {} m_outStream = null; if (m_errStream != null) try { m_errStream.close(); } catch (Exception e) {} m_errStream = null; // return true; } return false; } // checkInterrupted /** * Get Out Info * @return StringBuffer */ public StringBuffer getOut() { return m_out; } // getOut /** * Get Err Info * @return StringBuffer */ public StringBuffer getErr() { return m_err; } // getErr /** * Get The process input stream - i.e. we output to it * @return OutputStream */
public OutputStream getInStream() { return m_inStream; } // getInStream /* * metas: c.ghita@metas.ro * if the value is 0, means that was a normal termination * get exit value */ public Integer getExitValue() { return m_exitValue; } /* * metas: c.ghita@metas.ro * get error log */ public String getErrorLog() { return m_errorLog; } } // Task
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Task.java
1
请完成以下Java代码
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 Span log(Map<String, ?> fields) { return null; } @Override public Span log(long timestampMicroseconds, Map<String, ?> fields) { return null; } @Override public Span log(String event) { return null; } @Override public Span log(long timestampMicroseconds, String event) { return null; } @Override public Span setBaggageItem(String key, String value) { return null; } @Override public String getBaggageItem(String key) { return null; } @Override
public Span setOperationName(String operationName) { return null; } @Override public void finish() { transaction.setStatus(Transaction.SUCCESS); transaction.complete(); } @Override public void finish(long finishMicros) { } }
repos\SpringBoot-Labs-master\lab-61\lab-61-cat-opentracing\src\main\java\cn\iocoder\springboot\lab61\cat\opentracing\CatSpan.java
1
请完成以下Java代码
public CostAmount getCostAmountOrNull(final CostElementId costElementId) { final BOMCostElementPrice costPriceHolder = getCostPrice().getCostElementPriceOrNull(costElementId); if (costPriceHolder == null) { return null; } final CostPrice costPrice; if (isByProduct()) { costPrice = costPriceHolder.getCostPrice().withZeroComponentsCostPrice(); } else { costPrice = costPriceHolder.getCostPrice(); } final Quantity qty = getQtyIncludingScrap(); return costPrice.multiply(qty); }
void setComponentsCostPrice( @NonNull final CostAmount elementCostPrice, @NonNull final CostElementId costElementId) { getCostPrice().setComponentsCostPrice(elementCostPrice, costElementId); } void clearComponentsCostPrice(@NonNull final CostElementId costElementId) { getCostPrice().clearComponentsCostPrice(costElementId); } public ImmutableList<BOMCostElementPrice> getElementPrices() { return getCostPrice().getElementPrices(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMLine.java
1
请完成以下Java代码
private CopyTemplateColumn getColumn(final String columnName) { final CopyTemplateColumn column = columnsByColumnName.get(columnName); if (column == null) { throw new AdempiereException("Column `" + columnName + "` not found in " + this); } return column; } private Optional<CopyTemplateColumn> getColumnIfExists(final String columnName) { return Optional.ofNullable(columnsByColumnName.get(columnName)); } public ValueToCopyResolved getValueToCopy(@NonNull ValueToCopyResolveContext context)
{ return getColumn(context.getColumnName()).getValueToCopy().resolve(context); } public Optional<ValueToCopyType> getValueToCopyType(@NonNull final String columnName) { return getColumnIfExists(columnName).map(column -> column.getValueToCopy().getType()); } public boolean hasChildTableName(@NonNull final String tableName) { return childTemplates.stream().anyMatch(childTemplate -> childTemplate.getTableName().equals(tableName)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\template\CopyTemplate.java
1
请完成以下Java代码
public Dimension getPreferredSize () { return s_size; } // getPreferredSize /** * Paint Component * @param g Graphics */ protected void paintComponent (Graphics g) { Graphics2D g2D = (Graphics2D)g; // center icon m_icon.paintIcon(this, g2D, s_size.width/2 - m_icon.getIconWidth()/2, 5); // Paint Text Color color = getForeground(); g2D.setPaint(color); Font font = getFont(); // AttributedString aString = new AttributedString(m_name); aString.addAttribute(TextAttribute.FONT, font); aString.addAttribute(TextAttribute.FOREGROUND, color);
AttributedCharacterIterator iter = aString.getIterator(); // LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext()); float width = s_size.width - m_icon.getIconWidth() - 2; TextLayout layout = measurer.nextLayout(width); // center text float xPos = (float)(s_size.width/2 - layout.getBounds().getWidth()/2); float yPos = m_icon.getIconHeight() + 20; // layout.draw(g2D, xPos, yPos); width = s_size.width - 4; // 2 pt while (measurer.getPosition() < iter.getEndIndex()) { layout = measurer.nextLayout(width); yPos += layout.getAscent() + layout.getDescent() + layout.getLeading(); layout.draw(g2D, xPos, yPos); } } // paintComponent } // WFNode
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFNodeComponent.java
1
请完成以下Java代码
public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setIsErrorAcknowledged (final boolean IsErrorAcknowledged) { set_Value (COLUMNNAME_IsErrorAcknowledged, IsErrorAcknowledged); } @Override public boolean isErrorAcknowledged() {
return get_ValueAsBoolean(COLUMNNAME_IsErrorAcknowledged); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog.java
1
请完成以下Java代码
public class StudentGradeQueryBuilder { final ObjectMapper om = new ObjectMapper(); public ViewQuery findAll() { return ViewQuery.from("studentGrades", "findByCourse"); } public ViewQuery findByCourse(String course) { return ViewQuery.from("studentGrades", "findByCourse") .key(course); } public ViewQuery findByCourses(String... courses) { return ViewQuery.from("studentGrades", "findByCourse") .keys(JsonArray.from(courses)); } public ViewQuery findByGradeInRange(int lower, int upper, boolean inclusiveEnd) { return ViewQuery.from("studentGrades", "findByGrade") .startKey(lower) .endKey(upper) .inclusiveEnd(inclusiveEnd); } public ViewQuery findByGradeLessThan(int upper) { return ViewQuery.from("studentGrades", "findByGrade") .endKey(upper) .inclusiveEnd(false); } public ViewQuery findByGradeGreaterThan(int lower) { return ViewQuery.from("studentGrades", "findByGrade") .startKey(lower); } public ViewQuery findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) { return ViewQuery.from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from(course, minGrade)) .endKey(JsonArray.from(course, maxGrade)) .inclusiveEnd(inclusiveEnd); } public ViewQuery findTopGradesByCourse(String course, int limit) {
return ViewQuery.from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from(course, 100)) .endKey(JsonArray.from(course, 0)) .inclusiveEnd(true) .descending() .limit(limit); } public ViewQuery countStudentsByCourse() { return ViewQuery.from("studentGrades", "countStudentsByCourse") .reduce() .groupLevel(1); } public ViewQuery sumCreditsByStudent() { return ViewQuery.from("studentGrades", "sumCreditsByStudent") .reduce() .groupLevel(1); } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\mapreduce\StudentGradeQueryBuilder.java
1
请完成以下Java代码
public CandidatesAutoCreateMode getGeneralCandidatesAutoCreateMode() { return CandidatesAutoCreateMode.DONT; } /** @return {@code false}. */ @Override public CandidatesAutoCreateMode getSpecificCandidatesAutoCreateMode(final Object model) { return CandidatesAutoCreateMode.DONT; } /** @return empty iterator */ @Override public Iterator<Object> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED) { return Collections.emptyIterator(); } /** @return empty result */ @Override public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { return InvoiceCandidateGenerateResult.of(this); } /** Does nothing */ @Override public void invalidateCandidatesFor(final Object model) { // nothing to do } /** * @return {@link #MANUAL} (i.e. not a real table name). */ @Override public String getSourceTable() { return ManualCandidateHandler.MANUAL; } /** @return {@code true}. */ @Override public boolean isUserInChargeUserEditable() { return true; }
/** * Does nothing. */ @Override public void setOrderedData(final I_C_Invoice_Candidate ic) { // nothing to do } /** * Does nothing. */ @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { // nothing to do } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { // nothing to do } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\ManualCandidateHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Path getBasePath() { return fileStorageLocation; } @Override public Resource loadFileAsResource(Path filePath) throws FileNotFoundException { LOG.info("loadFileAsResource: {}", filePath); try { Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize(); Resource resource = new UrlResource(resolvedFilePath.toUri()); if(resource.exists()) { return resource; } else { throw new FileNotFoundException("File not found " + filePath); } } catch (MalformedURLException ex) { throw new FileNotFoundException("File not found " + filePath); } } @Override public FileList getFilesInfo(Path filePath) throws IOException { LOG.info("getFilesInfo: {}", filePath); FileList fileList = new FileList(filePath.toString()); Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize(); try (Stream<Path> filesWalk = Files.walk(resolvedFilePath, 1)) { filesWalk.forEach(fw -> { if (resolvedFilePath.endsWith(fw)) { //skip parent directory } else if (Files.isDirectory(fw)) { fileList.add(new DirectoryInfo(fw.getFileName().toString())); } else { fileList.add(new FileInfo(fw.getFileName().toString())); } }); } return fileList; } @Override public void saveFile(Path filePath, InputStream inputStream) throws IOException { LOG.info("saveFile: {}", filePath); Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize(); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); File targetFile = resolvedFilePath.toFile();
OutputStream outStream = new FileOutputStream(targetFile); outStream.write(buffer); } @Override public void delete(Path filePath) throws IOException { LOG.info("delete: {}", filePath); Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize(); LOG.info("deleting: {}", resolvedFilePath.toString()); if (Files.isDirectory(resolvedFilePath)) { FileSystemUtils.deleteRecursively(resolvedFilePath); } else { Files.delete(resolvedFilePath); } } @Override public void createDirectory(Path filePath) throws IOException { LOG.info("createDirectory: {}", filePath); Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize(); Files.createDirectories(resolvedFilePath); } }
repos\spring-examples-java-17\spring-fileserver\src\main\java\itx\examples\springboot\fileserver\services\FileServiceImpl.java
2
请完成以下Java代码
public class BuildInfo { private final String time; private final String version; private final String name; private final String artifact; private final String group; private final String gitFullHash; private final String gitBranchName; public BuildInfo(String time, String version, String name, String artifact, String group, String gitFullHash, String gitBranchName) { this.time = time; this.version = version; this.name = name; this.artifact = artifact; this.group = group; this.gitFullHash = gitFullHash; this.gitBranchName = gitBranchName; } public String getTime() { return time; }
public String getVersion() { return version; } public String getName() { return name; } public String getArtifact() { return artifact; } public String getGroup() { return group; } public String getGitFullHash() { return gitFullHash; } public String getGitBranchName() { return gitBranchName; } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\dto\BuildInfo.java
1
请完成以下Java代码
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfos(PageLink pageLink) { log.debug("Find profile asset id infos by pageLink [{}]", pageLink); return nativeAssetRepository.findProfileEntityIdInfos(DaoUtil.toPageable(pageLink)); } @Override public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, PageLink pageLink) { log.debug("Find profile asset id infos by pageLink [{}]", pageLink); return nativeAssetRepository.findProfileEntityIdInfosByTenantId(tenantId, DaoUtil.toPageable(pageLink)); } @Override public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) { log.debug("Find asset entity infos by name [{}]", name); return assetRepository.findEntityInfosByNamePrefix(tenantId.getId(), name); } @Override public Long countByTenantId(TenantId tenantId) { return assetRepository.countByTenantId(tenantId.getId()); } @Override public Asset findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(assetRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public Asset findByTenantIdAndName(UUID tenantId, String name) { return findAssetsByTenantIdAndName(tenantId, name).orElse(null); } @Override public PageData<Asset> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAssetsByTenantId(tenantId, pageLink); } @Override public AssetId getExternalIdByInternal(AssetId internalId) { return Optional.ofNullable(assetRepository.getExternalIdById(internalId.getId())) .map(AssetId::new).orElse(null); } @Override public PageData<Asset> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<AssetFields> findNextBatch(UUID uuid, int batchSize) { return assetRepository.findAllFields(uuid, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.ASSET; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\asset\JpaAssetDao.java
1
请完成以下Java代码
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { if (ex instanceof IllegalArgumentException) { return handleIllegalArgument( (IllegalArgumentException) ex, request, response, handler); } } catch (Exception handlerException) { logger.warn("Handling of [{}] resulted in Exception", ex.getClass().getName(), handlerException); } return null; } private ModelAndView handleIllegalArgument(IllegalArgumentException ex, final HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { final String accept = request.getHeader(HttpHeaders.ACCEPT); response.sendError(HttpServletResponse.SC_CONFLICT); response.setHeader("ContentType", accept); final ModelAndView modelAndView = new ModelAndView("error"); modelAndView.addObject("error", prepareErrorResponse(accept)); return modelAndView;
} /** Prepares error object based on the provided accept type. * @param accept The Accept header present in the request. * @return The response to return * @throws JsonProcessingException */ private String prepareErrorResponse(String accept) throws JsonProcessingException { final Map<String, String> error = new HashMap<>(); error.put("Error", "Application specific error message"); final String response; if(MediaType.APPLICATION_JSON_VALUE.equals(accept)) { response = new ObjectMapper().writeValueAsString(error); } else { response = new XmlMapper().writeValueAsString(error); } return response; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\error\RestResponseStatusExceptionResolver.java
1
请完成以下Java代码
public de.metas.esb.edi.model.I_EDI_Desadv getEDI_Desadv() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class); } @Override public void setEDI_Desadv(de.metas.esb.edi.model.I_EDI_Desadv EDI_Desadv) { set_ValueFromPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class, EDI_Desadv); } /** Set DESADV. @param EDI_Desadv_ID DESADV */ @Override public void setEDI_Desadv_ID (int EDI_Desadv_ID) {
if (EDI_Desadv_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, Integer.valueOf(EDI_Desadv_ID)); } /** Get DESADV. @return DESADV */ @Override public int getEDI_Desadv_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EDI_Desadv_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_NullDelivery_C_OrderLine_v.java
1
请完成以下Java代码
public static MSV3OrderResponsePackageItemPartRepoId ofRepoId(final int repoId) { return new MSV3OrderResponsePackageItemPartRepoId(repoId); } public static MSV3OrderResponsePackageItemPartRepoId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new MSV3OrderResponsePackageItemPartRepoId(repoId) : null; } public static int getRepoId(final MSV3OrderResponsePackageItemPartRepoId id) { return getRepoIdOr(id, -1); } public static int getRepoIdOr(final MSV3OrderResponsePackageItemPartRepoId id, final int defaultValue) {
return id != null ? id.getRepoId() : defaultValue; } int repoId; private MSV3OrderResponsePackageItemPartRepoId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vendor.gateway.api\src\main\java\de\metas\vendor\gateway\api\order\MSV3OrderResponsePackageItemPartRepoId.java
1
请完成以下Java代码
public Boolean isChecked(String interfaceCode, Date billDate) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String billDateStr = sdf.format(billDate); LOG.info("检查,支付方式[" + interfaceCode + "],订单日期[" + billDateStr + "]"); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("billDate", billDateStr); paramMap.put("interfaceCode", interfaceCode); // 除非对账错误或者对账异常才可以发起第二次对账 paramMap.put("status", BatchStatusEnum.ERROR.name() + "," + BatchStatusEnum.FAIL.name()); List<RpAccountCheckBatch> list = rpAccountCheckBatchService.listBy(paramMap); if (list.isEmpty()) { return false; } return true; } /** * 如果缓冲池中有三天前的数据就清理掉并记录差错 */ public void validateScratchPool() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = sdf.format(DateUtil.addDay(new Date(), -3)); // 查询是否有创建时间是三天前的数据 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("maxDate", dateStr); List<RpAccountCheckMistakeScratchPool> list = rpAccountCheckMistakeScratchPoolService.listScratchPoolRecord(paramMap); List<RpAccountCheckMistake> mistakeList = null; // 如果有数据 if (!list.isEmpty()) { mistakeList = new ArrayList<RpAccountCheckMistake>(); for (RpAccountCheckMistakeScratchPool scratchRecord : list) { // 创建差错记录 RpAccountCheckMistake mistake = new RpAccountCheckMistake();
mistake.setAccountCheckBatchNo(scratchRecord.getBatchNo()); mistake.setBillDate(scratchRecord.getBillDate()); mistake.setErrType(ReconciliationMistakeTypeEnum.BANK_MISS.name()); mistake.setHandleStatus(MistakeHandleStatusEnum.NOHANDLE.name()); mistake.setBankType(scratchRecord.getPayWayCode()); mistake.setOrderNo(scratchRecord.getMerchantOrderNo()); mistake.setTradeTime(scratchRecord.getPaySuccessTime()); mistake.setTrxNo(scratchRecord.getTrxNo()); mistake.setOrderAmount(scratchRecord.getOrderAmount()); mistake.setRefundAmount(scratchRecord.getSuccessRefundAmount()); mistake.setTradeStatus(scratchRecord.getStatus()); mistake.setFee(scratchRecord.getPlatCost()); mistakeList.add(mistake); } rpAccountCheckTransactionService.removeDateFromPool(list, mistakeList); } } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\biz\ReconciliationValidateBiz.java
1
请完成以下Java代码
public long findGroupCountByQueryCriteria(GroupQueryImpl query) { return dataManager.findGroupCountByQueryCriteria(query); } @Override public List<Group> findGroupsByUser(String userId) { return dataManager.findGroupsByUser(userId); } @Override public List<Group> findGroupsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findGroupsByNativeQuery(parameterMap); } @Override public long findGroupCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findGroupCountByNativeQuery(parameterMap); }
@Override public boolean isNewGroup(Group group) { return ((GroupEntity) group).getRevision() == 0; } @Override public List<Group> findGroupsByPrivilegeId(String privilegeId) { return dataManager.findGroupsByPrivilegeId(privilegeId); } protected MembershipEntityManager getMembershipEntityManager() { return engineConfiguration.getMembershipEntityManager(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\GroupEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Sample08Application { private static final Log LOG = LogFactory.getLog(Sample08Application.class); public static void main(String[] args) { SpringApplication.run(Sample08Application.class, args); } @Bean ProducerListener<Object, Object> kafkaProducerListener() { return new ProducerListener<>() { @Override public void onSuccess(ProducerRecord<Object, Object> producerRecord, RecordMetadata recordMetadata) { LOG.info("Produced: " + producerRecord); }
}; } @Bean ApplicationRunner applicationRunner(KafkaTemplate<String, String> kafkaTemplate) { return args -> kafkaTemplate.sendDefault("test data"); } @KafkaListener(topics = "${spring.kafka.template.default-topic}") void processData(ConsumerRecord<Object, Object> consumerRecord) { LOG.info("Received: " + consumerRecord); } }
repos\spring-kafka-main\samples\sample-08\src\main\java\com\example\sample08\Sample08Application.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_BankStatementMatcher[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Bank Statement Matcher. @param C_BankStatementMatcher_ID Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments */ public void setC_BankStatementMatcher_ID (int C_BankStatementMatcher_ID) { if (C_BankStatementMatcher_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, Integer.valueOf(C_BankStatementMatcher_ID)); } /** Get Bank Statement Matcher. @return Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments */ public int getC_BankStatementMatcher_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementMatcher_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Classname. @param Classname Java Classname */ public void setClassname (String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Classname. @return Java Classname */ public String getClassname () { return (String)get_Value(COLUMNNAME_Classname); } /** 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 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 Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java
1
请完成以下Java代码
protected void applyQueryParams(MetricsQuery query, MultivaluedMap<String, String> queryParameters) { if(queryParameters.getFirst(QUERY_PARAM_START_DATE) != null) { Date startDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_START_DATE)); query.startDate(startDate); } if(queryParameters.getFirst(QUERY_PARAM_END_DATE) != null) { Date endDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_END_DATE)); query.endDate(endDate); } IntegerConverter intConverter = new IntegerConverter(); intConverter.setObjectMapper(objectMapper); if (queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT) != null) { int firstResult = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT)); query.offset(firstResult); } if (queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS) != null) {
int maxResults = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS)); query.limit(maxResults); } if(queryParameters.getFirst(QUERY_PARAM_AGG_BY_REPORTER) != null) { query.aggregateByReporter(); } } protected List<MetricsIntervalResultDto> convertToDtos(List<MetricIntervalValue> metrics) { List<MetricsIntervalResultDto> intervalMetrics = new ArrayList<>(); for (MetricIntervalValue m : metrics) { intervalMetrics.add(new MetricsIntervalResultDto(m)); } return intervalMetrics; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MetricsRestServiceImpl.java
1
请完成以下Java代码
private Chain createExecuteChain(GraphQlTransport transport) { Chain chain = (request) -> transport.execute(request) .map((response) -> new DefaultClientGraphQlResponse(request, response, getEncoder(), getDecoder())); return this.interceptors.stream() .reduce(GraphQlClientInterceptor::andThen) .map((i) -> (Chain) (request) -> i.intercept(request, chain)) .orElse(chain); } private SubscriptionChain createSubscriptionChain(GraphQlTransport transport) { SubscriptionChain chain = (request) -> transport .executeSubscription(request) .map((response) -> new DefaultClientGraphQlResponse(request, response, getEncoder(), getDecoder())); return this.interceptors.stream() .reduce(GraphQlClientInterceptor::andThen) .map((i) -> (SubscriptionChain) (request) -> i.interceptSubscription(request, chain)) .orElse(chain); } private Encoder<?> getEncoder() { Assert.notNull(this.jsonEncoder, "jsonEncoder has not been set"); return this.jsonEncoder; } private Decoder<?> getDecoder() { Assert.notNull(this.jsonDecoder, "jsonDecoder has not been set"); return this.jsonDecoder; } protected static class DefaultJacksonCodecs { private static final JsonMapper JSON_MAPPER = JsonMapper.builder() .addModule(new GraphQlJacksonModule()).build();
static Encoder<?> encoder() { return new JacksonJsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON); } static Decoder<?> decoder() { return new JacksonJsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE); } } @SuppressWarnings("removal") protected static class DefaultJackson2Codecs { private static final com.fasterxml.jackson.databind.ObjectMapper JSON_MAPPER = Jackson2ObjectMapperBuilder.json().modulesToInstall(new GraphQlJackson2Module()).build(); static Encoder<?> encoder() { return new Jackson2JsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON); } static Decoder<?> decoder() { return new Jackson2JsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientBuilder.java
1
请完成以下Java代码
public java.math.BigDecimal getPercentage_Scrap_Treshhold () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percentage_Scrap_Treshhold); if (bd == null) return Env.ZERO; return bd; } /** Set Entsorgungskosten pro Einheit. @param Scrap_Fee_Amt_Per_UOM Entsorgungskosten pro Einheit */ @Override public void setScrap_Fee_Amt_Per_UOM (java.math.BigDecimal Scrap_Fee_Amt_Per_UOM) { set_Value (COLUMNNAME_Scrap_Fee_Amt_Per_UOM, Scrap_Fee_Amt_Per_UOM); } /** Get Entsorgungskosten pro Einheit. @return Entsorgungskosten pro Einheit */ @Override public java.math.BigDecimal getScrap_Fee_Amt_Per_UOM () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Scrap_Fee_Amt_Per_UOM); if (bd == null) return Env.ZERO; return bd; } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_Version.java
1
请在Spring Boot框架中完成以下Java代码
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { List<String> fileNames = getFileNames(classLoader); List<String> locations = getLocations(classLoader); List<String> extensions = getExtensions(classLoader); if (logger.isDebugEnabled()) { logger.debug("Registering application configuration hints for " + fileNames + "(" + extensions + ") at " + locations); } FilePatternResourceHintsRegistrar.forClassPathLocations(locations) .withFilePrefixes(fileNames) .withFileExtensions(extensions) .registerHints(hints.resources(), classLoader); } /** * Get the application file names to consider. * @param classLoader the classloader to use * @return the configuration file names */ protected List<String> getFileNames(@Nullable ClassLoader classLoader) { return Arrays.asList(StandardConfigDataLocationResolver.DEFAULT_CONFIG_NAMES); } /** * Get the locations to consider. A location is a classpath location that may or may * not use the standard {@code classpath:} prefix. * @param classLoader the classloader to use * @return the configuration file locations */ protected List<String> getLocations(@Nullable ClassLoader classLoader) { List<String> classpathLocations = new ArrayList<>(); for (ConfigDataLocation candidate : ConfigDataEnvironment.DEFAULT_SEARCH_LOCATIONS) { for (ConfigDataLocation configDataLocation : candidate.split()) { String location = configDataLocation.getValue(); if (location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { classpathLocations.add(location);
} } } return classpathLocations; } /** * Get the application file extensions to consider. A valid extension starts with a * dot. * @param classLoader the classloader to use * @return the configuration file extensions */ protected List<String> getExtensions(@Nullable ClassLoader classLoader) { List<String> extensions = new ArrayList<>(); List<PropertySourceLoader> propertySourceLoaders = getSpringFactoriesLoader(classLoader) .load(PropertySourceLoader.class); for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { for (String fileExtension : propertySourceLoader.getFileExtensions()) { String candidate = "." + fileExtension; if (!extensions.contains(candidate)) { extensions.add(candidate); } } } return extensions; } protected SpringFactoriesLoader getSpringFactoriesLoader(@Nullable ClassLoader classLoader) { return SpringFactoriesLoader.forDefaultResourceLocation(classLoader); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationRuntimeHints.java
2
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password;
} public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
repos\SpringAll-master\11.Spring-Boot-Shiro-Authentication\src\main\java\com\springboot\pojo\User.java
1
请完成以下Java代码
protected String obtainUsername(HttpServletRequest request) { return request.getParameter(this.usernameParameter); } /** * Provided so that subclasses may configure what is put into the authentication * request's details property. * @param request that an authentication request is being created for * @param authRequest the authentication request object that should have its details * set */ protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); } /** * Sets the parameter name which will be used to obtain the username from the login * request. * @param usernameParameter the parameter name. Defaults to "username". */ public void setUsernameParameter(String usernameParameter) { Assert.hasText(usernameParameter, "Username parameter must not be empty or null"); this.usernameParameter = usernameParameter; } /** * Sets the parameter name which will be used to obtain the password from the login * request. * @param passwordParameter the parameter name. Defaults to "password". */ public void setPasswordParameter(String passwordParameter) { Assert.hasText(passwordParameter, "Password parameter must not be empty or null"); this.passwordParameter = passwordParameter; } /**
* Defines whether only HTTP POST requests will be allowed by this filter. If set to * true, and an authentication request is received which is not a POST request, an * exception will be raised immediately and authentication will not be attempted. The * <tt>unsuccessfulAuthentication()</tt> method will be called as if handling a failed * authentication. * <p> * Defaults to <tt>true</tt> but may be overridden by subclasses. */ public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getUsernameParameter() { return this.usernameParameter; } public final String getPasswordParameter() { return this.passwordParameter; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\UsernamePasswordAuthenticationFilter.java
1
请完成以下Spring Boot application配置
spring: security: oauth2: client: registration: cognito: client-id: your_clientId client-secret: your_clientSecret scope: openid redirect-uri: http://localhost:8080/login/oauth2/code/cognito clientName: your_clientName provider:
cognito: issuerUri: https://cognito-idp.{region}.amazonaws.com/{poolId} user-name-attribute: cognito:username
repos\tutorials-master\spring-security-modules\spring-security-cognito\src\main\resources\application.yml
2
请完成以下Java代码
private final Optional<BPartnerLocationId> computeShipReceiptBPLocationId() { final I_M_InOutLine inoutLine = getInOutLine().orElse(null); if (inoutLine != null) { final I_M_InOut inout = inoutLine.getM_InOut(); return Optional.of(BPartnerLocationId.ofRepoId(inout.getC_BPartner_ID(), inout.getC_BPartner_Location_ID())); } final I_C_Order order = invoiceCandidate.getC_Order(); if (order != null) { return Optional.of(BPartnerLocationId.ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID())); } return Optional.empty(); } public ArrayKey getInvoiceLineAttributesKey() {
ArrayKey invoiceLineAttributesKey = _invoiceLineAttributesKey; if (invoiceLineAttributesKey == null) { invoiceLineAttributesKey = _invoiceLineAttributesKey = computeInvoiceLineAttributesKey(); } return invoiceLineAttributesKey; } private ArrayKey computeInvoiceLineAttributesKey() { final ArrayKeyBuilder keyBuilder = ArrayKey.builder(); for (final IInvoiceLineAttribute invoiceLineAttribute : invoiceLineAttributes) { keyBuilder.append(invoiceLineAttribute.toAggregationKey()); } return keyBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationKeyEvaluationContext.java
1
请完成以下Java代码
public class SortHashMap { private static Map<String, Employee> map = new HashMap<>(); public static void main(String[] args) { initialize(); treeMapSortByKey(); arrayListSortByValue(); arrayListSortByKey(); sortStream(); sortGuava(); addDuplicates(); treeSetByKey(); treeSetByValue(); } private static void sortGuava() { final Ordering naturalOrdering = Ordering.natural().onResultOf(Functions.forMap(map, null)); System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering)); } private static void sortStream() { map.entrySet().stream() .sorted(Map.Entry.<String, Employee>comparingByKey().reversed()) .forEach(System.out::println); Map<String, Employee> result = map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); result.entrySet().forEach(System.out::println); } private static void treeSetByValue() { SortedSet<Employee> values = new TreeSet<>(map.values()); System.out.println(values); } private static void treeSetByKey() { SortedSet<String> keysSet = new TreeSet<>(map.keySet()); System.out.println(keysSet); }
private static void treeMapSortByKey() { TreeMap<String, Employee> sorted = new TreeMap<>(map); sorted.putAll(map); sorted.entrySet().forEach(System.out::println); } private static void arrayListSortByValue() { List<Employee> employeeById = new ArrayList<>(map.values()); Collections.sort(employeeById); System.out.println(employeeById); } private static void arrayListSortByKey() { List<String> employeeByKey = new ArrayList<>(map.keySet()); Collections.sort(employeeByKey); System.out.println(employeeByKey); } private static void initialize() { Employee employee1 = new Employee(1L, "Mher"); map.put(employee1.getName(), employee1); Employee employee2 = new Employee(22L, "Annie"); map.put(employee2.getName(), employee2); Employee employee3 = new Employee(8L, "John"); map.put(employee3.getName(), employee3); Employee employee4 = new Employee(2L, "George"); map.put(employee4.getName(), employee4); } private static void addDuplicates() { Employee employee5 = new Employee(1L, "Mher"); map.put(employee5.getName(), employee5); Employee employee6 = new Employee(22L, "Annie"); map.put(employee6.getName(), employee6); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\sort\SortHashMap.java
1
请完成以下Java代码
public void setIsTaxIncluded (boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded)); } /** Get Preis inklusive Steuern. @return Tax is included in the price */ @Override public boolean isTaxIncluded () { Object oo = get_Value(COLUMNNAME_IsTaxIncluded); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Preisliste. @param M_PriceList_ID Unique identifier of a Price List */ @Override public void setM_PriceList_ID (int M_PriceList_ID) { if (M_PriceList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, Integer.valueOf(M_PriceList_ID)); } /** Get Preisliste. @return Unique identifier of a Price List */ @Override public int getM_PriceList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PriceList_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Preissystem. @param M_PricingSystem_ID Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten. */ @Override public void setM_PricingSystem_ID (int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID)); } /** Get Preissystem. @return Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten. */ @Override public int getM_PricingSystem_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Preis Präzision. @param PricePrecision Precision (number of decimals) for the Price */ @Override public void setPricePrecision (int PricePrecision) { set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision)); } /** Get Preis Präzision. @return Precision (number of decimals) for the Price */ @Override public int getPricePrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractRequiredTemplates insuranceContractRequiredTemplates = (InsuranceContractRequiredTemplates) o; return Objects.equals(this.templateId, insuranceContractRequiredTemplates.templateId) && Objects.equals(this.careType, insuranceContractRequiredTemplates.careType); } @Override public int hashCode() { return Objects.hash(templateId, careType); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractRequiredTemplates {\n"); sb.append(" templateId: ").append(toIndentedString(templateId)).append("\n");
sb.append(" careType: ").append(toIndentedString(careType)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractRequiredTemplates.java
2
请完成以下Java代码
public class Location { private String place; private String year; public Location(String place, String year) { super(); this.place = place; this.year = year; } public String getPlace() { return place; }
public void setPlace(String place) { this.place = place; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } }
repos\spring-boot-student-master\spring-boot-student-data-mongo\src\main\java\com\xiaolyuh\entity\Location.java
1
请完成以下Java代码
final class ChartOfAccountsMap { private final ImmutableList<ChartOfAccounts> list; private final ImmutableMap<ChartOfAccountsId, ChartOfAccounts> byId; ChartOfAccountsMap(@NonNull final List<ChartOfAccounts> list) { this.list = ImmutableList.copyOf(list); this.byId = Maps.uniqueIndex(list, ChartOfAccounts::getId); } public ChartOfAccounts getById(@NonNull final ChartOfAccountsId chartOfAccountsId) { final ChartOfAccounts chartOfAccounts = byId.get(chartOfAccountsId); if (chartOfAccounts == null) { throw new AdempiereException("No Chart of Accounts found for " + chartOfAccountsId); } return chartOfAccounts; } public List<ChartOfAccounts> getByIds(@NonNull final Set<ChartOfAccountsId> chartOfAccountsIds) { return chartOfAccountsIds.stream() .map(this::getById)
.collect(ImmutableList.toImmutableList()); } public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { return list.stream() .filter(matchByName(chartOfAccountsName, clientId, orgId)) .findFirst(); } private static Predicate<ChartOfAccounts> matchByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { return chartOfAccounts -> Objects.equals(chartOfAccounts.getName(), chartOfAccountsName) && ClientId.equals(chartOfAccounts.getClientId(), clientId) && OrgId.equals(chartOfAccounts.getOrgId(), orgId); } public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId) { return list.stream() .filter(coa -> AdTreeId.equals(coa.getTreeId(), treeId)) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsMap.java
1
请完成以下Java代码
public class Article { private List<Author> listOfAuthors; private int id; private String name; public Article(String name) { this.name = name; } public Article(List<Author> listOfAuthors, int id) { super(); this.listOfAuthors = listOfAuthors; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public int getId() { return id; } public void setId(int id) { this.id = id; } public List<Author> getListOfAuthors() { return listOfAuthors; } public void setListOfAuthors(List<Author> listOfAuthors) { this.listOfAuthors = listOfAuthors; } }
repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\spliterator\Article.java
1
请完成以下Java代码
private GreetingsMap retrieveGreetingsMap() { final ImmutableList<Greeting> list = queryBL .createQueryBuilder(I_C_Greeting.class) // We need also inactive greetings. If we have to render an address, but the AD_User's greeting was dectivated, // then we still need the greeting in order to render that address //.addOnlyActiveRecordsFilter() .create() .stream(I_C_Greeting.class) .map(GreetingRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new GreetingsMap(list); } private static Greeting fromRecord(@NonNull final I_C_Greeting record) { final IModelTranslationMap trlsMap = InterfaceWrapperHelper.getModelTranslationMap(record); return Greeting.builder() .id(GreetingId.ofRepoId(record.getC_Greeting_ID())) .name(record.getName()) .greeting(trlsMap.getColumnTrl(I_C_Greeting.COLUMNNAME_Greeting, record.getGreeting())) .standardType(GreetingStandardType.ofNullableCode(record.getGreetingStandardType())) .active(record.isActive()) .build(); } public Greeting createGreeting(@NonNull final CreateGreetingRequest request)
{ final I_C_Greeting record = InterfaceWrapperHelper.newInstance(I_C_Greeting.class); record.setName(request.getName()); record.setGreeting(request.getGreeting()); record.setGreetingStandardType(GreetingStandardType.toCode(request.getStandardType())); record.setAD_Org_ID(request.getOrgId().getRepoId()); InterfaceWrapperHelper.saveRecord(record); return fromRecord(record); } public Optional<Greeting> getComposite( @Nullable final GreetingId greetingId1, @Nullable final GreetingId greetingId2) { return getGreetingsMap().getComposite(greetingId1, greetingId2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\greeting\GreetingRepository.java
1
请完成以下Java代码
default List<String> getScopes() { return getClaimAsStringList(OAuth2ProtectedResourceMetadataClaimNames.SCOPES_SUPPORTED); } /** * Returns a list of the supported methods for sending an OAuth 2.0 bearer token to * the protected resource. Defined values are "header", "body" and "query". * {@code (bearer_methods_supported)}. * @return a list of the supported methods for sending an OAuth 2.0 bearer token to * the protected resource */ default List<String> getBearerMethodsSupported() { return getClaimAsStringList(OAuth2ProtectedResourceMetadataClaimNames.BEARER_METHODS_SUPPORTED); } /** * Returns the name of the protected resource intended for display to the end user * {@code (resource_name)}.
* @return the name of the protected resource intended for display to the end user */ default String getResourceName() { return getClaimAsString(OAuth2ProtectedResourceMetadataClaimNames.RESOURCE_NAME); } /** * Returns {@code true} to indicate protected resource support for mutual-TLS client * certificate-bound access tokens * {@code (tls_client_certificate_bound_access_tokens)}. * @return {@code true} to indicate protected resource support for mutual-TLS client * certificate-bound access tokens */ default boolean isTlsClientCertificateBoundAccessTokens() { return Boolean.TRUE.equals(getClaimAsBoolean( OAuth2ProtectedResourceMetadataClaimNames.TLS_CLIENT_CERTIFICATE_BOUND_ACCESS_TOKENS)); } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\OAuth2ProtectedResourceMetadataClaimAccessor.java
1
请完成以下Java代码
public class QueryInfo { private String workflowId; private String workflowRunId; private String queryName; private String result; public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public String getWorkflowRunId() { return workflowRunId; } public void setWorkflowRunId(String workflowRunId) { this.workflowRunId = workflowRunId;
} public String getQueryName() { return queryName; } public void setQueryName(String queryName) { this.queryName = queryName; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\model\QueryInfo.java
1
请完成以下Java代码
public void setRemoteURL (final java.lang.String RemoteURL) { set_Value (COLUMNNAME_RemoteURL, RemoteURL); } @Override public String getRemoteURL() { return get_ValueAsString(COLUMNNAME_RemoteURL); } @Override public void setRouting_Key (final String Routing_Key) { set_Value (COLUMNNAME_Routing_Key, Routing_Key); } @Override public String getRouting_Key() {
return get_ValueAsString(COLUMNNAME_Routing_Key); } @Override public void setAuthToken (final String AuthToken) { set_Value (COLUMNNAME_AuthToken, AuthToken); } @Override public String getAuthToken() { return get_ValueAsString(COLUMNNAME_AuthToken); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_RabbitMQ_HTTP.java
1
请完成以下Java代码
public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set SubLine ID. @param SubLine_ID Transaction sub line ID (internal) */ @Override public void setSubLine_ID (int SubLine_ID) { if (SubLine_ID < 1) set_ValueNoCheck (COLUMNNAME_SubLine_ID, null); else
set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID)); } /** Get SubLine ID. @return Transaction sub line ID (internal) */ @Override public int getSubLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest.java
1
请完成以下Java代码
public void addEventLog(@NonNull final EventLogEntryRequest eventLogRequest) { final EventLogEntry eventLogEntry = EventLogEntry.builder() .uuid(event.getUuid()) .clientId(eventLogRequest.getClientId()) .orgId(eventLogRequest.getOrgId()) .processed(eventLogRequest.isProcessed()) .error(eventLogRequest.isError()) .adIssueId(eventLogRequest.getAdIssueId()) .message(eventLogRequest.getMessage()) .eventHandlerClass(eventLogRequest.getEventHandlerClass()) .build(); eventLogEntries.add(eventLogEntry); } @Override public void close() { // Restore previous entry collector // or clear the current one if (previousEntryCollector != null) { threadLocalCollector.set(previousEntryCollector); } else
{ threadLocalCollector.remove(); } // Avoid throwing exception because EventLogService is not available in unit tests if (Adempiere.isUnitTestMode()) { return; } try { final EventLogService eventStoreService = SpringContextHolder.instance.getBean(EventLogService.class); eventStoreService.saveEventLogEntries(eventLogEntries); } catch (final Exception ex) { logger.warn("Failed saving {}. Ignored", eventLogEntries, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogEntryCollector.java
1
请完成以下Java代码
public class DFSMazeSolver { private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; public List<Coordinate> solve(Maze maze) { List<Coordinate> path = new ArrayList<>(); if (explore(maze, maze.getEntry() .getX(), maze.getEntry() .getY(), path)) { return path; } return Collections.emptyList(); } private boolean explore(Maze maze, int row, int col, List<Coordinate> path) { if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) { return false; } path.add(new Coordinate(row, col)); maze.setVisited(row, col, true);
if (maze.isExit(row, col)) { return true; } for (int[] direction : DIRECTIONS) { Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]); if (explore(maze, coordinate.getX(), coordinate.getY(), path)) { return true; } } path.remove(path.size() - 1); return false; } private Coordinate getNextCoordinate(int row, int col, int i, int j) { return new Coordinate(row + i, col + j); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\maze\solver\DFSMazeSolver.java
1
请完成以下Java代码
private void fillExtraInfo(List<ArticleData> articles, User currentUser) { setFavoriteCount(articles); if (currentUser != null) { setIsFavorite(articles, currentUser); setIsFollowingAuthor(articles, currentUser); } } private void setIsFollowingAuthor(List<ArticleData> articles, User currentUser) { Set<String> followingAuthors = userRelationshipQueryService.followingAuthors( currentUser.getId(), articles.stream() .map(articleData1 -> articleData1.getProfileData().getId()) .collect(toList())); articles.forEach( articleData -> { if (followingAuthors.contains(articleData.getProfileData().getId())) { articleData.getProfileData().setFollowing(true); } }); } private void setFavoriteCount(List<ArticleData> articles) { List<ArticleFavoriteCount> favoritesCounts = articleFavoritesReadService.articlesFavoriteCount( articles.stream().map(ArticleData::getId).collect(toList())); Map<String, Integer> countMap = new HashMap<>(); favoritesCounts.forEach( item -> { countMap.put(item.getId(), item.getCount()); }); articles.forEach( articleData -> articleData.setFavoritesCount(countMap.get(articleData.getId()))); } private void setIsFavorite(List<ArticleData> articles, User currentUser) { Set<String> favoritedArticles =
articleFavoritesReadService.userFavorites( articles.stream().map(articleData -> articleData.getId()).collect(toList()), currentUser); articles.forEach( articleData -> { if (favoritedArticles.contains(articleData.getId())) { articleData.setFavorited(true); } }); } private void fillExtraInfo(String id, User user, ArticleData articleData) { articleData.setFavorited(articleFavoritesReadService.isUserFavorite(user.getId(), id)); articleData.setFavoritesCount(articleFavoritesReadService.articleFavoriteCount(id)); articleData .getProfileData() .setFollowing( userRelationshipQueryService.isUserFollowing( user.getId(), articleData.getProfileData().getId())); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\ArticleQueryService.java
1
请完成以下Java代码
public PageData<EventInfo> findEvents(TenantId tenantId, EntityId entityId, EventType eventType, TimePageLink pageLink) { return convert(entityId.getEntityType(), eventDao.findEvents(tenantId.getId(), entityId.getId(), eventType, pageLink)); } @Override public List<EventInfo> findLatestEvents(TenantId tenantId, EntityId entityId, EventType eventType, int limit) { return convert(entityId.getEntityType(), eventDao.findLatestEvents(tenantId.getId(), entityId.getId(), eventType, limit)); } @Override public EventInfo findLatestDebugRuleNodeInEvent(TenantId tenantId, EntityId entityId) { return convert(entityId.getEntityType(), eventDao.findLatestDebugRuleNodeInEvent(tenantId.getId(), entityId.getId())); } @Override public PageData<EventInfo> findEventsByFilter(TenantId tenantId, EntityId entityId, EventFilter eventFilter, TimePageLink pageLink) { return convert(entityId.getEntityType(), eventDao.findEventByFilter(tenantId.getId(), entityId.getId(), eventFilter, pageLink)); } @Override public void removeEvents(TenantId tenantId, EntityId entityId) { removeEvents(tenantId, entityId, null, null, null); } @Override public void removeEvents(TenantId tenantId, EntityId entityId, EventFilter eventFilter, Long startTime, Long endTime) { if (eventFilter == null) { eventDao.removeEvents(tenantId.getId(), entityId.getId(), startTime, endTime);
} else { eventDao.removeEvents(tenantId.getId(), entityId.getId(), eventFilter, startTime, endTime); } } @Override public void cleanupEvents(long regularEventExpTs, long debugEventExpTs, boolean cleanupDb) { eventDao.cleanupEvents(regularEventExpTs, debugEventExpTs, cleanupDb); } private PageData<EventInfo> convert(EntityType entityType, PageData<? extends Event> pd) { return new PageData<>(pd.getData() == null ? null : pd.getData().stream().map(e -> e.toInfo(entityType)).collect(Collectors.toList()) , pd.getTotalPages(), pd.getTotalElements(), pd.hasNext()); } private List<EventInfo> convert(EntityType entityType, List<? extends Event> list) { return list == null ? null : list.stream().map(e -> e.toInfo(entityType)).collect(Collectors.toList()); } private EventInfo convert(EntityType entityType, Event event) { return Optional.ofNullable(event).map(e -> e.toInfo(entityType)).orElse(null); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\event\BaseEventService.java
1
请完成以下Java代码
public UomId getResultUomId() { return (UomId)assumeNotNull(pricingResult.getPriceUomId()); } @NonNull public TaxCategoryId getResultTaxCategory() { return (TaxCategoryId)assumeNotNull(pricingResult.getTaxCategoryId()); } @NonNull public LocalDate getResultPriceDate() { return pricingResult.getPriceDate(); } public boolean isTaxIncluded() { return pricingResult.isTaxIncluded(); }
@NonNull public ProductPrice getProductPrice() { return ProductPrice.builder() .productId(getProductId()) .uomId(getResultUomId()) .money(Money.of(pricingResult.getPriceStd(), getResultCurrencyId())) .build(); } private static Object assumeNotNull(@Nullable final Object arg) { Check.assumeNotNull(arg, "applies() - should've taken care of this!"); return arg; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginPricingRule.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricEntityLink(String id) { getHistoricEntityLinkEntityManager().delete(id); } @Override public void deleteHistoricEntityLink(HistoricEntityLink entityLink) { getHistoricEntityLinkEntityManager().delete((HistoricEntityLinkEntity) entityLink); } @Override public void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksByScopeIdAndScopeType(scopeId, scopeType); } @Override public void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(scopeDefinitionId, scopeType); } @Override public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) {
getHistoricEntityLinkEntityManager().bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(scopeType, scopeIds); } @Override public void deleteHistoricEntityLinksForNonExistingProcessInstances() { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksForNonExistingProcessInstances(); } @Override public void deleteHistoricEntityLinksForNonExistingCaseInstances() { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksForNonExistingCaseInstances(); } public HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() { return configuration.getHistoricEntityLinkEntityManager(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\HistoricEntityLinkServiceImpl.java
2
请完成以下Java代码
public Object getCredentials() { return null; } @Override public Object getPrincipal() { return principal; } }; } class SpringSessionBackedReactiveSessionInformation extends ReactiveSessionInformation { SpringSessionBackedReactiveSessionInformation(S session) { super(resolvePrincipalName(session), session.getId(), session.getLastAccessedTime()); } private static String resolvePrincipalName(Session session) { String principalName = session
.getAttribute(ReactiveFindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { return principalName; } SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT); if (securityContext != null && securityContext.getAuthentication() != null) { return securityContext.getAuthentication().getName(); } return ""; } @Override public Mono<Void> invalidate() { return super.invalidate() .then(Mono.defer(() -> SpringSessionBackedReactiveSessionRegistry.this.sessionRepository .deleteById(getSessionId()))); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedReactiveSessionRegistry.java
1
请完成以下Java代码
private boolean isClosed() { return closed.get(); } @Override public void close() { if (closed.getAndSet(true)) { // already closed return; } QuerySelectionToDeleteHelper.scheduleDeleteSelectionNoFail(querySelectionUUID, trxName); } @Override public boolean hasNext() { if (isClosed()) { return false; } // NOTE: we do this checking only to have last page optimizations // e.g. consider having 100 records, page size=10, so last page will be fully loaded. // If we are not doing this checking, the buffered iterator will try to load the next page (which is empty), // in order to find out that there is nothing to be loaded. if (rowsFetched >= rowsCount) { close(); return false; } try { while (peekingBufferedIterator.hasNext()) { // Check the rowsFetched again, because in this while we are also navigating forward and we skip invalid values if (rowsFetched >= rowsCount) { close(); return false; } final ET value = peekingBufferedIterator.peek(); if (isValidModel(value)) { return true; } // not a valid model: else { peekingBufferedIterator.next(); // skip this element because it's not valid rowsFetched++; // increase the rowsFetched because we use it to compare with "rowsCount" in order to figure out when we reached the end of the selection. } } close(); return false; } catch (final RuntimeException ex) { throw ex; } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex); } } @Override public ET next() { if (isClosed()) { throw new AdempiereException("Iterator was already closed: " + this); } try {
final ET value = peekingBufferedIterator.next(); rowsFetched++; return value; } catch (final RuntimeException ex) { throw ex; } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex); } } @Override public void remove() { peekingBufferedIterator.remove(); } /** * Sets buffer/page size, i.e. the number of rows to be loaded by this iterator at a time. * * @see IQuery#OPTION_IteratorBufferSize */ public void setBufferSize(final int bufferSize) { bufferedIterator.setBufferSize(bufferSize); } @Override public String toString() { return "GuaranteedPOBufferedIterator [clazz=" + clazz + ", querySelectionUUID=" + querySelectionUUID + ", rowsFetched=" + rowsFetched + ", rowsCount=" + rowsCount + ", query=" + query + ", bufferedIterator=" + bufferedIterator + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\GuaranteedPOBufferedIterator.java
1
请完成以下Java代码
public void setM_ProductOperation_ID (int M_ProductOperation_ID) { if (M_ProductOperation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductOperation_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductOperation_ID, Integer.valueOf(M_ProductOperation_ID)); } /** Get Product Operation. @return Product Manufacturing Operation */ public int getM_ProductOperation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set 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 Setup Time. @param SetupTime Setup time before starting Production */ public void setSetupTime (BigDecimal SetupTime) { set_Value (COLUMNNAME_SetupTime, SetupTime); } /** Get Setup Time. @return Setup time before starting Production */ public BigDecimal getSetupTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SetupTime); if (bd == null) return Env.ZERO; return bd; } /** Set Teardown Time. @param TeardownTime Time at the end of the operation */
public void setTeardownTime (BigDecimal TeardownTime) { set_Value (COLUMNNAME_TeardownTime, TeardownTime); } /** Get Teardown Time. @return Time at the end of the operation */ public BigDecimal getTeardownTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TeardownTime); if (bd == null) return Env.ZERO; return bd; } /** Set Runtime per Unit. @param UnitRuntime Time to produce one unit */ public void setUnitRuntime (BigDecimal UnitRuntime) { set_Value (COLUMNNAME_UnitRuntime, UnitRuntime); } /** Get Runtime per Unit. @return Time to produce one unit */ public BigDecimal getUnitRuntime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitRuntime); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_OperationResource.java
1
请完成以下Java代码
public class RunningLogEndpoint { /** * concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。 */ private static ConcurrentHashMap<String, Session> SESSION_POOLS = new ConcurrentHashMap<>(); /** * 新的WebSocket请求开启 */ @OnOpen public void onOpen(@PathParam("key") String key, Session session) { long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); SESSION_POOLS.put(key, session); log.info("[WebSocket] 连接成功,当前连接人数为:={}", SESSION_POOLS.size()); try { session.getBasicRemote().sendText("Web socket 消息"); } catch (Exception e) { log.error(e.getMessage(), e); } } /**
* WebSocket请求关闭 */ @OnClose public void onClose(@PathParam("key") String key) { SESSION_POOLS.remove(key); log.info("WebSocket请求关闭"); } @OnError public void onError(Throwable thr) { log.info("WebSocket 异常"); } /** * 收到客户端信息 */ @OnMessage public void onMessage(@PathParam("key") String key, String message, Session session) throws IOException { message = "客户端:" + message + ",已收到"; log.info(message); } }
repos\spring-boot-student-master\spring-boot-student-skywalking\src\main\java\com\xiaolyuh\controller\RunningLogEndpoint.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set IP Address. @param IP_Address Defines the IP address to transfer data to */ public void setIP_Address (String IP_Address) { set_Value (COLUMNNAME_IP_Address, IP_Address); } /** Get IP Address. @return Defines the IP address to transfer data to */ public String getIP_Address () { return (String)get_Value(COLUMNNAME_IP_Address); } /** Set Transfer passive. @param IsPassive FTP passive transfer */ public void setIsPassive (boolean IsPassive) { set_Value (COLUMNNAME_IsPassive, Boolean.valueOf(IsPassive)); } /** Get Transfer passive. @return FTP passive transfer */ public boolean isPassive () { Object oo = get_Value(COLUMNNAME_IsPassive); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ 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 Password. @param Password Password of any length (case sensitive) */ public void setPassword (String Password) { set_Value (COLUMNNAME_Password, Password); }
/** Get Password. @return Password of any length (case sensitive) */ public String getPassword () { return (String)get_Value(COLUMNNAME_Password); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ public void setUserName (String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ public String getUserName () { return (String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public User(int id, String name, String email, LocalDateTime createdAt) { this.id = id; this.name = name; this.email = email; this.createdAt = createdAt; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\hateoasvsswagger\model\User.java
1
请完成以下Java代码
public class AuthorizationQueryDto extends AbstractQueryDto<AuthorizationQuery> { private static final String SORT_BY_RESOURCE_TYPE = "resourceType"; private static final String SORT_BY_RESOURCE_ID = "resourceId"; private static final List<String> VALID_SORT_BY_VALUES; static { VALID_SORT_BY_VALUES = new ArrayList<String>(); VALID_SORT_BY_VALUES.add(SORT_BY_RESOURCE_TYPE); VALID_SORT_BY_VALUES.add(SORT_BY_RESOURCE_ID); } protected String id; protected Integer type; protected String[] userIdIn; protected String[] groupIdIn; protected Integer resourceType; protected String resourceId; public AuthorizationQueryDto() { } public AuthorizationQueryDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) { super(objectMapper, queryParameters); } @CamundaQueryParam("id") public void setId(String id) { this.id = id; } @CamundaQueryParam(value="type", converter = IntegerConverter.class) public void setType(Integer type) { this.type = type; } @CamundaQueryParam(value="userIdIn", converter = StringArrayConverter.class) public void setUserIdIn(String[] userIdIn) { this.userIdIn = userIdIn; } @CamundaQueryParam(value="groupIdIn", converter = StringArrayConverter.class) public void setGroupIdIn(String[] groupIdIn) { this.groupIdIn = groupIdIn; } @CamundaQueryParam(value="resourceType", converter = IntegerConverter.class) public void setResourceType(int resourceType) { this.resourceType = resourceType; } @CamundaQueryParam("resourceId") public void setResourceId(String resourceId) { this.resourceId = resourceId; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value);
} protected AuthorizationQuery createNewQuery(ProcessEngine engine) { return engine.getAuthorizationService().createAuthorizationQuery(); } protected void applyFilters(AuthorizationQuery query) { if (id != null) { query.authorizationId(id); } if (type != null) { query.authorizationType(type); } if (userIdIn != null) { query.userIdIn(userIdIn); } if (groupIdIn != null) { query.groupIdIn(groupIdIn); } if (resourceType != null) { query.resourceType(resourceType); } if (resourceId != null) { query.resourceId(resourceId); } } @Override protected void applySortBy(AuthorizationQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_RESOURCE_ID)) { query.orderByResourceId(); } else if (sortBy.equals(SORT_BY_RESOURCE_TYPE)) { query.orderByResourceType(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationQueryDto.java
1
请完成以下Java代码
public void setPercentage (final @Nullable BigDecimal Percentage) { set_Value (COLUMNNAME_Percentage, Percentage); } @Override public BigDecimal getPercentage() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriceActual (final @Nullable BigDecimal PriceActual) { set_Value (COLUMNNAME_PriceActual, PriceActual); } @Override public BigDecimal getPriceActual() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriceEntered (final @Nullable BigDecimal PriceEntered) { set_Value (COLUMNNAME_PriceEntered, PriceEntered); } @Override public BigDecimal getPriceEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceEntered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPrice_UOM_ID (final int Price_UOM_ID) { if (Price_UOM_ID < 1) set_Value (COLUMNNAME_Price_UOM_ID, null); else set_Value (COLUMNNAME_Price_UOM_ID, Price_UOM_ID); } @Override public int getPrice_UOM_ID() { return get_ValueAsInt(COLUMNNAME_Price_UOM_ID); } @Override public void setQty (final @Nullable BigDecimal Qty)
{ set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyEnteredInPriceUOM (final @Nullable BigDecimal QtyEnteredInPriceUOM) { set_Value (COLUMNNAME_QtyEnteredInPriceUOM, QtyEnteredInPriceUOM); } @Override public BigDecimal getQtyEnteredInPriceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInPriceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Detail.java
1
请完成以下Java代码
private void make_AD_Element_Mandatory_In_AD_Tab() { final I_AD_Column elementIdColumn = Services.get(IADTableDAO.class).retrieveColumn(I_AD_Tab.Table_Name, I_AD_Tab.COLUMNNAME_AD_Element_ID); makeElementColumnMandatory(elementIdColumn); } private void makeElementColumnMandatory(final I_AD_Column elementIdColumn) { elementIdColumn.setIsMandatory(true); save(elementIdColumn); final TableDDLSyncService syncService = SpringContextHolder.instance.getBean(TableDDLSyncService.class); syncService.syncToDatabase(AdColumnId.ofRepoId(elementIdColumn.getAD_Column_ID())); } @Override public I_AD_Element getById(final int elementId) { return loadOutOfTrx(elementId, I_AD_Element.class);
} @Override public AdElementId createNewElement(@NonNull final CreateADElementRequest request) { final I_AD_Element record = newInstance(I_AD_Element.class); record.setName(request.getName()); record.setPrintName(request.getPrintName()); record.setDescription(request.getDescription()); record.setHelp(request.getHelp()); record.setCommitWarning(request.getTabCommitWarning()); saveRecord(record); return AdElementId.ofRepoId(record.getAD_Element_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\impl\ADElementDAO.java
1
请完成以下Java代码
public DocumentFieldWidgetType getWidgetType() { return widgetType; } public Builder displayName(@NonNull final ITranslatableString displayName) { this.displayName = TranslatableStrings.copyOf(displayName); return this; } public Builder displayName(final String displayName) { this.displayName = TranslatableStrings.constant(displayName); return this; } public Builder displayName(final AdMessageKey displayName) { return displayName(TranslatableStrings.adMessage(displayName)); } public ITranslatableString getDisplayName() { return displayName; }
public Builder lookupDescriptor(@NonNull final Optional<LookupDescriptor> lookupDescriptor) { this.lookupDescriptor = lookupDescriptor; return this; } public Builder lookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor) { return lookupDescriptor(Optional.ofNullable(lookupDescriptor)); } public Builder lookupDescriptor(@NonNull final UnaryOperator<LookupDescriptor> mapper) { if (this.lookupDescriptor!= null) // don't replace with isPresent() since it could be null at this point { return lookupDescriptor(this.lookupDescriptor.map(mapper)); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParamDescriptor.java
1
请完成以下Java代码
class FetchCurrentChargesCommand { FetchCurrentChargesCommand() { } private FetchCurrentChargesService service = getDefault(); @Parameter(names = "--help", help = true) private boolean help; @Parameter( names = { "--customer", "-C" }, description = "Id of the Customer who's using the services", validateWith = UUIDValidator.class, order = 1, required = true ) private String customerId; @Parameter( names = { "--subscription", "-S" }, description = "Filter charges for specific subscription Ids, includes all subscriptions if no value is specified", variableArity = true, splitter = ColonParameterSplitter.class, order = 2 ) private List<String> subscriptionIds;
@Parameter( names = { "--itemized" }, description = "Whether the response should contain breakdown by subscription, only aggregate values are returned by default", order = 3 ) private boolean itemized; void fetch() { CurrentChargesRequest req = CurrentChargesRequest.builder() .customerId(customerId) .subscriptionIds(subscriptionIds) .itemized(itemized) .build(); CurrentChargesResponse response = service.fetch(req); System.out.println(response); } }
repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\cli\FetchCurrentChargesCommand.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return orderLine.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int bpartnerId) { orderLine.setC_BPartner_ID(bpartnerId); values.setC_BPartner_ID(bpartnerId); } public void setQtyLU(@NonNull final BigDecimal qtyLU) { orderLine.setQtyLU(qtyLU); } public BigDecimal getQtyLU() { return orderLine.getQtyLU(); } @Override public void setLuId(@Nullable final HuPackingInstructionsId luId) { orderLine.setM_LU_HU_PI_ID(HuPackingInstructionsId.toRepoId(luId)); } @Override public HuPackingInstructionsId getLuId() { return HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID()); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute();
} @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public String toString() { return String .format("OrderLineHUPackingAware [orderLine=%s, getM_Product_ID()=%s, getM_Product()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, qtyLU()=%s, luId()=%s, isInDispute()=%s]", orderLine, getM_Product_ID(), getM_Product_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQtyTU(), getC_BPartner_ID(), getM_HU_PI_Item_Product_ID(), getQtyLU(), getLuId(), isInDispute()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } 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 Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(Set<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java
2
请完成以下Java代码
public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { protected final Log logger = LogFactory.getLog(this.getClass()); private RequestCache requestCache = new HttpSessionRequestCache(); @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = this.requestCache.getRequest(request, response); if (savedRequest == null) { super.onAuthenticationSuccess(request, response, authentication); return; } String targetUrlParameter = getTargetUrlParameter(); if (isAlwaysUseDefaultTargetUrl()
|| (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) { this.requestCache.removeRequest(request, response); super.onAuthenticationSuccess(request, response, authentication); return; } clearAuthenticationAttributes(request); // Use the DefaultSavedRequest URL String targetUrl = savedRequest.getRedirectUrl(); getRedirectStrategy().sendRedirect(request, response, targetUrl); } public void setRequestCache(RequestCache requestCache) { this.requestCache = requestCache; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\SavedRequestAwareAuthenticationSuccessHandler.java
1
请在Spring Boot框架中完成以下Java代码
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.context = beanFactory; } private AuthenticationConfiguration getAuthenticationConfiguration() { return this.context.getBean(AuthenticationConfiguration.class); } private boolean prePostEnabled() { return enableMethodSecurity().getBoolean("prePostEnabled"); } private boolean securedEnabled() { return enableMethodSecurity().getBoolean("securedEnabled"); }
private boolean jsr250Enabled() { return enableMethodSecurity().getBoolean("jsr250Enabled"); } private boolean isAspectJ() { return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ; } private AnnotationAttributes enableMethodSecurity() { if (this.enableMethodSecurity == null) { // if it is null look at this instance (i.e. a subclass was used) EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(), EnableGlobalMethodSecurity.class); Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required"); Map<String, Object> methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation); this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs); } return this.enableMethodSecurity; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public EventSubscriptionBuilder scopeDefinitionKey(String scopeDefinitionKey) { this.scopeDefinitionKey = scopeDefinitionKey; return this; } @Override public EventSubscriptionBuilder scopeType(String scopeType) { this.scopeType = scopeType; return this; } @Override public EventSubscriptionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public EventSubscriptionBuilder configuration(String configuration) { this.configuration = configuration; return this; } @Override public EventSubscription create() { return eventSubscriptionService.createEventSubscription(this); } @Override public String getEventType() { return eventType; } @Override public String getEventName() { return eventName; } @Override public Signal getSignal() { return signal; } @Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getActivityId() { return activityId; } @Override public String getSubScopeId() { return subScopeId;
} @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getScopeDefinitionKey() { return scopeDefinitionKey; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String getConfiguration() { return configuration; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java
2
请完成以下Java代码
public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } * */ public void setRsn(String value) { this.rsn = value; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxCharges2 }
* */ public TaxCharges2 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxCharges2 } * */ public void setTax(TaxCharges2 value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\InterestRecord1.java
1
请完成以下Java代码
private static final class Counter { private boolean unknownValue; private int value = 0; @Override public String toString() { return unknownValue ? "N/A" : String.valueOf(value); } public void set(final int value) { if (value < 0) { throw new AdempiereException("value shall NOT be negative: " + value); }
this.value = value; this.unknownValue = false; } public void add(final int valueToAdd) { Check.assumeGreaterOrEqualToZero(valueToAdd, "valueToAdd"); set(this.value + valueToAdd); } public OptionalInt toOptionalInt() {return unknownValue ? OptionalInt.empty() : OptionalInt.of(value);} public int toIntOr(final int defaultValue) {return unknownValue ? defaultValue : value;} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportProcessResult.java
1
请完成以下Java代码
public ProcessId getProcessId() { return processId; } @Override public DocumentId getInstanceId() { return pinstanceId; } @Override public Collection<IProcessInstanceParameter> getParameters() { if (parametersDocument == null) { return ImmutableList.of(); } return parametersDocument.getFieldViews() .stream() .map(DocumentFieldAsProcessInstanceParameter::of) .collect(ImmutableList.toImmutableList()); } @Override public LookupValuesList getParameterLookupValues(final String parameterName) { return parametersDocument.getFieldLookupValues(parameterName); } @Override public LookupValuesPage getParameterLookupValuesForQuery(final String parameterName, final String query) { return parametersDocument.getFieldLookupValuesForQuery(parameterName, query); } @Override public void processParameterValueChanges(final List<JSONDocumentChangedEvent> events, final ReasonSupplier reason) { parametersDocument.processValueChanges(events, reason); } @Override public ProcessInstanceResult getExecutionResult() { Check.assumeNotNull(result, "action was already executed"); return result; } @Override public ProcessInstanceResult startProcess(@NonNull final ProcessExecutionContext context) { assertNotExecuted(); // // Validate parameters, if any if (parametersDocument != null) { parametersDocument.checkAndGetValidStatus().throwIfInvalid(); } // // Execute view action's method final IView view = getView(); final Method viewActionMethod = viewActionDescriptor.getViewActionMethod(); final Object[] viewActionParams = viewActionDescriptor.extractMethodArguments(view, parametersDocument, selectedDocumentIds); try { final Object targetObject = Modifier.isStatic(viewActionMethod.getModifiers()) ? null : view; final Object resultActionObj = viewActionMethod.invoke(targetObject, viewActionParams); final ResultAction resultAction = viewActionDescriptor.convertReturnType(resultActionObj);
final ResultAction resultActionProcessed = processResultAction(resultAction, context.getViewsRepo()); final ProcessInstanceResult result = ProcessInstanceResult.builder(pinstanceId) .action(resultActionProcessed) .build(); this.result = result; return result; } catch (final Throwable ex) { throw AdempiereException.wrapIfNeeded(ex); } } private ResultAction processResultAction(final ResultAction resultAction, final IViewsRepository viewRepos) { if (resultAction == null) { return null; } if (resultAction instanceof CreateAndOpenIncludedViewAction) { final IView view = viewRepos.createView(((CreateAndOpenIncludedViewAction)resultAction).getCreateViewRequest()); return OpenIncludedViewAction.builder().viewId(view.getViewId()).build(); } return resultAction; } /* package */ void assertNotExecuted() { Check.assumeNull(result, "view action instance not already executed"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionInstance.java
1
请完成以下Java代码
public Set<String> getParameterNames() { return stringExpression.getParameterNames(); } @Override public Set<CtxName> getParameters() { return stringExpression.getParameters(); } @Override public V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { final String resultStr = stringExpression.evaluate(ctx, onVariableNotFound); if (stringExpression.isNoResult(resultStr))
{ if (onVariableNotFound == OnVariableNotFound.ReturnNoResult) // i.e. !ignoreUnparsable { return noResultValue; } // else if (onVariableNotFound == OnVariableNotFound.Fail) // no need to handle this case because we expect an exception to be already thrown else { throw new IllegalArgumentException("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound); } } return valueConverter.convertFrom(resultStr, options); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\StringExpressionSupportTemplate.java
1
请完成以下Java代码
public Job findLatestJobByKey(TenantId tenantId, String key) { return jobDao.findLatestByTenantIdAndKey(tenantId, key); } @Override public void deleteJob(TenantId tenantId, JobId jobId) { Job job = findJobById(tenantId, jobId); if (!job.getStatus().isOneOf(CANCELLED, COMPLETED, FAILED)) { throw new IllegalArgumentException("Job must be cancelled, completed or failed"); } jobDao.removeById(tenantId, jobId.getId()); } @Override public int deleteJobsByEntityId(TenantId tenantId, EntityId entityId) { // TODO: cancel all jobs for this entity return jobDao.removeByEntityId(tenantId, entityId); } private Job findForUpdate(TenantId tenantId, JobId jobId) { return jobDao.findByIdForUpdate(tenantId, jobId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findJobById(tenantId, (JobId) entityId)); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(jobDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor()); } @Override public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { jobDao.removeById(tenantId, id.getId()); } @Override public void deleteByTenantId(TenantId tenantId) { jobDao.removeByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.JOB; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\job\DefaultJobService.java
1
请完成以下Java代码
public JsonGetNextEligiblePickFromLineResponse getNextEligiblePickFromLine(@NonNull final JsonGetNextEligiblePickFromLineRequest request, @NonNull final UserId callerId) { return distributionRestService.getNextEligiblePickFromLine(request, callerId); } public WFProcess processEvent(final JsonDistributionEvent event, final UserId callerId) { DistributionJob job = distributionRestService.processEvent(event, callerId); return toWFProcess(job); } public void dropAll(final JsonDropAllRequest request, final UserId callerId) { distributionRestService.dropAll(request, callerId); } @Override
public void logout(final @NonNull UserId userId) { abortAll(userId); } public WFProcess complete(@NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId) { final DistributionJob job = distributionRestService.complete(DistributionJobId.ofWFProcessId(wfProcessId), callerId); return toWFProcess(job); } public void printMaterialInTransitReport(@NonNull final UserId userId, @NonNull final String adLanguage) { distributionRestService.printMaterialInTransitReport(userId, adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\DistributionMobileApplication.java
1
请完成以下Java代码
public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Redo. @param Redo Redo */ @Override public void setRedo (java.lang.String Redo) { set_Value (COLUMNNAME_Redo, Redo); } /** Get Redo. @return Redo */ @Override public java.lang.String getRedo () { return (java.lang.String)get_Value(COLUMNNAME_Redo); } /** Set Transaktion. @param TrxName Name of the transaction */ @Override public void setTrxName (java.lang.String TrxName) { set_ValueNoCheck (COLUMNNAME_TrxName, TrxName); } /** Get Transaktion. @return Name of the transaction */ @Override public java.lang.String getTrxName ()
{ return (java.lang.String)get_Value(COLUMNNAME_TrxName); } /** Set Undo. @param Undo Undo */ @Override public void setUndo (java.lang.String Undo) { set_Value (COLUMNNAME_Undo, Undo); } /** Get Undo. @return Undo */ @Override public java.lang.String getUndo () { return (java.lang.String)get_Value(COLUMNNAME_Undo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog.java
1
请完成以下Java代码
public static final <T> Builder<T> builder() { return new Builder<>(); } private List<T> cardinalityList; private CardinalityOrderComparator(final Builder<T> builder) { super(); // NOTE: we shall not copy the cardinality list because we don't know what type is it, // and maybe the developer is rellying on a specific indexOf implementation of that list. Check.assumeNotNull(builder.cardinalityList, "cardinalityList not null"); this.cardinalityList = builder.cardinalityList; } @Override public int compare(final T o1, final T o2) { final int cardinality1 = cardinality(o1); final int cardinality2 = cardinality(o2); return cardinality1 - cardinality2; } private final int cardinality(final T item) { final int cardinality = cardinalityList.indexOf(item); // If item was not found in our cardinality list, return MAX_VALUE // => not found items will be comsidered last ones if (cardinality < 0) { return Integer.MAX_VALUE; } return cardinality; } public static final class Builder<T> { private List<T> cardinalityList; Builder() { super(); } public CardinalityOrderComparator<T> build() { return new CardinalityOrderComparator<>(this); }
/** * Convenient method to copy and sort a given list. * * @param list * @return sorted list (as a new copy) */ public List<T> copyAndSort(final List<T> list) { final CardinalityOrderComparator<T> comparator = build(); final List<T> listSorted = new ArrayList<>(list); Collections.sort(listSorted, comparator); return listSorted; } /** * Sets the list of all items. * When sorting, this is the list which will give the cardinality of a given item (i.e. the indexOf). * * WARNING: the given cardinality list will be used on line, as it is and it won't be copied, because we don't know what indexOf implementation to use. * So, please make sure you are not chaning the list in meantime. * * @param cardinalityList * @return */ public Builder<T> setCardinalityList(final List<T> cardinalityList) { this.cardinalityList = cardinalityList; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\CardinalityOrderComparator.java
1
请完成以下Java代码
private static ProjectStats buildStats(FilePath root) throws IOException, InterruptedException { int classesNumber = 0; int linesNumber = 0; Stack<FilePath> toProcess = new Stack<>(); toProcess.push(root); while (!toProcess.isEmpty()) { FilePath path = toProcess.pop(); if (path.isDirectory()) { toProcess.addAll(path.list()); } else if (path.getName().endsWith(".java")) { classesNumber++; linesNumber += countLines(path); } } return new ProjectStats(classesNumber, linesNumber); } private static int countLines(FilePath path) throws IOException, InterruptedException { byte[] buffer = new byte[1024]; int result = 1; try (InputStream in = path.read()) { while (true) { int read = in.read(buffer); if (read < 0) { return result; } for (int i = 0; i < read; i++) { if (buffer[i] == '\n') { result++; } } } } } private static String generateReport(String projectName, ProjectStats stats) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try (InputStream in = ProjectStatsBuildWrapper.class.getResourceAsStream(REPORT_TEMPLATE_PATH)) { byte[] buffer = new byte[1024]; int read;
while ((read = in.read(buffer)) >= 0) { bOut.write(buffer, 0, read); } } String content = new String(bOut.toByteArray(), StandardCharsets.UTF_8); content = content.replace(PROJECT_NAME_VAR, projectName); content = content.replace(CLASSES_NUMBER_VAR, String.valueOf(stats.getClassesNumber())); content = content.replace(LINES_NUMBER_VAR, String.valueOf(stats.getLinesNumber())); return content; } @Extension public static final class DescriptorImpl extends BuildWrapperDescriptor { @Override public boolean isApplicable(AbstractProject<?, ?> item) { return true; } @Nonnull @Override public String getDisplayName() { return "Construct project stats during build"; } } }
repos\tutorials-master\jenkins-modules\plugins\src\main\java\com\baeldung\jenkins\plugins\ProjectStatsBuildWrapper.java
1
请完成以下Java代码
private NERInstance createInstance(String[] wordArray, String[] posArray) { final FeatureTemplate[] featureTemplateArray = model.getFeatureTemplateArray(); return new NERInstance(wordArray, posArray, model.featureMap) { @Override protected int[] extractFeature(String[] wordArray, String[] posArray, FeatureMap featureMap, int position) { StringBuilder sbFeature = new StringBuilder(); List<Integer> featureVec = new LinkedList<Integer>(); for (int i = 0; i < featureTemplateArray.length; i++) { Iterator<int[]> offsetIterator = featureTemplateArray[i].offsetList.iterator(); Iterator<String> delimiterIterator = featureTemplateArray[i].delimiterList.iterator(); delimiterIterator.next(); // ignore U0 之类的id while (offsetIterator.hasNext()) { int[] offset = offsetIterator.next(); int t = offset[0] + position; boolean first = offset[1] == 0; if (t < 0) sbFeature.append(FeatureIndex.BOS[-(t + 1)]); else if (t >= wordArray.length) sbFeature.append(FeatureIndex.EOS[t - wordArray.length]); else sbFeature.append(first ? wordArray[t] : posArray[t]); if (delimiterIterator.hasNext()) sbFeature.append(delimiterIterator.next()); else sbFeature.append(i); } addFeatureThenClear(sbFeature, featureVec, featureMap); } return toFeatureArray(featureVec); } }; } @Override protected String getDefaultFeatureTemplate() { return "# Unigram\n" + // form "U0:%x[-2,0]\n" +
"U1:%x[-1,0]\n" + "U2:%x[0,0]\n" + "U3:%x[1,0]\n" + "U4:%x[2,0]\n" + // pos "U5:%x[-2,1]\n" + "U6:%x[-1,1]\n" + "U7:%x[0,1]\n" + "U8:%x[1,1]\n" + "U9:%x[2,1]\n" + // pos 2-gram "UA:%x[-2,1]%x[-1,1]\n" + "UB:%x[-1,1]%x[0,1]\n" + "UC:%x[0,1]%x[1,1]\n" + "UD:%x[1,1]%x[2,1]\n" + "UE:%x[2,1]%x[3,1]\n" + "\n" + "# Bigram\n" + "B"; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFNERecognizer.java
1
请完成以下Java代码
public boolean isRejected() { return !accepted; } public ITranslatableString getRejectReason() { if (accepted) { return TranslatableStrings.empty(); } return reason != null ? reason : TranslatableStrings.empty(); } public ProcessPreconditionsResolution toInternal() { // makes no sense to change the internal flag if accepted if (accepted) { return this; } if (internal) { return this; } return toBuilder().internal(true).build(); } public String computeCaption(@NonNull final ITranslatableString originalProcessCaption, @NonNull final String adLanguage) { final ITranslatableString caption = captionMapper != null ? captionMapper.computeCaption(originalProcessCaption) : originalProcessCaption; return caption.translate(adLanguage); } /** * Derive this resolution, overriding the caption. * * @param captionOverride caption override; null value will be considered as no override */ public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final String captionOverride) { return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride)); } public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final ITranslatableString captionOverride) { return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride)); } @Value private static class ProcessCaptionOverrideMapper implements ProcessCaptionMapper { @NonNull ITranslatableString captionOverride; public ProcessCaptionOverrideMapper(@NonNull final ITranslatableString captionOverride)
{ this.captionOverride = captionOverride; } public ProcessCaptionOverrideMapper(@NonNull final String captionOverride) { this.captionOverride = TranslatableStrings.anyLanguage(captionOverride); } @Override public ITranslatableString computeCaption(final ITranslatableString originalProcessCaption) { return captionOverride; } } public ProcessPreconditionsResolution withCaptionMapper(@Nullable final ProcessCaptionMapper captionMapper) { return toBuilder().captionMapper(captionMapper).build(); } /** * Override default SortNo used with ordering related processes */ public ProcessPreconditionsResolution withSortNo(final int sortNo) { return !this.sortNo.isPresent() || this.sortNo.getAsInt() != sortNo ? toBuilder().sortNo(OptionalInt.of(sortNo)).build() : this; } public @NonNull OptionalInt getSortNo() {return this.sortNo;} public ProcessPreconditionsResolution and(final Supplier<ProcessPreconditionsResolution> resolutionSupplier) { if (isRejected()) { return this; } return resolutionSupplier.get(); } public void throwExceptionIfRejected() { if (isRejected()) { throw new AdempiereException(getRejectReason()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionsResolution.java
1
请完成以下Java代码
private Mono<OAuth2Token> oauth2Token() { // @formatter:off return Mono.deferContextual(Mono::just) .cast(Context.class) .flatMap(this::currentAuthentication) .filter((authentication) -> authentication.getCredentials() instanceof OAuth2Token) .map(Authentication::getCredentials) .cast(OAuth2Token.class); // @formatter:on } private Mono<Authentication> currentAuthentication(Context ctx) { return Mono.justOrEmpty(getAttribute(ctx, Authentication.class)); } private <T> T getAttribute(Context ctx, Class<T> clazz) { // NOTE: SecurityReactorContextConfiguration.SecurityReactorContextSubscriber adds
// this key if (!ctx.hasKey(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY)) { return null; } Map<Class<T>, T> attributes = ctx.get(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY); return attributes.get(clazz); } private ClientRequest bearer(ClientRequest request, OAuth2Token token) { // @formatter:off return ClientRequest.from(request) .headers((headers) -> headers.setBearerAuth(token.getTokenValue())) .build(); // @formatter:on } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\reactive\function\client\ServletBearerExchangeFilterFunction.java
1
请完成以下Java代码
public static List<ProcessesXmlWrapper> getProcessesXmls(DeploymentUnit deploymentUnit) { return deploymentUnit.getAttachmentList(PROCESSES_XML_LIST); } /** * marks a a {@link DeploymentUnit} as a process application */ public static void mark(DeploymentUnit unit) { unit.putAttachment(MARKER, Boolean.TRUE); } /** * marks a a {@link DeploymentUnit} as part of a process application */ public static void markPartOfProcessApplication(DeploymentUnit unit) { if(unit.getParent() != null && unit.getParent() != unit) { unit.getParent().putAttachment(PART_OF_MARKER, Boolean.TRUE); } } /** * return true if the deployment unit is either itself a process * application or part of a process application. */ public static boolean isPartOfProcessApplication(DeploymentUnit unit) { if(isProcessApplication(unit)) { return true; } if(unit.getParent() != null && unit.getParent() != unit) { return unit.getParent().hasAttachment(PART_OF_MARKER); } return false; } /** * Returns true if the {@link DeploymentUnit} itself is a process application (carries a processes.xml) * */ public static boolean isProcessApplication(DeploymentUnit deploymentUnit) { return deploymentUnit.hasAttachment(MARKER); } /** * Returns the {@link ComponentDescription} for the {@link AbstractProcessApplication} component */ public static ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) { return deploymentUnit.getAttachment(PA_COMPONENT); } /** * Attach the {@link ComponentDescription} for the {@link AbstractProcessApplication} component */ public static void attachProcessApplicationComponent(DeploymentUnit deploymentUnit, ComponentDescription componentDescription){ deploymentUnit.putAttachment(PA_COMPONENT, componentDescription); }
/** * Attach the {@link AnnotationInstance}s for the PostDeploy methods */ public static void attachPostDeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){ deploymentUnit.putAttachment(POST_DEPLOY_METHOD, annotation); } /** * Attach the {@link AnnotationInstance}s for the PreUndeploy methods */ public static void attachPreUndeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){ deploymentUnit.putAttachment(PRE_UNDEPLOY_METHOD, annotation); } /** * @return the description of the PostDeploy method */ public static AnnotationInstance getPostDeployDescription(DeploymentUnit deploymentUnit) { return deploymentUnit.getAttachment(POST_DEPLOY_METHOD); } /** * @return the description of the PreUndeploy method */ public static AnnotationInstance getPreUndeployDescription(DeploymentUnit deploymentUnit) { return deploymentUnit.getAttachment(PRE_UNDEPLOY_METHOD); } private ProcessApplicationAttachments() { } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\marker\ProcessApplicationAttachments.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=create spring.jpa.properties.hibernate.dialect=org.hibernate.dialect
.MySQL5InnoDBDialect #sql\u8F93\u51FA spring.jpa.show-sql=true #format\u4E00\u4E0Bsql\u8FDB\u884C\u8F93\u51FA spring.jpa.properties.hibernate.format_sql=true
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\resources\application.properties
2
请完成以下Java代码
public EventDefinitionEntity findEventDefinitionByDeploymentAndKey(String deploymentId, String eventDefinitionKey) { return dataManager.findEventDefinitionByDeploymentAndKey(deploymentId, eventDefinitionKey); } @Override public EventDefinitionEntity findEventDefinitionByDeploymentAndKeyAndTenantId(String deploymentId, String eventDefinitionKey, String tenantId) { return dataManager.findEventDefinitionByDeploymentAndKeyAndTenantId(deploymentId, eventDefinitionKey, tenantId); } @Override public EventDefinitionEntity findLatestEventDefinitionByKeyAndTenantId(String eventDefinitionKey, String tenantId) { if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findLatestEventDefinitionByKey(eventDefinitionKey); } else { return dataManager.findLatestEventDefinitionByKeyAndTenantId(eventDefinitionKey, tenantId); } } @Override public EventDefinitionEntity findEventDefinitionByKeyAndVersionAndTenantId(String eventDefinitionKey, Integer eventVersion, String tenantId) { if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return dataManager.findEventDefinitionByKeyAndVersion(eventDefinitionKey, eventVersion); } else { return dataManager.findEventDefinitionByKeyAndVersionAndTenantId(eventDefinitionKey, eventVersion, tenantId); } } @Override public List<EventDefinition> findEventDefinitionsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findEventDefinitionsByNativeQuery(parameterMap); } @Override public long findEventDefinitionCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findEventDefinitionCountByNativeQuery(parameterMap); } @Override public void updateEventDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateEventDefinitionTenantIdForDeployment(deploymentId, newTenantId); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDefinitionEntityManagerImpl.java
1
请完成以下Java代码
protected void validateAndSwitchVersionOfExecution(CommandContext commandContext, ExecutionEntity execution, ProcessDefinitionEntity newProcessDefinition) { // check that the new process definition version contains the current activity if (execution.getActivity() != null) { String activityId = execution.getActivity().getId(); PvmActivity newActivity = newProcessDefinition.findActivity(activityId); if (newActivity == null) { throw new ProcessEngineException( "The new process definition " + "(key = '" + newProcessDefinition.getKey() + "') " + "does not contain the current activity " + "(id = '" + activityId + "') " + "of the process instance " + "(id = '" + processInstanceId + "')."); }
// clear cached activity so that outgoing transitions are refreshed execution.setActivity(newActivity); } // switch the process instance to the new process definition version execution.setProcessDefinition(newProcessDefinition); // and change possible existing tasks (as the process definition id is stored there too) List<TaskEntity> tasks = commandContext.getTaskManager().findTasksByExecutionId(execution.getId()); for (TaskEntity taskEntity : tasks) { taskEntity.setProcessDefinitionId(newProcessDefinition.getId()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetProcessDefinitionVersionCmd.java
1
请完成以下Java代码
public void customize(Members<Object> members) { members.applyingPathFilter(this::filterPath); members.applyingNameProcessor(this::renameJsonMembers); Map<String, String> add = this.properties.add(); if (!CollectionUtils.isEmpty(add)) { if (this.nested) { ContextPairs contextPairs = new ContextPairs(true, ""); members.add().usingPairs(contextPairs.nested((pairs) -> pairs.addMapEntries((source) -> add))); } else { add.forEach(members::add); } } this.properties.customizers(this.instantiator).forEach((customizer) -> customizer.customize(members)); }
String renameJsonMembers(MemberPath path, String existingName) { Map<String, String> rename = this.properties.rename(); String key = path.toUnescapedString(); return !CollectionUtils.isEmpty(rename) ? rename.getOrDefault(key, existingName) : existingName; } boolean filterPath(MemberPath path) { boolean included = CollectionUtils.isEmpty(this.properties.include()) || this.properties.include().contains(path.toUnescapedString()); boolean excluded = !CollectionUtils.isEmpty(this.properties.exclude()) && this.properties.exclude().contains(path.toUnescapedString()); return (!included || excluded); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\StructuredLoggingJsonPropertiesJsonMembersCustomizer.java
1
请完成以下Java代码
public void setIsAllowOverdelivery (final boolean IsAllowOverdelivery) { set_Value (COLUMNNAME_IsAllowOverdelivery, IsAllowOverdelivery); } @Override public boolean isAllowOverdelivery() { return get_ValueAsBoolean(COLUMNNAME_IsAllowOverdelivery); } @Override public void setIsAutoProcess (final boolean IsAutoProcess) { set_Value (COLUMNNAME_IsAutoProcess, IsAutoProcess); } @Override public boolean isAutoProcess() { return get_ValueAsBoolean(COLUMNNAME_IsAutoProcess); } @Override public void setIsForbidAggCUsForDifferentOrders (final boolean IsForbidAggCUsForDifferentOrders) { set_Value (COLUMNNAME_IsForbidAggCUsForDifferentOrders, IsForbidAggCUsForDifferentOrders); } @Override public boolean isForbidAggCUsForDifferentOrders() { return get_ValueAsBoolean(COLUMNNAME_IsForbidAggCUsForDifferentOrders); } @Override public void setM_Picking_Config_ID (final int M_Picking_Config_ID) { if (M_Picking_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, M_Picking_Config_ID); } @Override
public int getM_Picking_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Config_ID); } /** * WEBUI_PickingTerminal_ViewProfile AD_Reference_ID=540772 * Reference name: WEBUI_PickingTerminal_ViewProfile */ public static final int WEBUI_PICKINGTERMINAL_VIEWPROFILE_AD_Reference_ID=540772; /** groupByProduct = groupByProduct */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByProduct = "groupByProduct"; /** Group by Order = groupByOrder */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByOrder = "groupByOrder"; @Override public void setWEBUI_PickingTerminal_ViewProfile (final java.lang.String WEBUI_PickingTerminal_ViewProfile) { set_Value (COLUMNNAME_WEBUI_PickingTerminal_ViewProfile, WEBUI_PickingTerminal_ViewProfile); } @Override public java.lang.String getWEBUI_PickingTerminal_ViewProfile() { return get_ValueAsString(COLUMNNAME_WEBUI_PickingTerminal_ViewProfile); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config.java
1