instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class AD_UI_ElementGroup_AddField extends JavaProcess { @Param(parameterName = "AD_Field_ID", mandatory = true) private AdFieldId adFieldId; // @Param(parameterName = "After_UI_Element_ID", mandatory = false) // private UIElementId afterUIElementId; private AdUIElementGroupId getAdElementGroupId() { return AdUIElementGroupId.ofRepoId(getRecord_ID()); } @Override protected String doIt() { final I_AD_Field adField = loadOutOfTrx(adFieldId, I_AD_Field.class); final AdTabId adTabId = AdTabId.ofRepoId(adField.getAD_Tab_ID()); // // final AdUIElementGroupId uiElementGroupId = getAdElementGroupId(); I_AD_UI_Element uiElement = getUIElementByTabAndFieldId(adTabId, adFieldId); if (uiElement == null) { uiElement = createUIElement(adField, uiElementGroupId); } else { uiElement.setAD_UI_ElementGroup_ID(uiElementGroupId.getRepoId()); } final int seqNo = Services.get(IADWindowDAO.class).getUIElementNextSeqNo(uiElementGroupId); uiElement.setIsDisplayed(true); uiElement.setSeqNo(seqNo); // if (afterUIElementId != null) // { // // TODO implement // addLog("WARNING: Adding after a given element not yet implemented, so your element will be added last.");
// } saveRecord(uiElement); return MSG_OK; } private I_AD_UI_Element getUIElementByTabAndFieldId(final AdTabId adTabId, final AdFieldId adFieldId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_UI_Element.class) .addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Tab_ID, adTabId) .addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Field_ID, adFieldId) .create() .firstOnly(I_AD_UI_Element.class); } private I_AD_UI_Element createUIElement( @NonNull final I_AD_Field adField, @NonNull final AdUIElementGroupId uiElementGroupId) { final I_AD_UI_Element uiElement = WindowUIElementsGenerator.createUIElementNoSave(uiElementGroupId, adField); uiElement.setIsDisplayed(true); uiElement.setSeqNo(10); return uiElement; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\process\AD_UI_ElementGroup_AddField.java
1
请完成以下Java代码
public Integer getCollectCount() { return collectCount; } public void setCollectCount(Integer collectCount) { this.collectCount = collectCount; } public Integer getReadCount() { return readCount; } public void setReadCount(Integer readCount) { this.readCount = readCount; } public Integer getCommentCount() { return commentCount; } public void setCommentCount(Integer commentCount) { this.commentCount = commentCount; } public String getAlbumPics() { return albumPics; } public void setAlbumPics(String albumPics) { this.albumPics = albumPics; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getForwardCount() { return forwardCount; } public void setForwardCount(Integer forwardCount) { this.forwardCount = forwardCount; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName;
} public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", categoryId=").append(categoryId); sb.append(", title=").append(title); sb.append(", pic=").append(pic); sb.append(", productCount=").append(productCount); sb.append(", recommendStatus=").append(recommendStatus); sb.append(", createTime=").append(createTime); sb.append(", collectCount=").append(collectCount); sb.append(", readCount=").append(readCount); sb.append(", commentCount=").append(commentCount); sb.append(", albumPics=").append(albumPics); sb.append(", description=").append(description); sb.append(", showStatus=").append(showStatus); sb.append(", forwardCount=").append(forwardCount); sb.append(", categoryName=").append(categoryName); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubject.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof AclImpl)) { return false; } AclImpl other = (AclImpl) obj; boolean result = true; result = result && this.aces.equals(other.aces); result = result && ObjectUtils.nullSafeEquals(this.parentAcl, other.parentAcl); result = result && ObjectUtils.nullSafeEquals(this.objectIdentity, other.objectIdentity); result = result && ObjectUtils.nullSafeEquals(this.id, other.id); result = result && ObjectUtils.nullSafeEquals(this.owner, other.owner); result = result && this.entriesInheriting == other.entriesInheriting; result = result && ObjectUtils.nullSafeEquals(this.loadedSids, other.loadedSids); return result; } @Override public int hashCode() { int result = (this.parentAcl != null) ? this.parentAcl.hashCode() : 0; result = 31 * result + this.aclAuthorizationStrategy.hashCode(); result = 31 * result + ((this.permissionGrantingStrategy != null) ? this.permissionGrantingStrategy.hashCode() : 0); result = 31 * result + ((this.aces != null) ? this.aces.hashCode() : 0); result = 31 * result + this.objectIdentity.hashCode(); result = 31 * result + this.id.hashCode(); result = 31 * result + ((this.owner != null) ? this.owner.hashCode() : 0); result = 31 * result + ((this.loadedSids != null) ? this.loadedSids.hashCode() : 0); result = 31 * result + (this.entriesInheriting ? 1 : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AclImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("objectIdentity: ").append(this.objectIdentity).append("; "); sb.append("owner: ").append(this.owner).append("; "); int count = 0; for (AccessControlEntry ace : this.aces) {
count++; if (count == 1) { sb.append("\n"); } sb.append(ace).append("\n"); } if (count == 0) { sb.append("no ACEs; "); } sb.append("inheriting: ").append(this.entriesInheriting).append("; "); sb.append("parent: ").append((this.parentAcl == null) ? "Null" : this.parentAcl.getObjectIdentity().toString()); sb.append("; "); sb.append("aclAuthorizationStrategy: ").append(this.aclAuthorizationStrategy).append("; "); sb.append("permissionGrantingStrategy: ").append(this.permissionGrantingStrategy); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AclImpl.java
1
请完成以下Java代码
public TenantQuery tenantId(String id) { ensureNotNull("tenant ud", id); this.id = id; return this; } public TenantQuery tenantIdIn(String... ids) { ensureNotNull("tenant ids", (Object[]) ids); this.ids = ids; return this; } public TenantQuery tenantName(String name) { ensureNotNull("tenant name", name); this.name = name; return this; } public TenantQuery tenantNameLike(String nameLike) { ensureNotNull("tenant name like", nameLike); this.nameLike = nameLike; return this; } public TenantQuery userMember(String userId) { ensureNotNull("user id", userId); this.userId = userId; return this; } public TenantQuery groupMember(String groupId) { ensureNotNull("group id", groupId); this.groupId = groupId; return this; } public TenantQuery includingGroupsOfUser(boolean includingGroups) { this.includingGroups = includingGroups; return this; } //sorting //////////////////////////////////////////////////////// public TenantQuery orderByTenantId() {
return orderBy(TenantQueryProperty.GROUP_ID); } public TenantQuery orderByTenantName() { return orderBy(TenantQueryProperty.NAME); } //getters //////////////////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String[] getIds() { return ids; } public String getUserId() { return userId; } public String getGroupId() { return groupId; } public boolean isIncludingGroups() { return includingGroups; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TenantQueryImpl.java
1
请完成以下Java代码
private void executeNow0( @NonNull final Object model, @NonNull final Pointcut pointcut, final int timing) throws IllegalAccessException, InvocationTargetException { final Method method = pointcut.getMethod(); // Make sure the method is accessible if (!method.isAccessible()) { method.setAccessible(true); } final Stopwatch stopwatch = Stopwatch.createStarted(); if (pointcut.isMethodRequiresTiming()) { final Object timingParam = pointcut.convertToMethodTimingParameterType(timing); method.invoke(annotatedObject, model, timingParam);
} else { method.invoke(annotatedObject, model); } logger.trace("Executed in {}: {} (timing={}) on {}", stopwatch, pointcut, timing, model); } /** * @return true if timing is change (before, after) */ private static boolean isTimingChange(final int timing) { return ModelValidator.TYPE_BEFORE_CHANGE == timing || ModelValidator.TYPE_AFTER_CHANGE == timing || ModelValidator.TYPE_AFTER_CHANGE_REPLICATION == timing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AnnotatedModelInterceptor.java
1
请完成以下Java代码
public String getProcessMsg() { return m_processMsg; } // getProcessMsg @Override public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID @Override public BigDecimal getApprovalAmt() { // TODO Auto-generated method stub return null; } @Override
public int getC_Currency_ID() { // TODO Auto-generated method stub return 0; } /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { final String docStatus = getDocStatus(); return DOCSTATUS_Completed.equals(docStatus) || DOCSTATUS_Closed.equals(docStatus) || DOCSTATUS_Reversed.equals(docStatus); } } // MDDOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\model\MDDOrder.java
1
请完成以下Java代码
public static ColumnNameFQ ofTableAndColumnName(@NonNull final TableName tableName, @NonNull final ColumnName columnName) { return new ColumnNameFQ(tableName, columnName); } private ColumnNameFQ(@NonNull final TableName tableName, @NonNull final ColumnName columnName) { this.tableName = tableName; this.columnName = columnName; } @Override @Deprecated public String toString() { return getAsString(); } public String getAsString() { return tableName.getAsString() + "." + columnName.getAsString(); } public static TableName extractSingleTableName(final ColumnNameFQ... columnNames) { if (columnNames == null || columnNames.length == 0) { throw new AdempiereException("Cannot extract table name from null/empty column names array"); } TableName singleTableName = null; for (final ColumnNameFQ columnNameFQ : columnNames) {
if (columnNameFQ == null) { continue; } else if (singleTableName == null) { singleTableName = columnNameFQ.getTableName(); } else if (!TableName.equals(singleTableName, columnNameFQ.getTableName())) { throw new AdempiereException("More than one table name found in " + Arrays.asList(columnNames)); } } if (singleTableName == null) { throw new AdempiereException("Cannot extract table name from null/empty column names array: " + Arrays.asList(columnNames)); } return singleTableName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\ColumnNameFQ.java
1
请完成以下Java代码
public static BatchExecutorException findBatchExecutorException(PersistenceException exception) { Throwable cause = exception; do { if (cause instanceof BatchExecutorException) { return (BatchExecutorException) cause; } cause = cause.getCause(); } while (cause != null); return null; } /** * Pass logic, which directly calls MyBatis API. In case a MyBatis exception is thrown, it is * wrapped into a {@link ProcessEngineException} and never propagated directly to an Engine API * call. In some cases, the top-level exception and its message are shown as a response body in * the REST API. Wrapping all MyBatis API calls in our codebase makes sure that the top-level * exception is always a {@link ProcessEngineException} with a generic message. Like this, SQL * details are never disclosed to potential attackers. * * @param supplier which calls MyBatis API * @param <T> is the type of the return value
* @return the value returned by the supplier * @throws ProcessEngineException which wraps the actual exception */ public static <T> T doWithExceptionWrapper(Supplier<T> supplier) { try { return supplier.get(); } catch (Exception ex) { throw wrapPersistenceException(ex); } } public static ProcessEnginePersistenceException wrapPersistenceException(Exception ex) { return new ProcessEnginePersistenceException(PERSISTENCE_EXCEPTION_MESSAGE, ex); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ExceptionUtil.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache(); ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); ensureNotNull("Process Definition '" + processDefinitionId + "' not found", "processDefinition", processDefinition); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadProcessDefinition(processDefinition); } StartFormHandler startFormHandler = processDefinition.getStartFormHandler(); if (startFormHandler == null) { return null; } FormEngine formEngine = Context .getProcessEngineConfiguration() .getFormEngines()
.get(formEngineName); ensureNotNull("No formEngine '" + formEngineName + "' defined process engine configuration", "formEngine", formEngine); StartFormData startForm = startFormHandler.createStartFormData(processDefinition); Object renderedStartForm = null; try { renderedStartForm = formEngine.renderStartForm(startForm); } catch (ScriptEvaluationException e) { LOG.exceptionWhenStartFormScriptEvaluation(processDefinitionId, e); } return renderedStartForm; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetRenderedStartFormCmd.java
1
请完成以下Java代码
public boolean isExtended() { return extensionId != null && !extensionId.isEmpty(); } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public boolean hasBoundaryErrorEvents() { if (this.boundaryEvents != null && !this.boundaryEvents.isEmpty()) { return this.boundaryEvents.stream().anyMatch(boundaryEvent -> boundaryEvent.hasErrorEventDefinition()); } return false; } public ServiceTask clone() { ServiceTask clone = new ServiceTask(); clone.setValues(this); return clone; } public void setValues(ServiceTask otherElement) { super.setValues(otherElement); setImplementation(otherElement.getImplementation()); setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName()); setType(otherElement.getType()); setOperationRef(otherElement.getOperationRef()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); fieldExtensions = new ArrayList<FieldExtension>(); if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherElement.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } customProperties = new ArrayList<CustomProperty>(); if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) { for (CustomProperty property : otherElement.getCustomProperties()) { customProperties.add(property.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ServiceTask.java
1
请完成以下Java代码
public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType) { if (actionType == CopyPasteActionType.Copy) { return hasTextToCopy(); } else if (actionType == CopyPasteActionType.Cut) { return isEditable() && hasTextToCopy(); } else if (actionType == CopyPasteActionType.Paste) { return isEditable(); } else if (actionType == CopyPasteActionType.SelectAll) { return !isEmpty(); } else { return false; } } @Override public void executeCopyPasteAction(final CopyPasteActionType actionType) { if (actionType == CopyPasteActionType.Cut) { doCut(); } else if (actionType == CopyPasteActionType.Copy) { doCopy(); } else if (actionType == CopyPasteActionType.Paste) { doPaste(); } else if (actionType == CopyPasteActionType.SelectAll) { doSelectAll(); } } private final boolean isEditable() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return false; } return textComponent.isEditable() && textComponent.isEnabled(); } private final boolean hasTextToCopy() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return false; } // Document document = textComponent.getDocument(); // final JComboBox<?> comboBox = getComboBox(); // final ComboBoxEditor editor = comboBox.getEditor(); // comboBox.getClass().getMethod("getDisplay").invoke(comboBox); final String selectedText = textComponent.getSelectedText(); return selectedText != null && !selectedText.isEmpty(); } private final boolean isEmpty() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return false;
} final String text = textComponent.getText(); return Check.isEmpty(text, false); } private void doCopy() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return; } textComponent.copy(); } private void doCut() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return; } textComponent.cut(); } private void doPaste() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return; } textComponent.paste(); } private void doSelectAll() { final JTextComponent textComponent = getTextComponent(); if (textComponent == null) { return; } // NOTE: we need to request focus first because it seems in some case the code below is not working when the component does not have the focus. textComponent.requestFocus(); textComponent.selectAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JComboBoxCopyPasteSupportEditor.java
1
请完成以下Java代码
public void setResources(Map<String, ResourceEntity> resources) { this.resources = resources; } public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } public boolean isNew() { return isNew; } public void setNew(boolean isNew) { this.isNew = isNew; } public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public Integer getVersion() { return version; }
public void setVersion(Integer version) { this.version = version; } public String getProjectReleaseVersion() { return projectReleaseVersion; } public void setProjectReleaseVersion(String projectReleaseVersion) { this.projectReleaseVersion = projectReleaseVersion; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "DeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java
1
请完成以下Java代码
public DocumentLayoutElementLineDescriptor build() { final DocumentLayoutElementLineDescriptor result = new DocumentLayoutElementLineDescriptor(this); logger.trace("Built {} for {}", result, this); return result; } private List<DocumentLayoutElementDescriptor> buildElements() { return elementsBuilders .stream() .filter(elementBuilder -> checkValid(elementBuilder)) .map(elementBuilder -> elementBuilder.build()) .filter(element -> checkValid(element)) .collect(GuavaCollectors.toImmutableList()); } private final boolean checkValid(final DocumentLayoutElementDescriptor.Builder elementBuilder) { if (elementBuilder.isConsumed()) { logger.trace("Skip adding {} to {} because it's already consumed", elementBuilder, this); return false; } if (elementBuilder.isEmpty()) { logger.trace("Skip adding {} to {} because it's empty", elementBuilder, this); return false; } return true; } private final boolean checkValid(final DocumentLayoutElementDescriptor element) { if (element.isEmpty()) { logger.trace("Skip adding {} to {} because it does not have fields", element, this); return false; } return true; } public Builder setInternalName(final String internalName) {
this.internalName = internalName; return this; } public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder) { elementsBuilders.add(elementBuilder); return this; } public boolean hasElements() { return !elementsBuilders.isEmpty(); } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementsBuilders.stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementLineDescriptor.java
1
请完成以下Java代码
PaySelectionLineCandidate build() { return new PaySelectionLineCandidate(this); } public String getPaymentRule() { Check.assumeNotNull(paymentRule, "paymentRule not null"); return paymentRule; } public Builder setPaymentRule(final String paymentRule) { this.paymentRule = paymentRule; return this; } public Builder setInvoiceId(final @Nullable InvoiceId invoiceId) { this.invoiceId = invoiceId; return this; } public Builder setOrderPayScheduleId(final @Nullable OrderPayScheduleId orderPayScheduleId) { this.orderPayScheduleId = orderPayScheduleId; return this; } public Builder setOrderId(final @Nullable OrderId orderId) { this.orderId = orderId; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { this.isSOTrx = isSOTrx; return this; } public boolean isSOTrx() { return isSOTrx; } public BPartnerId getBPartnerId() { return bpartnerId; } public Builder setBPartnerId(final BPartnerId bpartnerId) { this.bpartnerId = bpartnerId; return this; } public @Nullable BankAccountId getBPartnerBankAccountId() { return bpBankAccountId; } public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId) { this.bpBankAccountId = bpBankAccountId; return this; } public BigDecimal getOpenAmt() { return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO); } public Builder setOpenAmt(final BigDecimal openAmt)
{ this._openAmt = openAmt; return this; } public BigDecimal getPayAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(discountAmt); } public BigDecimal getDiscountAmt() { return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO); } public Builder setDiscountAmt(final BigDecimal discountAmt) { this._discountAmt = discountAmt; return this; } public BigDecimal getDifferenceAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal payAmt = getPayAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(payAmt).subtract(discountAmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java
1
请完成以下Java代码
public class ClusterAppAssignResultVO { private Set<String> failedServerSet; private Set<String> failedClientSet; private Integer totalCount; public Set<String> getFailedServerSet() { return failedServerSet; } public ClusterAppAssignResultVO setFailedServerSet(Set<String> failedServerSet) { this.failedServerSet = failedServerSet; return this; } public Set<String> getFailedClientSet() { return failedClientSet; } public ClusterAppAssignResultVO setFailedClientSet(Set<String> failedClientSet) { this.failedClientSet = failedClientSet; return this; } public Integer getTotalCount() { return totalCount; }
public ClusterAppAssignResultVO setTotalCount(Integer totalCount) { this.totalCount = totalCount; return this; } @Override public String toString() { return "ClusterAppAssignResultVO{" + "failedServerSet=" + failedServerSet + ", failedClientSet=" + failedClientSet + ", totalCount=" + totalCount + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\ClusterAppAssignResultVO.java
1
请在Spring Boot框架中完成以下Java代码
public List<UmsRole> getRoleList(Long adminId) { return adminRoleRelationDao.getRoleList(adminId); } @Override public List<UmsResource> getResourceList(Long adminId) { //先从缓存中获取数据 List<UmsResource> resourceList = getCacheService().getResourceList(adminId); if(CollUtil.isNotEmpty(resourceList)){ return resourceList; } //缓存中没有从数据库中获取 resourceList = adminRoleRelationDao.getResourceList(adminId); if(CollUtil.isNotEmpty(resourceList)){ //将数据库中的数据存入缓存中 getCacheService().setResourceList(adminId,resourceList); } return resourceList; } @Override public int updatePassword(UpdateAdminPasswordParam param) { if(StrUtil.isEmpty(param.getUsername()) ||StrUtil.isEmpty(param.getOldPassword()) ||StrUtil.isEmpty(param.getNewPassword())){ return -1; } UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(param.getUsername()); List<UmsAdmin> adminList = adminMapper.selectByExample(example); if(CollUtil.isEmpty(adminList)){ return -2; } UmsAdmin umsAdmin = adminList.get(0); if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){ return -3; } umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword())); adminMapper.updateByPrimaryKey(umsAdmin); getCacheService().delAdmin(umsAdmin.getId()); return 1; }
@Override public UserDetails loadUserByUsername(String username){ //获取用户信息 UmsAdmin admin = getAdminByUsername(username); if (admin != null) { List<UmsResource> resourceList = getResourceList(admin.getId()); return new AdminUserDetails(admin,resourceList); } throw new UsernameNotFoundException("用户名或密码错误"); } @Override public UmsAdminCacheService getCacheService() { return SpringUtil.getBean(UmsAdminCacheService.class); } @Override public void logout(String username) { //清空缓存中的用户相关数据 UmsAdmin admin = getCacheService().getAdmin(username); getCacheService().delAdmin(admin.getId()); getCacheService().delResourceList(admin.getId()); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsAdminServiceImpl.java
2
请完成以下Java代码
public class EventSubscriptionJobDeclaration extends JobDeclaration<EventSubscriptionEntity, MessageEntity> { private static final long serialVersionUID = 1L; protected EventSubscriptionDeclaration eventSubscriptionDeclaration; public EventSubscriptionJobDeclaration(EventSubscriptionDeclaration eventSubscriptionDeclaration) { super(ProcessEventJobHandler.TYPE); EnsureUtil.ensureNotNull("eventSubscriptionDeclaration", eventSubscriptionDeclaration); this.eventSubscriptionDeclaration = eventSubscriptionDeclaration; } protected MessageEntity newJobInstance(EventSubscriptionEntity eventSubscription) { MessageEntity message = new MessageEntity(); // initialize job message.setActivityId(eventSubscription.getActivityId()); message.setExecutionId(eventSubscription.getExecutionId()); message.setProcessInstanceId(eventSubscription.getProcessInstanceId()); ProcessDefinitionEntity processDefinition = eventSubscription.getProcessDefinition(); if (processDefinition != null) { message.setProcessDefinitionId(processDefinition.getId()); message.setProcessDefinitionKey(processDefinition.getKey()); } // TODO: support payload // if(payload != null) { // message.setEventPayload(payload); // } return message; } public String getEventType() { return eventSubscriptionDeclaration.getEventType(); } public String getEventName() { return eventSubscriptionDeclaration.getUnresolvedEventName(); } public String getActivityId() { return eventSubscriptionDeclaration.getActivityId(); }
protected ExecutionEntity resolveExecution(EventSubscriptionEntity context) { return context.getExecution(); } protected JobHandlerConfiguration resolveJobHandlerConfiguration(EventSubscriptionEntity context) { return new EventSubscriptionJobConfiguration(context.getId()); } @SuppressWarnings("unchecked") public static List<EventSubscriptionJobDeclaration> getDeclarationsForActivity(PvmActivity activity) { Object result = activity.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_JOB_DECLARATION); if (result != null) { return (List<EventSubscriptionJobDeclaration>) result; } else { return Collections.emptyList(); } } /** * Assumes that an activity has at most one declaration of a certain eventType. */ public static EventSubscriptionJobDeclaration findDeclarationForSubscription(EventSubscriptionEntity eventSubscription) { List<EventSubscriptionJobDeclaration> declarations = getDeclarationsForActivity(eventSubscription.getActivity()); for (EventSubscriptionJobDeclaration declaration : declarations) { if (declaration.getEventType().equals(eventSubscription.getEventType())) { return declaration; } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\EventSubscriptionJobDeclaration.java
1
请完成以下Java代码
public static String processStatement (String sqlStatement, boolean allowDML) { if (sqlStatement == null) return ""; StringBuffer sb = new StringBuffer(); char[] chars = sqlStatement.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isWhitespace(c)) sb.append(' '); else sb.append(c); } String sql = sb.toString().trim(); if (sql.length() == 0) return ""; // StringBuffer result = new StringBuffer("SQL> ") .append(sql) .append(Env.NL); if (!allowDML) { boolean error = false; String SQL = sql.toUpperCase(); for (int i = 0; i < DML_KEYWORDS.length; i++) { if (SQL.startsWith(DML_KEYWORDS[i] + " ") || SQL.indexOf(" " + DML_KEYWORDS[i] + " ") != -1 || SQL.indexOf("(" + DML_KEYWORDS[i] + " ") != -1) { result.append("===> ERROR: Not Allowed Keyword ") .append(DML_KEYWORDS[i]) .append(Env.NL); error = true; } } if (error) return result.toString(); } // !allowDML // Process Connection conn = DB.createConnection(true, Connection.TRANSACTION_READ_COMMITTED); Statement stmt = null;
try { stmt = conn.createStatement(); boolean OK = stmt.execute(sql); int count = stmt.getUpdateCount(); if (count == -1) { result.append("---> ResultSet"); } else result.append("---> Result=").append(count); } catch (SQLException e) { log.error("process statement: " + sql + " - " + e.toString()); result.append("===> ").append(e.toString()); } // Clean up try { stmt.close(); } catch (SQLException e1) { log.error("processStatement - close statement", e1); } stmt = null; try { conn.close(); } catch (SQLException e2) { log.error("processStatement - close connection", e2); } conn = null; // result.append(Env.NL); return result.toString(); } // processStatement } // VSQLProcess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VSQLProcess.java
1
请完成以下Java代码
public TaskCompletionBuilder variables(Map<String, Object> variables) { this.variables = variables; return this; } @Override public TaskCompletionBuilder variablesLocal(Map<String, Object> variablesLocal) { this.variablesLocal = variablesLocal; return this; } @Override public TaskCompletionBuilder transientVariables(Map<String, Object> transientVariables) { this.transientVariables = transientVariables; return this; } @Override public TaskCompletionBuilder transientVariablesLocal(Map<String, Object> transientVariablesLocal) { this.transientVariablesLocal = transientVariablesLocal; return this; } @Override public TaskCompletionBuilder variable(String variableName, Object variableValue) { if (this.variables == null) { this.variables = new HashMap<>(); } this.variables.put(variableName, variableValue); return this; } @Override public TaskCompletionBuilder variableLocal(String variableName, Object variableValue) { if (this.variablesLocal == null) { this.variablesLocal = new HashMap<>(); } this.variablesLocal.put(variableName, variableValue); return this; } @Override public TaskCompletionBuilder transientVariable(String variableName, Object variableValue) { if (this.transientVariables == null) { this.transientVariables = new HashMap<>(); } this.transientVariables.put(variableName, variableValue); return this; } @Override public TaskCompletionBuilder transientVariableLocal(String variableName, Object variableValue) { if (this.transientVariablesLocal == null) {
this.transientVariablesLocal = new HashMap<>(); } this.transientVariablesLocal.put(variableName, variableValue); return this; } @Override public TaskCompletionBuilder taskId(String id) { this.taskId = id; return this; } @Override public TaskCompletionBuilder formDefinitionId(String formDefinitionId) { this.formDefinitionId = formDefinitionId; return this; } @Override public TaskCompletionBuilder outcome(String outcome) { this.outcome = outcome; return this; } protected void completeTask() { this.commandExecutor.execute(new CompleteTaskCmd(this.taskId, variables, variablesLocal, transientVariables, transientVariablesLocal)); } protected void completeTaskWithForm() { this.commandExecutor.execute(new CompleteTaskWithFormCmd(this.taskId, formDefinitionId, outcome, variables, variablesLocal, transientVariables, transientVariablesLocal)); } @Override public void complete() { if (this.formDefinitionId != null) { completeTaskWithForm(); } else { completeTask(); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\task\TaskCompletionBuilderImpl.java
1
请完成以下Java代码
public class TbGetCustomerAttributeNode extends TbAbstractGetEntityDataNode<CustomerId> { @Override protected TbGetEntityDataNodeConfiguration loadNodeConfiguration(TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbGetEntityDataNodeConfiguration.class); checkIfMappingIsNotEmptyOrElseThrow(config.getDataMapping()); checkDataToFetchSupportedOrElseThrow(config.getDataToFetch()); return config; } @Override protected ListenableFuture<CustomerId> findEntityAsync(TbContext ctx, EntityId originator) { if (originator.getEntityType() == EntityType.CUSTOMER) { return immediateFuture((CustomerId) originator); } return ctx.getEntityService().fetchEntityCustomerIdAsync(ctx.getTenantId(), originator) .transform(customerIdOpt -> {
if (customerIdOpt.isEmpty()) { throw new NoSuchElementException("Originator not found"); } if (customerIdOpt.get().isNullUid()) { throw new IllegalStateException("Originator is not assigned to any customer"); } return customerIdOpt.get(); }, ctx.getDbCallbackExecutor()); } @Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { return fromVersion == 0 ? upgradeToUseFetchToAndDataToFetch(oldConfiguration) : new TbPair<>(false, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbGetCustomerAttributeNode.java
1
请完成以下Java代码
public GridFieldVOsLoader setWindowNo(final int windowNo) { _windowNo = windowNo; return this; } private int getWindowNo() { return _windowNo; } public GridFieldVOsLoader setTabNo(final int tabNo) { _tabNo = tabNo; return this; } private int getTabNo() { return _tabNo; } public GridFieldVOsLoader setAdWindowId(@Nullable final AdWindowId adWindowId) { _adWindowId = adWindowId; return this; } private AdWindowId getAD_Window_ID() { return _adWindowId; } public GridFieldVOsLoader setAD_Tab_ID(final int AD_Tab_ID) { _adTabId = AD_Tab_ID; return this; } public GridFieldVOsLoader setTemplateTabId(int templateTabId) { this._templateTabId = templateTabId; return this; } private int getAD_Tab_ID() { return _adTabId; } private int getTemplateTabIdEffective() { return _templateTabId > 0 ? _templateTabId : getAD_Tab_ID(); } public GridFieldVOsLoader setTabIncludeFiltersStrategy(@NonNull final TabIncludeFiltersStrategy tabIncludeFiltersStrategy) {
this.tabIncludeFiltersStrategy = tabIncludeFiltersStrategy; return this; } public GridFieldVOsLoader setTabReadOnly(final boolean tabReadOnly) { _tabReadOnly = tabReadOnly; return this; } private boolean isTabReadOnly() { return _tabReadOnly; } public GridFieldVOsLoader setLoadAllLanguages(final boolean loadAllLanguages) { _loadAllLanguages = loadAllLanguages; return this; } private boolean isLoadAllLanguages() { return _loadAllLanguages; } public GridFieldVOsLoader setApplyRolePermissions(final boolean applyRolePermissions) { this._applyRolePermissions = applyRolePermissions; return this; } private boolean isApplyRolePermissions() { return _applyRolePermissions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVOsLoader.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { provideHistoryCleanupStrategy(commandContext); checkQueryOk(); return commandContext .getHistoricDecisionInstanceManager() .findCleanableHistoricDecisionInstancesReportCountByCriteria(this); } @Override public List<CleanableHistoricDecisionInstanceReportResult> executeList(CommandContext commandContext, Page page) { provideHistoryCleanupStrategy(commandContext); checkQueryOk(); return commandContext .getHistoricDecisionInstanceManager() .findCleanableHistoricDecisionInstancesReportByCriteria(this, page); } public String[] getDecisionDefinitionIdIn() { return decisionDefinitionIdIn; } public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) { this.decisionDefinitionIdIn = decisionDefinitionIdIn; } public String[] getDecisionDefinitionKeyIn() { return decisionDefinitionKeyIn; } public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn;
} public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isCompact() { return isCompact; } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricDecisionInstanceReportImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class XmlProlog { /** "package" */ @Nullable XmlSoftware pkg; @NonNull XmlSoftware generator; public XmlProlog withMod(@Nullable PrologMod prologMod) { if (prologMod == null) { return this; } return toBuilder()
.pkg(pkg.withMod(prologMod.getPkgMod())) .pkg(generator.withMod(prologMod.getGeneratorMod())) .build(); } @Value @Builder public static class PrologMod { @Nullable SoftwareMod pkgMod; @Nullable SoftwareMod generatorMod; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\XmlProlog.java
2
请完成以下Java代码
public class AmountType3Choice { @XmlElement(name = "InstdAmt") protected ActiveOrHistoricCurrencyAndAmount instdAmt; @XmlElement(name = "EqvtAmt") protected EquivalentAmount2 eqvtAmt; /** * Gets the value of the instdAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getInstdAmt() { return instdAmt; } /** * Sets the value of the instdAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setInstdAmt(ActiveOrHistoricCurrencyAndAmount value) { this.instdAmt = value; }
/** * Gets the value of the eqvtAmt property. * * @return * possible object is * {@link EquivalentAmount2 } * */ public EquivalentAmount2 getEqvtAmt() { return eqvtAmt; } /** * Sets the value of the eqvtAmt property. * * @param value * allowed object is * {@link EquivalentAmount2 } * */ public void setEqvtAmt(EquivalentAmount2 value) { this.eqvtAmt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\AmountType3Choice.java
1
请完成以下Java代码
public static Builder builder() { return new Builder(); } /** * Constructs a new {@link Builder} with the provided claims. * @param claims the claims to initialize the builder * @return the {@link Builder} */ public static Builder withClaims(Map<String, Object> claims) { Assert.notEmpty(claims, "claims cannot be empty"); return new Builder().claims((c) -> c.putAll(claims)); } /** * Helps configure an {@link OAuth2AuthorizationServerMetadata}. */ public static final class Builder extends AbstractBuilder<OAuth2AuthorizationServerMetadata, Builder> { private Builder() { } /**
* Validate the claims and build the {@link OAuth2AuthorizationServerMetadata}. * <p> * The following claims are REQUIRED: {@code issuer}, * {@code authorization_endpoint}, {@code token_endpoint} and * {@code response_types_supported}. * @return the {@link OAuth2AuthorizationServerMetadata} */ @Override public OAuth2AuthorizationServerMetadata build() { validate(); return new OAuth2AuthorizationServerMetadata(getClaims()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationServerMetadata.java
1
请完成以下Java代码
public HistoricActivityStatisticsQuery startedBefore(Date date) { startedBefore = date; return this; } @Override public HistoricActivityStatisticsQuery finishedAfter(Date date) { finishedAfter = date; return this; } @Override public HistoricActivityStatisticsQuery finishedBefore(Date date) { finishedBefore = date; return this; } @Override public HistoricActivityStatisticsQuery processInstanceIdIn(String... processInstanceIds) { ensureNotNull("processInstanceIds", (Object[]) processInstanceIds); this.processInstanceIds = processInstanceIds; return this; } public HistoricActivityStatisticsQuery orderByActivityId() { return orderBy(HistoricActivityStatisticsQueryProperty.ACTIVITY_ID_); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricStatisticsManager() .getHistoricStatisticsCountGroupedByActivity(this); } public List<HistoricActivityStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricStatisticsManager() .getHistoricStatisticsGroupedByActivity(this, page); } protected void checkQueryOk() {
super.checkQueryOk(); ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId); } // getters ///////////////////////////////////////////////// public String getProcessDefinitionId() { return processDefinitionId; } public boolean isIncludeFinished() { return includeFinished; } public boolean isIncludeCanceled() { return includeCanceled; } public boolean isIncludeCompleteScope() { return includeCompleteScope; } public String[] getProcessInstanceIds() { return processInstanceIds; } public boolean isIncludeIncidents() { return includeIncidents; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricActivityStatisticsQueryImpl.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } public String getAddress() { return address;
} public void setAddress(String address) { this.address = address; } /** * 验证组1 */ public interface ParameterGroup1 { } /** * 验证组2 */ public interface ParameterGroup2 { } }
repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\param\InputParam.java
1
请完成以下Java代码
public class PageUtil extends cn.hutool.core.util.PageUtil { /** * List 分页 */ public static <T> List<T> paging(int page, int size , List<T> list) { int fromIndex = page * size; int toIndex = page * size + size; if(fromIndex > list.size()){ return Collections.emptyList(); } else if(toIndex >= list.size()) { return list.subList(fromIndex,list.size()); } else { return list.subList(fromIndex,toIndex); } } /** * Page 数据处理,预防redis反序列化报错 */ public static <T> PageResult<T> toPage(Page<T> page) { return new PageResult<>(page.getContent(), page.getTotalElements());
} /** * 自定义分页 */ public static <T> PageResult<T> toPage(List<T> list, long totalElements) { return new PageResult<>(list, totalElements); } /** * 返回空数据 */ public static <T> PageResult<T> noData () { return new PageResult<>(null, 0); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\PageUtil.java
1
请完成以下Java代码
public static <T> TypedSqlQueryFilter<T> of(final String sql, final List<Object> sqlParams) { return new TypedSqlQueryFilter<>(sql, sqlParams); } public static <T> TypedSqlQueryFilter<T> of(final String sql, final Object[] sqlParams) { return new TypedSqlQueryFilter<>(sql, sqlParams); } private final String sql; private final List<Object> sqlParams; private TypedSqlQueryFilter(final String sql, final Object[] sqlParams) { this(sql, sqlParams == null ? null : Arrays.asList(sqlParams)); } private TypedSqlQueryFilter(@NonNull final String sql, @Nullable final List<Object> sqlParams) { Check.assumeNotEmpty(sql, "sql not empty"); this.sql = sql; if (sqlParams == null || sqlParams.isEmpty()) { this.sqlParams = Collections.emptyList(); } else { // Take an immutable copy of given sqlParams // NOTE: we cannot use ImmutableList because it might be that some parameters are null this.sqlParams = Collections.unmodifiableList(new ArrayList<>(sqlParams)); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(sql) .add("params", sqlParams) .toString(); } @Override public int hashCode() { return Objects.hash(sql, sqlParams); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; }
if (obj instanceof TypedSqlQueryFilter) { final TypedSqlQueryFilter<?> other = (TypedSqlQueryFilter<?>)obj; return Objects.equals(sql, other.sql) && Objects.equals(sqlParams, other.sqlParams); } else { return false; } } @Override public String getSql() { return sql; } @Override public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return sqlParams; } @Override public boolean accept(final T model) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\TypedSqlQueryFilter.java
1
请完成以下Java代码
public void focusGained(FocusEvent e) { c.selectAll(); } }); } public static boolean isEmpty(Object editor) { if (editor == null) { return false; } if (editor instanceof CComboBox) { final CComboBox c = (CComboBox)editor; return c.isSelectionNone(); } else if (editor instanceof VDate) { VDate c = (VDate)editor; return c.getTimestamp() == null; } else if (editor instanceof VLookup) { VLookup c = (VLookup)editor; return c.getValue() == null; } else if (editor instanceof JTextComponent) { JTextComponent c = (JTextComponent)editor; return Check.isEmpty(c.getText(), true); } // log.warn("Component type not supported - "+editor.getClass()); return false; } public static boolean isEditable(Component c) { if (c == null) return false; if (!c.isEnabled()) return false; if (c instanceof CEditor) return ((CEditor)c).isReadWrite(); if (c instanceof JTextComponent) return ((JTextComponent)c).isEditable(); // log.warn("Unknown component type - "+c.getClass()); return false;
} public static void focusNextNotEmpty(Component component, Collection<Component> editors) { boolean found = false; Component last = null; for (Component c : editors) { last = c; if (found) { if (isEditable(c) && isEmpty(c)) { c.requestFocus(); return; } } else if (c == component) { found = true; } } // if (!found) log.warn("Component not found - "+component); if (found && last != null) last.requestFocus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\SwingFieldsUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final BookstoreService bookstoreService; public MainApplication(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { System.out.println("\nfetchBooksAndAuthorsJpql: ");
bookstoreService.fetchBooksAndAuthorsJpql() .forEach((e) -> System.out.println(e.getName() + " | " + e.getTitle())); System.out.println("\nfetchBooksAndAuthorsSql: "); bookstoreService.fetchBooksAndAuthorsSql() .forEach((e) -> System.out.println(e.getName() + " | " + e.getTitle())); System.out.println("\nfetchAuthorsAndBooksJpql: "); bookstoreService.fetchAuthorsAndBooksJpql() .forEach((e) -> System.out.println(e.getName() + " | " + e.getTitle())); System.out.println("\nfetchAuthorsAndBooksSql: "); bookstoreService.fetchAuthorsAndBooksSql() .forEach((e) -> System.out.println(e.getName() + " | " + e.getTitle())); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaLeftExcludingJoins\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public void setAD_ChangeLog_Config_ID (final int AD_ChangeLog_Config_ID) { if (AD_ChangeLog_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_ChangeLog_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_ChangeLog_Config_ID, AD_ChangeLog_Config_ID); } @Override public int getAD_ChangeLog_Config_ID() { return get_ValueAsInt(COLUMNNAME_AD_ChangeLog_Config_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setKeepChangeLogsDays (final int KeepChangeLogsDays) { set_Value (COLUMNNAME_KeepChangeLogsDays, KeepChangeLogsDays); } @Override public int getKeepChangeLogsDays() { return get_ValueAsInt(COLUMNNAME_KeepChangeLogsDays); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog_Config.java
1
请完成以下Java代码
public void remove() { if (removeFromHere) { scriptsToPrepend.remove(); } else { super.remove(); } } @Override public boolean hasNext() { return scriptsToPrepend.hasNext() || super.hasNext();
} @Override public IScript next() { final boolean hasNext = scriptsToPrepend.hasNext(); if (hasNext) { removeFromHere = true; return scriptsToPrepend.next(); } removeFromHere = false; return super.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\PrependScriptDecorator.java
1
请完成以下Java代码
public class InvoiceCandidateLockingUtil { private static final String LOCK_OWNER_PREFIX = "ICEnqueuer"; /** Lock all invoice candidates for selection and return an auto-closable lock. */ public static ILock lockInvoiceCandidatesForSelection(@NonNull final PInstanceId pinstanceId) { final ILockManager lockManager = Services.get(ILockManager.class); final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, "AD_PInstance_ID=" + pinstanceId.getRepoId()); return lockManager.lock() .setOwner(lockOwner) // allow these locks to be cleaned-up on server starts. // NOTE: when we will add the ICs to workpackages we will move the ICs to another owner and we will also set AutoCleanup=false .setAutoCleanup(true) .setFailIfAlreadyLocked(true) .setRecordsBySelection(I_C_Invoice_Candidate.class, pinstanceId)
.acquire(); } public static ILock lockInvoiceCandidates( @NonNull final Collection<I_C_Invoice_Candidate> invoiceCandidateRecords, @NonNull final String uniqueLockOwnerSuffix) { final ILockManager lockManager = Services.get(ILockManager.class); final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, assumeNotEmpty(uniqueLockOwnerSuffix, "uniqueLockOwnerSuffix")); return lockManager.lock() .setOwner(lockOwner) .setAutoCleanup(false) .setFailIfAlreadyLocked(true) .addRecordsByModel(invoiceCandidateRecords) .acquire(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\InvoiceCandidateLockingUtil.java
1
请完成以下Java代码
public static DocumentNoBuilderException wrapIfNeeded(final Throwable throwable) { if (throwable == null) { return null; } else if (throwable instanceof DocumentNoBuilderException) { return (DocumentNoBuilderException)throwable; } else { return new DocumentNoBuilderException(throwable.getLocalizedMessage(), throwable); } } private boolean skipGenerateDocumentNo = false; public DocumentNoBuilderException(final String message, final Throwable cause) { super(message, cause); } public DocumentNoBuilderException(final AdMessageKey adMessage, final Object... params) { super(adMessage, params); } // NOTE: please keep this constructor because it's used in Check.assume methods public DocumentNoBuilderException(final String message) { super(message);
} public DocumentNoBuilderException(@NonNull final ITranslatableString message) { super(message); } public DocumentNoBuilderException setSkipGenerateDocumentNo(final boolean skipGenerateDocumentNo) { this.skipGenerateDocumentNo = skipGenerateDocumentNo; return this; } public boolean isSkipGenerateDocumentNo() { return skipGenerateDocumentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\DocumentNoBuilderException.java
1
请完成以下Java代码
protected void setOnInsertOrUpdateValues(PreparedStatement ps, int i, List<AttributeKvEntity> insertEntities) throws SQLException { AttributeKvEntity kvEntity = insertEntities.get(i); ps.setObject(1, kvEntity.getId().getEntityId()); ps.setInt(2, kvEntity.getId().getAttributeType()); ps.setInt(3, kvEntity.getId().getAttributeKey()); ps.setString(4, replaceNullChars(kvEntity.getStrValue())); ps.setString(10, replaceNullChars(kvEntity.getStrValue())); if (kvEntity.getLongValue() != null) { ps.setLong(5, kvEntity.getLongValue()); ps.setLong(11, kvEntity.getLongValue()); } else { ps.setNull(5, Types.BIGINT); ps.setNull(11, Types.BIGINT); } if (kvEntity.getDoubleValue() != null) { ps.setDouble(6, kvEntity.getDoubleValue()); ps.setDouble(12, kvEntity.getDoubleValue()); } else { ps.setNull(6, Types.DOUBLE); ps.setNull(12, Types.DOUBLE); } if (kvEntity.getBooleanValue() != null) { ps.setBoolean(7, kvEntity.getBooleanValue()); ps.setBoolean(13, kvEntity.getBooleanValue()); } else { ps.setNull(7, Types.BOOLEAN); ps.setNull(13, Types.BOOLEAN); } ps.setString(8, replaceNullChars(kvEntity.getJsonValue()));
ps.setString(14, replaceNullChars(kvEntity.getJsonValue())); ps.setLong(9, kvEntity.getLastUpdateTs()); ps.setLong(15, kvEntity.getLastUpdateTs()); } @Override protected String getBatchUpdateQuery() { return BATCH_UPDATE; } @Override protected String getInsertOrUpdateQuery() { return INSERT_OR_UPDATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\attributes\AttributeKvInsertRepository.java
1
请在Spring Boot框架中完成以下Java代码
protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
2
请完成以下Java代码
protected String generateActivityInstanceId(String activityId) { int nextId = idGenerator.incrementAndGet(); String compositeId = activityId+":"+nextId; if(compositeId.length()>64) { return String.valueOf(nextId); } else { return compositeId; } } // toString ///////////////////////////////////////////////////////////////// public String toString() { if (isProcessInstanceExecution()) { return "ProcessInstance["+getToStringIdentity()+"]"; } else { return (isEventScope? "EventScope":"")+(isConcurrent? "Concurrent" : "")+(isScope() ? "Scope" : "")+"Execution["+getToStringIdentity()+"]"; } } protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } // allow for subclasses to expose a real id ///////////////////////////////// public String getId() { return String.valueOf(System.identityHashCode(this)); } // getters and setters ////////////////////////////////////////////////////// protected VariableStore<CoreVariableInstance> getVariableStore() { return variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; } @Override 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
请完成以下Java代码
public AccessPredicate and(final Predicate<? super Authentication> other) { throw fail(); } /** * @deprecated Should never be called */ @Override @Deprecated // Should never be called public AccessPredicate or(final Predicate<? super Authentication> other) { throw fail(); } /** * @deprecated Should never be called
*/ @Override @Deprecated // Should never be called public AccessPredicate negate() { throw fail(); } private UnsupportedOperationException fail() { return new UnsupportedOperationException("Not allowed for 'permit-all' access predicate"); } }; private AccessPredicates() {} }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\check\AccessPredicates.java
1
请完成以下Java代码
class CouchbaseHealth { private final DiagnosticsResult diagnostics; CouchbaseHealth(DiagnosticsResult diagnostics) { this.diagnostics = diagnostics; } void applyTo(Health.Builder builder) { builder = isCouchbaseUp(this.diagnostics) ? builder.up() : builder.down(); builder.withDetail("sdk", this.diagnostics.sdk()); builder.withDetail("endpoints", this.diagnostics.endpoints() .values() .stream() .flatMap(Collection::stream) .map(this::describe) .toList());
} private boolean isCouchbaseUp(DiagnosticsResult diagnostics) { return diagnostics.state() == ClusterState.ONLINE; } private Map<String, Object> describe(EndpointDiagnostics endpointHealth) { Map<String, Object> map = new HashMap<>(); map.put("id", endpointHealth.id()); map.put("lastActivity", endpointHealth.lastActivity()); map.put("local", endpointHealth.local()); map.put("remote", endpointHealth.remote()); map.put("state", endpointHealth.state()); map.put("type", endpointHealth.type()); return map; } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\health\CouchbaseHealth.java
1
请在Spring Boot框架中完成以下Java代码
private void initRepository(String key, RepositorySettings settings) { try { repositories.remove(key); Path directory = getRepoDirectory(settings); GitRepository repository = GitRepository.openOrClone(directory, settings, true); repositories.put(key, repository); log.info("[{}] Initialized repository", key); onUpdate(key); } catch (Throwable e) { log.error("[{}] Failed to initialize repository with settings {}", key, settings, e); } } private void onUpdate(String key) { Runnable listener = updateListeners.get(key); if (listener != null) { log.debug("[{}] Handling repository update", key); try { listener.run(); } catch (Throwable e) { log.error("[{}] Failed to handle repository update", key, e); } } }
private Path getRepoDirectory(RepositorySettings settings) { // using uri to define folder name in case repo url is changed String name = URI.create(settings.getRepositoryUri()).getPath().replaceAll("[^a-zA-Z]", ""); return Path.of(repositoriesFolder, name); } private String getBranchRef(GitRepository repository) { return "refs/remotes/origin/" + repository.getSettings().getDefaultBranch(); } @PreDestroy private void preDestroy() { executor.shutdownNow(); } }
repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\DefaultGitSyncService.java
2
请在Spring Boot框架中完成以下Java代码
public void setReplicationTypeAttr(ReplicationTypeEnum value) { this.replicationTypeAttr = value; } /** * Gets the value of the versionAttr property. * * @return * possible object is * {@link String } * */ public String getVersionAttr() { if (versionAttr == null) { return "*"; } else { return versionAttr; } } /** * Sets the value of the versionAttr property. * * @param value * allowed object is * {@link String } * */ public void setVersionAttr(String value) { this.versionAttr = value; } /** * Gets the value of the sequenceNoAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getSequenceNoAttr() { return sequenceNoAttr; } /** * Sets the value of the sequenceNoAttr property. * * @param value * allowed object is * {@link BigInteger } * */
public void setSequenceNoAttr(BigInteger value) { this.sequenceNoAttr = value; } /** * Gets the value of the trxNameAttr property. * * @return * possible object is * {@link String } * */ public String getTrxNameAttr() { return trxNameAttr; } /** * Sets the value of the trxNameAttr property. * * @param value * allowed object is * {@link String } * */ public void setTrxNameAttr(String value) { this.trxNameAttr = value; } /** * Gets the value of the adSessionIDAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getADSessionIDAttr() { return adSessionIDAttr; } /** * Sets the value of the adSessionIDAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setADSessionIDAttr(BigInteger value) { this.adSessionIDAttr = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCBPartnerProductVType.java
2
请完成以下Java代码
public class MovementUserNotificationsProducer { public static MovementUserNotificationsProducer newInstance() { return new MovementUserNotificationsProducer(); } /** Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously */ public static final Topic USER_NOTIFICATIONS_TOPIC = Topic.builder() .name("de.metas.movement.UserNotifications") .type(Type.DISTRIBUTED) .build(); // services private final transient INotificationBL notificationBL = Services.get(INotificationBL.class); private static final AdMessageKey MSG_Event_MovementGenerated = AdMessageKey.of("Event_MovementGenerated"); private MovementUserNotificationsProducer() { } public MovementUserNotificationsProducer notifyProcessed(final Collection<? extends I_M_Movement> movements) { if (movements == null || movements.isEmpty()) { return this; } postNotifications(movements.stream() .map(this::createUserNotification) .collect(ImmutableList.toImmutableList())); return this; } public final MovementUserNotificationsProducer notifyProcessed(@NonNull final I_M_Movement movement) { notifyProcessed(ImmutableList.of(movement)); return this; } private UserNotificationRequest createUserNotification(@NonNull final I_M_Movement movement) { final UserId recipientUserId = getNotificationRecipientUserId(movement); final TableRecordReference movementRef = TableRecordReference.of(movement); return newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(MSG_Event_MovementGenerated) .contentADMessageParam(movementRef) .targetAction(TargetRecordAction.of(movementRef)) .build(); }
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC); } private UserId getNotificationRecipientUserId(final I_M_Movement movement) { // // In case of reversal i think we shall notify the current user too final DocStatus docStatus = DocStatus.ofCode(movement.getDocStatus()); if (docStatus.isReversedOrVoided()) { final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user if (currentUserId > 0) { return UserId.ofRepoId(currentUserId); } return UserId.ofRepoId(movement.getUpdatedBy()); // last updated } // // Fallback: notify only the creator else { return UserId.ofRepoId(movement.getCreatedBy()); } } private void postNotifications(final List<UserNotificationRequest> notifications) { notificationBL.sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\movement\event\MovementUserNotificationsProducer.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnableHistoricTaskLogging() { return enableHistoricTaskLogging; } public TaskServiceConfiguration setEnableHistoricTaskLogging(boolean enableHistoricTaskLogging) { this.enableHistoricTaskLogging = enableHistoricTaskLogging; return this; } @Override public TaskServiceConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) { this.enableEventDispatcher = enableEventDispatcher; return this; } @Override public TaskServiceConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; return this; }
@Override public TaskServiceConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { this.eventListeners = eventListeners; return this; } @Override public TaskServiceConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } public TaskPostProcessor getTaskPostProcessor() { return taskPostProcessor; } public TaskServiceConfiguration setTaskPostProcessor(TaskPostProcessor processor) { this.taskPostProcessor = processor; return this; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\TaskServiceConfiguration.java
2
请完成以下Java代码
public HistoricDecisionInstanceQuery includeInputs() { includeInput = true; return this; } @Override public HistoricDecisionInstanceQuery includeOutputs() { includeOutputs = true; return this; } public boolean isIncludeInput() { return includeInput; } public boolean isIncludeOutputs() { return includeOutputs; } @Override public HistoricDecisionInstanceQuery disableBinaryFetching() { isByteArrayFetchingEnabled = false; return this; } @Override public HistoricDecisionInstanceQuery disableCustomObjectDeserialization() { isCustomObjectDeserializationEnabled = false; return this; } public boolean isByteArrayFetchingEnabled() { return isByteArrayFetchingEnabled; } public boolean isCustomObjectDeserializationEnabled() { return isCustomObjectDeserializationEnabled; } public String getRootDecisionInstanceId() { return rootDecisionInstanceId; } public HistoricDecisionInstanceQuery rootDecisionInstanceId(String rootDecisionInstanceId) { ensureNotNull(NotValidException.class, "rootDecisionInstanceId", rootDecisionInstanceId); this.rootDecisionInstanceId = rootDecisionInstanceId; return this;
} public boolean isRootDecisionInstancesOnly() { return rootDecisionInstancesOnly; } public HistoricDecisionInstanceQuery rootDecisionInstancesOnly() { this.rootDecisionInstancesOnly = true; return this; } @Override public HistoricDecisionInstanceQuery decisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionId", decisionRequirementsDefinitionId); this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; return this; } @Override public HistoricDecisionInstanceQuery decisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionKey", decisionRequirementsDefinitionKey); this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; return this; } public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDecisionInstanceQueryImpl.java
1
请完成以下Java代码
public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (final int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); }
@Override public org.compiere.model.I_S_Resource getWorkStation() { return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class); } @Override public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation) { set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation); } @Override public void setWorkStation_ID (final int WorkStation_ID) { if (WorkStation_ID < 1) set_Value (COLUMNNAME_WorkStation_ID, null); else set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID); } @Override public int getWorkStation_ID() { return get_ValueAsInt(COLUMNNAME_WorkStation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Candidate.java
1
请在Spring Boot框架中完成以下Java代码
public class AdTabId implements RepoIdAware { @JsonCreator public static AdTabId ofRepoId(final int repoId) { return new AdTabId(repoId); } @Nullable public static AdTabId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new AdTabId(repoId) : null; } public static int toRepoId(@Nullable final AdTabId id) { return id != null ? id.getRepoId() : -1; } int repoId;
private AdTabId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Tab_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final AdTabId id1, @Nullable final AdTabId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\AdTabId.java
2
请完成以下Java代码
static final class Range<T extends Number> { private final String value; private final T min; private final T max; private Range(String value, T min, T max) { this.value = value; this.min = min; this.max = max; } T getMin() { return this.min; } T getMax() { return this.max; }
@Override public String toString() { return this.value; } static <T extends Number & Comparable<T>> Range<T> of(String value, Function<String, T> parse) { T zero = parse.apply("0"); String[] tokens = StringUtils.commaDelimitedListToStringArray(value); T min = parse.apply(tokens[0]); if (tokens.length == 1) { Assert.state(min.compareTo(zero) > 0, "Bound must be positive."); return new Range<>(value, zero, min); } T max = parse.apply(tokens[1]); Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound."); return new Range<>(value, min, max); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\RandomValuePropertySource.java
1
请在Spring Boot框架中完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final HUEditorRow row = getSingleSelectedRowOrNull(); if (row == null) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } if (!row.isTopLevel()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a top level HU"); } final HUsToReturnViewContext viewContext = getHUsToReturnViewContext(); final HuId huId = row.getHuId(); final InOutId customerReturnsId = viewContext.getCustomerReturnsId(); if (!isValidHuForInOut(customerReturnsId, huId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("already added"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final HUEditorRow row = getSingleSelectedRow(); final HUsToReturnViewContext viewContext = getHUsToReturnViewContext(); final HuId huId = row.getHuId();
final InOutId customerReturnsId = viewContext.getCustomerReturnsId(); if (isValidHuForInOut(customerReturnsId, huId)) { repairCustomerReturnsService.prepareCloneHUAndCreateCustomerReturnLine() .customerReturnId(customerReturnsId) .productId(row.getProductId()) .qtyReturned(row.getQtyCUAsQuantity()) .cloneFromHuId(huId) .build(); } getResult().setCloseWebuiModalView(true); getView().removeHUIdsAndInvalidate(ImmutableList.of(huId)); return MSG_OK; } private boolean isValidHuForInOut(final InOutId inOutId, final HuId huId) { return repairCustomerReturnsService.isValidHuForInOut(inOutId, huId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\HUsToReturn_SelectHU.java
2
请完成以下Java代码
public class SimpleHttpCodeStatusMapper implements HttpCodeStatusMapper { private static final Map<String, Integer> DEFAULT_MAPPINGS; static { Map<String, Integer> defaultMappings = new HashMap<>(); defaultMappings.put(Status.DOWN.getCode(), WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); defaultMappings.put(Status.OUT_OF_SERVICE.getCode(), WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); DEFAULT_MAPPINGS = getUniformMappings(defaultMappings); } private final Map<String, Integer> mappings; /** * Create a new {@link SimpleHttpCodeStatusMapper} instance using default mappings. */ public SimpleHttpCodeStatusMapper() { this(null); } /** * Create a new {@link SimpleHttpCodeStatusMapper} with the specified mappings. * @param mappings the mappings to use or {@code null} to use the default mappings */ public SimpleHttpCodeStatusMapper(@Nullable Map<String, Integer> mappings) { this.mappings = CollectionUtils.isEmpty(mappings) ? DEFAULT_MAPPINGS : getUniformMappings(mappings); } @Override public int getStatusCode(Status status) { String code = getUniformCode(status.getCode()); return this.mappings.getOrDefault(code, WebEndpointResponse.STATUS_OK); } private static Map<String, Integer> getUniformMappings(Map<String, Integer> mappings) { Map<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : mappings.entrySet()) { String code = getUniformCode(entry.getKey()); if (code != null) { result.putIfAbsent(code, entry.getValue()); } } return Collections.unmodifiableMap(result); } private static @Nullable String getUniformCode(@Nullable String code) { if (code == null) { return null; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < code.length(); i++) { char ch = code.charAt(i); if (Character.isAlphabetic(ch) || Character.isDigit(ch)) { builder.append(Character.toLowerCase(ch)); } } return builder.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\SimpleHttpCodeStatusMapper.java
1
请在Spring Boot框架中完成以下Java代码
protected void configureSslContext(HttpClientProperties.Ssl ssl, SslProvider.SslContextSpec sslContextSpec) { SslProvider.ProtocolSslContextSpec clientSslContext = (serverProperties.getHttp2().isEnabled()) ? Http2SslContextSpec.forClient() : Http11SslContextSpec.forClient(); clientSslContext.configure(sslContextBuilder -> { X509Certificate[] trustedX509Certificates = getTrustedX509CertificatesForTrustManager(); SslBundle bundle = getBundle(); if (trustedX509Certificates.length > 0) { setTrustManager(sslContextBuilder, trustedX509Certificates); } else if (ssl.isUseInsecureTrustManager()) { setTrustManager(sslContextBuilder, InsecureTrustManagerFactory.INSTANCE); } else if (bundle != null) { setTrustManager(sslContextBuilder, bundle.getManagers().getTrustManagerFactory()); } try { if (bundle != null) {
sslContextBuilder.keyManager(bundle.getManagers().getKeyManagerFactory()); } else { sslContextBuilder.keyManager(getKeyManagerFactory()); } } catch (Exception e) { logger.error(e); } }); sslContextSpec.sslContext(clientSslContext) .handshakeTimeout(ssl.getHandshakeTimeout()) .closeNotifyFlushTimeout(ssl.getCloseNotifyFlushTimeout()) .closeNotifyReadTimeout(ssl.getCloseNotifyReadTimeout()); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientSslConfigurer.java
2
请完成以下Java代码
protected UpdateProcessInstanceSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); if (processDefinitionId != null) { return selectBuilder.byProcessDefinitionId(processDefinitionId); } else { // processDefinitionKey != null UpdateProcessInstanceSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); if (processDefinitionTenantId != null) { tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); } else if (processDefinitionWithoutTenantId) { tenantBuilder.processDefinitionWithoutTenantId(); } return tenantBuilder; } } protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) { UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null; if (processInstanceIds != null) { groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds); } if (processInstanceQuery != null) { if (groupBuilder == null) { groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); } else { groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); } } if (historicProcessInstanceQuery != null) {
if (groupBuilder == null) { groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); } else { groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); } } return groupBuilder; } protected int parameterCount(Object... o) { int count = 0; for (Object o1 : o) { count += (o1 != null ? 1 : 0); } return count; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateDto.java
1
请完成以下Java代码
public void setC_RfQResponseLineQty_ID (int C_RfQResponseLineQty_ID) { if (C_RfQResponseLineQty_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RfQResponseLineQty_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RfQResponseLineQty_ID, Integer.valueOf(C_RfQResponseLineQty_ID)); } /** Get RfQ Response Line Qty. @return Request for Quotation Response Line Quantity */ @Override public int getC_RfQResponseLineQty_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQResponseLineQty_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugesagter Termin. @param DatePromised Zugesagter Termin für diesen Auftrag */ @Override public void setDatePromised (java.sql.Timestamp DatePromised) { set_Value (COLUMNNAME_DatePromised, DatePromised); } /** Get Zugesagter Termin. @return Zugesagter Termin für diesen Auftrag */ @Override public java.sql.Timestamp getDatePromised () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DatePromised); } /** Set Rabatt %. @param Discount Discount in percent */ @Override public void setDiscount (java.math.BigDecimal Discount) { set_Value (COLUMNNAME_Discount, Discount); } /** Get Rabatt %. @return Discount in percent */ @Override public java.math.BigDecimal getDiscount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Preis. @param Price Price */
@Override public void setPrice (java.math.BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } /** Get Preis. @return Price */ @Override public java.math.BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zusagbar. @param QtyPromised Zusagbar */ @Override public void setQtyPromised (java.math.BigDecimal QtyPromised) { set_Value (COLUMNNAME_QtyPromised, QtyPromised); } /** Get Zusagbar. @return Zusagbar */ @Override public java.math.BigDecimal getQtyPromised () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ranking. @param Ranking Relative Rank Number */ @Override public void setRanking (int Ranking) { set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking)); } /** Get Ranking. @return Relative Rank Number */ @Override public int getRanking () { Integer ii = (Integer)get_Value(COLUMNNAME_Ranking); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty.java
1
请完成以下Java代码
public String getExpressionString() { return expressionStr; } @Override public String getFormatedExpressionString() { return parameter.toStringWithMarkers(); } @Override public Set<CtxName> getParameters() { return parametersAsCtxName; } @Override public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { try { return StringExpressionsHelper.evaluateParam(parameter, ctx, onVariableNotFound); } catch (final Exception e) {
throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } @Override public IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException { try { final String value = StringExpressionsHelper.evaluateParam(parameter, ctx, OnVariableNotFound.ReturnNoResult); if (value == null || value == EMPTY_RESULT) { return this; } return ConstantStringExpression.of(value); } catch (final Exception e) { throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SingleParameterStringExpression.java
1
请完成以下Java代码
public void registerListener(final IC_Order_CreatePOFromSOsListener listener) { listeners.add(listener); } @Override public IC_Order_CreatePOFromSOsListener getCompositeListener() { return (purchaseOrderLine, salesOrderLine) -> { for (final IC_Order_CreatePOFromSOsListener actualListener : listeners) { actualListener.afterPurchaseOrderLineCreatedBeforeSave(purchaseOrderLine, salesOrderLine); } }; } @Override public String getConfigPurchaseQtySource() {
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); // afaiu, qtyReserved would make more sense, but there seem to be problems in C_OrderLine.QtyReserved final String purchaseQtySource = sysConfigBL.getValue(SYSCONFIG_PURCHASE_QTY_SOURCE, SYSCONFIG_PURCHASE_QTY_SOURCE_DEFAULT); if (!SYSCONFIG_PURCHASE_QTY_SOURCE_DEFAULT.equalsIgnoreCase(purchaseQtySource) && !I_C_OrderLine.COLUMNNAME_QtyReserved.equalsIgnoreCase(purchaseQtySource)) { Loggables.addLog( "AD_SysConfig " + SYSCONFIG_PURCHASE_QTY_SOURCE + " has an unsupported value: " + purchaseQtySource + "; Instead we use the default value: " + SYSCONFIG_PURCHASE_QTY_SOURCE_DEFAULT); return SYSCONFIG_PURCHASE_QTY_SOURCE_DEFAULT; } return purchaseQtySource; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\po_from_so\impl\C_Order_CreatePOFromSOsBL.java
1
请完成以下Java代码
public static final boolean isNumber(final String stringToVerify) { // Null or empty strings are not numbers if (stringToVerify == null || stringToVerify.isEmpty()) { return false; } final int length = stringToVerify.length(); for (int i = 0; i < length; i++) { if (!Character.isDigit(stringToVerify.charAt(i))) { return false; } } return true; } public static final String toString(final Collection<?> collection, final String separator) { if (collection == null) { return "null";
} if (collection.isEmpty()) { return ""; } final StringBuilder sb = new StringBuilder(); for (final Object item : collection) { if (sb.length() > 0) { sb.append(separator); } sb.append(String.valueOf(item)); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\util\StringUtils.java
1
请完成以下Java代码
public class SuspendTaskCmd extends NeedsActiveTaskCmd<Void> { private static final long serialVersionUID = 1L; protected String userId; public SuspendTaskCmd(String taskId, String userId) { super(taskId); this.userId = userId; } @Override protected Void execute(CommandContext commandContext, TaskEntity task) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); Clock clock = cmmnEngineConfiguration.getClock(); Date updateTime = clock.getCurrentTime(); task.setSuspendedTime(updateTime);
task.setSuspendedBy(userId); task.setState(Task.SUSPENDED); task.setSuspensionState(SuspensionState.SUSPENDED.getStateCode()); HistoricTaskService historicTaskService = cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskService(); historicTaskService.recordTaskInfoChange(task, updateTime, cmmnEngineConfiguration); return null; } @Override protected String getSuspendedTaskExceptionPrefix() { return "Cannot suspend on"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SuspendTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { http.headers( it -> it.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("baeldung") .password("scribejava") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("baeldung_api_key") .clientSecret("baeldung_api_secret") .authorizationGrantType(AuthorizationGrantType.PASSWORD) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .scope("read") .scope("write") .clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build()) .build(); return new InMemoryRegisteredClientRepository(oidcClient); } @Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0 http // Redirect to the login page when not authenticated from the
// authorization endpoint .exceptionHandling((exceptions) -> exceptions .defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), new MediaTypeRequestMatcher(MediaType.TEXT_HTML) ) ) // Accept access tokens for User Info and/or Client Registration .oauth2ResourceServer((resourceServer) -> resourceServer .jwt(Customizer.withDefaults())); return http.build(); } @Bean @Order(2) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) // Form login handles the redirect to the login page from the // authorization server filter chain .formLogin(Customizer.withDefaults()); return http.build(); } }
repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\scribejava\oauth\AuthServiceConfig.java
2
请完成以下Java代码
public class ADHyperlinkHandler implements HyperlinkListener { private final ADHyperlinkBuilder helper = new ADHyperlinkBuilder(); @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { ADHyperlink link = helper.getADHyperlink(e.getURL().toString()); handle(link); } } private void handle(ADHyperlink link) { if (link == null) { return; } else if (ADHyperlink.Action.ShowWindow == link.getAction()) { handleShowWindow(link); } } private void handleShowWindow(ADHyperlink link) { Map<String, String> params = link.getParameters(); int AD_Table_ID = Integer.valueOf(params.get("AD_Table_ID")); if (AD_Table_ID <= 0) { return; } int adWindowId = -1; String adWindowIdStr = params.get("AD_Window_ID");
if (adWindowIdStr != null && !adWindowIdStr.isEmpty()) { adWindowId = Integer.valueOf(adWindowIdStr); } String whereClause = params.get("WhereClause"); MQuery query = new MQuery(AD_Table_ID); if (!Check.isEmpty(whereClause)) query.addRestriction(whereClause); if (adWindowId > 0) { AEnv.zoom(query, adWindowId); } else { AEnv.zoom(query); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\ADHyperlinkHandler.java
1
请完成以下Java代码
public static BigDecimal getWeightTare(final I_M_HU_PI_Version piVersion) { final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); BigDecimal weightTareTotal = BigDecimal.ZERO; final BPartnerId partnerId = null; // FIXME: get context C_BPartner for (final I_M_HU_PI_Item piItem : handlingUnitsDAO.retrievePIItems(piVersion, partnerId)) { final String itemType = piItem.getItemType(); if (!X_M_HU_PI_Item.ITEMTYPE_PackingMaterial.equals(itemType)) { continue; } final I_M_HU_PackingMaterial huPackingMaterial = piItem.getM_HU_PackingMaterial(); if (huPackingMaterial == null) { continue; } final BigDecimal weightTare = getWeightTare(huPackingMaterial); weightTareTotal = weightTareTotal.add(weightTare); } return weightTareTotal; } /** * @param huPackingMaterial * @return never returns {@code null}. */ private static BigDecimal getWeightTare(final I_M_HU_PackingMaterial huPackingMaterial) { if (!huPackingMaterial.isActive()) { return BigDecimal.ZERO; } final I_M_Product product = IHUPackingMaterialDAO.extractProductOrNull(huPackingMaterial); if (product == null) { return BigDecimal.ZERO; } final BigDecimal weightTare = product.getWeight();
return weightTare; } @Override public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_Number; } @Override public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return true; } @Override public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { final Object valueInitialDefault = null; // no initial default value return (BigDecimal)generateSeedValue(attributeSet, attribute, valueInitialDefault); } @Override protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { return !Objects.equals(valueOld, valueNew); } @Override public boolean isDisplayedUI(@NonNull final IAttributeSet attributeSet, @NonNull final I_M_Attribute attribute) { return isLUorTUorTopLevelVHU(attributeSet); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightTareAttributeValueCallout.java
1
请在Spring Boot框架中完成以下Java代码
public class HUTraceRepository { private static final Logger logger = LogManager.getLogger(HUTraceRepository.class); /** * Persists the given event.<br> * If an event with the same properties was already persisted earlier, * then that record is loaded and logged, but nothing more is done. * * @return {@code true} if a new record was inserted, {@code false} if an existing one was updated. */ public boolean addEvent(@NonNull final HUTraceEvent huTraceEvent) { final HUTraceEventQuery query = huTraceEvent.asQueryBuilder().build(); final List<HUTraceEvent> existingDbRecords = RetrieveDbRecordsUtil.query(query); final boolean inserted = existingDbRecords.isEmpty(); if (inserted) { final I_M_HU_Trace dbRecord = newInstance(I_M_HU_Trace.class); logger.debug("Found no existing M_HU_Trace record; creating new one; query={}", query); HuTraceEventToDbRecordUtil.copyToDbRecord(huTraceEvent, dbRecord); save(dbRecord); } else { Check.errorIf(existingDbRecords.size() > 1, "Expected only one M_HU_Trace record for the given query, but found {}; query={}, M_HU_Trace records={}", existingDbRecords.size(), query, existingDbRecords); HUTraceEvent existingHuTraceEvent = existingDbRecords.get(0); logger.debug("Found exiting HUTraceEvent record with ID={}; nothing to do; query={}", existingHuTraceEvent.getHuTraceEventId().getAsInt(), query);
} return inserted; } /** * Return records according to the given specification. * <p> * <b>Important:</b> if the specification is "empty", i.e. if it specifies no conditions, then return an empty list to prevent an {@code OutOfMemoryError}. */ public List<HUTraceEvent> query(@NonNull final HUTraceEventQuery query) { return RetrieveDbRecordsUtil.query(query); } /** * Similar to {@link #query(HUTraceEventQuery)}, but returns an ID that can be used with {@link IQueryBuilder#setOnlySelection(int)} to retrieve the query result. */ public PInstanceId queryToSelection(@NonNull final HUTraceEventQuery query) { return RetrieveDbRecordsUtil.queryToSelection(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\HUTraceRepository.java
2
请完成以下Java代码
public void setParentItem(final I_M_HU hu, final I_M_HU_Item parentItem) { // TODO: Skip if no actual change; shall not happen because the caller it's already checking this final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); final HuItemId parentHUItemIdOld = HuItemId.ofRepoIdOrNull(hu.getM_HU_Item_Parent_ID()); // // Perform database change db.setParentItem(hu, parentItem); // // Remove HU from included HUs list of old parent (if any) if (parentHUItemIdOld != null) { final ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(parentHUItemIdOld); if (includedHUs != null) { boolean removed = false; for (final Iterator<I_M_HU> it = includedHUs.iterator(); it.hasNext(); ) { final I_M_HU includedHU = it.next(); final HuId includedHUId = HuId.ofRepoId(includedHU.getM_HU_ID()); if (HuId.equals(includedHUId, huId)) { it.remove(); removed = true; break; } } if (!removed) { throw new HUException("Included HU not found in cached included HUs list of old parent" + "\n HU: " + Services.get(IHandlingUnitsBL.class).getDisplayName(hu) + "\n Included HUs (cached): " + includedHUs); } } } // // Add HU to include HUs list of new parent (if any) final HuItemId parentHUItemIdNew = HuItemId.ofRepoIdOrNull(hu.getM_HU_Item_Parent_ID()); if (parentHUItemIdNew != null)
{ final ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(parentHUItemIdNew); if (includedHUs != null) { boolean added = false; for (final ListIterator<I_M_HU> it = includedHUs.listIterator(); it.hasNext(); ) { final I_M_HU includedHU = it.next(); final HuId includedHUId = HuId.ofRepoId(includedHU.getM_HU_ID()); if (HuId.equals(includedHUId, huId)) { it.set(hu); added = true; break; } } if (!added) { includedHUs.add(hu); } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CachedHUAndItemsDAO.java
1
请完成以下Java代码
public DeploymentCache<AppDefinitionCacheEntry> getAppDefinitionCache() { return appDefinitionCache; } public void setAppDefinitionCache(DeploymentCache<AppDefinitionCacheEntry> appDefinitionCache) { this.appDefinitionCache = appDefinitionCache; } public AppEngineConfiguration getAppEngineConfiguration() { return appEngineConfiguration; } public void setAppEngineConfiguration(AppEngineConfiguration appEngineConfiguration) { this.appEngineConfiguration = appEngineConfiguration; } public AppDefinitionEntityManager getAppDefinitionEntityManager() { return appDefinitionEntityManager;
} public void setAppDefinitionEntityManager(AppDefinitionEntityManager appDefinitionEntityManager) { this.appDefinitionEntityManager = appDefinitionEntityManager; } public AppDeploymentEntityManager getDeploymentEntityManager() { return deploymentEntityManager; } public void setDeploymentEntityManager(AppDeploymentEntityManager deploymentEntityManager) { this.deploymentEntityManager = deploymentEntityManager; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\AppDeploymentManager.java
1
请完成以下Java代码
protected static <T> T getValueOverrideOrNull(final IModelInternalAccessor modelAccessor, final String columnName) { // // Try ColumnName_Override // e.g. for "C_Tax_ID", the C_Tax_ID_Override" will be checked { final String overrideColumnName = (columnName + COLUMNNAME_SUFFIX_Override); if (modelAccessor.hasColumnName(overrideColumnName)) { @SuppressWarnings("unchecked") final T value = (T)modelAccessor.getValue(overrideColumnName, Object.class); if (value != null) { return value; } } } // // Try ColumnName_Override_ID // e.g. for "C_Tax_ID", the C_Tax_Override_ID" will be checked if (columnName.endsWith("_ID")) { final String overrideColumnName; if (columnName.endsWith("_Value_ID")) { overrideColumnName = (columnName.substring(0, columnName.length() - 9) + COLUMNNAME_SUFFIX_Override + "_Value_ID"); } else
{ overrideColumnName = (columnName.substring(0, columnName.length() - 3) + COLUMNNAME_SUFFIX_Override + "_ID"); } if (modelAccessor.hasColumnName(overrideColumnName)) { @SuppressWarnings("unchecked") final T value = (T)modelAccessor.getValue(overrideColumnName, Object.class); return value; // might be null as well } } // No override values found => return null return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\AbstractInterfaceWrapperHelper.java
1
请完成以下Java代码
public String getComponentName() { return getName(ruleNode); } private String getName(RuleNode ruleNode) { return ruleNode != null ? ruleNode.getName() : UNKNOWN_NAME; } private TbNode initComponent(RuleNode ruleNode) throws Exception { TbNode tbNode = null; if (ruleNode != null) { Class<?> componentClazz = Class.forName(ruleNode.getType()); tbNode = (TbNode) (componentClazz.getDeclaredConstructor().newInstance()); tbNode.init(defaultCtx, new TbNodeConfiguration(ruleNode.getConfiguration())); } return tbNode; } @Override protected RuleNodeException getInactiveException() { return new RuleNodeException("Rule Node is not active! Failed to initialize.", ruleChainName, ruleNode); } private boolean isMyNodePartition() { return isMyNodePartition(this.ruleNode); } private boolean isMyNodePartition(RuleNode ruleNode) { boolean result = ruleNode == null || !ruleNode.isSingletonMode() || systemContext.getDiscoveryService().isMonolith() || defaultCtx.isLocalEntity(ruleNode.getId()); if (!result) { log.trace("[{}][{}] Is not my node partition", tenantId, entityId); } return result; } //Message will return after processing. See RuleChainActorMessageProcessor.pushToTarget. private void putToNodePartition(TbMsg source) {
TbMsg tbMsg = TbMsg.newMsg(source, source.getQueueName(), source.getRuleChainId(), entityId); TopicPartitionInfo tpi = systemContext.resolve(ServiceType.TB_RULE_ENGINE, tbMsg.getQueueName(), tenantId, ruleNode.getId()); TransportProtos.ToRuleEngineMsg toQueueMsg = TransportProtos.ToRuleEngineMsg.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setTbMsgProto(TbMsg.toProto(tbMsg)) .build(); systemContext.getClusterService().pushMsgToRuleEngine(tpi, tbMsg.getId(), toQueueMsg, null); defaultCtx.ack(source); } private void persistDebugInputIfAllowed(TbMsg msg, String fromNodeConnectionType) { if (DebugModeUtil.isDebugAllAvailable(ruleNode)) { systemContext.persistDebugInput(tenantId, entityId, msg, fromNodeConnectionType); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleNodeActorMessageProcessor.java
1
请完成以下Java代码
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID) { if (M_HU_PackingMaterial_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID); } @Override public int getM_HU_PackingMaterial_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setStackabilityFactor (final int StackabilityFactor) { set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor);
} @Override public int getStackabilityFactor() { return get_ValueAsInt(COLUMNNAME_StackabilityFactor); } @Override public void setWidth (final @Nullable BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java
1
请完成以下Java代码
public java.lang.String getOffsetName() { return get_ValueAsString(COLUMNNAME_OffsetName); } @Override public void setSQL_Select (final @Nullable java.lang.String SQL_Select) { set_Value (COLUMNNAME_SQL_Select, SQL_Select); } @Override public java.lang.String getSQL_Select() { return get_ValueAsString(COLUMNNAME_SQL_Select); } @Override public void setUOMSymbol (final @Nullable java.lang.String UOMSymbol) { set_Value (COLUMNNAME_UOMSymbol, UOMSymbol); } @Override public java.lang.String getUOMSymbol() { return get_ValueAsString(COLUMNNAME_UOMSymbol); } @Override public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID) { if (WEBUI_KPI_Field_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID); } @Override public int getWEBUI_KPI_Field_ID()
{ return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI() { return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class); } @Override public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI) { set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI_Field.java
1
请完成以下Java代码
public class DoubleDataEntry extends BasicKvEntry { private final Double value; public DoubleDataEntry(String key, Double value) { super(key); this.value = value; } @Override public DataType getDataType() { return DataType.DOUBLE; } @Override public Optional<Double> getDoubleValue() { return Optional.ofNullable(value); } @Override public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DoubleDataEntry)) return false; if (!super.equals(o)) return false;
DoubleDataEntry that = (DoubleDataEntry) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(super.hashCode(), value); } @Override public String toString() { return "DoubleDataEntry{" + "value=" + value + "} " + super.toString(); } @Override public String getValueAsString() { return Double.toString(value); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\DoubleDataEntry.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonPOSTerminal { @NonNull POSTerminalId id; @NonNull String caption; @Nullable WorkplaceId workplaceId; @NonNull String currencySymbol; int pricePrecision; int currencyPrecision; @NonNull Set<POSPaymentMethod> availablePaymentMethods; boolean cashJournalOpen; @NonNull BigDecimal cashLastBalance; @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable List<JsonProduct> products; @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable List<JsonPOSOrder> openOrders; @NonNull
public static JsonPOSTerminal from(@NonNull final POSTerminal posTerminal, @NonNull final String adLanguage) { return builderFrom(posTerminal, adLanguage).build(); } public static JsonPOSTerminalBuilder builderFrom(final @NonNull POSTerminal posTerminal, final @NonNull String adLanguage) { return JsonPOSTerminal.builder() .id(posTerminal.getId()) .caption(posTerminal.getName()) .workplaceId(posTerminal.getWorkplaceId()) .currencySymbol(posTerminal.getCurrencySymbol(adLanguage)) .pricePrecision(posTerminal.getPricePrecision().toInt()) .currencyPrecision(posTerminal.getCurrencyPrecision().toInt()) .availablePaymentMethods(posTerminal.getAvailablePaymentMethods()) .cashJournalOpen(posTerminal.isCashJournalOpen()) .cashLastBalance(posTerminal.getCashLastBalance().toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\json\JsonPOSTerminal.java
2
请在Spring Boot框架中完成以下Java代码
protected void setOwner(TenantId tenantId, EntityView entityView, IdProvider idProvider) { entityView.setTenantId(tenantId); entityView.setCustomerId(idProvider.getInternalId(entityView.getCustomerId())); } @Override protected EntityView prepare(EntitiesImportCtx ctx, EntityView entityView, EntityView old, EntityExportData<EntityView> exportData, IdProvider idProvider) { entityView.setEntityId(idProvider.getInternalId(entityView.getEntityId())); return entityView; } @Override protected EntityView saveOrUpdate(EntitiesImportCtx ctx, EntityView entityView, EntityExportData<EntityView> exportData, IdProvider idProvider, CompareResult compareResult) { return entityViewService.saveEntityView(entityView); } @Override protected void onEntitySaved(User user, EntityView savedEntityView, EntityView oldEntityView) throws ThingsboardException { tbEntityViewService.updateEntityViewAttributes(user.getTenantId(), savedEntityView, oldEntityView, user); super.onEntitySaved(user, savedEntityView, oldEntityView); } @Override protected EntityView deepCopy(EntityView entityView) { return new EntityView(entityView); }
@Override protected void cleanupForComparison(EntityView e) { super.cleanupForComparison(e); if (e.getCustomerId() != null && e.getCustomerId().isNullUid()) { e.setCustomerId(null); } } @Override public EntityType getEntityType() { return EntityType.ENTITY_VIEW; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\EntityViewImportService.java
2
请完成以下Java代码
public class MultipartServlet extends HttpServlet { private static final long serialVersionUID = 1L; private String getFileName(Part part) { for (String content : part.getHeader("content-disposition").split(";")) { if (content.trim().startsWith("filename")) return content.substring(content.indexOf("=") + 2, content.length() - 1); } return Constants.DEFAULT_FILENAME; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdir(); try { String fileName = ""; for (Part part : request.getParts()) { fileName = getFileName(part); part.write(uploadPath + File.separator + fileName); } request.setAttribute("message", "File " + fileName + " has uploaded successfully!"); } catch (FileNotFoundException fne) { request.setAttribute("message", "There was an error: " + fne.getMessage()); } getServletContext().getRequestDispatcher("/result.jsp").forward(request, response); } }
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\upload\MultipartServlet.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue private Integer id; private String name; private Long salary; public Employee() { } public Employee(Integer id, String name, Long salary) { this.id = id; this.name = name; this.salary = salary; } public Integer getId() { return id; } public void setId(Integer id) {
this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getSalary() { return salary; } public void setSalary(Long salary) { this.salary = salary; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\maxvalue\Employee.java
2
请完成以下Java代码
protected final BigDecimal calculateQtyToMove(final I_M_ReceiptSchedule rs) { final BigDecimal qtyOrdered = getQtyOrdered(rs); final BigDecimal qtyMoved = getQtyMoved(rs); BigDecimal qtyToMove = qtyOrdered.subtract(qtyMoved); // In case there is an over-delivery we don't want our QtyToMove to be negative but ZERO // qtyOrdered is not updated if receiptSchedule row is closed (isProcessed == true) if (qtyToMove.signum() <= 0 || rs.isProcessed()) { qtyToMove = BigDecimal.ZERO; } return qtyToMove; } protected final BigDecimal calculateQtyOverUnderDelivery(final I_M_ReceiptSchedule rs) { final BigDecimal qtyOrdered = getQtyOrdered(rs); final BigDecimal qtyMoved = getQtyMoved(rs); final BigDecimal qtyOverUnderDelivery = qtyMoved.subtract(qtyOrdered); // // Case: receipt schedule was marked as processed. // Now we precisely know which is the actual Over/Under Delivery. // i.e. if qtyOverUnder < 0 it means it's an under delivery (we delivered less) // but we know this for sure ONLY when receipt schedule line is closed. // Else we can consider that more receipts will come after. if (rs.isProcessed()) { return qtyOverUnderDelivery; }
// // Case: we have an Over-Delivery (i.e. we delivered more than it was required) if (qtyOverUnderDelivery.signum() > 0) { return qtyOverUnderDelivery; } // // Case: we delivered exactly what was needed else if (qtyOverUnderDelivery.signum() == 0) { return BigDecimal.ZERO; } // // Case: we have an Under-Delivery (i.e. we delivered less than it was required) // Because receipt schedule is not yet processed, we are not sure this is a true under-delivery so we consider it ZERO else { return BigDecimal.ZERO; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleQtysBL.java
1
请完成以下Java代码
public Builder setParentRowId(final DocumentId parentRowId) { this.parentRowId = parentRowId; _rowIdEffective = null; return this; } private DocumentId getParentRowId() { return parentRowId; } public boolean isRootRow() { return getParentRowId() == null; } private IViewRowType getType() { return type; } public Builder setType(final IViewRowType type) { this.type = type; return this; } public Builder setProcessed(final boolean processed) { this.processed = processed; return this; } private boolean isProcessed() { if (processed == null) { // NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example. // return DisplayType.toBoolean(values.getOrDefault("Processed", false)); return false; } else { return processed.booleanValue(); } } public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue) {
if (jsonValue == null || JSONNullValue.isNull(jsonValue)) { values.remove(fieldName); } else { values.put(fieldName, jsonValue); } return this; } private Map<String, Object> getValues() { return values; } public LookupValue getFieldValueAsLookupValue(final String fieldName) { return LookupValue.cast(values.get(fieldName)); } public Builder addIncludedRow(final IViewRow includedRow) { if (includedRows == null) { includedRows = new ArrayList<>(); } includedRows.add(includedRow); return this; } private List<IViewRow> buildIncludedRows() { if (includedRows == null || includedRows.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(includedRows); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
1
请在Spring Boot框架中完成以下Java代码
public class PPOrderCandidateToAllocate { @NonNull I_PP_Order_Candidate ppOrderCandidate; @NonNull String headerAggregationKey; @NonFinal @NonNull Quantity openQty; @NonNull public static PPOrderCandidateToAllocate of(@NonNull final I_PP_Order_Candidate candidate, @NonNull final String headerAggregationKey) { final UomId uomId = UomId.ofRepoId(candidate.getC_UOM_ID()); final Quantity openQty = Quantitys.of(candidate.getQtyToProcess(), uomId); return new PPOrderCandidateToAllocate(candidate, headerAggregationKey, openQty); }
public void subtractAllocatedQty(@NonNull final Quantity allocatedQty) { openQty = openQty.subtract(allocatedQty); if (openQty.signum() < 0) { throw new AdempiereException("This is a development error! allocatedQty cannot go beyond openQty!") .appendParametersToMessage() .setParameter(I_PP_Order_Candidate.COLUMNNAME_PP_Order_Candidate_ID, ppOrderCandidate.getPP_Order_Candidate_ID()) .setParameter("OpenQty", openQty) .setParameter("AllocatedQty", allocatedQty); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\produce\PPOrderCandidateToAllocate.java
2
请完成以下Java代码
public String getF_TAX() { return F_TAX; } public void setF_TAX(String f_TAX) { F_TAX = f_TAX; } public String getF_ISPUB() { return F_ISPUB; } public void setF_ISPUB(String f_ISPUB) { F_ISPUB = f_ISPUB; } public String getF_ALLOWADD() { return F_ALLOWADD; } public void setF_ALLOWADD(String f_ALLOWADD) { F_ALLOWADD = f_ALLOWADD; } public String getF_MEMO() { return F_MEMO; } public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_LEVEL() { return F_LEVEL; } public void setF_LEVEL(String f_LEVEL) { F_LEVEL = f_LEVEL; } public String getF_END() { return F_END; } public void setF_END(String f_END) { F_END = f_END; } public String getF_SHAREDIREC() { return F_SHAREDIREC; } public void setF_SHAREDIREC(String f_SHAREDIREC) { F_SHAREDIREC = f_SHAREDIREC; } public String getF_HISTORYID() { return F_HISTORYID; } public void setF_HISTORYID(String f_HISTORYID) { F_HISTORYID = f_HISTORYID; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_VERSION() { return F_VERSION; }
public void setF_VERSION(String f_VERSION) { F_VERSION = f_VERSION; } public String getF_ISSTD() { return F_ISSTD; } public void setF_ISSTD(String f_ISSTD) { F_ISSTD = f_ISSTD; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; } public String getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(String f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISENTERPRISES() { return F_ISENTERPRISES; } public void setF_ISENTERPRISES(String f_ISENTERPRISES) { F_ISENTERPRISES = f_ISENTERPRISES; } public String getF_ISCLEAR() { return F_ISCLEAR; } public void setF_ISCLEAR(String f_ISCLEAR) { F_ISCLEAR = f_ISCLEAR; } public String getF_PARENTID() { return F_PARENTID; } public void setF_PARENTID(String f_PARENTID) { F_PARENTID = f_PARENTID; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java
1
请完成以下Java代码
public void setTtlCdtNtries(NumberAndSumOfTransactions1 value) { this.ttlCdtNtries = value; } /** * Gets the value of the ttlDbtNtries property. * * @return * possible object is * {@link NumberAndSumOfTransactions1 } * */ public NumberAndSumOfTransactions1 getTtlDbtNtries() { return ttlDbtNtries; } /** * Sets the value of the ttlDbtNtries property. * * @param value * allowed object is * {@link NumberAndSumOfTransactions1 } * */ public void setTtlDbtNtries(NumberAndSumOfTransactions1 value) { this.ttlDbtNtries = value; } /** * Gets the value of the ttlNtriesPerBkTxCd 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 ttlNtriesPerBkTxCd property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTtlNtriesPerBkTxCd().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TotalsPerBankTransactionCode2 } * * */ public List<TotalsPerBankTransactionCode2> getTtlNtriesPerBkTxCd() { if (ttlNtriesPerBkTxCd == null) { ttlNtriesPerBkTxCd = new ArrayList<TotalsPerBankTransactionCode2>(); } return this.ttlNtriesPerBkTxCd; } }
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\TotalTransactions2.java
1
请在Spring Boot框架中完成以下Java代码
public String getShopPriceEnd() { return shopPriceEnd; } public void setShopPriceEnd(String shopPriceEnd) { this.shopPriceEnd = shopPriceEnd; } public String getTopCategoryId() { return topCategoryId; } public void setTopCategoryId(String topCategoryId) { this.topCategoryId = topCategoryId; } public String getSubCategoryId() { return subCategoryId; } public void setSubCategoryId(String subCategoryId) { this.subCategoryId = subCategoryId; } public String getBrandId() { return brandId; } public void setBrandId(String brandId) { this.brandId = brandId; } public Integer getProdStateCode() { return prodStateCode; } public void setProdStateCode(Integer prodStateCode) { this.prodStateCode = prodStateCode; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId;
} public Integer getOrderByPrice() { return orderByPrice; } public void setOrderByPrice(Integer orderByPrice) { this.orderByPrice = orderByPrice; } public Integer getOrderBySales() { return orderBySales; } public void setOrderBySales(Integer orderBySales) { this.orderBySales = orderBySales; } @Override public String toString() { return "ProdQueryReq{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", shopPriceStart='" + shopPriceStart + '\'' + ", shopPriceEnd='" + shopPriceEnd + '\'' + ", topCategoryId='" + topCategoryId + '\'' + ", subCategoryId='" + subCategoryId + '\'' + ", brandId='" + brandId + '\'' + ", prodStateCode=" + prodStateCode + ", companyId='" + companyId + '\'' + ", orderByPrice=" + orderByPrice + ", orderBySales=" + orderBySales + ", page=" + page + ", numPerPage=" + numPerPage + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdQueryReq.java
2
请完成以下Java代码
/* package */final class AutoCommitTrxListenerManager implements ITrxListenerManager { public static final transient AutoCommitTrxListenerManager instance = new AutoCommitTrxListenerManager(); private AutoCommitTrxListenerManager() { } @Override public void registerListener(@NonNull final RegisterListenerRequest listener) { execute(listener); } @Override public boolean canRegisterOnTiming(@NonNull final TrxEventTiming timing) { // any timing is accepted because we are executing directly return true; } private void execute(final RegisterListenerRequest listener) { if (!listener.isActive()) { return; // nothing to do } if (!TrxEventTiming.BEFORE_COMMIT.equals(listener.getTiming()) && !TrxEventTiming.AFTER_COMMIT.equals(listener.getTiming()) && !TrxEventTiming.AFTER_CLOSE.equals(listener.getTiming())) { return; // nothing to do } try { listener.getHandlingMethod().onTransactionEvent(ITrx.TRX_None); } catch (Exception e) { throw AdempiereException.wrapIfNeeded(e) .setParameter("listener", listener) .appendParametersToMessage(); } }
@Override public void fireBeforeCommit(final ITrx trx) { throw new UnsupportedOperationException(); } @Override public void fireAfterCommit(final ITrx trx) { throw new UnsupportedOperationException(); } @Override public void fireAfterRollback(final ITrx trx) { throw new UnsupportedOperationException(); } @Override public void fireAfterClose(ITrx trx) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AutoCommitTrxListenerManager.java
1
请完成以下Java代码
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (!invocation.getHttpRequest().isSecure()) { HttpServletResponse response = invocation.getResponse(); Assert.notNull(response, "HttpServletResponse is required"); this.entryPoint.commence(invocation.getRequest(), response); } } } } public ChannelEntryPoint getEntryPoint() { return this.entryPoint; } public String getSecureKeyword() { return this.secureKeyword;
} public void setEntryPoint(ChannelEntryPoint entryPoint) { this.entryPoint = entryPoint; } public void setSecureKeyword(String secureKeyword) { this.secureKeyword = secureKeyword; } @Override public boolean supports(ConfigAttribute attribute) { return (attribute != null) && (attribute.getAttribute() != null) && attribute.getAttribute().equals(getSecureKeyword()); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\SecureChannelProcessor.java
1
请完成以下Java代码
public void createMembership(String groupId) { ensureNotReadOnly(); groupId = PathUtil.decodePathParam(groupId); identityService.createTenantGroupMembership(resourceId, groupId); } public void deleteMembership(String groupId) { ensureNotReadOnly(); groupId = PathUtil.decodePathParam(groupId); identityService.deleteTenantGroupMembership(resourceId, groupId); } public ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); URI uri = context.getBaseUriBuilder()
.path(relativeRootResourcePath) .path(TenantRestService.PATH) .path(resourceId) .path(TenantGroupMembersResource.PATH) .build(); if (!identityService.isReadOnly() && isAuthorized(DELETE)) { dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); } if (!identityService.isReadOnly() && isAuthorized(CREATE)) { dto.addReflexiveLink(uri, HttpMethod.PUT, "create"); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\TenantGroupMembersResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Result save(@RequestParam("categoryName") String categoryName) { if (!StringUtils.hasText(categoryName)) { return ResultGenerator.genFailResult("参数异常!"); } if (categoryService.saveCategory(categoryName)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("分类名称重复"); } } /** * 分类修改 */ @RequestMapping(value = "/categories/update", method = RequestMethod.POST) @ResponseBody public Result update(@RequestParam("categoryId") Long categoryId, @RequestParam("categoryName") String categoryName) { if (!StringUtils.hasText(categoryName)) { return ResultGenerator.genFailResult("参数异常!"); } if (categoryService.updateCategory(categoryId, categoryName)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("分类名称重复"); } } /**
* 分类删除 */ @RequestMapping(value = "/categories/delete", method = RequestMethod.POST) @ResponseBody public Result delete(@RequestBody Integer[] ids) { if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!"); } if (categoryService.deleteBatchByIds(ids)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("删除失败"); } } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\CategoryController.java
2
请完成以下Java代码
public void setOnMouseDown (String script) { addAttribute ("onmousedown", script); } /** * The onmouseup event occurs when the pointing device button is released * over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseUp (String script) { addAttribute ("onmouseup", script); } /** * The onmouseover event occurs when the pointing device is moved onto an * element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOver (String script) { addAttribute ("onmouseover", script); } /** * The onmousemove event occurs when the pointing device is moved while it * is over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseMove (String script) { addAttribute ("onmousemove", script); } /** * The onmouseout event occurs when the pointing device is moved away from * an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOut (String script) { addAttribute ("onmouseout", script); } /** * The onkeypress event occurs when a key is pressed and released over an * element. This attribute may be used with most elements. * * @param script script */
public void setOnKeyPress (String script) { addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements. * * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\acronym.java
1
请完成以下Java代码
boolean isHyphenCharacter() { return this.character == '-'; } } /** * A single document within the properties file. */ static class Document { private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>(); void put(String key, OriginTrackedValue value) { if (!key.isEmpty()) {
this.values.put(key, value); } } boolean isEmpty() { return this.values.isEmpty(); } Map<String, OriginTrackedValue> asMap() { return this.values; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
1
请完成以下Java代码
private TableRecordReference getRecordReference(final CreateViewRequest request) { final TableRecordReference recordRef = request.getParameterAs(PARAM_RecordRef, TableRecordReference.class); if (recordRef == null) { throw new AdempiereException("Invalid request, parameter " + PARAM_RecordRef + " is not set: " + request); } return recordRef; } @Override public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, final ViewProfileId profileId) { final ITranslatableString caption = processDAO .retrieveProcessNameByClassIfUnique(WEBUI_C_Flatrate_DataEntry_Detail_Launcher.class) .orElse(null); return ViewLayout.builder() .setWindowId(windowId) .setCaption(caption) //.allowViewCloseAction(ViewCloseAction.CANCEL) .allowViewCloseAction(ViewCloseAction.DONE) // .setFocusOnFieldName(DataEntryDetailsRow.FIELD_Qty) .addElementsFromViewRowClassAndFieldNames( DataEntryDetailsRow.class, viewDataType, ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_Department), ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_ASI), ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_Qty), ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_UOM)) // .setAllowOpeningRowDetails(false) .build(); } @Override public WindowId getWindowId() { return WINDOW_ID; } @Override public final void put(@NonNull final IView view) { views.put(view.getViewId(), DataEntryDetailsView.cast(view)); }
@Nullable @Override public IView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { } @Override public Stream<IView> streamAllViews() { return Stream.empty(); } @Override public void invalidateView(final ViewId viewId) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\view\DataEntryDedailsViewFactory.java
1
请完成以下Java代码
public List<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getProcessDefinitionNameLike() { return processDefinitionNameLike; } public List<String> getProcessCategoryInList() { return processCategoryInList; } public List<String> getProcessCategoryNotInList() { return processCategoryNotInList; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getProcessInstanceBusinessKeyLike() { return processInstanceBusinessKeyLike; } public Date getDueDate() { return dueDate; } public Date getDueBefore() { return dueBefore; } public Date getDueAfter() { return dueAfter; } public boolean isWithoutDueDate() { return withoutDueDate; } public SuspensionState getSuspensionState() { return suspensionState; } public boolean isIncludeTaskLocalVariables() { return includeTaskLocalVariables; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isBothCandidateAndAssigned() { return bothCandidateAndAssigned; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase;
} public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
private Fact createEmptyFact(final AcctSchema as) { return new Fact(doc, as, PostingType.Actual); } /** * Calculate the tax amount part. * * @return (taxAmt / invoice grand total amount) * taxAmt */ private MoneySourceAndAcct calcAmount( final MoneySourceAndAcct taxAmt, final MoneySourceAndAcct invoiceGrandTotalAmt, final Money discountAmt, final CurrencyPrecision acctPrecision) { if (taxAmt.signum() == 0 || invoiceGrandTotalAmt.signum() == 0 || discountAmt.signum() == 0) { return taxAmt.toZero(); } final CurrencyPrecision sourcePrecision = services.getCurrencyStandardPrecision(taxAmt.getSourceCurrencyId()); return taxAmt.divide(invoiceGrandTotalAmt, CurrencyPrecision.TEN) .multiply(discountAmt.toBigDecimal()) .roundIfNeeded(sourcePrecision, acctPrecision); } private static MoneySourceAndAcct extractMoneySourceAndAcctDebit(final I_Fact_Acct factAcct, final AcctSchema as) { return extractMoneySourceAndAcct(factAcct, as, true); }
private static MoneySourceAndAcct extractMoneySourceAndAcctCredit(final I_Fact_Acct factAcct, final AcctSchema as) { return extractMoneySourceAndAcct(factAcct, as, false); } private static MoneySourceAndAcct extractMoneySourceAndAcct(final I_Fact_Acct factAcct, final AcctSchema as, boolean isDebit) { final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(factAcct.getC_AcctSchema_ID()); Check.assumeEquals(acctSchemaId, as.getId(), "acctSchema"); final CurrencyId sourceCurrencyId = CurrencyId.ofRepoId(factAcct.getC_Currency_ID()); final CurrencyId acctCurrencyId = as.getCurrencyId(); final Money source; final Money acct; if (isDebit) { source = Money.of(factAcct.getAmtSourceDr(), sourceCurrencyId); acct = Money.of(factAcct.getAmtAcctDr(), acctCurrencyId); } else { source = Money.of(factAcct.getAmtSourceCr(), sourceCurrencyId); acct = Money.of(factAcct.getAmtAcctCr(), acctCurrencyId); } return MoneySourceAndAcct.ofSourceAndAcct(source, acct); } } // Doc_AllocationTax
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_AllocationHdr.java
1
请完成以下Java代码
public Integer getBestellSupportId() { return bestellSupportId; } /** * Sets the value of the bestellSupportId property. * * @param value * allowed object is * {@link Integer } * */ public void setBestellSupportId(Integer value) { this.bestellSupportId = value; } /** * Gets the value of the auftraege 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 auftraege property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAuftraege().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BestellungAntwortAuftrag } * * */ public List<BestellungAntwortAuftrag> getAuftraege() { if (auftraege == null) { auftraege = new ArrayList<BestellungAntwortAuftrag>(); } return this.auftraege; } /** * Gets the value of the id property. * * @return * possible object is
* {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link Bestellstatus } * */ public Bestellstatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link Bestellstatus } * */ public void setStatus(Bestellstatus value) { this.status = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellstatusAntwort.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } public org.eevolution.model.I_HR_Job getNext_Job() throws RuntimeException { return (org.eevolution.model.I_HR_Job)MTable.get(getCtx(), org.eevolution.model.I_HR_Job.Table_Name) .getPO(getNext_Job_ID(), get_TrxName()); } /** Set Next Job. @param Next_Job_ID Next Job */ public void setNext_Job_ID (int Next_Job_ID) { if (Next_Job_ID < 1) set_Value (COLUMNNAME_Next_Job_ID, null); else set_Value (COLUMNNAME_Next_Job_ID, Integer.valueOf(Next_Job_ID)); } /** Get Next Job. @return Next Job */ public int getNext_Job_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Next_Job_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval
*/ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Job.java
1
请完成以下Java代码
public void setShipperGateway (final @Nullable java.lang.String ShipperGateway) { set_Value (COLUMNNAME_ShipperGateway, ShipperGateway); } @Override public java.lang.String getShipperGateway() { return get_ValueAsString(COLUMNNAME_ShipperGateway); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override
public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper.java
1
请在Spring Boot框架中完成以下Java代码
public String getTopicNamePrefix() {return TOPIC_PREFIX;} @Override public WebSocketProducer createProducer(@NonNull final WebsocketTopicName topicName) { return WorkflowLaunchersWebSocketProducer.builder() .workflowRestAPIService(workflowRestAPIService) .query(parseWorkflowLaunchersQuery(topicName)) .build(); } private WorkflowLaunchersQuery parseWorkflowLaunchersQuery(@NonNull final WebsocketTopicName topicName) { if (!topicName.startsWith(TOPIC_PREFIX)) { throw new AdempiereException("Invalid topic: " + topicName); } try { final MultiValueMap<String, String> queryParams = UriComponentsBuilder.fromUriString(topicName.getAsString()).build().getQueryParams(); return WorkflowLaunchersQuery.builder() .applicationId(extractApplicationId(queryParams)) .userId(extractUserId(queryParams)) .filterByQRCode(ScannedCode.ofNullableString(queryParams.getFirst(TOPIC_PARAM_qrCode))) .filterByDocumentNo(DocumentNoFilter.ofNullableString(queryParams.getFirst(TOPIC_PARAM_documentNo))) .filterByQtyAvailableAtPickFromLocator(StringUtils.toOptionalBoolean(queryParams.getFirst(TOPIC_PARAM_filterByQtyAvailableAtPickFromLocator)).orElseFalse()) .facetIds(extractFacetIdsFromQueryParams(queryParams)) .computeActions(true) .build(); } catch (Exception ex) { throw new AdempiereException("Invalid topic: " + topicName, ex); } } @NonNull private UserId extractUserId(final MultiValueMap<String, String> queryParams) { return StringUtils.trimBlankToOptional(queryParams.getFirst(TOPIC_PARAM_userToken)) .map(userAuthTokenService::getByToken) .map(UserAuthToken::getUserId) .orElseThrow(() -> new AdempiereException("Parameter " + TOPIC_PARAM_userToken + " is mandatory")); } @NonNull
private static MobileApplicationId extractApplicationId(final MultiValueMap<String, String> queryParams) { return StringUtils.trimBlankToOptional(queryParams.getFirst(TOPIC_PARAM_applicationId)) .map(MobileApplicationId::ofString) .orElseThrow(() -> new AdempiereException("Parameter " + TOPIC_PARAM_applicationId + " is mandatory")); } private static ImmutableSet<WorkflowLaunchersFacetId> extractFacetIdsFromQueryParams(final MultiValueMap<String, String> queryParams) throws IOException { String facetIdsStr = StringUtils.trimBlankToNull(queryParams.getFirst(TOPIC_PARAM_facetIds)); if (facetIdsStr == null) { return ImmutableSet.of(); } facetIdsStr = URLDecoder.decode(facetIdsStr, "UTF-8"); return Splitter.on(",") .trimResults() .omitEmptyStrings() .splitToList(facetIdsStr) .stream() .map(WorkflowLaunchersFacetId::fromJson) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\ws\WorkflowLaunchersWebSocketProducerFactory.java
2
请完成以下Java代码
private String getTableName(T t) { Table tableAnnotation = t.getClass().getAnnotation(Table.class); if (ObjectUtil.isNotNull(tableAnnotation)) { return StrUtil.format("`{}`", tableAnnotation.name()); } else { return StrUtil.format("`{}`", t.getClass().getName().toLowerCase()); } } /** * 获取表名 * * @return 表名 */ private String getTableName() { Table tableAnnotation = clazz.getAnnotation(Table.class); if (ObjectUtil.isNotNull(tableAnnotation)) { return StrUtil.format("`{}`", tableAnnotation.name()); } else { return StrUtil.format("`{}`", clazz.getName().toLowerCase()); } } /** * 获取列 * * @param fieldList 字段列表 * @return 列信息列表 */ private List<String> getColumns(List<Field> fieldList) { // 构造列 List<String> columnList = CollUtil.newArrayList(); for (Field field : fieldList) { Column columnAnnotation = field.getAnnotation(Column.class); String columnName; if (ObjectUtil.isNotNull(columnAnnotation)) { columnName = columnAnnotation.name(); } else { columnName = field.getName(); } columnList.add(StrUtil.format("`{}`", columnName)); } return columnList; }
/** * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列} * * @param t 对象 * @param ignoreNull 是否忽略空值 * @return 字段列表 */ private List<Field> getField(T t, Boolean ignoreNull) { // 获取所有字段,包含父类中的字段 Field[] fields = ReflectUtil.getFields(t.getClass()); // 过滤数据库中不存在的字段,以及自增列 List<Field> filterField; Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class))); // 是否过滤字段值为null的字段 if (ignoreNull) { filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList()); } else { filterField = fieldStream.collect(Collectors.toList()); } return filterField; } }
repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\dao\base\BaseDao.java
1
请完成以下Java代码
public Enumeration<String> getParameterNames() { Enumeration<String> paramaterNames = super.getParameterNames(); return new Enumeration<>() { @Override public boolean hasMoreElements() { return paramaterNames.hasMoreElements(); } @Override public String nextElement() { String name = paramaterNames.nextElement(); validateAllowedParameterName(name); return name; } }; } @Override public String[] getParameterValues(String name) { if (name != null) { validateAllowedParameterName(name); } String[] values = super.getParameterValues(name); if (values != null) { for (String value : values) { validateAllowedParameterValue(name, value); } } return values; } private void validateAllowedHeaderName(String headerNames) { if (!StrictHttpFirewall.this.allowedHeaderNames.test(headerNames)) { throw new RequestRejectedException( "The request was rejected because the header name \"" + headerNames + "\" is not allowed."); } } private void validateAllowedHeaderValue(String name, String value) { if (!StrictHttpFirewall.this.allowedHeaderValues.test(value)) { throw new RequestRejectedException("The request was rejected because the header: \"" + name + " \" has a value \"" + value + "\" that is not allowed."); }
} private void validateAllowedParameterName(String name) { if (!StrictHttpFirewall.this.allowedParameterNames.test(name)) { throw new RequestRejectedException( "The request was rejected because the parameter name \"" + name + "\" is not allowed."); } } private void validateAllowedParameterValue(String name, String value) { if (!StrictHttpFirewall.this.allowedParameterValues.test(value)) { throw new RequestRejectedException("The request was rejected because the parameter: \"" + name + " \" has a value \"" + value + "\" that is not allowed."); } } @Override public void reset() { } }; }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\StrictHttpFirewall.java
1
请在Spring Boot框架中完成以下Java代码
public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the linenumber property. * * @return * possible object is * {@link String } * */ public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property. * * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the quantityqual property. * * @return * possible object is * {@link String } * */ public String getQUANTITYQUAL() { return quantityqual; } /** * Sets the value of the quantityqual property. * * @param value * allowed object is * {@link String } * */ public void setQUANTITYQUAL(String value) { this.quantityqual = value; } /** * Gets the value of the datequal property. * * @return * possible object is * {@link String } * */ public String getDATEQUAL() { return datequal; } /** * Sets the value of the datequal property. * * @param value * allowed object is * {@link String } * */ public void setDATEQUAL(String value) { this.datequal = value; } /** * Gets the value of the datefrom property. * * @return * possible object is * {@link String } * */ public String getDATEFROM() { return datefrom; } /** * Sets the value of the datefrom property. * * @param value * allowed object is
* {@link String } * */ public void setDATEFROM(String value) { this.datefrom = value; } /** * Gets the value of the dateto property. * * @return * possible object is * {@link String } * */ public String getDATETO() { return dateto; } /** * Sets the value of the dateto property. * * @param value * allowed object is * {@link String } * */ public void setDATETO(String value) { this.dateto = value; } /** * Gets the value of the days property. * * @return * possible object is * {@link String } * */ public String getDAYS() { return days; } /** * Sets the value of the days property. * * @param value * allowed object is * {@link String } * */ public void setDAYS(String value) { this.days = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DDTDQ1.java
2
请完成以下Java代码
public InventoryLineAggregationKey createAggregationKey(@NonNull final HuForInventoryLine huForInventoryLine) { final Quantity qty = CoalesceUtil.coalesce(huForInventoryLine.getQuantityCount(), huForInventoryLine.getQuantityBooked()); final UomId uomId = qty == null ? null : qty.getUomId(); return MultipleHUInventoryLineInventoryLineAggregationKey.builder() .productId(huForInventoryLine.getProductId()) .uomId(uomId) .storageAttributesKey(huForInventoryLine.getStorageAttributesKey()) .locatorId(huForInventoryLine.getLocatorId()) .build(); } @Override public InventoryLineAggregationKey createAggregationKey(@NonNull final InventoryLine inventoryLine) { final Quantity qty = CoalesceUtil.coalesce(inventoryLine.getQtyCount(), inventoryLine.getQtyBook()); final UomId uomId = qty == null ? null : qty.getUomId(); return MultipleHUInventoryLineInventoryLineAggregationKey.builder() .productId(inventoryLine.getProductId()) .uomId(uomId) .storageAttributesKey(AttributesKeys.createAttributesKeyFromASIStorageAttributes(inventoryLine.getAsiId()).orElse(AttributesKey.NONE)) .locatorId(inventoryLine.getLocatorId())
.build(); } @Override public AggregationType getAggregationType() { return AggregationType.MULTIPLE_HUS; } @Value @Builder private static class MultipleHUInventoryLineInventoryLineAggregationKey implements InventoryLineAggregationKey { @NonNull ProductId productId; // needed for the case that stocking UOM has changed, and there are still HUs with an old UOM @Nullable UomId uomId; @NonNull AttributesKey storageAttributesKey; @NonNull LocatorId locatorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\aggregator\MultipleHUInventoryLineAggregator.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Response Text. @param ResponseText Request Response Text */ public void setResponseText (String ResponseText) { set_Value (COLUMNNAME_ResponseText, ResponseText); } /** Get Response Text. @return Request Response Text */ public String getResponseText () { return (String)get_Value(COLUMNNAME_ResponseText);
} /** Set Standard Response. @param R_StandardResponse_ID Request Standard Response */ public void setR_StandardResponse_ID (int R_StandardResponse_ID) { if (R_StandardResponse_ID < 1) set_ValueNoCheck (COLUMNNAME_R_StandardResponse_ID, null); else set_ValueNoCheck (COLUMNNAME_R_StandardResponse_ID, Integer.valueOf(R_StandardResponse_ID)); } /** Get Standard Response. @return Request Standard Response */ public int getR_StandardResponse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_StandardResponse_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_StandardResponse.java
1
请完成以下Java代码
public java.lang.String getSOPOType() { return get_ValueAsString(COLUMNNAME_SOPOType); } @Override public void setTaxIndicator (final @Nullable java.lang.String TaxIndicator) { set_Value (COLUMNNAME_TaxIndicator, TaxIndicator); } @Override public java.lang.String getTaxIndicator() { return get_ValueAsString(COLUMNNAME_TaxIndicator); } @Override public org.compiere.model.I_C_Country getTo_Country() { return get_ValueAsPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class); } @Override public void setTo_Country(final org.compiere.model.I_C_Country To_Country) { set_ValueFromPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class, To_Country); } @Override public void setTo_Country_ID (final int To_Country_ID) { if (To_Country_ID < 1) set_Value (COLUMNNAME_To_Country_ID, null); else set_Value (COLUMNNAME_To_Country_ID, To_Country_ID); } @Override public int getTo_Country_ID() { return get_ValueAsInt(COLUMNNAME_To_Country_ID); } @Override public org.compiere.model.I_C_Region getTo_Region() { return get_ValueAsPO(COLUMNNAME_To_Region_ID, org.compiere.model.I_C_Region.class); } @Override public void setTo_Region(final org.compiere.model.I_C_Region To_Region) { set_ValueFromPO(COLUMNNAME_To_Region_ID, org.compiere.model.I_C_Region.class, To_Region); } @Override public void setTo_Region_ID (final int To_Region_ID) { if (To_Region_ID < 1) set_Value (COLUMNNAME_To_Region_ID, null); else set_Value (COLUMNNAME_To_Region_ID, To_Region_ID); } @Override public int getTo_Region_ID() { return get_ValueAsInt(COLUMNNAME_To_Region_ID); } /** * TypeOfDestCountry AD_Reference_ID=541323 * Reference name: TypeDestCountry */ public static final int TYPEOFDESTCOUNTRY_AD_Reference_ID=541323; /** Domestic = DOMESTIC */ public static final String TYPEOFDESTCOUNTRY_Domestic = "DOMESTIC";
/** EU-foreign = WITHIN_COUNTRY_AREA */ public static final String TYPEOFDESTCOUNTRY_EU_Foreign = "WITHIN_COUNTRY_AREA"; /** Non-EU country = OUTSIDE_COUNTRY_AREA */ public static final String TYPEOFDESTCOUNTRY_Non_EUCountry = "OUTSIDE_COUNTRY_AREA"; @Override public void setTypeOfDestCountry (final @Nullable java.lang.String TypeOfDestCountry) { set_Value (COLUMNNAME_TypeOfDestCountry, TypeOfDestCountry); } @Override public java.lang.String getTypeOfDestCountry() { return get_ValueAsString(COLUMNNAME_TypeOfDestCountry); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Tax.java
1
请完成以下Java代码
public class AtomicOperationProcessStartInitial extends AbstractEventAtomicOperation { @Override protected ScopeImpl getScope(InterpretableExecution execution) { return (ScopeImpl) execution.getActivity(); } @Override protected String getEventName() { return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_START; } @Override protected void eventNotificationsCompleted(InterpretableExecution execution) { ActivityImpl activity = (ActivityImpl) execution.getActivity(); ProcessDefinitionImpl processDefinition = execution.getProcessDefinition(); StartingExecution startingExecution = execution.getStartingExecution(); if (activity == startingExecution.getInitial()) { execution.disposeStartingExecution(); execution.performOperation(ACTIVITY_EXECUTE); } else {
List<ActivityImpl> initialActivityStack = processDefinition.getInitialActivityStack(startingExecution.getInitial()); int index = initialActivityStack.indexOf(activity); activity = initialActivityStack.get(index + 1); InterpretableExecution executionToUse = null; if (activity.isScope()) { executionToUse = (InterpretableExecution) execution.getExecutions().get(0); } else { executionToUse = execution; } executionToUse.setActivity(activity); executionToUse.performOperation(PROCESS_START_INITIAL); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationProcessStartInitial.java
1
请完成以下Java代码
public String getRawPassword() { return rawPassword; } public void setRawPassword(String rawPassword) { this.rawPassword = rawPassword; } @JsonIgnore @Override public boolean isAccountNonExpired() { return true; } @JsonIgnore @Override public boolean isAccountNonLocked() { return true; } @JsonIgnore @Override public boolean isCredentialsNonExpired() { return true; } @JsonIgnore @Override
public boolean isEnabled() { return true; } @JsonIgnore @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) { this.authorities = authorities; } }
repos\springBoot-master\springboot-springSecurity2\src\main\java\com\us\example\domain\SysUser.java
1
请在Spring Boot框架中完成以下Java代码
protected Pair<Boolean, Boolean> saveOrUpdateRuleChain(TenantId tenantId, RuleChainId ruleChainId, RuleChainUpdateMsg ruleChainUpdateMsg, RuleChainType ruleChainType) { boolean created = false; RuleChain ruleChainFromDb = edgeCtx.getRuleChainService().findRuleChainById(tenantId, ruleChainId); if (ruleChainFromDb == null) { created = true; } RuleChain ruleChain = JacksonUtil.fromString(ruleChainUpdateMsg.getEntity(), RuleChain.class, true); if (ruleChain == null) { throw new RuntimeException("[{" + tenantId + "}] ruleChainUpdateMsg {" + ruleChainUpdateMsg + "} cannot be converted to rule chain"); } boolean isRoot = ruleChain.isRoot(); if (RuleChainType.CORE.equals(ruleChainType)) { ruleChain.setRoot(false); } else { ruleChain.setRoot(ruleChainFromDb == null ? false : ruleChainFromDb.isRoot()); } ruleChain.setType(ruleChainType); ruleChainValidator.validate(ruleChain, RuleChain::getTenantId); if (created) { ruleChain.setId(ruleChainId); }
edgeCtx.getRuleChainService().saveRuleChain(ruleChain, true, false); return Pair.of(created, isRoot); } protected void saveOrUpdateRuleChainMetadata(TenantId tenantId, RuleChainMetadataUpdateMsg ruleChainMetadataUpdateMsg) { RuleChainMetaData ruleChainMetadata = JacksonUtil.fromString(ruleChainMetadataUpdateMsg.getEntity(), RuleChainMetaData.class, true); if (ruleChainMetadata == null) { throw new RuntimeException("[{" + tenantId + "}] ruleChainMetadataUpdateMsg {" + ruleChainMetadataUpdateMsg + "} cannot be converted to rule chain metadata"); } if (!ruleChainMetadata.getNodes().isEmpty()) { ruleChainMetadata.setVersion(null); for (RuleNode ruleNode : ruleChainMetadata.getNodes()) { ruleNode.setRuleChainId(null); ruleNode.setId(null); } edgeCtx.getRuleChainService().saveRuleChainMetaData(tenantId, ruleChainMetadata, Function.identity(), true); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\rule\BaseRuleChainProcessor.java
2