instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class Address { private Integer addressId; private String addressLocation; public Address() { } public Address(Integer addressId, String addressLocation) { this.addressId = addressId; this.addressLocation = addressLocation; } public Integer getAddressId() { return addressId;
} public void setAddressId(Integer addressId) { this.addressId = addressId; } public String getAddressLocation() { return addressLocation; } public void setAddressLocation(String addressLocation) { this.addressLocation = addressLocation; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-4\src\main\java\com\baeldung\nestedhashmaps\Address.java
1
请完成以下Java代码
protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); } public ExecutionImpl getReplacedBy() { return (ExecutionImpl) replacedBy; } public void setExecutions(List<ExecutionImpl> executions) { this.executions = executions; } public String getCurrentActivityName() { String currentActivityName = null; if (this.activity != null) { currentActivityName = (String) activity.getProperty("name"); } return currentActivityName; } public FlowElement getBpmnModelElementInstance() { throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl"); } public BpmnModelInstance getBpmnModelInstance() { throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl");
} public ProcessEngineServices getProcessEngineServices() { throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl"); } public ProcessEngine getProcessEngine() { throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl"); } public void forceUpdate() { // nothing to do } public void fireHistoricProcessStartEvent() { // do nothing } protected void removeVariablesLocalInternal(){ // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ExecutionImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ProcessDefinitionResourceDataResource extends BaseDeploymentResourceDataResource { @ApiOperation(value = "Get a process definition resource content", tags = { "Process Definitions" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates both process definition and resource have been found and the resource data has been returned."), @ApiResponse(code = 404, message = "Indicates the requested process definition was not found or there is no resource with the given id present in the process definition. The status-description contains additional information.") }) @GetMapping(value = "/repository/process-definitions/{processDefinitionId}/resourcedata") public byte[] getProcessDefinitionResource(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId, HttpServletResponse response) { ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId); return getDeploymentResourceData(processDefinition.getDeploymentId(), processDefinition.getResourceName(), response); } /** * Returns the {@link ProcessDefinition} that is requested. Throws the right exceptions when bad request was made or definition was not found.
*/ protected ProcessDefinition getProcessDefinitionFromRequest(String processDefinitionId) { ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult(); if (processDefinition == null) { throw new FlowableObjectNotFoundException("Could not find a process definition with id '" + processDefinitionId + "'.", ProcessDefinition.class); } if (restApiInterceptor != null) { restApiInterceptor.accessProcessDefinitionById(processDefinition); } return processDefinition; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionResourceDataResource.java
2
请完成以下Java代码
public class LongestCommonSubsequence { public static int compute(char[] str1, char[] str2) { int substringLength1 = str1.length; int substringLength2 = str2.length; // 构造二维数组记录子问题A[i]和B[j]的LCS的长度 int[][] opt = new int[substringLength1 + 1][substringLength2 + 1]; // 从后向前,动态规划计算所有子问题。也可从前到后。 for (int i = substringLength1 - 1; i >= 0; i--) { for (int j = substringLength2 - 1; j >= 0; j--) { if (str1[i] == str2[j]) opt[i][j] = opt[i + 1][j + 1] + 1;// 状态转移方程 else opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]);// 状态转移方程 } } // System.out.println("substring1:" + new String(str1)); // System.out.println("substring2:" + new String(str2)); // System.out.print("LCS:");
// int i = 0, j = 0; // while (i < substringLength1 && j < substringLength2) // { // if (str1[i] == str2[j]) // { // System.out.print(str1[i]); // i++; // j++; // } // else if (opt[i + 1][j] >= opt[i][j + 1]) // i++; // else // j++; // } // System.out.println(); return opt[0][0]; } public static int compute(String str1, String str2) { return compute(str1.toCharArray(), str2.toCharArray()); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\LongestCommonSubsequence.java
1
请在Spring Boot框架中完成以下Java代码
public SpringCacheBasedAclCache aclCache() { final ConcurrentMapCache aclCache = new ConcurrentMapCache("acl_cache"); return new SpringCacheBasedAclCache(aclCache, permissionGrantingStrategy(), aclAuthorizationStrategy()); } @Bean public PermissionGrantingStrategy permissionGrantingStrategy() { return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()); } @Bean public AclAuthorizationStrategy aclAuthorizationStrategy() { return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN")); } @Bean public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() { DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService()); expressionHandler.setPermissionEvaluator(permissionEvaluator);
expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService())); return expressionHandler; } @Bean public LookupStrategy lookupStrategy() { return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger()); } @Bean public JdbcMutableAclService aclService() { return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache()); } }
repos\tutorials-master\spring-security-modules\spring-security-acl\src\main\java\com\baeldung\acl\config\ACLContext.java
2
请完成以下Java代码
public class TaskWithAttachmentAndCommentDto extends TaskWithVariablesDto { private boolean hasAttachment; private boolean hasComment; public TaskWithAttachmentAndCommentDto() { } public TaskWithAttachmentAndCommentDto(Task task, Map<String, VariableValueDto> variables) { super(task, variables); } public TaskWithAttachmentAndCommentDto(Task task) { super(task); } public boolean getAttachment() { return hasAttachment; } public void setAttachment(boolean hasAttachment) { this.hasAttachment = hasAttachment; } public boolean getComment() { return hasComment;
} public void setComment(boolean hasComment) { this.hasComment = hasComment; } public static TaskDto fromEntity(Task task, Map<String, VariableValueDto> variables) { TaskWithAttachmentAndCommentDto result = new TaskWithAttachmentAndCommentDto(task, variables); result.hasAttachment = task.hasAttachment(); result.hasComment = task.hasComment(); return result; } public static TaskDto fromEntity(Task task) { return fromEntity(task, null); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskWithAttachmentAndCommentDto.java
1
请完成以下Java代码
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } public void setFrom(@NonNull final I_C_Invoice_Candidate from) { setFrom(new BillLocationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Order order) { setFrom(OrderDocumentLocationAdapterFactory.billLocationAdapter(order).toDocumentLocation()); } @Override
public I_C_Invoice_Candidate getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public BillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new BillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Invoice_Candidate.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\location\adapter\BillLocationAdapter.java
1
请完成以下Java代码
public Timestamp getA_Renewal_Date () { return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date); } /** Set Account State. @param A_State State of the Credit Card or Account holder */ public void setA_State (String A_State) { set_Value (COLUMNNAME_A_State, A_State); } /** Get Account State. @return State of the Credit Card or Account holder */ public String getA_State ()
{ return (String)get_Value(COLUMNNAME_A_State); } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Lic.java
1
请在Spring Boot框架中完成以下Java代码
public Mapper<T> getMapper() { return mapper; } @Override public Long getSequence(@Param("seqName") String seqName){ return seqenceMapper.getSequence(seqName); } @Override public List<T> selectAll() { //说明:查询所有数据 return mapper.selectAll(); } @Override public T selectByKey(Object key) { //说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号 return mapper.selectByPrimaryKey(key); } @Override public int save(T entity) { //说明:保存一个实体,null的属性也会保存,不会使用数据库默认值 return mapper.insert(entity); } @Override public int delete(Object key) { //说明:根据主键字段进行删除,方法参数必须包含完整的主键属性 return mapper.deleteByPrimaryKey(key); } @Override public int updateAll(T entity) { //说明:根据主键更新实体全部字段,null值会被更新
return mapper.updateByPrimaryKey(entity); } @Override public int updateNotNull(T entity) { //根据主键更新属性不为null的值 return mapper.updateByPrimaryKeySelective(entity); } @Override public List<T> selectByExample(Object example) { //说明:根据Example条件进行查询 //重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列 return mapper.selectByExample(example); } }
repos\SpringAll-master\27.Spring-Boot-Mapper-PageHelper\src\main\java\com\springboot\service\impl\BaseService.java
2
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemMessageSender { private final RabbitTemplate rabbitTemplate; private final Queue queue; public ExternalSystemMessageSender( @NonNull final RabbitTemplate rabbitTemplate, @NonNull @Qualifier(QUEUE_NAME_MF_TO_ES) final Queue queue ) { this.rabbitTemplate = rabbitTemplate; this.queue = queue; } public void send(@NonNull final JsonExternalSystemRequest externalSystemRequest) { final byte[] messageAsBytes;
try { messageAsBytes = JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsBytes(externalSystemRequest); } catch (final JsonProcessingException e) { throw new AdempiereException("Exception serializing externalSystemRequest", e) .appendParametersToMessage() .setParameter("externalSystemRequest", externalSystemRequest); } final MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentEncoding(StandardCharsets.UTF_8.displayName()); messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON); rabbitTemplate.convertAndSend(queue.getName(), new Message(messageAsBytes, messageProperties)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmq\ExternalSystemMessageSender.java
2
请完成以下Java代码
public class ContentSecurityPolicyProvider extends HeaderSecurityProvider { public static final String HEADER_NAME = "Content-Security-Policy"; public static final String HEADER_NONCE_PLACEHOLDER = "$NONCE"; public static final String HEADER_DEFAULT_VALUE = "" + "base-uri 'self';" + "script-src " + HEADER_NONCE_PLACEHOLDER + " 'strict-dynamic' 'unsafe-eval' https: 'self' 'unsafe-inline';" + "style-src 'unsafe-inline' 'self';" + "default-src 'self';" + "img-src 'self' data:;" + "block-all-mixed-content;" + "form-action 'self';" + "frame-ancestors 'none';" + "object-src 'none';" + "sandbox allow-forms allow-scripts allow-same-origin allow-popups allow-downloads"; public static final String DISABLED_PARAM = "contentSecurityPolicyDisabled"; public static final String VALUE_PARAM = "contentSecurityPolicyValue"; public static final String ATTR_CSP_FILTER_NONCE = "org.camunda.bpm.csp.nonce"; public static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); @Override public Map<String, String> initParams() { initParams.put(VALUE_PARAM, null); initParams.put(DISABLED_PARAM, null); return initParams; } @Override public void parseParams() { String disabled = initParams.get(DISABLED_PARAM); if (ServletFilterUtil.isEmpty(disabled)) { setDisabled(false); } else { setDisabled(Boolean.parseBoolean(disabled));
} String value = initParams.get(VALUE_PARAM); if (!ServletFilterUtil.isEmpty(value)) { value = normalizeString(value); setValue(value); } else { setValue(HEADER_DEFAULT_VALUE); } } protected String normalizeString(String value) { return value .trim() .replaceAll("\\s+", " "); // replaces [\t\n\x0B\f\r] } @Override public String getHeaderName() { return HEADER_NAME; } @Override public String getHeaderValue(final ServletContext servletContext) { final String nonce = generateNonce(); servletContext.setAttribute(ATTR_CSP_FILTER_NONCE, nonce); return value.replaceAll("\\" + HEADER_NONCE_PLACEHOLDER, String.format("'nonce-%s'", nonce)); } protected String generateNonce() { final byte[] bytes = new byte[20]; ThreadLocalRandom.current().nextBytes(bytes); return ENCODER.encodeToString(bytes); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\ContentSecurityPolicyProvider.java
1
请完成以下Java代码
public byte[] writeConfiguration(T configuration) { JsonElement jsonObject = getJsonConverterInstance().toJsonObject(configuration); return JsonUtil.asBytes(jsonObject); } @Override public T readConfiguration(byte[] serializedConfiguration) { return getJsonConverterInstance().toObject(JsonUtil.asObject(serializedConfiguration)); } protected abstract AbstractBatchConfigurationObjectConverter<T> getJsonConverterInstance(); @Override public Class<? extends DbEntity> getEntityType() { return BatchEntity.class; } @Override public OptimisticLockingResult failedOperation(final DbOperation operation) {
if (operation instanceof DbEntityOperation) { return OptimisticLockingResult.IGNORE; } return OptimisticLockingResult.THROW; } @Override public int calculateInvocationsPerBatchJob(String batchType, T configuration) { ProcessEngineConfigurationImpl engineConfig = Context.getProcessEngineConfiguration(); Map<String, Integer> invocationsPerBatchJobByBatchType = engineConfig.getInvocationsPerBatchJobByBatchType(); Integer invocationCount = invocationsPerBatchJobByBatchType.get(batchType); if (invocationCount != null) { return invocationCount; } else { return engineConfig.getInvocationsPerBatchJob(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\AbstractBatchJobHandler.java
1
请完成以下Java代码
public class CancelEndEventActivityBehavior extends AbstractBpmnActivityBehavior { protected PvmActivity cancelBoundaryEvent; @Override public void execute(ActivityExecution execution) throws Exception { EnsureUtil .ensureNotNull("Could not find cancel boundary event for cancel end event " + execution.getActivity(), "cancelBoundaryEvent", cancelBoundaryEvent); List<EventSubscriptionEntity> compensateEventSubscriptions = CompensationUtil.collectCompensateEventSubscriptionsForScope(execution); if(compensateEventSubscriptions.isEmpty()) { leave(execution); } else { CompensationUtil.throwCompensationEvent(compensateEventSubscriptions, execution, false); } } public void doLeave(ActivityExecution execution) { // continue via the appropriate cancel boundary event ScopeImpl eventScope = (ScopeImpl) cancelBoundaryEvent.getEventScope(); ActivityExecution boundaryEventScopeExecution = execution.findExecutionForFlowScope(eventScope); boundaryEventScopeExecution.executeActivity(cancelBoundaryEvent);
} public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception { // join compensating executions if(!execution.hasChildren()) { leave(execution); } else { ((ExecutionEntity)execution).forceUpdate(); } } public void setCancelBoundaryEvent(PvmActivity cancelBoundaryEvent) { this.cancelBoundaryEvent = cancelBoundaryEvent; } public PvmActivity getCancelBoundaryEvent() { return cancelBoundaryEvent; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CancelEndEventActivityBehavior.java
1
请完成以下Spring Boot application配置
server.ssl.key-store=../store/keystore.jks server.ssl.key-store-password=changeit server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.
port=8443 spring.security.user.name=Admin spring.security.user.password=admin
repos\tutorials-master\spring-security-modules\spring-security-web-x509\spring-security-web-x509-basic-auth\src\main\resources\application.properties
2
请完成以下Java代码
public void deploy(final DeploymentEntity deployment) { Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() { public Void call() throws Exception { for (Deployer deployer : deployers) { deployer.deploy(deployment); } return null; } }); } public void deployOnlyGivenResourcesOfDeployment(final DeploymentEntity deployment, String... resourceNames) { initDeployment(deployment, resourceNames); Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() { public Void call() throws Exception { for (Deployer deployer : deployers) { deployer.deploy(deployment); } return null;
} }); deployment.setResources(null); } protected void initDeployment(final DeploymentEntity deployment, String... resourceNames) { deployment.clearResources(); for (String resourceName : resourceNames) { if (resourceName != null) { // with the given resource we prevent the deployment of querying // the database which means using all resources that were utilized during the deployment ResourceEntity resource = Context.getCommandContext().getResourceManager().findResourceByDeploymentIdAndResourceName(deployment.getId(), resourceName); deployment.addResource(resource); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CacheDeployer.java
1
请在Spring Boot框架中完成以下Java代码
class ActiveMQConnectionFactoryConfigurer { private final ActiveMQProperties properties; private final List<ActiveMQConnectionFactoryCustomizer> factoryCustomizers; ActiveMQConnectionFactoryConfigurer(ActiveMQProperties properties, @Nullable List<ActiveMQConnectionFactoryCustomizer> factoryCustomizers) { Assert.notNull(properties, "'properties' must not be null"); this.properties = properties; this.factoryCustomizers = (factoryCustomizers != null) ? factoryCustomizers : Collections.emptyList(); } void configure(ActiveMQConnectionFactory factory) { if (this.properties.getCloseTimeout() != null) { factory.setCloseTimeout((int) this.properties.getCloseTimeout().toMillis()); } factory.setNonBlockingRedelivery(this.properties.isNonBlockingRedelivery()); if (this.properties.getSendTimeout() != null) { factory.setSendTimeout((int) this.properties.getSendTimeout().toMillis()); }
Packages packages = this.properties.getPackages(); if (packages.getTrustAll() != null) { factory.setTrustAllPackages(packages.getTrustAll()); } if (!packages.getTrusted().isEmpty()) { factory.setTrustedPackages(packages.getTrusted()); } customize(factory); } private void customize(ActiveMQConnectionFactory connectionFactory) { for (ActiveMQConnectionFactoryCustomizer factoryCustomizer : this.factoryCustomizers) { factoryCustomizer.customize(connectionFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQConnectionFactoryConfigurer.java
2
请完成以下Java代码
public Object put(String name, Object value) { if (storeScriptVariables) { Object oldValue = null; if (!UNSTORED_KEYS.contains(name)) { oldValue = scopeContainer.getVariable(name); scopeContainer.setVariable(name, value); return oldValue; } } return defaultBindings.put(name, value); } @Override public Set<Map.Entry<String, Object>> entrySet() { Set<Map.Entry<String, Object>> entries = new HashSet<>(); for (String key : inputVariableContainer.getVariableNames()) { entries.add(Pair.of(key, inputVariableContainer.getVariable(key))); } return entries; } @Override public Set<String> keySet() { return inputVariableContainer.getVariableNames(); } @Override public int size() { return inputVariableContainer.getVariableNames().size(); } @Override public Collection<Object> values() { Set<String> variableNames = inputVariableContainer.getVariableNames(); List<Object> values = new ArrayList<>(variableNames.size()); for (String key : variableNames) { values.add(inputVariableContainer.getVariable(key)); } return values; }
@Override public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } protected Map<String, Object> getVariables() { if (this.scopeContainer instanceof VariableScope) { return ((VariableScope) this.scopeContainer).getVariables(); } return Collections.emptyMap(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public void saveNew(@NonNull final FTSSearchResult result) { final ImmutableList<FTSSearchResultItem> items = result.getItems(); if (items.isEmpty()) { return; } PreparedStatement pstmt = null; try { int nextLineNo = 1; pstmt = DB.prepareStatement(SQL_INSERT, ITrx.TRXNAME_None); final ArrayList<Object> sqlParams = new ArrayList<>(); for (final FTSSearchResultItem item : items) { final int lineNo = nextLineNo++; sqlParams.clear(); sqlParams.add(result.getSearchId()); sqlParams.add(lineNo); sqlParams.add(item.getJson());
for (final String keyColumnName : I_T_ES_FTS_Search_Result.COLUMNNAME_ALL_Keys) { final Object value = item.getKey().getValueBySelectionTableColumnName(keyColumnName); sqlParams.add(value); } DB.setParameters(pstmt, sqlParams); pstmt.addBatch(); } pstmt.executeBatch(); } catch (final SQLException ex) { throw new DBException(ex, SQL_INSERT); } finally { DB.close(pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchResultRepository.java
1
请在Spring Boot框架中完成以下Java代码
public ModelAndView coreTags(final Model model) { ModelAndView mv = new ModelAndView("core_tags"); return mv; } @RequestMapping(value = "/core_tags_redirect", method = RequestMethod.GET) public ModelAndView coreTagsRedirect(final Model model) { ModelAndView mv = new ModelAndView("core_tags_redirect"); return mv; } @RequestMapping(value = "/formatting_tags", method = RequestMethod.GET) public ModelAndView formattingTags(final Model model) { ModelAndView mv = new ModelAndView("formatting_tags"); return mv; } @RequestMapping(value = "/sql_tags", method = RequestMethod.GET) public ModelAndView sqlTags(final Model model) { ModelAndView mv = new ModelAndView("sql_tags"); return mv; } @RequestMapping(value = "/xml_tags", method = RequestMethod.GET) public ModelAndView xmlTags(final Model model) { System.out.println("dddddddddddddddddffffffffffffff"); ModelAndView mv = new ModelAndView("xml_tags"); return mv; } @RequestMapping(value = "/items_xml", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile(HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/xml"); return new FileSystemResource(new File(servletContext.getRealPath("/WEB-INF/items.xsl"))); } @RequestMapping(value = "/function_tags", method = RequestMethod.GET) public ModelAndView functionTags(final Model model) { ModelAndView mv = new ModelAndView("function_tags"); return mv; } private void generateDummy(Connection connection) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO USERS " + "(email, first_name, last_name, registered) VALUES (?, ?, ?, ?);"); preparedStatement.setString(1, "patrick@baeldung.com"); preparedStatement.setString(2, "Patrick"); preparedStatement.setString(3, "Frank"); preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis())); preparedStatement.addBatch(); preparedStatement.setString(1, "bfrank@baeldung.com"); preparedStatement.setString(2, "Benjamin"); preparedStatement.setString(3, "Franklin"); preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis())); preparedStatement.executeBatch(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-jsp\src\main\java\com\baeldung\jstl\controllers\JSTLController.java
2
请在Spring Boot框架中完成以下Java代码
private void deleteProductCategoryRelation(Long id) { SmsCouponProductCategoryRelationExample productCategoryRelationExample = new SmsCouponProductCategoryRelationExample(); productCategoryRelationExample.createCriteria().andCouponIdEqualTo(id); productCategoryRelationMapper.deleteByExample(productCategoryRelationExample); } private void deleteProductRelation(Long id) { SmsCouponProductRelationExample productRelationExample = new SmsCouponProductRelationExample(); productRelationExample.createCriteria().andCouponIdEqualTo(id); productRelationMapper.deleteByExample(productRelationExample); } @Override public int update(Long id, SmsCouponParam couponParam) { couponParam.setId(id); int count =couponMapper.updateByPrimaryKey(couponParam); //删除后插入优惠券和商品关系表 if(couponParam.getUseType().equals(2)){ for(SmsCouponProductRelation productRelation:couponParam.getProductRelationList()){ productRelation.setCouponId(couponParam.getId()); } deleteProductRelation(id); productRelationDao.insertList(couponParam.getProductRelationList()); } //删除后插入优惠券和商品分类关系表 if(couponParam.getUseType().equals(1)){ for (SmsCouponProductCategoryRelation couponProductCategoryRelation : couponParam.getProductCategoryRelationList()) { couponProductCategoryRelation.setCouponId(couponParam.getId()); } deleteProductCategoryRelation(id); productCategoryRelationDao.insertList(couponParam.getProductCategoryRelationList()); } return count; } @Override
public List<SmsCoupon> list(String name, Integer type, Integer pageSize, Integer pageNum) { SmsCouponExample example = new SmsCouponExample(); SmsCouponExample.Criteria criteria = example.createCriteria(); if(!StrUtil.isEmpty(name)){ criteria.andNameLike("%"+name+"%"); } if(type!=null){ criteria.andTypeEqualTo(type); } PageHelper.startPage(pageNum,pageSize); return couponMapper.selectByExample(example); } @Override public SmsCouponParam getItem(Long id) { return couponDao.getItem(id); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsCouponServiceImpl.java
2
请完成以下Java代码
private Percent calculateDefaultDiscountPercentage(final GroupTemplateCompensationLine templateLine, final Group group) { if (templateLine.getPercentage() != null) { return templateLine.getPercentage(); } return retrieveDiscountPercentageFromPricing(templateLine, group); } private Percent retrieveDiscountPercentageFromPricing(final GroupTemplateCompensationLine templateLine, final Group group) { final IEditablePricingContext pricingCtx = pricingBL.createPricingContext(); pricingCtx.setProductId(templateLine.getProductId()); pricingCtx.setBPartnerId(group.getBpartnerId());
pricingCtx.setSOTrx(group.getSoTrx()); pricingCtx.setDisallowDiscount(false);// just to be sure pricingCtx.setQty(BigDecimal.ONE); final IPricingResult pricingResult = pricingBL.createInitialResult(pricingCtx); pricingResult.setCalculated(true); // important, else the Discount rule does not react pricingResult.setPriceStd(group.getTotalNetAmt()); final Discount discountRule = new Discount(); discountRule.calculate(pricingCtx, pricingResult); return pricingResult.getDiscount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupCompensationLineCreateRequestFactory.java
1
请完成以下Java代码
public class LoggingSessionLoggerOutput { private static final Logger LOGGER = LoggerFactory.getLogger(LoggingSessionLoggerOutput.class); public static void printLogNodes(List<ObjectNode> logNodes) { printLogNodes(logNodes, "info"); } public static void printLogNodes(List<ObjectNode> logNodes, String logLevel) { if (logNodes == null) { return; } StringBuilder logBuilder = new StringBuilder("\n"); for (ObjectNode logNode : logNodes) { logBuilder.append(logNode.get(LoggingSessionUtil.TIMESTAMP).asString()).append(": "); String scopeType = null; if (logNode.has("scopeType")) { scopeType = logNode.get("scopeType").asString(); if (ScopeTypes.BPMN.equals(scopeType)) { logBuilder.append("(").append(logNode.get("scopeId").asString()); if (logNode.has("subScopeId")) { logBuilder.append(",").append(logNode.get("subScopeId").asString()); } logBuilder.append(") "); } } logBuilder.append(logNode.get("message").asString()); if (ScopeTypes.BPMN.equals(scopeType)) { logBuilder.append(" (processInstanceId: '").append(logNode.get("scopeId").asString()); if (logNode.has("subScopeId")) { logBuilder.append("', executionId: '").append(logNode.get("subScopeId").asString()); } logBuilder.append("', processDefinitionId: '").append(logNode.get("scopeDefinitionId").asString()).append("'"); } if (logNode.has("elementId")) { logBuilder.append(", elementId: '").append(logNode.get("elementId").asString()); if (logNode.has("elementName")) { logBuilder.append("', elementName: '").append(logNode.get("elementName").asString()); }
logBuilder.append("', elementType: '").append(logNode.get("elementType").asString()).append("'"); } logBuilder.append(")\n"); } log(logBuilder.toString(), logLevel); } protected static void log(String message, String logLevel) { if ("info".equalsIgnoreCase(logLevel)) { LOGGER.info(message); } else if ("error".equalsIgnoreCase(logLevel)) { LOGGER.error(message); } else if ("warn".equalsIgnoreCase(logLevel)) { LOGGER.warn(message); } else if ("debug".equalsIgnoreCase(logLevel)) { LOGGER.debug(message); } else if ("trace".equalsIgnoreCase(logLevel)) { LOGGER.trace(message); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSessionLoggerOutput.java
1
请完成以下Java代码
private static FMeasure calculate(int c, int size, double[] TP, double[] TP_FP, double[] TP_FN) { double precision[] = new double[c]; double recall[] = new double[c]; double f1[] = new double[c]; double accuracy[] = new double[c]; FMeasure result = new FMeasure(); result.size = size; for (int i = 0; i < c; i++) { double TN = result.size - TP_FP[i] - (TP_FN[i] - TP[i]); accuracy[i] = (TP[i] + TN) / result.size; if (TP[i] != 0) { precision[i] = TP[i] / TP_FP[i]; recall[i] = TP[i] / TP_FN[i]; result.average_accuracy += TP[i]; } else { precision[i] = 0;
recall[i] = 0; } f1[i] = 2 * precision[i] * recall[i] / (precision[i] + recall[i]); } result.average_precision = MathUtility.average(precision); result.average_recall = MathUtility.average(recall); result.average_f1 = 2 * result.average_precision * result.average_recall / (result.average_precision + result.average_recall); result.average_accuracy /= (double) result.size; result.accuracy = accuracy; result.precision = precision; result.recall = recall; result.f1 = f1; return result; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\statistics\evaluations\Evaluator.java
1
请完成以下Java代码
public ShipmentScheduleReferencedLine provideFor(@NonNull final I_M_ShipmentSchedule sched) { final int subscriptionProgressId = sched.getRecord_ID(); final I_C_SubscriptionProgress subscriptionLine = load(subscriptionProgressId, I_C_SubscriptionProgress.class); Check.errorIf(subscriptionLine == null, "Unable to load the referenced C_SubscriptionProgress for M_ShipmentSchedule_ID={}; M_ShipmentSchedule.Record_ID={}", sched.getM_ShipmentSchedule_ID(), subscriptionProgressId); final ZoneId timeZone = Services.get(IOrgDAO.class).getTimeZone(OrgId.ofRepoId(sched.getAD_Org_ID())); final ZonedDateTime eventDate = TimeUtil.asZonedDateTime(subscriptionLine.getEventDate(), timeZone); return ShipmentScheduleReferencedLine.builder() .recordRef(TableRecordReference.of(I_C_Flatrate_Term.Table_Name, subscriptionLine.getC_Flatrate_Term_ID())) .shipperId(ShipperId.optionalOfRepoId(1)) .deliveryDate(eventDate) .preparationDate(eventDate) .warehouseId(getWarehouseId(subscriptionLine)) .documentLineDescriptor(createDocumentLineDescriptor(subscriptionLine)) .build(); }
public WarehouseId getWarehouseId(@NonNull final I_C_SubscriptionProgress subscriptionLine) { return Services.get(IFlatrateBL.class).getWarehouseId(subscriptionLine.getC_Flatrate_Term()); } private SubscriptionLineDescriptor createDocumentLineDescriptor( @NonNull final I_C_SubscriptionProgress subscriptionLine) { return SubscriptionLineDescriptor.builder() .flatrateTermId(subscriptionLine.getC_Flatrate_Term_ID()) .subscriptionProgressId(subscriptionLine.getC_SubscriptionProgress_ID()) .subscriptionBillBPartnerId(subscriptionLine.getC_Flatrate_Term().getBill_BPartner_ID()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\inoutcandidate\ShipmentScheduleSubscriptionReferenceProvider.java
1
请完成以下Java代码
public class MapIterationBenchmark { private static final int MAP_SIZE = 1000000; @Param({ "100", "1000", "10000", "100000", "1000000" }) public int size; MapIteration mapIteration = new MapIteration(); Map<Integer, Integer> map; IterableMap<Integer, Integer> iterableMap; MutableMap<Integer, Integer> mutableMap; public static void main(String[] args) throws IOException, RunnerException { Options opt = new OptionsBuilder().include(MapIterationBenchmark.class.getSimpleName()) .param("size", "100", "1000", "10000", "100000", "1000000") .forks(1) .build(); new Runner(opt).run(); } @Setup(Level.Trial) public void setup() { map = new HashMap<>(); iterableMap = new HashedMap<>(); mutableMap = UnifiedMap.newMap(); for (int i = 0; i < size; i++) { map.put(i, i); iterableMap.put(i, i); mutableMap.put(i, i); } } @Benchmark public long iterateUsingIteratorAndValues() { return mapIteration.iterateUsingIteratorAndValues(map); } @Benchmark public long iterateUsingEnhancedForLoopAndEntrySet() { return mapIteration.iterateUsingEnhancedForLoopAndEntrySet(map); } @Benchmark public long iterateByKeysUsingLambdaAndForEach() { return mapIteration.iterateByKeysUsingLambdaAndForEach(map); } @Benchmark public long iterateValuesUsingLambdaAndForEach() { return mapIteration.iterateValuesUsingLambdaAndForEach(map);
} @Benchmark public long iterateUsingIteratorAndKeySet() { return mapIteration.iterateUsingIteratorAndKeySet(map); } @Benchmark public long iterateUsingIteratorAndEntrySet() { return mapIteration.iterateUsingIteratorAndEntrySet(map); } @Benchmark public long iterateUsingKeySetAndEnhanceForLoop() { return mapIteration.iterateUsingKeySetAndEnhanceForLoop(map); } @Benchmark public long iterateUsingStreamAPIAndEntrySet() { return mapIteration.iterateUsingStreamAPIAndEntrySet(map); } @Benchmark public long iterateUsingStreamAPIAndKeySet() { return mapIteration.iterateUsingStreamAPIAndKeySet(map); } @Benchmark public long iterateKeysUsingKeySetAndEnhanceForLoop() { return mapIteration.iterateKeysUsingKeySetAndEnhanceForLoop(map); } @Benchmark public long iterateUsingMapIteratorApacheCollection() { return mapIteration.iterateUsingMapIteratorApacheCollection(iterableMap); } @Benchmark public long iterateEclipseMap() throws IOException { return mapIteration.iterateEclipseMap(mutableMap); } @Benchmark public long iterateMapUsingParallelStreamApi() throws IOException { return mapIteration.iterateMapUsingParallelStreamApi(map); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIterationBenchmark.java
1
请完成以下Java代码
public String getSrcCcy() { return srcCcy; } /** * Sets the value of the srcCcy property. * * @param value * allowed object is * {@link String } * */ public void setSrcCcy(String value) { this.srcCcy = value; } /** * Gets the value of the trgtCcy property. * * @return * possible object is * {@link String } * */ public String getTrgtCcy() { return trgtCcy; } /** * Sets the value of the trgtCcy property. * * @param value * allowed object is * {@link String } * */ public void setTrgtCcy(String value) { this.trgtCcy = value; } /** * Gets the value of the unitCcy property. * * @return * possible object is * {@link String } * */ public String getUnitCcy() { return unitCcy; } /** * Sets the value of the unitCcy property. * * @param value * allowed object is * {@link String } * */ public void setUnitCcy(String value) { this.unitCcy = value; } /** * Gets the value of the xchgRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getXchgRate() { return xchgRate; } /** * Sets the value of the xchgRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setXchgRate(BigDecimal value) { this.xchgRate = value; } /** * Gets the value of the ctrctId property. * * @return
* possible object is * {@link String } * */ public String getCtrctId() { return ctrctId; } /** * Sets the value of the ctrctId property. * * @param value * allowed object is * {@link String } * */ public void setCtrctId(String value) { this.ctrctId = value; } /** * Gets the value of the qtnDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getQtnDt() { return qtnDt; } /** * Sets the value of the qtnDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setQtnDt(XMLGregorianCalendar value) { this.qtnDt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CurrencyExchange5.java
1
请在Spring Boot框架中完成以下Java代码
static LazyInitializationExcludeFilter eagerJpaMetamodelCacheCleanup() { return (name, definition, type) -> "org.springframework.data.jpa.util.JpaMetamodelCacheCleanup".equals(name); } private @Nullable AsyncTaskExecutor determineBootstrapExecutor(Map<String, AsyncTaskExecutor> taskExecutors) { if (taskExecutors.size() == 1) { return taskExecutors.values().iterator().next(); } return taskExecutors.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); } private static final class BootstrapExecutorCondition extends AnyNestedCondition { BootstrapExecutorCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "deferred") static class DeferredBootstrapMode { } @ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "lazy") static class LazyBootstrapMode { } }
static class JpaRepositoriesImportSelector implements ImportSelector { private static final boolean ENVERS_AVAILABLE = ClassUtils.isPresent( "org.springframework.data.envers.repository.config.EnableEnversRepositories", JpaRepositoriesImportSelector.class.getClassLoader()); @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[] { determineImport() }; } private String determineImport() { return ENVERS_AVAILABLE ? EnversRevisionRepositoriesRegistrar.class.getName() : DataJpaRepositoriesRegistrar.class.getName(); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-jpa\src\main\java\org\springframework\boot\data\jpa\autoconfigure\DataJpaRepositoriesAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class FreeMarkerTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider { private static final String REQUIRED_CLASS_NAME = "freemarker.template.Configuration"; public FreeMarkerTemplateAvailabilityProvider() { super(REQUIRED_CLASS_NAME, FreeMarkerTemplateAvailabilityProperties.class, "spring.freemarker"); } protected static final class FreeMarkerTemplateAvailabilityProperties extends TemplateAvailabilityProperties { private List<String> templateLoaderPath = new ArrayList<>( Arrays.asList(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH)); FreeMarkerTemplateAvailabilityProperties() { super(FreeMarkerProperties.DEFAULT_PREFIX, FreeMarkerProperties.DEFAULT_SUFFIX); } @Override protected List<String> getLoaderPath() { return this.templateLoaderPath; } public List<String> getTemplateLoaderPath() { return this.templateLoaderPath; } public void setTemplateLoaderPath(List<String> templateLoaderPath) { this.templateLoaderPath = templateLoaderPath; }
} static class FreeMarkerTemplateAvailabilityRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { if (ClassUtils.isPresent(REQUIRED_CLASS_NAME, classLoader)) { BindableRuntimeHintsRegistrar.forTypes(FreeMarkerTemplateAvailabilityProperties.class) .registerHints(hints, classLoader); } } } }
repos\spring-boot-4.0.1\module\spring-boot-freemarker\src\main\java\org\springframework\boot\freemarker\autoconfigure\FreeMarkerTemplateAvailabilityProvider.java
2
请完成以下Java代码
public void deletePPOrderCandidates(@NonNull final DeletePPOrderCandidatesQuery deletePPOrderCandidatesQuery) { final IQueryBuilder<I_PP_Order_Candidate> deleteQuery = queryBL.createQueryBuilder(I_PP_Order_Candidate.class); if (deletePPOrderCandidatesQuery.isOnlySimulated()) { deleteQuery.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsSimulated, true); } if (deletePPOrderCandidatesQuery.getSalesOrderLineId() != null) { deleteQuery.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_C_OrderLine_ID, deletePPOrderCandidatesQuery.getSalesOrderLineId()); } if (deleteQuery.getCompositeFilter().isEmpty()) { throw new AdempiereException("Deleting all PP_Order_Candidate records is not allowed!"); } final boolean failIfProcessed = false; deleteQuery .create() .iterateAndStream() .peek(this::deleteLines) .forEach(simulatedOrder -> InterfaceWrapperHelper.delete(simulatedOrder, failIfProcessed)); } private void deleteLines(@NonNull final I_PP_Order_Candidate ppOrderCandidate) { deleteLines(PPOrderCandidateId.ofRepoId(ppOrderCandidate.getPP_Order_Candidate_ID())); } public void deleteLines(@NonNull final PPOrderCandidateId ppOrderCandidateId)
{ queryBL.createQueryBuilder(I_PP_OrderLine_Candidate.class) .addEqualsFilter(I_PP_OrderLine_Candidate.COLUMNNAME_PP_Order_Candidate_ID, ppOrderCandidateId) .create() .deleteDirectly(); } public List<PPOrderCandidateId> listIdsByQuery(@NonNull final PPOrderCandidatesQuery query) { final IQueryBuilder<I_PP_Order_Candidate> builder = queryBL.createQueryBuilder(I_PP_Order_Candidate.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_M_Product_ID, query.getProductId()) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_M_Warehouse_ID, query.getWarehouseId()) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_AD_Org_ID, query.getOrgId()) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_M_AttributeSetInstance_ID, query.getAttributesKey().getAsString(), ASIQueryFilterModifier.instance); if (query.isOnlyNonZeroQty()) { builder.addNotEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_QtyToProcess, 0); } return builder.create() .listIds(PPOrderCandidateId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\dao\PPOrderCandidateDAO.java
1
请完成以下Java代码
public void deleteCommentsByTaskId(String taskId) { getDbSqlSession().delete("deleteCommentsByTaskId", taskId, CommentEntityImpl.class); } @Override public void deleteCommentsByProcessInstanceId(String processInstanceId) { getDbSqlSession().delete("deleteCommentsByProcessInstanceId", processInstanceId, CommentEntityImpl.class); } @Override public void bulkDeleteCommentsForTaskIds(Collection<String> taskIds) { getDbSqlSession().delete("bulkDeleteCommentsForTaskIds", createSafeInValuesList(taskIds), CommentEntityImpl.class); } @Override public void bulkDeleteCommentsForProcessInstanceIds(Collection<String> processInstanceIds) { getDbSqlSession().delete("bulkDeleteCommentsForProcessInstanceIds", createSafeInValuesList(processInstanceIds), CommentEntityImpl.class); } @Override @SuppressWarnings("unchecked") public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) {
return getDbSqlSession().selectList("selectCommentsByProcessInstanceId", processInstanceId); } @Override @SuppressWarnings("unchecked") public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) { Map<String, Object> params = new HashMap<>(); params.put("processInstanceId", processInstanceId); params.put("type", type); return getDbSqlSession().selectListWithRawParameter("selectCommentsByProcessInstanceIdAndType", params); } @Override public Comment findComment(String commentId) { return findById(commentId); } @Override public Event findEvent(String commentId) { return findById(commentId); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisCommentDataManager.java
1
请完成以下Java代码
public PendingType getPending() { return pending; } /** * Sets the value of the pending property. * * @param value * allowed object is * {@link PendingType } * */ public void setPending(PendingType value) { this.pending = value; } /** * Gets the value of the accepted property. * * @return * possible object is * {@link AcceptedType } * */ public AcceptedType getAccepted() { return accepted; } /** * Sets the value of the accepted property. * * @param value * allowed object is * {@link AcceptedType } *
*/ public void setAccepted(AcceptedType value) { this.accepted = value; } /** * Gets the value of the rejected property. * * @return * possible object is * {@link RejectedType } * */ public RejectedType getRejected() { return rejected; } /** * Sets the value of the rejected property. * * @param value * allowed object is * {@link RejectedType } * */ public void setRejected(RejectedType value) { this.rejected = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\BodyType.java
1
请完成以下Java代码
public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setPharmacy_PriceList_ID (final int Pharmacy_PriceList_ID) { if (Pharmacy_PriceList_ID < 1) set_Value (COLUMNNAME_Pharmacy_PriceList_ID, null);
else set_Value (COLUMNNAME_Pharmacy_PriceList_ID, Pharmacy_PriceList_ID); } @Override public int getPharmacy_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_Pharmacy_PriceList_ID); } @Override public void setTenant (final String Tenant) { set_Value (COLUMNNAME_Tenant, Tenant); } @Override public String getTenant() { return get_ValueAsString(COLUMNNAME_Tenant); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Alberta.java
1
请完成以下Java代码
public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setQtyPicked (final BigDecimal QtyPicked) { set_Value (COLUMNNAME_QtyPicked, QtyPicked); } @Override public BigDecimal getQtyPicked() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); }
@Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } /** * Status AD_Reference_ID=541435 * Reference name: DD_OrderLine_Schedule_Status */ public static final int STATUS_AD_Reference_ID=541435; /** NotStarted = NS */ public static final String STATUS_NotStarted = "NS"; /** InProgress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java
1
请完成以下Java代码
public Optional<Node<T>> getNode(final T value) { return Optional.ofNullable(getNode_rec(this, value)); } @NonNull public String toString() { return this.getValue().toString(); } @Nullable private Node<T> getNode_rec(final Node<T> currentNode, final T value) { if (currentNode.value.equals(value)) { return currentNode; } else { final Iterator<Node<T>> iterator = currentNode.getChildren().iterator(); Node<T> requestedNode = null; while (requestedNode == null && iterator.hasNext()) { requestedNode = getNode_rec(iterator.next(), value); }
return requestedNode; } } private void listAllNodesBelow_rec(final Node<T> currentNode, final List<Node<T>> nodeList) { nodeList.add(currentNode); if (!currentNode.isLeaf()) { currentNode.getChildren().forEach(child -> listAllNodesBelow_rec(child, nodeList)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Node.java
1
请完成以下Java代码
public Executor getExecutor() { log.info("getExecutor\n\r"); return null; } }); } catch (Exception e) { log.error("从nacos接收动态路由配置出错!!!", e); } } /** * 创建ConfigService * * @return */ private ConfigService createConfigService() { try { Properties properties = new Properties(); properties.setProperty("serverAddr", gatewayRoutersConfig.getServerAddr()); if(StringUtils.isNotBlank(gatewayRoutersConfig.getNamespace())){ properties.setProperty("namespace", gatewayRoutersConfig.getNamespace()); } if(StringUtils.isNotBlank( gatewayRoutersConfig.getUsername())){ properties.setProperty("username", gatewayRoutersConfig.getUsername());
} if(StringUtils.isNotBlank(gatewayRoutersConfig.getPassword())){ properties.setProperty("password", gatewayRoutersConfig.getPassword()); } return configService = NacosFactory.createConfigService(properties); } catch (Exception e) { log.error("创建ConfigService异常", e); return null; } } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\DynamicRouteLoader.java
1
请完成以下Java代码
public Void execute(CommandContext context) { TaskEntity task = validateAndGet(taskId, context); executeSetOperation(task, value); task.triggerUpdateEvent(); logOperation(context, task); return null; } protected void logOperation(CommandContext context, TaskEntity task) { task.logUserOperation(getUserOperationLogName()); } /** * Validates the given taskId against to verify it references an existing task before returning the task. * * @param taskId the given taskId, non-null * @param context the context, non-null * @return the corresponding task entity */ protected TaskEntity validateAndGet(String taskId, CommandContext context) { TaskManager taskManager = context.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull(NotFoundException.class, "Cannot find task with id " + taskId, "task", task); checkTaskAgainstContext(task, context); return task; } /** * Perform multi-tenancy & authorization checks on the given task against the given command context. * * @param task the given task * @param context the given command context to check against */ protected void checkTaskAgainstContext(TaskEntity task, CommandContext context) { for (CommandChecker checker : context.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskAssign(task); } } /** * Returns the User Operation Log name that corresponds to this command. Meant to be implemented by concretions. * * @return the user operation log name */
protected abstract String getUserOperationLogName(); /** * Executes the set operation of the concrete command. * * @param task the task entity on which to set a property * @param value the value to se */ protected abstract void executeSetOperation(TaskEntity task, T value); /** * Ensures the value is not null and returns the value. * * @param value the value * @param <T> the type of the value * @return the value * @throws NullValueException in case the given value is null */ protected <T> T ensureNotNullAndGet(String variableName, T value) { ensureNotNull(variableName, value); return value; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetTaskPropertyCmd.java
1
请完成以下Java代码
public Duration calculateDuration(@NonNull final PPRoutingActivity activity) { final Duration setupTime = activity.getSetupTime(); final Duration duration = estimateWorkingTimePerOneUnit(activity).getDuration(); final BigDecimal qtyPerBatch = activity.getQtyPerBatch(); final Duration setupTimePerBatch = Duration.ofNanos((long)(setupTime.toNanos() / qtyPerBatch.doubleValue())); return setupTimePerBatch.plus(duration); } @Override public int calculateDurationDays(final PPRoutingId routingId, @Nullable final ResourceId plantId, final BigDecimal qty) { if (plantId == null) { return 0; } Duration durationTotal = Duration.ZERO; final PPRouting routing = Services.get(IPPRoutingRepository.class).getById(routingId); final int intQty = qty.setScale(0, RoundingMode.UP).intValueExact(); for (final PPRoutingActivity activity : routing.getActivities()) { // Qty independent times: durationTotal = durationTotal .plus(activity.getQueuingTime()) .plus(activity.getSetupTime()) .plus(activity.getWaitingTime()) .plus(activity.getMovingTime()); // Get OverlapUnits - number of units that must be completed before they are moved the next activity final int overlapUnits = Integer.max(activity.getOverlapUnits(), 0); final int batchUnits = Integer.max(intQty - overlapUnits, 0); final Duration durationBeforeOverlap = activity.getDurationPerOneUnit().multipliedBy(batchUnits); durationTotal = durationTotal.plus(durationBeforeOverlap); } //
final IResourceProductService resourceProductService = Services.get(IResourceProductService.class); final ResourceType resourceType = resourceProductService.getResourceTypeByResourceId(plantId); final BigDecimal availableDayTimeInHours = BigDecimal.valueOf(resourceType.getTimeSlotInHours()); final int availableDays = resourceType.getAvailableDaysPerWeek(); // Weekly Factor final BigDecimal weeklyFactor = BigDecimal.valueOf(7).divide(BigDecimal.valueOf(availableDays), 8, RoundingMode.UP); return BigDecimal.valueOf(durationTotal.toHours()) .multiply(weeklyFactor) .divide(availableDayTimeInHours, 0, RoundingMode.UP) .intValueExact(); } @Override public Duration getResourceBaseValue(@NonNull final PPRoutingActivity activity) { return calculateDuration(activity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\DefaultRoutingServiceImpl.java
1
请完成以下Java代码
/*package*/class POWrapperCacheLocal extends AbstractPOCacheLocal { private final WeakReference<POWrapper> parentPOWrapperRef; private final int parentColumnIndex; public POWrapperCacheLocal(final POWrapper parentPOWrapper, final String parentColumnName, final String refTableName) { super(parentColumnName, refTableName); this.parentPOWrapperRef = new WeakReference<>(parentPOWrapper); this.parentColumnIndex = parentPOWrapper.getColumnIndex(parentColumnName); } private final POWrapper getParentPOWrapper() { final POWrapper poWrapper = parentPOWrapperRef.getValue(); if (poWrapper == null) { throw new AdempiereException("POWrapper reference expired"); } return poWrapper; } @Override protected Properties getParentCtx() { return getParentPOWrapper().getCtx(); }
@Override protected String getParentTrxName() { return getParentPOWrapper().getTrxName(); } @Override protected int getId() { return getParentPOWrapper().getValueAsInt(parentColumnIndex); } @Override protected boolean setId(int id) { getParentPOWrapper().setValue(getParentColumnName(), id); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\POWrapperCacheLocal.java
1
请完成以下Java代码
public <S> List<S> getServiceValuesByType(ServiceType type) { // query the MBeanServer for all services of the given type Set<String> serviceNames = getServiceNames(type); List<S> res = new ArrayList<S>(); for (String serviceName : serviceNames) { PlatformService<S> BpmPlatformService = (PlatformService<S>) servicesByName.get(getObjectName(serviceName)); if (BpmPlatformService != null) { res.add(BpmPlatformService.getValue()); } } return res; } public MBeanServer getmBeanServer() { if (mBeanServer == null) { synchronized (this) { if (mBeanServer == null) {
mBeanServer = createOrLookupMbeanServer(); } } } return mBeanServer; } public void setmBeanServer(MBeanServer mBeanServer) { this.mBeanServer = mBeanServer; } protected MBeanServer createOrLookupMbeanServer() { return ManagementFactory.getPlatformMBeanServer(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\MBeanServiceContainer.java
1
请完成以下Java代码
public String getScopeType() { return scopeType; } public boolean isWithoutScopeType() { return withoutScopeType; } public String getProcessInstanceIdWithChildren() { return processInstanceIdWithChildren; } public String getCaseInstanceIdWithChildren() { return caseInstanceIdWithChildren; }
public Boolean getFailed() { return failed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\HistoricDecisionExecutionQueryImpl.java
1
请完成以下Java代码
private PrintablePDF createPrintable() { final byte[] data = printingDAO.retrievePrintPackageData(printPackage).getPrintData(); if (data == null) { return null; } final InputStream in = new ByteArrayInputStream(data); final PrintablePDF printable = new PrintablePDF(in); return printable; } public byte[] printToBytes() throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); print(out); return out.toByteArray(); } public void print(@NonNull final OutputStream bos) throws Exception { final I_C_Print_Job_Instructions print_Job_Instructions = printPackage.getC_Print_Job_Instructions(); final Document document = new Document(); final PdfCopy copy = new PdfCopy(document, bos); document.open(); final PrintablePDF printable = createPrintable(); if (printable == null) { return; } try { for (final I_C_Print_PackageInfo printPackageInfo : printingDAO.retrievePrintPackageInfos(printPackage)) { final byte[] pdf = print(printPackageInfo, printable); final PdfReader reader = new PdfReader(pdf); for (int page = 0; page < reader.getNumberOfPages(); ) { copy.addPage(copy.getImportedPage(reader, ++page)); } copy.freeReader(reader); reader.close();
} document.close(); print_Job_Instructions.setErrorMsg(null); print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Done); InterfaceWrapperHelper.save(print_Job_Instructions); } catch (final Exception e) { print_Job_Instructions.setErrorMsg(e.getLocalizedMessage()); print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Error); InterfaceWrapperHelper.save(print_Job_Instructions); throw new AdempiereException(e.getLocalizedMessage()); } } private byte[] print(@NonNull final I_C_Print_PackageInfo printPackageInfo, @NonNull final PrintablePDF printable) { printable.setCalX(printPackageInfo.getCalX()); printable.setCalY(printPackageInfo.getCalY()); final PrintablePDF clone = printable; return PdfPrinter.print(printable, clone); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\PrintPackagePDFBuilder.java
1
请完成以下Java代码
static ServerResponse.BodyBuilder unprocessableEntity() { return status(HttpStatus.UNPROCESSABLE_ENTITY); } /** * Create a (built) response with the given asynchronous response. Parameter * {@code asyncResponse} can be a {@link CompletableFuture * CompletableFuture&lt;ServerResponse&gt;} or {@link Publisher * Publisher&lt;ServerResponse&gt;} (or any asynchronous producer of a single * {@code ServerResponse} that can be adapted via the * {@link ReactiveAdapterRegistry}). * * <p> * This method can be used to set the response status code, headers, and body based on * an asynchronous result. If only the body is asynchronous, * {@link ServerResponse.BodyBuilder#body(Object)} can be used instead. * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or * {@code Publisher<ServerResponse>} * @return the asynchronous response * @since 5.3 */ static ServerResponse async(Object asyncResponse) { return GatewayAsyncServerResponse.create(asyncResponse, null); } /** * Create a (built) response with the given asynchronous response. Parameter
* {@code asyncResponse} can be a {@link CompletableFuture * CompletableFuture&lt;ServerResponse&gt;} or {@link Publisher * Publisher&lt;ServerResponse&gt;} (or any asynchronous producer of a single * {@code ServerResponse} that can be adapted via the * {@link ReactiveAdapterRegistry}). * * <p> * This method can be used to set the response status code, headers, and body based on * an asynchronous result. If only the body is asynchronous, * {@link ServerResponse.BodyBuilder#body(Object)} can be used instead. * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or * {@code Publisher<ServerResponse>} * @param timeout maximum time period to wait for before timing out * @return the asynchronous response * @since 5.3.2 */ static ServerResponse async(Object asyncResponse, Duration timeout) { return GatewayAsyncServerResponse.create(asyncResponse, timeout); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponse.java
1
请在Spring Boot框架中完成以下Java代码
public BatchBuilder batchType(String batchType) { this.batchType = batchType; return this; } @Override public BatchBuilder searchKey(String searchKey) { this.searchKey = searchKey; return this; } @Override public BatchBuilder searchKey2(String searchKey2) { this.searchKey2 = searchKey2; return this; } @Override public BatchBuilder status(String status) { this.status = status; return this; } @Override public BatchBuilder batchDocumentJson(String batchDocumentJson) { this.batchDocumentJson = batchDocumentJson; return this; } @Override public BatchBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public Batch create() { if (commandExecutor != null) { BatchBuilder selfBatchBuilder = this; return commandExecutor.execute(new Command<>() { @Override public Batch execute(CommandContext commandContext) { return batchServiceConfiguration.getBatchEntityManager().createBatch(selfBatchBuilder); } }); } else { return ((BatchServiceImpl) batchServiceConfiguration.getBatchService()).createBatch(this); } }
@Override public String getBatchType() { return batchType; } @Override public String getSearchKey() { return searchKey; } @Override public String getSearchKey2() { return searchKey2; } @Override public String getStatus() { return status; } @Override public String getBatchDocumentJson() { return batchDocumentJson; } @Override public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class UserDashboardWebsocketProducerFactory implements WebSocketProducerFactory { private final UserDashboardDataService dashboardDataService; private final UserDashboardSessionContextHolder contextHolder; public UserDashboardWebsocketProducerFactory( @NonNull final UserDashboardDataService dashboardDataService, @NonNull final UserDashboardSessionContextHolder contextHolder) { this.dashboardDataService = dashboardDataService; this.contextHolder = contextHolder; } @Override public String getTopicNamePrefix() { return WebsocketTopicNames.TOPIC_Dashboard; } @Override public UserDashboardWebsocketProducer createProducer(final WebsocketTopicName topicName) { final WebuiSessionId sessionId = extractSessionId(topicName); if (sessionId == null) { throw new AdempiereException("Invalid websocket topic name: " + topicName); } final KPIDataContext kpiDataContext = contextHolder.getSessionContext(sessionId);
return UserDashboardWebsocketProducer.builder() .dashboardDataService(dashboardDataService) .websocketTopicName(topicName) .kpiDataContext(kpiDataContext) .build(); } @Nullable public static WebuiSessionId extractSessionId(@NonNull final WebsocketTopicName topicName) { final String topicNameString = topicName.getAsString(); if (topicNameString.startsWith(WebsocketTopicNames.TOPIC_Dashboard)) { final String sessionId = topicNameString.substring(WebsocketTopicNames.TOPIC_Dashboard.length() + 1).trim(); return WebuiSessionId.ofNullableString(sessionId); } else { return null; } } public static WebsocketTopicName createWebsocketTopicName(@NonNull final WebuiSessionId sessionId) { return WebsocketTopicName.ofString(WebsocketTopicNames.TOPIC_Dashboard + "/" + sessionId.getAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketProducerFactory.java
2
请完成以下Java代码
String removeDuplicatesUsingHashSet(String str) { StringBuilder sb = new StringBuilder(); Set<Character> hashSet = new HashSet<>(); for (int i = 0; i < str.length(); i++) { hashSet.add(str.charAt(i)); } for (Character c : hashSet) { sb.append(c); } return sb.toString(); } String removeDuplicatesUsingIndexOf(String str) { StringBuilder sb = new StringBuilder(); int idx; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); idx = str.indexOf(c, i + 1); if (idx == -1) {
sb.append(c); } } return sb.toString(); } String removeDuplicatesUsingDistinct(String str) { StringBuilder sb = new StringBuilder(); str.chars().distinct().forEach(c -> sb.append((char) c)); return sb.toString(); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-4\src\main\java\com\baeldung\removeduplicates\RemoveDuplicateFromString.java
1
请完成以下Java代码
private static Bank toBank(@NonNull final I_C_Bank record) { return Bank.builder() .bankId(BankId.ofRepoId(record.getC_Bank_ID())) .bankName(StringUtils.trimBlankToNull(record.getName())) .swiftCode(StringUtils.trimBlankToNull(record.getSwiftCode())) .routingNo(StringUtils.trimBlankToNull(record.getRoutingNo())) .dataImportConfigId(DataImportConfigId.ofRepoIdOrNull(record.getC_DataImport_ID())) .cashBank(record.isCashBank()) .locationId(LocationId.ofRepoIdOrNull(record.getC_Location_ID())) // // ESR: .esrPostBank(record.isESR_PostBank()) // .importAsSingleSummaryLine(record.isImportAsSingleSummaryLine()) .build(); } @NonNull public Optional<BankId> getBankIdBySwiftCode(final String swiftCode) { return bankIdsBySwiftCode.getOrLoad(swiftCode, this::retrieveBankIdBySwiftCode); } @NonNull private Optional<BankId> retrieveBankIdBySwiftCode(final String swiftCode) { final int bankRepoId = queryBL.createQueryBuilderOutOfTrx(I_C_Bank.class) .addEqualsFilter(I_C_Bank.COLUMNNAME_SwiftCode, swiftCode) .addOnlyActiveRecordsFilter() .orderBy(I_C_Bank.COLUMNNAME_C_Bank_ID) .create() .firstId(); return BankId.optionalOfRepoId(bankRepoId); } public boolean isCashBank(@NonNull final BankId bankId) { return getById(bankId).isCashBank(); } public Bank createBank(@NonNull final BankCreateRequest request) {
final I_C_Bank record = newInstance(I_C_Bank.class); record.setName(request.getBankName()); record.setSwiftCode(request.getSwiftCode()); record.setRoutingNo(request.getRoutingNo()); record.setIsCashBank(request.isCashBank()); record.setC_Location_ID(LocationId.toRepoId(request.getLocationId())); // ESR: record.setESR_PostBank(request.isEsrPostBank()); record.setC_DataImport_ID(DataImportConfigId.toRepoId(request.getDataImportConfigId())); saveRecord(record); return toBank(record); } @NonNull public DataImportConfigId retrieveDataImportConfigIdForBank(@Nullable final BankId bankId) { if (bankId == null) { return retrieveDefaultBankDataImportConfigId(); } final Bank bank = getById(bankId); return CoalesceUtil.coalesceSuppliersNotNull( bank::getDataImportConfigId, this::retrieveDefaultBankDataImportConfigId); } public boolean isImportAsSingleSummaryLine(@NonNull final BankId bankId) { return getById(bankId).isImportAsSingleSummaryLine(); } @NonNull public Set<BankId> retrieveBankIdsByName(@NonNull final String bankName) { return queryBL.createQueryBuilder(I_C_Bank.class) .addOnlyActiveRecordsFilter() .addStringLikeFilter(I_C_Bank.COLUMNNAME_Name, bankName, true) .create() .idsAsSet(BankId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\api\BankRepository.java
1
请完成以下Java代码
public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();} public @NonNull Quantity getQtyToDeliver() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToDeliver(); } public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();} public @NonNull Quantity getQtyToPick() { return schedule != null ? schedule.getQtyToPick()
: packageable.getQtyToPick(); } public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();} public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();} public @Nullable ShipperId getShipperId() {return packageable.getShipperId();} public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();} public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();} public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java
1
请完成以下Java代码
public final String getNavTabId() { return navTabId; } /** * @param argNavTabId * the navTabId to set */ public final void setNavTabId(final String argNavTabId) { this.navTabId = argNavTabId; } /** * @return the callbackType */ public final String getCallbackType() { return callbackType; } /** * @param argCallbackType * the callbackType to set */ public final void setCallbackType(final String argCallbackType) { this.callbackType = argCallbackType;
} /** * @return the forwardUrl */ public final String getForwardUrl() { return forwardUrl; } /** * @param argForwardUrl * the forwardUrl to set */ public final void setForwardUrl(final String argForwardUrl) { this.forwardUrl = argForwardUrl; } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\dwz\DwzAjax.java
1
请完成以下Java代码
protected boolean isFormRunnable() { // nothing at this level return true; } @Override public final void run() { final FormFrame formFrame = AEnv.createForm(getAD_Form()); if (formFrame == null) { return; } customizeBeforeOpen(formFrame); AEnv.showCenterWindow(getCallingFrame(), formFrame); } protected void customizeBeforeOpen(final FormFrame formFrame) { // nothing on this level } /** @return the {@link Frame} in which this action was executed or <code>null</code> if not available. */ protected final Frame getCallingFrame() { final GridField gridField = getContext().getEditor().getField(); if (gridField == null) { return null; } final int windowNo = gridField.getWindowNo(); final Frame frame = Env.getWindow(windowNo); return frame; }
protected final int getAD_Form_ID() { return _adFormId; } private final synchronized I_AD_Form getAD_Form() { if (!_adFormLoaded) { _adForm = retrieveAD_Form(); _adFormLoaded = true; } return _adForm; } private final I_AD_Form retrieveAD_Form() { final IContextMenuActionContext context = getContext(); Check.assumeNotNull(context, "context not null"); final Properties ctx = context.getCtx(); // Check if user has access to Payment Allocation form final int adFormId = getAD_Form_ID(); final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId); if (formAccess == null || !formAccess) { return null; } // Retrieve the form final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None); // Translate it to user's language final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class); return formTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java
1
请在Spring Boot框架中完成以下Java代码
protected void update() { resetInvocationCounter(); fetchAlarmCount(); } @Override public boolean isDynamic() { return true; } public void fetchAlarmCount() { alarmCountInvocationAttempts++; log.trace("[{}] Fetching alarms: {}", cmdId, alarmCountInvocationAttempts); if (alarmCountInvocationAttempts <= maxAlarmQueriesPerRefreshInterval) { int newCount = (int) alarmService.countAlarmsByQuery(getTenantId(), getCustomerId(), query, entitiesIds); if (newCount != result) { result = newCount; sendWsMsg(new AlarmCountUpdate(cmdId, result)); } } else { log.trace("[{}] Ignore alarm count fetch due to rate limit: [{}] of maximum [{}]", cmdId, alarmCountInvocationAttempts, maxAlarmQueriesPerRefreshInterval); } } public void doFetchAlarmCount() { result = (int) alarmService.countAlarmsByQuery(getTenantId(), getCustomerId(), query, entitiesIds); sendWsMsg(new AlarmCountUpdate(cmdId, result)); } private EntityDataQuery buildEntityDataQuery() { EntityDataPageLink edpl = new EntityDataPageLink(maxEntitiesPerAlarmSubscription, 0, null, new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, ModelConstants.CREATED_TIME_PROPERTY))); return new EntityDataQuery(query.getEntityFilter(), edpl, null, null, query.getKeyFilters()); } private void resetInvocationCounter() { alarmCountInvocationAttempts = 0; } public void createAlarmSubscriptions() { for (EntityId entityId : entitiesIds) { createAlarmSubscriptionForEntity(entityId);
} } private void createAlarmSubscriptionForEntity(EntityId entityId) { int subIdx = sessionRef.getSessionSubIdSeq().incrementAndGet(); subToEntityIdMap.put(subIdx, entityId); log.trace("[{}][{}][{}] Creating alarms subscription for [{}] ", serviceId, cmdId, subIdx, entityId); TbAlarmsSubscription subscription = TbAlarmsSubscription.builder() .serviceId(serviceId) .sessionId(sessionRef.getSessionId()) .subscriptionId(subIdx) .tenantId(sessionRef.getSecurityCtx().getTenantId()) .entityId(entityId) .updateProcessor((sub, update) -> fetchAlarmCount()) .build(); localSubscriptionService.addSubscription(subscription, sessionRef); } public void clearAlarmSubscriptions() { if (subToEntityIdMap != null) { for (Integer subId : subToEntityIdMap.keySet()) { localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId); } subToEntityIdMap.clear(); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAlarmCountSubCtx.java
2
请完成以下Java代码
public long allocate(long deltaSeconds, long workerId, long sequence) { return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence; } /** * Getters */ public int getSignBits() { return signBits; } public int getTimestampBits() { return timestampBits; } public int getWorkerIdBits() { return workerIdBits; } public int getSequenceBits() { return sequenceBits; } public long getMaxDeltaSeconds() { return maxDeltaSeconds; } public long getMaxWorkerId() { return maxWorkerId; } public long getMaxSequence() {
return maxSequence; } public int getTimestampShift() { return timestampShift; } public int getWorkerIdShift() { return workerIdShift; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\BitsAllocator.java
1
请完成以下Java代码
public ObjectNode execute(CommandContext commandContext) { if (processDefinitionId == null) { throw new ActivitiIllegalArgumentException("process definition id is null"); } DeploymentManager deploymentManager = commandContext.getProcessEngineConfiguration().getDeploymentManager(); // make sure the process definition is in the cache var processDefinition = resolveProcessDefinition(deploymentManager); return executeInternal(deploymentManager, commandContext, processDefinition); } protected ProcessDefinition resolveProcessDefinition(DeploymentManager deploymentManager) { return Optional.ofNullable(processDefinition).orElseGet(() -> deploymentManager.findDeployedProcessDefinitionById(processDefinitionId) ); }
protected ObjectNode executeInternal( DeploymentManager deploymentManager, CommandContext commandContext, ProcessDefinition processDefinition ) { ObjectNode resultNode = null; ProcessDefinitionInfoCacheObject definitionInfoCacheObject = deploymentManager .getProcessDefinitionInfoCache() .get(processDefinitionId); if (definitionInfoCacheObject != null) { resultNode = definitionInfoCacheObject.getInfoNode(); } return resultNode; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetProcessDefinitionInfoCmd.java
1
请在Spring Boot框架中完成以下Java代码
public IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() { return this; } public IdentityLinkService getIdentityLinkService() { return identityLinkService; } public IdentityLinkServiceConfiguration setIdentityLinkService(IdentityLinkService identityLinkService) { this.identityLinkService = identityLinkService; return this; } public HistoricIdentityLinkService getHistoricIdentityLinkService() { return historicIdentityLinkService; } public IdentityLinkServiceConfiguration setHistoricIdentityLinkService(HistoricIdentityLinkService historicIdentityLinkService) { this.historicIdentityLinkService = historicIdentityLinkService; return this; } public IdentityLinkDataManager getIdentityLinkDataManager() { return identityLinkDataManager; } public IdentityLinkServiceConfiguration setIdentityLinkDataManager(IdentityLinkDataManager identityLinkDataManager) { this.identityLinkDataManager = identityLinkDataManager; return this; } public HistoricIdentityLinkDataManager getHistoricIdentityLinkDataManager() { return historicIdentityLinkDataManager; } public IdentityLinkServiceConfiguration setHistoricIdentityLinkDataManager(HistoricIdentityLinkDataManager historicIdentityLinkDataManager) { this.historicIdentityLinkDataManager = historicIdentityLinkDataManager; return this; } public IdentityLinkEntityManager getIdentityLinkEntityManager() { return identityLinkEntityManager; } public IdentityLinkServiceConfiguration setIdentityLinkEntityManager(IdentityLinkEntityManager identityLinkEntityManager) { this.identityLinkEntityManager = identityLinkEntityManager; return this; } public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return historicIdentityLinkEntityManager; }
public IdentityLinkServiceConfiguration setHistoricIdentityLinkEntityManager(HistoricIdentityLinkEntityManager historicIdentityLinkEntityManager) { this.historicIdentityLinkEntityManager = historicIdentityLinkEntityManager; return this; } @Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public IdentityLinkServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public IdentityLinkEventHandler getIdentityLinkEventHandler() { return identityLinkEventHandler; } public IdentityLinkServiceConfiguration setIdentityLinkEventHandler(IdentityLinkEventHandler identityLinkEventHandler) { this.identityLinkEventHandler = identityLinkEventHandler; return this; } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\IdentityLinkServiceConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class C_Invoice_SalesInvoiceJasperWithAttachedDocumentsStrategy implements ExecuteReportStrategy { private static final Logger logger = LogManager.getLogger(C_Invoice_SalesInvoiceJasperWithAttachedDocumentsStrategy.class); private static final String C_INVOICE_REPORT_AD_PROCESS_ID = "de.metas.invoice.C_Invoice.SalesInvoice.Report.AD_Process_ID"; private final AttachmentEntryService attachmentEntryService; public C_Invoice_SalesInvoiceJasperWithAttachedDocumentsStrategy(@NonNull final AttachmentEntryService attachmentEntryService) { this.attachmentEntryService = attachmentEntryService; } @Override public ExecuteReportResult executeReport( @NonNull final ProcessInfo processInfo, @NonNull final OutputType outputType) { final int invoiceDocReportProcessId = Services.get(ISysConfigBL.class) .getIntValue( C_INVOICE_REPORT_AD_PROCESS_ID, -1, Env.getAD_Client_ID(), Env.getAD_Org_ID(Env.getCtx())); Check.assume(invoiceDocReportProcessId > 0, "The sysconfig with name {} needs to have a value greater than 0; AD_Client_ID={}; AD_Org_ID={}", C_INVOICE_REPORT_AD_PROCESS_ID, Env.getAD_Client_ID(), Env.getAD_Org_ID(Env.getCtx())); final Resource invoiceData = ExecuteReportStrategyUtil.executeJasperProcess(invoiceDocReportProcessId, processInfo, outputType); final boolean isPDF = OutputType.PDF.equals(outputType); if (!isPDF) {
Loggables.withLogger(logger, Level.WARN).addLog("Concatenating additional PDF-Data is not supported with outputType={}; returning only the jasper data itself.", outputType); return ExecuteReportResult.of(outputType, invoiceData); } final InvoiceId invoiceId = InvoiceId.ofRepoId(processInfo.getRecord_ID()); final AttachmentEntryQuery attachmentQuery = AttachmentEntryQuery.builder() .referencedRecord(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId)) .tagSetToTrue(AttachmentTags.TAGNAME_CONCATENATE_PDF_TO_INVOICE_PDF) .mimeType(MimeType.TYPE_PDF) .build(); final List<AttachmentEntry> attachments = attachmentEntryService.getByQuery(attachmentQuery); final ImmutableList<PdfDataProvider> additionalPdfData = attachments.stream() .map(AttachmentEntry::getId) .map(attachmentEntryService::retrieveData) .map(ByteArrayResource::new) .map(PdfDataProvider::forData) .collect(ImmutableList.toImmutableList()); final Resource result = ExecuteReportStrategyUtil.concatenatePDF(invoiceData, additionalPdfData); return ExecuteReportResult.of(outputType, result); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_SalesInvoiceJasperWithAttachedDocumentsStrategy.java
2
请在Spring Boot框架中完成以下Java代码
public String toString() { return "XLSConfigurationContext [" + "CamelFileName=" + CamelFileName // + ", EDIMessageDatePattern=" + EDIMessageDatePattern + ", AD_Client_Value=" + AD_Client_Value + ", AD_Org_ID=" + AD_Org_ID + ", ADInputDataDestination_InternalName=" + ADInputDataDestination_InternalName + ", ADInputDataSourceID=" + ADInputDataSourceID + ", ADUserEnteredByID=" + ADUserEnteredByID + ", DeliveryRule=" + DeliveryRule + ", DeliveryViaRule=" + DeliveryViaRule + ", currencyISOCode=" + currencyISOCode + "]"; } /** * @return processor which sets the properties of this configuration as exchange properties. */ public Processor asSetPropertiesToExchangeProcessor() { return new Processor() { private final HeaderExpression headerFileName = new HeaderExpression(Exchange.FILE_NAME); @Override public void process(Exchange exchange) throws Exception { // NOTE: use the Header FILE_NAME instead of our context property // because that's dynamic and also the filename is not set when creating the context from CamelContext exchange.setProperty(Exchange.FILE_NAME, headerFileName.evaluate(exchange, String.class)); // exchange.setProperty(CONTEXT_EDIMessageDatePattern, EDIMessageDatePattern); exchange.setProperty(CONTEXT_AD_Client_Value, AD_Client_Value); exchange.setProperty(CONTEXT_AD_Org_ID, AD_Org_ID); exchange.setProperty(CONTEXT_ADInputDataDestination_InternalName, ADInputDataDestination_InternalName); exchange.setProperty(CONTEXT_ADInputDataSourceID, ADInputDataSourceID); exchange.setProperty(CONTEXT_ADUserEnteredByID, ADUserEnteredByID); exchange.setProperty(CONTEXT_DELIVERY_RULE, DeliveryRule); exchange.setProperty(CONTEXT_DELIVERY_VIA_RULE, DeliveryViaRule); // exchange.setProperty(CONTEXT_CurrencyISOCode, currencyISOCode); } }; } /** @return Excel filename which is currently imported */ public String getCamelFileName() { return CamelFileName; } // public String getEDIMessageDatePattern() // { // return EDIMessageDatePattern; // } public String getAD_Client_Value() {
return AD_Client_Value; } public int getAD_Org_ID() { return AD_Org_ID; } public String getADInputDataDestination_InternalName() { return ADInputDataDestination_InternalName; } public BigInteger getADInputDataSourceID() { return ADInputDataSourceID; } public BigInteger getADUserEnteredByID() { return ADUserEnteredByID; } public String getDeliveryRule() { return DeliveryRule; } public String getDeliveryViaRule() { return DeliveryViaRule; } public String getCurrencyISOCode() { return currencyISOCode; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelConfigurationContext.java
2
请完成以下Java代码
public ProjectBuilder setJavaVersion(JavaVersion version) { this.javaVersion = version; return this; } public void build(String userName, Path projectPath, String packageName) throws IOException { Model model = new Model(); configureModel(userName, model); dependencies.forEach(model::addDependency); Build build = configureJavaVersion(); model.setBuild(build); MavenXpp3Writer writer = new MavenXpp3Writer(); writer.write(new FileWriter(projectPath.resolve(POM_XML).toFile()), model); generateFolders(projectPath, SRC_TEST); Path generatedPackage = generateFolders(projectPath, SRC_MAIN_JAVA + packageName.replace(PACKAGE_DELIMITER, FileSystems.getDefault().getSeparator())); String generatedClass = generateMainClass(PACKAGE + packageName); Files.writeString(generatedPackage.resolve(MAIN_JAVA), generatedClass); } private static void configureModel(String userName, Model model) { model.setModelVersion("4.0.0"); model.setArtifactId("com." + userName.toLowerCase()); model.setGroupId("learning-project"); model.setVersion("0.0.1-SNAPSHOT"); } private static String generateMainClass(String packageName) { return packageName + ";\n" + "\n" + "public class Main {\n" + " public static void main(String[] args){\n" + " System.out.println(\"Hello World!\");\n" + " }\n" + "}\n"; } private static Path generateFolders(Path sourceFolder, String packageName) throws IOException { return Files.createDirectories(sourceFolder.resolve(packageName)); } private Build configureJavaVersion() {
Plugin plugin = new Plugin(); plugin.setGroupId("org.apache.maven.plugins"); plugin.setArtifactId("maven-compiler-plugin"); plugin.setVersion("3.8.1"); Xpp3Dom configuration = new Xpp3Dom("configuration"); Xpp3Dom source = new Xpp3Dom("source"); source.setValue(javaVersion.getVersion()); Xpp3Dom target = new Xpp3Dom("target"); target.setValue(javaVersion.getVersion()); configuration.addChild(source); configuration.addChild(target); plugin.setConfiguration(configuration); Build build = new Build(); build.addPlugin(plugin); return build; } }
repos\tutorials-master\maven-modules\maven-exec-plugin\src\main\java\com\baeldung\learningplatform\ProjectBuilder.java
1
请完成以下Java代码
public class AD_User_CopyFavoritesPanel extends JavaProcess { private int p_AD_User_ID = -1; public static final String PARAM_AD_User_ID = "AD_User_ID"; @Override protected void prepare() { for (ProcessInfoParameter para : getParametersAsArray()) { final String name = para.getParameterName(); if (para.getParameter() == null) { continue; } else if (name.equals(PARAM_AD_User_ID)) { p_AD_User_ID = para.getParameterAsInt(); } } } @Override protected String doIt() { Check.assume(p_AD_User_ID > 0, "User should not be empty! "); final int targetUser_ID = getRecord_ID(); Check.assume(targetUser_ID > 0, "There is no record selected! "); final I_AD_User targetUser = Services.get(IUserDAO.class).getById(targetUser_ID); Check.assume(targetUser.isSystemUser(), "Selected user is not system user! "); final String whereClause = I_AD_TreeBar.COLUMNNAME_AD_User_ID + " = ? "; final List<I_AD_TreeBar> treBars = new TypedSqlQuery<I_AD_TreeBar>(getCtx(), I_AD_TreeBar.class, whereClause, get_TrxName()) .setOnlyActiveRecords(true) .setParameters(p_AD_User_ID) .list();
int cnt = 0; for (final I_AD_TreeBar treeBar : treBars) { if (!existsAlready(targetUser_ID, treeBar.getNode_ID())) { final I_AD_TreeBar tb = InterfaceWrapperHelper.create(getCtx(), I_AD_TreeBar.class, get_TrxName()); tb.setAD_Org_ID(treeBar.getAD_Org_ID()); tb.setNode_ID(treeBar.getNode_ID()); tb.setAD_User_ID(targetUser_ID); InterfaceWrapperHelper.save(tb); cnt++; } } return "Count: " + cnt; } /** * check if the TreeBar already exists */ private boolean existsAlready(final int AD_User_ID, final int Node_ID) { final String whereClause = I_AD_TreeBar.COLUMNNAME_AD_User_ID + " = ? AND " + I_AD_TreeBar.COLUMNNAME_Node_ID + " = ?"; return new TypedSqlQuery<I_AD_TreeBar>(getCtx(), I_AD_TreeBar.class, whereClause, get_TrxName()) .setOnlyActiveRecords(true) .setParameters(AD_User_ID, Node_ID) .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_CopyFavoritesPanel.java
1
请在Spring Boot框架中完成以下Java代码
public class InOutId implements RepoIdAware { @JsonCreator public static InOutId ofRepoId(final int repoId) { return new InOutId(repoId); } public static InOutId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new InOutId(repoId) : null; } public static Optional<InOutId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final InOutId id) { return id != null ? id.getRepoId() : -1;
} int repoId; private InOutId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_InOut_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable InOutId id1, @Nullable InOutId id2) {return Objects.equals(id1, id2);} public TableRecordReference toRecordRef() {return TableRecordReference.of(I_M_InOut.Table_Name, repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\InOutId.java
2
请在Spring Boot框架中完成以下Java代码
public class JsonExternalReferenceLookupItem { @ApiModelProperty(value = "JsonMetasfreshId of the referenced resource") @JsonInclude(JsonInclude.Include.NON_NULL) JsonMetasfreshId metasfreshId; @ApiModelProperty(required = true, value = "Type of the externally referenced resource. E.g. user, issue, timebooking") String type; @ApiModelProperty(value = "External identifier of the referenced resource") @JsonInclude(JsonInclude.Include.NON_NULL) String id; @JsonCreator @Builder
private JsonExternalReferenceLookupItem( @JsonProperty("metasfreshId") @Nullable final JsonMetasfreshId metasfreshId, @JsonProperty("type") @NonNull final String type, @JsonProperty("id") @Nullable final String id) { if (metasfreshId == null && id == null) { throw new RuntimeException("metasfreshId && externalReference cannot be both null!"); } this.id = id; this.type = type; this.metasfreshId = metasfreshId; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-externalreference\src\main\java\de\metas\common\externalreference\v2\JsonExternalReferenceLookupItem.java
2
请完成以下Java代码
private void addLinesTo(@NonNull final Fact fact) { final AcctSchemaId acctSchemaId = fact.getAcctSchemaId(); final List<FactAcctChanges> additions = linesToAddGroupedByAcctSchemaId.removeAll(acctSchemaId); additions.forEach(addition -> addLine(fact, addition)); } public void addLine(@NonNull final Fact fact, @NonNull final FactAcctChanges changesToAdd) { if (!changesToAdd.getType().isAdd()) { throw new AdempiereException("Expected type `Add` but it was " + changesToAdd); } final FactLine factLine = fact.createLine() .alsoAddZeroLine()
.setAccount(changesToAdd.getAccountIdNotNull()) .setAmtSource(changesToAdd.getAmtSourceDr(), changesToAdd.getAmtSourceCr()) .setAmtAcct(changesToAdd.getAmtAcctDr(), changesToAdd.getAmtAcctCr()) .setC_Tax_ID(changesToAdd.getTaxId()) .description(changesToAdd.getDescription()) .productId(changesToAdd.getProductId()) .userElementString1(changesToAdd.getUserElementString1()) .salesOrderId(changesToAdd.getSalesOrderId()) .activityId(changesToAdd.getActivityId()) .buildAndAdd(); if (factLine != null) { factLine.updateFrom(changesToAdd); // just to have appliedUserChanges set } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctChangesApplier.java
1
请完成以下Java代码
public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public String getAccountStatus() { return accountStatus; } public void setAccountStatus(String accountStatus) { this.accountStatus = accountStatus; } public Long getBalance() { return balance; }
public void setBalance(Long balance) { this.balance = balance; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\model\Account.java
1
请完成以下Java代码
public class MethodRoutePredicateFactory extends AbstractRoutePredicateFactory<MethodRoutePredicateFactory.Config> { /** * Methods key. */ public static final String METHODS_KEY = "methods"; public MethodRoutePredicateFactory() { super(Config.class); } @Override public List<String> shortcutFieldOrder() { return List.of(METHODS_KEY); } @Override public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST; } @Override public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { HttpMethod requestMethod = exchange.getRequest().getMethod(); return stream(config.getMethods()).anyMatch(httpMethod -> httpMethod == requestMethod); } @Override public String toString() { return String.format("Methods: %s", Arrays.toString(config.getMethods())); } };
} public static class Config { private HttpMethod[] methods = new HttpMethod[0]; public HttpMethod[] getMethods() { return methods; } public void setMethods(HttpMethod... methods) { this.methods = methods; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\MethodRoutePredicateFactory.java
1
请完成以下Java代码
private void updatePhoneAndFax(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_C_BPartner_Location bpartnerLocation) { if (!Check.isEmpty(importRecord.getb00tel1())) { bpartnerLocation.setPhone(importRecord.getb00tel1()); } if (!Check.isEmpty(importRecord.getb00tel2())) { bpartnerLocation.setPhone2(importRecord.getb00tel2()); } if (!Check.isEmpty(importRecord.getb00fax1())) { bpartnerLocation.setFax(importRecord.getb00fax1()); } if (!Check.isEmpty(importRecord.getb00fax2())) {
bpartnerLocation.setFax2(importRecord.getb00fax2()); } } private void updateEmails(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_C_BPartner_Location bpartnerLocation) { if (!Check.isEmpty(importRecord.getb00email())) { bpartnerLocation.setEMail(importRecord.getb00email()); } if (!Check.isEmpty(importRecord.getb00email2())) { bpartnerLocation.setEMail2(importRecord.getb00email2()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerLocationImportHelper.java
1
请完成以下Java代码
private WebuiEmailEntry getEmailEntry(final String emailId) { final WebuiEmailEntry emailEntry = emailsById.getIfPresent(emailId); if (emailEntry == null) { throw new EntityNotFoundException("Email not found") .setParameter("emailId", emailId); } return emailEntry; } public WebuiEmail getEmail(final String emailId) { return getEmailEntry(emailId).getEmail(); } WebuiEmailChangeResult changeEmail(final String emailId, final UnaryOperator<WebuiEmail> emailModifier) { return getEmailEntry(emailId).compute(emailModifier); } public void removeEmailById(final String emailId) { emailsById.invalidate(emailId); } /** * Called when the email was removed from our internal cache. */ private void onEmailRemoved(final WebuiEmail email) { eventPublisher.publishEvent(new WebuiEmailRemovedEvent(email)); } public LookupValuesPage getToTypeahead(final String ignoredEmailId, final String query) { final Evaluatee ctx = Evaluatees.empty(); // TODO // TODO: filter only those which have a valid email address return emailToLookup.findEntities(ctx, query); } public LookupValue getToByUserId(final Integer adUserId) { return emailToLookup.findById(adUserId); }
@ToString private static final class WebuiEmailEntry { private WebuiEmail email; public WebuiEmailEntry(@NonNull final WebuiEmail email) { this.email = email; } public synchronized WebuiEmail getEmail() { return email; } public synchronized WebuiEmailChangeResult compute(final UnaryOperator<WebuiEmail> modifier) { final WebuiEmail emailOld = email; final WebuiEmail emailNew = modifier.apply(emailOld); if (emailNew == null) { throw new NullPointerException("email"); } email = emailNew; return WebuiEmailChangeResult.builder().email(emailNew).originalEmail(emailOld).build(); } } @Value @AllArgsConstructor public static class WebuiEmailRemovedEvent { @NonNull WebuiEmail email; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class CommentsApi { private ArticleRepository articleRepository; private CommentRepository commentRepository; private CommentQueryService commentQueryService; @PostMapping public ResponseEntity<?> createComment( @PathVariable("slug") String slug, @AuthenticationPrincipal User user, @Valid @RequestBody NewCommentParam newCommentParam) { Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); Comment comment = new Comment(newCommentParam.getBody(), user.getId(), article.getId()); commentRepository.save(comment); return ResponseEntity.status(201) .body(commentResponse(commentQueryService.findById(comment.getId(), user).get())); } @GetMapping public ResponseEntity getComments( @PathVariable("slug") String slug, @AuthenticationPrincipal User user) { Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); List<CommentData> comments = commentQueryService.findByArticleId(article.getId(), user); return ResponseEntity.ok( new HashMap<String, Object>() { { put("comments", comments); } }); } @RequestMapping(path = "{id}", method = RequestMethod.DELETE) public ResponseEntity deleteComment(
@PathVariable("slug") String slug, @PathVariable("id") String commentId, @AuthenticationPrincipal User user) { Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); return commentRepository .findById(article.getId(), commentId) .map( comment -> { if (!AuthorizationService.canWriteComment(user, article, comment)) { throw new NoAuthorizationException(); } commentRepository.remove(comment); return ResponseEntity.noContent().build(); }) .orElseThrow(ResourceNotFoundException::new); } private Map<String, Object> commentResponse(CommentData commentData) { return new HashMap<String, Object>() { { put("comment", commentData); } }; } } @Getter @NoArgsConstructor @JsonRootName("comment") class NewCommentParam { @NotBlank(message = "can't be empty") private String body; }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\CommentsApi.java
2
请完成以下Java代码
public void setPayerIdentifier(@Nullable final String payerIdentifier) { this.payerIdentifier = payerIdentifier; this.payerIdentifierSet = true; } public void setPayerType(@Nullable final String payerType) { this.payerType = payerType; this.payerTypeSet = true; } public void setNumberOfInsured(@Nullable final String numberOfInsured) { this.numberOfInsured = numberOfInsured; this.numberOfInsuredSet = true; } public void setCopaymentFrom(@Nullable final LocalDate copaymentFrom) { this.copaymentFrom = copaymentFrom; this.copaymentFromSet = true; } public void setCopaymentTo(@Nullable final LocalDate copaymentTo) { this.copaymentTo = copaymentTo; this.copaymentToSet = true; } public void setIsTransferPatient(@Nullable final Boolean isTransferPatient) { this.isTransferPatient = isTransferPatient; this.transferPatientSet = true; } public void setIVTherapy(@Nullable final Boolean IVTherapy) { this.isIVTherapy = IVTherapy; this.ivTherapySet = true; } public void setFieldNurseIdentifier(@Nullable final String fieldNurseIdentifier) { this.fieldNurseIdentifier = fieldNurseIdentifier; this.fieldNurseIdentifierSet = true; } public void setDeactivationReason(@Nullable final String deactivationReason) { this.deactivationReason = deactivationReason; this.deactivationReasonSet = true; } public void setDeactivationDate(@Nullable final LocalDate deactivationDate) { this.deactivationDate = deactivationDate; this.deactivationDateSet = true; } public void setDeactivationComment(@Nullable final String deactivationComment) { this.deactivationComment = deactivationComment; this.deactivationCommentSet = true; } public void setClassification(@Nullable final String classification)
{ this.classification = classification; this.classificationSet = true; } public void setCareDegree(@Nullable final BigDecimal careDegree) { this.careDegree = careDegree; this.careDegreeSet = true; } public void setCreatedAt(@Nullable final Instant createdAt) { this.createdAt = createdAt; this.createdAtSet = true; } public void setCreatedByIdentifier(@Nullable final String createdByIdentifier) { this.createdByIdentifier = createdByIdentifier; this.createdByIdentifierSet = true; } public void setUpdatedAt(@Nullable final Instant updatedAt) { this.updatedAt = updatedAt; this.updatedAtSet = true; } public void setUpdateByIdentifier(@Nullable final String updateByIdentifier) { this.updateByIdentifier = updateByIdentifier; this.updateByIdentifierSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaPatient.java
1
请完成以下Java代码
protected String determineResourceName(final Resource resource) { String resourceName = null; if (resource instanceof ContextResource) { resourceName = ((ContextResource) resource).getPathWithinContext(); } else if (resource instanceof ByteArrayResource) { resourceName = resource.getDescription(); } else { try { resourceName = resource.getFile().getAbsolutePath(); } catch (Exception e) { // Catching any exception here, as e.g. Graal will throw an UnsupportedException instead of an IOException resourceName = resource.getFilename(); } } return resourceName; } public CommonAutoDeploymentProperties getDeploymentProperties() { return deploymentProperties; } public void setDeploymentProperties(CommonAutoDeploymentProperties deploymentProperties) { this.deploymentProperties = deploymentProperties; }
public boolean isUseLockForDeployments() { return deploymentProperties.isUseLock(); } public Duration getDeploymentLockWaitTime() { return deploymentProperties.getLockWaitTime(); } public boolean isThrowExceptionOnDeploymentFailure() { return deploymentProperties.isThrowExceptionOnDeploymentFailure(); } public String getLockName() { return deploymentProperties.getLockName(); } }
repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\CommonAutoDeploymentStrategy.java
1
请完成以下Java代码
public void setC_Phonecall_Schema_ID (int C_Phonecall_Schema_ID) { if (C_Phonecall_Schema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Phonecall_Schema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Phonecall_Schema_ID, Integer.valueOf(C_Phonecall_Schema_ID)); } /** Get Anrufliste. @return Anrufliste */ @Override public int getC_Phonecall_Schema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Phonecall_Schema_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schema.java
1
请完成以下Java代码
public class ClientTlsVersionExamples { public static CloseableHttpClient setViaSocketFactory() { final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() .setDefaultTlsConfig(TlsConfig.custom() .setHandshakeTimeout(Timeout.ofSeconds(30)) .setSupportedProtocols(TLS.V_1_2, TLS.V_1_3) .build()) .build(); return HttpClients.custom() .setConnectionManager(cm) .build(); } public static CloseableHttpClient setTlsVersionPerConnection() { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) { @Override protected void prepareSocket(SSLSocket socket) { String hostname = socket.getInetAddress() .getHostName(); if (hostname.endsWith("internal.system.com")) { socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }); } else { socket.setEnabledProtocols(new String[] { "TLSv1.3" }); } } }; HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(sslsf) .build(); return HttpClients.custom() .setConnectionManager(connManager) .build();
} // To configure the TLS versions for the client, set the https.protocols system property during runtime. // For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar public static CloseableHttpClient setViaSystemProperties() { return HttpClients.createSystem(); // Alternatively: //return HttpClients.custom().useSystemProperties().build(); } public static void main(String[] args) throws IOException { try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } } }
repos\tutorials-master\apache-httpclient-2\src\main\java\com\baeldung\tlsversion\ClientTlsVersionExamples.java
1
请完成以下Java代码
public static UIDefaults.ActiveValue createActiveValueProxy(final String proxyKey, final Object defaultValue) { return new UIDefaults.ActiveValue() { @Override public Object createValue(final UIDefaults table) { final Object value = table.get(proxyKey); return value != null ? value : defaultValue; } }; } /** * Gets integer value of given key. If no value was found or the value is not {@link Integer} the default value will be returned. * * @return integer value or default value */ public static int getInt(final String key, final int defaultValue) { final Object value = UIManager.getDefaults().get(key); if (value instanceof Integer) { return ((Integer)value).intValue(); } return defaultValue; } public static boolean getBoolean(final String key, final boolean defaultValue) { final Object value = UIManager.getDefaults().get(key); if (value instanceof Boolean) {
return ((Boolean)value).booleanValue(); } return defaultValue; } public static String getString(final String key, final String defaultValue) { final Object value = UIManager.getDefaults().get(key); if(value == null) { return defaultValue; } return value.toString(); } public static void setDefaultBackground(final JComponent comp) { comp.putClientProperty(AdempiereLookAndFeel.BACKGROUND, MFColor.ofFlatColor(AdempierePLAF.getFormBackground())); } } // AdempierePLAF
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempierePLAF.java
1
请完成以下Java代码
public EqualsBuilder append(final boolean value1, final boolean value2) { if (!isEqual) { return this; } if (value1 != value2) { isEqual = false; } return this; } // added for optimization (avoid autoboxing and equals()) public EqualsBuilder append(final int value1, final int value2) { if (!isEqual) { return this; } if (value1 != value2) { isEqual = false; } return this; } public <T> EqualsBuilder append(final T value1, final T value2) { if (!isEqual) { return this; } if (!Check.equals(value1, value2)) { isEqual = false; } return this; } /** * Append values by reference, so values will be considered equal only if <code>value1 == value2</code>. * * @param value1 * @param value2 * @return this */ public <T> EqualsBuilder appendByRef(final T value1, final T value2) { if (!isEqual) { return this; } if (value1 != value2) { isEqual = false; } return this; } public EqualsBuilder append(final Map<String, Object> map1, final Map<String, Object> map2, final boolean handleEmptyAsNull) { if (!isEqual) { return this; } if (handleEmptyAsNull) { final Object value1 = map1 == null || map1.isEmpty() ? null : map1;
final Object value2 = map2 == null || map2.isEmpty() ? null : map2; return append(value1, value2); } return append(map1, map2); } public boolean isEqual() { return isEqual; } /** * Checks and casts <code>other</code> to same class as <code>obj</code>. * * This method shall be used as first statement in an {@link Object#equals(Object)} implementation. <br/> * <br/> * Example: * * <pre> * public boolean equals(Object obj) * { * if (this == obj) * { * return true; * } * final MyClass other = EqualsBuilder.getOther(this, obj); * if (other == null) * { * return false; * } * * return new EqualsBuilder() * .append(prop1, other.prop1) * .append(prop2, other.prop2) * .append(prop3, other.prop3) * // .... * .isEqual(); * } * </pre> * * @param thisObj this object * @param obj other object * @return <code>other</code> casted to same class as <code>obj</code> or null if <code>other</code> is null or does not have the same class */ public static <T> T getOther(final T thisObj, final Object obj) { if (thisObj == null) { throw new IllegalArgumentException("obj is null"); } if (thisObj == obj) { @SuppressWarnings("unchecked") final T otherCasted = (T)obj; return otherCasted; } if (obj == null) { return null; } if (thisObj.getClass() != obj.getClass()) { return null; } @SuppressWarnings("unchecked") final T otherCasted = (T)obj; return otherCasted; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\EqualsBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public Saml2MessageBinding getBinding() { return Saml2MessageBinding.POST; } /** * Constructs a {@link Builder} from a {@link RelyingPartyRegistration} object. * @param registration a relying party registration * @return a modifiable builder object * @since 5.7 */ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { String location = registration.getAssertingPartyMetadata().getSingleSignOnServiceLocation(); return new Builder(registration).authenticationRequestUri(location); } /** * Builder class for a {@link Saml2PostAuthenticationRequest} object. */ public static final class Builder extends AbstractSaml2AuthenticationRequest.Builder<Builder> {
private Builder(RelyingPartyRegistration registration) { super(registration); } /** * Constructs an immutable {@link Saml2PostAuthenticationRequest} object. * @return an immutable {@link Saml2PostAuthenticationRequest} object. */ public Saml2PostAuthenticationRequest build() { return new Saml2PostAuthenticationRequest(this.samlRequest, this.relayState, this.authenticationRequestUri, this.relyingPartyRegistrationId, this.id); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2PostAuthenticationRequest.java
2
请完成以下Java代码
public class DataSetToDataFrameConverterApp { private static final SparkSession SPARK_SESSION = SparkDriver.getSparkSession(); public static void main(String[] args) { Dataset<Customer> customerDataset = convertToDataSetFromPOJO(); Dataset<Row> customerDataFrame = customerDataset.toDF(); print(customerDataFrame); List<String> names = getNames(); Dataset<String> namesDataset = convertToDataSetFromStrings(names); Dataset<Row> namesDataFrame = namesDataset.toDF(); print(namesDataFrame); } private static Dataset<String> convertToDataSetFromStrings(List<String> names) { return SPARK_SESSION.createDataset(names, Encoders.STRING()); } private static Dataset<Customer> convertToDataSetFromPOJO() { return SPARK_SESSION.createDataset(CUSTOMERS, Encoders.bean(Customer.class)); } private static final List<Customer> CUSTOMERS = Arrays.asList( aCustomerWith("01", "jo", "Female", 2000), aCustomerWith("02", "jack", "Female", 1200), aCustomerWith("03", "ash", "male", 2000), aCustomerWith("04", "emma", "Female", 2000) );
private static List<String> getNames() { return CUSTOMERS.stream() .map(Customer::getName) .collect(Collectors.toList()); } private static void print(Dataset<Row> df) { df.show(); df.printSchema(); } private static Customer aCustomerWith(String id, String name, String gender, int amount) { return new Customer(id, name, gender, amount); } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\dataframes\DataSetToDataFrameConverterApp.java
1
请完成以下Java代码
public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public boolean isOpen() { return IncidentState.DEFAULT.getStateCode() == incidentState; } public boolean isDeleted() { return IncidentState.DELETED.getStateCode() == incidentState; } public boolean isResolved() { return IncidentState.RESOLVED.getStateCode() == incidentState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getFailedActivityId() { return failedActivityId;
} public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java
1
请完成以下Java代码
public class Sandbox { public static void main(String[] args) { //Class singleton ClassSingleton classSingleton1 = ClassSingleton.getInstance(); //OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible System.out.println(classSingleton1.getInfo()); //Initial class info ClassSingleton classSingleton2 = ClassSingleton.getInstance(); classSingleton2.setInfo("New class info"); System.out.println(classSingleton1.getInfo()); //New class info
System.out.println(classSingleton2.getInfo()); //New class info //Enum singleton EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance(); System.out.println(enumSingleton1.getInfo()); //Initial enum info EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance(); enumSingleton2.setInfo("New enum info"); System.out.println(enumSingleton1.getInfo()); //New enum info System.out.println(enumSingleton2.getInfo()); //New enum info } }
repos\tutorials-master\patterns-modules\design-patterns-creational\src\main\java\com\baeldung\singleton\Sandbox.java
1
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { updateEntry(); return success; } // afterSave /** * After Delete * * @param success success * @return success */ @Override protected boolean afterDelete(boolean success) { updateEntry(); return success; } // afterDelete /** * Update Entry.
* Calculate/update Amt/Qty */ private void updateEntry() { // we do not count the fee line as an item, but it sum it up. String sql = "UPDATE C_DunningRunEntry e " + "SET Amt=COALESCE((SELECT SUM(ConvertedAmt)+SUM(FeeAmt)+SUM(InterestAmt)" + " FROM C_DunningRunLine l " + "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID), 0), " + "QTY=(SELECT COUNT(*)" + " FROM C_DunningRunLine l " + "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID " + " AND (NOT C_Invoice_ID IS NULL OR NOT C_Payment_ID IS NULL))" + " WHERE C_DunningRunEntry_ID=" + getC_DunningRunEntry_ID(); DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); } // updateEntry } // MDunningRunLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRunLine.java
1
请完成以下Java代码
private final static String format(short shortval) { String formatted = Integer.toHexString(shortval); StringBuilder buf = new StringBuilder("0000"); buf.replace(4 - formatted.length(), 4, formatted); return buf.toString(); } private final static int getJvm() { return JVM; } private final static short getCount() { synchronized (UUIDGenerator.class) { if (counter < 0) { counter = 0; } return counter++; } } /** * Unique in a local network */ private final static int getIp() { return IP; } /** * Unique down to millisecond
*/ private final static short getHiTime() { return (short) (System.currentTimeMillis() >>> 32); } private final static int getLoTime() { return (int) System.currentTimeMillis(); } private final static int toInt(byte[] bytes) { int result = 0; int length = 4; for (int i = 0; i < length; i++) { result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\UUIDGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public static class PackageInfo { @NonNull PackageId packageId; @Nullable String poReference; @Nullable String description; @Nullable BigDecimal weightInKg; @NonNull PackageDimensions packageDimension; public BigDecimal getWeightInKgOr(final BigDecimal minValue) {return weightInKg != null ? weightInKg.max(minValue) : minValue;} } } @Value @EqualsAndHashCode(exclude = "carrierServices") class DeliveryOrderKey { @NonNull ShipperId shipperId; @NonNull ShipperTransportationId shipperTransportationId; int fromOrgId; int deliverToBPartnerId; int deliverToBPartnerLocationId; @NonNull LocalDate pickupDate; @NonNull LocalTime timeFrom; @NonNull LocalTime timeTo; @Nullable CarrierProductId carrierProductId; @Nullable CarrierGoodsTypeId carrierGoodsTypeId; @Nullable Set<CarrierServiceId> carrierServices; AsyncBatchId asyncBatchId; @Builder public DeliveryOrderKey( @NonNull final ShipperId shipperId, @NonNull final ShipperTransportationId shipperTransportationId, final int fromOrgId, final int deliverToBPartnerId, final int deliverToBPartnerLocationId, @NonNull final LocalDate pickupDate, @NonNull final LocalTime timeFrom, @NonNull final LocalTime timeTo, @Nullable final CarrierProductId carrierProductId, @Nullable final CarrierGoodsTypeId carrierGoodsTypeId, @Nullable final Set<CarrierServiceId> carrierServices, @Nullable final AsyncBatchId asyncBatchId) {
Check.assume(fromOrgId > 0, "fromOrgId > 0"); Check.assume(deliverToBPartnerId > 0, "deliverToBPartnerId > 0"); Check.assume(deliverToBPartnerLocationId > 0, "deliverToBPartnerLocationId > 0"); this.shipperId = shipperId; this.shipperTransportationId = shipperTransportationId; this.fromOrgId = fromOrgId; this.deliverToBPartnerId = deliverToBPartnerId; this.deliverToBPartnerLocationId = deliverToBPartnerLocationId; this.pickupDate = pickupDate; this.timeFrom = timeFrom; this.timeTo = timeTo; this.carrierProductId = carrierProductId; this.carrierGoodsTypeId = carrierGoodsTypeId; this.carrierServices = carrierServices; this.asyncBatchId = asyncBatchId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\DraftDeliveryOrderCreator.java
2
请完成以下Java代码
public boolean isQueueEmpty() { if (foundGoal) { return true; } return queueItemsToProcess.isEmpty(); } @Override public ITableRecordReference nextFromQueue() { return queueItemsToProcess.removeFirst(); } @Override public void registerHandler(IIterateResultHandler handler) { handlerSupport.registerListener(handler); } @Override public List<IIterateResultHandler> getRegisteredHandlers() { return handlerSupport.getRegisteredHandlers(); } @Override public boolean isHandlerSignaledToStop() { return handlerSupport.isHandlerSignaledToStop(); } public boolean isFoundGoalRecord() { return foundGoal; } @Override public boolean contains(final ITableRecordReference forwardReference) { return g.containsVertex(forwardReference); } public List<ITableRecordReference> getPath() { final List<ITableRecordReference> result = new ArrayList<>(); final AsUndirectedGraph<ITableRecordReference, DefaultEdge> undirectedGraph = new AsUndirectedGraph<>(g); final List<DefaultEdge> path = DijkstraShortestPath.<ITableRecordReference, DefaultEdge> findPathBetween( undirectedGraph, start, goal); if (path == null || path.isEmpty()) {
return ImmutableList.of(); } result.add(start); for (final DefaultEdge e : path) { final ITableRecordReference edgeSource = undirectedGraph.getEdgeSource(e); if (!result.contains(edgeSource)) { result.add(edgeSource); } else { result.add(undirectedGraph.getEdgeTarget(e)); } } return ImmutableList.copyOf(result); } /* package */ Graph<ITableRecordReference, DefaultEdge> getGraph() { return g; } @Override public String toString() { return "FindPathIterateResult [start=" + start + ", goal=" + goal + ", size=" + size + ", foundGoal=" + foundGoal + ", queueItemsToProcess.size()=" + queueItemsToProcess.size() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\graph\FindPathIterateResult.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderLine { @NonNull OrderLineId orderLineId; @NonNull ProductId productId; @Nullable HUPIItemProductId packingMaterialId; boolean packingMaterialWithInfiniteCapacity; @NonNull BigDecimal priceActual; @NonNull BigDecimal priceEntered; @NonNull Currency currency; @NonNull BigDecimal qtyEnteredCU; @NonNull AttributeSetInstanceId asiId;
int qtyEnteredTU; String description; public boolean isMatching( @NonNull final ProductId productId, @Nullable final HUPIItemProductId packingMaterialId) { return ProductId.equals(this.productId, productId) && HUPIItemProductId.equals( HUPIItemProductId.nullToVirtual(this.packingMaterialId), HUPIItemProductId.nullToVirtual(packingMaterialId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\service\OrderLine.java
2
请完成以下Java代码
public static LocalDateAndOrgId ofLocalDate(@NonNull final LocalDate localDate, @NonNull final OrgId orgId) { return new LocalDateAndOrgId(localDate, orgId); } @Nullable public static LocalDateAndOrgId ofNullableLocalDate(@Nullable final LocalDate localDate, @NonNull final OrgId orgId) { return localDate != null ? ofLocalDate(localDate, orgId) : null; } public static LocalDateAndOrgId ofTimestamp(@NonNull final Timestamp timestamp, @NonNull final OrgId orgId, @NonNull final Function<OrgId, ZoneId> orgMapper) { final LocalDate localDate = timestamp.toInstant().atZone(orgMapper.apply(orgId)).toLocalDate(); return new LocalDateAndOrgId(localDate, orgId); } @Nullable public static LocalDateAndOrgId ofNullableTimestamp(@Nullable final Timestamp timestamp, @NonNull final OrgId orgId, @NonNull final Function<OrgId, ZoneId> orgMapper) { return timestamp != null ? ofTimestamp(timestamp, orgId, orgMapper) : null; } @Nullable public static Timestamp toTimestamp( @Nullable final LocalDateAndOrgId localDateAndOrgId, @NonNull final Function<OrgId, ZoneId> orgMapper) { return localDateAndOrgId != null ? localDateAndOrgId.toTimestamp(orgMapper) : null; } public static long daysBetween(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { assertSameOrg(d2, d2); return ChronoUnit.DAYS.between(d1.toLocalDate(), d2.toLocalDate()); } private static void assertSameOrg(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { Check.assumeEquals(d1.getOrgId(), d2.getOrgId(), "Dates have the same org: {}, {}", d1, d2); } public Instant toInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atStartOfDay().atZone(orgMapper.apply(orgId)).toInstant(); } public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant(); } public LocalDate toLocalDate() { return localDate; }
public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) { return Timestamp.from(toInstant(orgMapper)); } @Override public int compareTo(final @Nullable LocalDateAndOrgId o) { return compareToByLocalDate(o); } /** * In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes. * A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?" * That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s. * * @see #compareTo(LocalDateAndOrgId) */ private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o) { if (o == null) { return 1; } return this.localDate.compareTo(o.localDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
1
请完成以下Java代码
private Map<String, Object> createMessage(InstanceEvent event, Instance instance) { Map<String, Object> parameters = new HashMap<>(); parameters.put("chat_id", this.chatId); parameters.put("parse_mode", this.parseMode); parameters.put("disable_notification", this.disableNotify); parameters.put("text", createContent(event, instance)); return parameters; } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } @Nullable public String getChatId() { return chatId; } public void setChatId(@Nullable String chatId) { this.chatId = chatId; } @Nullable public String getAuthToken() { return authToken; }
public void setAuthToken(@Nullable String authToken) { this.authToken = authToken; } public boolean isDisableNotify() { return disableNotify; } public void setDisableNotify(boolean disableNotify) { this.disableNotify = disableNotify; } public String getParseMode() { return parseMode; } public void setParseMode(String parseMode) { this.parseMode = parseMode; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\TelegramNotifier.java
1
请完成以下Java代码
public I_AD_User getUserById(@NonNull final UserId userId) { return userDAO.getById(userId); } public String getUserFullname() { return getUserFullnameById(getUserId()); } public String getUserFullnameById(@NonNull final UserId userId) { return userDAO.retrieveUserFullName(userId); } public OrgInfo getOrgInfoById(@NonNull final OrgId orgId) { return orgsRepo.getOrgInfoById(orgId); } public void sendNotification(@NonNull final WFUserNotification notification) { notificationBL.sendAfterCommit(UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC) .recipientUserId(notification.getUserId()) .contentADMessage(notification.getContent().getAdMessage()) .contentADMessageParams(notification.getContent().getParams()) .targetAction(notification.getDocumentToOpen() != null ? UserNotificationRequest.TargetRecordAction.of(notification.getDocumentToOpen()) : null) .build()); } public MailTextBuilder newMailTextBuilder( @NonNull final TableRecordReference documentRef, @NonNull final MailTemplateId mailTemplateId) {
return mailService.newMailTextBuilder(mailTemplateId) .recordAndUpdateBPartnerAndContact(getPO(documentRef)); } public void save(@NonNull final WFEventAudit audit) { auditRepo.save(audit); } public void addEventAudit(@NonNull final WFEventAudit audit) { auditList.add(audit); } public void createNewAttachment( @NonNull final Object referencedRecord, @NonNull final File file) { attachmentEntryService.createNewAttachment(referencedRecord, file); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WorkflowExecutionContext.java
1
请在Spring Boot框架中完成以下Java代码
public List<ArticleAssembly> findAllAssemblyByFollowerId(long userId, Integer limit, Integer offset) { return assemblyRepository.findFeed(userId, limit, offset).stream() .map(articleMapper::toDomain) .toList(); } @Override public long countByFilters(Long tagId, Long authorId, Long favoritedById) { return assemblyRepository.countFiltered(tagId, authorId, favoritedById); } @Override public long countFeed(long userId) { return assemblyRepository.countFeed(userId); } @Mapper(config = MappingConfig.class) interface ArticleMapper { @Mapping(target = "tagList", source = "tags") @Mapping(target = "tagIds", source = "tags") ArticleJdbcEntity fromDomain(Article source); @Mapping(target = "tag", ignore = true) @Mapping(target = "tags", source = "source") Article toDomain(ArticleJdbcEntity source); @Mapping(target = "author", source = "source") ArticleAssembly toDomain(ArticleAssemblyJdbcEntity source); default Profile profile(ArticleAssemblyJdbcEntity source) { return new Profile(source.authorUsername(), source.authorBio(), source.authorImage(), source.authorFollowing()); } default List<String> tagList(String source) { if (source == null) { return null; } return Arrays.stream(source.split(",")).toList(); }
default String tagList(List<Tag> source) { if (source == null || source.isEmpty()) { return null; } return source.stream().map(Tag::name).collect(Collectors.joining(",")); } default List<ArticleTagJdbcEntity> tagIds(List<Tag> source) { return source.stream().map(t -> new ArticleTagJdbcEntity(t.id())).toList(); } default List<Tag> tags(ArticleJdbcEntity source) { var tagIds = source.tagIds(); if (tagIds != null) { var tagList = source.tagList(); if (tagList != null) { var tagNames = tagList.split(","); if (tagNames.length == tagIds.size()) { List<Tag> tags = new ArrayList<>(); for (var i = 0; i < tagIds.size(); i++) { var tag = new Tag(tagIds.get(i).tagId(), tagNames[i]); tags.add(tag); } return tags; } } } return List.of(); } } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\ArticleJdbcRepositoryAdapter.java
2
请完成以下Java代码
public XMLGregorianCalendar getStartDt() { return startDt; } /** * Sets the value of the startDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setStartDt(XMLGregorianCalendar value) { this.startDt = value; } /** * Gets the value of the endDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getEndDt() { return endDt; } /** * Sets the value of the endDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setEndDt(XMLGregorianCalendar value) { this.endDt = value; } /** * Gets the value of the txDtTm property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getTxDtTm() { return txDtTm; } /** * Sets the value of the txDtTm property. *
* @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setTxDtTm(XMLGregorianCalendar value) { this.txDtTm = value; } /** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryDate2 } * * */ public List<ProprietaryDate2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryDate2>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionDates2.java
1