instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Date getUpdateTime() { return updateTime; } /** * Set the update time. * * @param updateTime the update time */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * Get the disabled. * * @return the disabled */ public Integer getDisabled() { return disabled; } /** * Set the disabled. * * @param disabled the disabled */ public void setDisabled(Integer disabled) { this.disabled = disabled; } /** * Get the theme. *
* @return the theme */ public String getTheme() { return theme; } /** * Set the theme. * * @param theme theme */ public void setTheme(String theme) { this.theme = theme; } /** * Get the checks if is ldap. * * @return the checks if is ldap */ public Integer getIsLdap() { return isLdap; } /** * Set the checks if is ldap. * * @param isLdap the checks if is ldap */ public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } }
repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java
1
请完成以下Java代码
public String getCommentBody() { return commentBody; } public void setCommentBody(String commentBody) { this.commentBody = commentBody == null ? null : commentBody.trim(); } public Byte getCommentStatus() { return commentStatus; } public void setCommentStatus(Byte commentStatus) { this.commentStatus = commentStatus; } public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; }
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", commentId=").append(commentId); sb.append(", newsId=").append(newsId); sb.append(", commentator=").append(commentator); sb.append(", commentBody=").append(commentBody); sb.append(", commentStatus=").append(commentStatus); sb.append(", isDeleted=").append(isDeleted); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsComment.java
1
请完成以下Java代码
public static <T> T readValue(String jsonStr, Class<T> clazz) { try { return getInstance().readValue(jsonStr, clazz); } catch (JsonParseException e) { logger.error(e.getMessage(), e); } catch (JsonMappingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return null; } /** * string --> List<Bean>... * * @param jsonStr * @param parametrized * @param parameterClasses
* @param <T> * @return */ public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) { try { JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses); return getInstance().readValue(jsonStr, javaType); } catch (JsonParseException e) { logger.error(e.getMessage(), e); } catch (JsonMappingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\JacksonUtil.java
1
请完成以下Java代码
public Collection<Documentation> getDocumentations() { return documentationCollection.get(this); } public ExtensionElements getExtensionElements() { return extensionElementsChild.getChild(this); } public void setExtensionElements(ExtensionElements extensionElements) { extensionElementsChild.setChild(this, extensionElements); } @SuppressWarnings("rawtypes") public DiagramElement getDiagramElement() { Collection<Reference> incomingReferences = getIncomingReferencesByType(DiagramElement.class); for (Reference<?> reference : incomingReferences) { for (ModelElementInstance sourceElement : reference.findReferenceSourceElements(this)) { String referenceIdentifier = reference.getReferenceIdentifier(sourceElement); if (referenceIdentifier != null && referenceIdentifier.equals(getId())) { return (DiagramElement) sourceElement; } } } return null; } @SuppressWarnings("rawtypes") public Collection<Reference> getIncomingReferencesByType(Class<? extends ModelElementInstance> referenceSourceTypeClass) {
Collection<Reference> references = new ArrayList<Reference>(); // we traverse all incoming references in reverse direction for (Reference<?> reference : idAttribute.getIncomingReferences()) { ModelElementType sourceElementType = reference.getReferenceSourceElementType(); Class<? extends ModelElementInstance> sourceInstanceType = sourceElementType.getInstanceType(); // if the referencing element (source element) is a BPMNDI element, dig deeper if (referenceSourceTypeClass.isAssignableFrom(sourceInstanceType)) { references.add(reference); } } return references; } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BaseElementImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static String getMessage(PropertySource<?> propertySource, @Nullable ConfigDataResource location, String propertyName, @Nullable Origin origin) { StringBuilder message = new StringBuilder("Inactive property source '"); message.append(propertySource.getName()); if (location != null) { message.append("' imported from location '"); message.append(location); } message.append("' cannot contain property '"); message.append(propertyName); message.append("'"); if (origin != null) { message.append(" [origin: "); message.append(origin); message.append("]"); } return message.toString(); } /** * Return the inactive property source that contained the property. * @return the property source */ public PropertySource<?> getPropertySource() { return this.propertySource; } /** * Return the {@link ConfigDataResource} of the property source or {@code null} if the * source was not loaded from {@link ConfigData}. * @return the config data location or {@code null} */ public @Nullable ConfigDataResource getLocation() { return this.location; } /** * Return the name of the property. * @return the property name */ public String getPropertyName() { return this.propertyName; } /**
* Return the origin or the property or {@code null}. * @return the property origin */ public @Nullable Origin getOrigin() { return this.origin; } /** * Throw an {@link InactiveConfigDataAccessException} if the given * {@link ConfigDataEnvironmentContributor} contains the property. * @param contributor the contributor to check * @param name the name to check */ static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor, ConfigurationPropertyName name) { ConfigurationPropertySource source = contributor.getConfigurationPropertySource(); ConfigurationProperty property = (source != null) ? source.getConfigurationProperty(name) : null; if (property != null) { PropertySource<?> propertySource = contributor.getPropertySource(); ConfigDataResource location = contributor.getResource(); Assert.state(propertySource != null, "'propertySource' must not be null"); throw new InactiveConfigDataAccessException(propertySource, location, name.toString(), property.getOrigin()); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InactiveConfigDataAccessException.java
2
请完成以下Java代码
public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { return value instanceof BpmnAggregation; } @Override public boolean isReadOnly() { return true; } @Override public void setValue(Object value, ValueFields valueFields) { if (value instanceof BpmnAggregation) { valueFields.setTextValue(((BpmnAggregation) value).getExecutionId()); } else { valueFields.setTextValue(null);
} } @Override public Object getValue(ValueFields valueFields) { CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { return BpmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), commandContext); } else { return processEngineConfiguration.getCommandExecutor() .execute(context -> BpmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), context)); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\variable\BpmnAggregatedVariableType.java
1
请完成以下Java代码
public class TimerScheduledListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNTimerScheduledEvent>> processRuntimeEventListeners; private ToTimerScheduledConverter converter; public TimerScheduledListenerDelegate( List<BPMNElementEventListener<BPMNTimerScheduledEvent>> processRuntimeEventListeners, ToTimerScheduledConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override
public void onEvent(ActivitiEvent event) { converter .from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerScheduledEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TimerScheduledListenerDelegate.java
1
请完成以下Spring Boot application配置
quarkus.datasource.db-kind=h2 quarkus.datasource.jdbc.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 quarkus.datasource.username=sa quarkus.datasource.password=sa quarkus.hibernate
-orm.database.generation=drop-and-create quarkus.hibernate-orm.log.sql=true
repos\tutorials-master\quarkus-modules\quarkus-panache\src\main\resources\application.properties
2
请完成以下Java代码
public boolean isProcessed() { return false; } @Nullable @Override public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames();
} @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override @NonNull public List<ProductionSimulationRow> getIncludedRows() { return includedRows; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationRow.java
1
请完成以下Java代码
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 class OAuth2AuthorizationCodeRequestAuthenticationException extends OAuth2AuthenticationException { private final OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication; /** * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationException} using * the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param authorizationCodeRequestAuthentication the {@link Authentication} instance * of the OAuth 2.0 Authorization Request (or Consent) */ public OAuth2AuthorizationCodeRequestAuthenticationException(OAuth2Error error, @Nullable OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication) { super(error); this.authorizationCodeRequestAuthentication = authorizationCodeRequestAuthentication; } /** * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationException} using * the provided parameters. * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param cause the root cause * @param authorizationCodeRequestAuthentication the {@link Authentication} instance * of the OAuth 2.0 Authorization Request (or Consent)
*/ public OAuth2AuthorizationCodeRequestAuthenticationException(OAuth2Error error, Throwable cause, @Nullable OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication) { super(error, cause); this.authorizationCodeRequestAuthentication = authorizationCodeRequestAuthentication; } /** * Returns the {@link Authentication} instance of the OAuth 2.0 Authorization Request * (or Consent), or {@code null} if not available. * @return the {@link OAuth2AuthorizationCodeRequestAuthenticationToken} */ @Nullable public OAuth2AuthorizationCodeRequestAuthenticationToken getAuthorizationCodeRequestAuthentication() { return this.authorizationCodeRequestAuthentication; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeRequestAuthenticationException.java
1
请完成以下Java代码
public boolean isRetriesLeft() { return retriesLeft; } public boolean isExecutable() { return executable; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; }
public boolean isNoRetriesLeft() { return noRetriesLeft; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class DelayedCallable implements Callable<String> { private String name; private long period; private CountDownLatch latch; public DelayedCallable(String name, long period, CountDownLatch latch) { this(name, period); this.latch = latch; } public DelayedCallable(String name, long period) { this.name = name; this.period = period; } public String call() {
try { Thread.sleep(period); if (latch != null) { latch.countDown(); } } catch (InterruptedException ex) { // handle exception ex.printStackTrace(); Thread.currentThread().interrupt(); } return name; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-3\src\main\java\com\baeldung\concurrent\executorservice\DelayedCallable.java
2
请完成以下Java代码
public java.sql.Timestamp getSupplierApproval_Date() { return get_ValueAsTimestamp(COLUMNNAME_SupplierApproval_Date); } /** * SupplierApproval_Norm AD_Reference_ID=541363 * Reference name: SupplierApproval_Norm */ public static final int SUPPLIERAPPROVAL_NORM_AD_Reference_ID=541363; /** ISO 9100 Luftfahrt = ISO9100 */ public static final String SUPPLIERAPPROVAL_NORM_ISO9100Luftfahrt = "ISO9100"; /** TS 16949 = TS16949 */ public static final String SUPPLIERAPPROVAL_NORM_TS16949 = "TS16949"; @Override public void setSupplierApproval_Norm (final java.lang.String SupplierApproval_Norm) { set_Value (COLUMNNAME_SupplierApproval_Norm, SupplierApproval_Norm); } @Override public java.lang.String getSupplierApproval_Norm() { return get_ValueAsString(COLUMNNAME_SupplierApproval_Norm); }
/** * SupplierApproval_Type AD_Reference_ID=541361 * Reference name: Supplier Approval Type */ public static final int SUPPLIERAPPROVAL_TYPE_AD_Reference_ID=541361; /** Customer = C */ public static final String SUPPLIERAPPROVAL_TYPE_Customer = "C"; /** Vendor = V */ public static final String SUPPLIERAPPROVAL_TYPE_Vendor = "V"; @Override public void setSupplierApproval_Type (final @Nullable java.lang.String SupplierApproval_Type) { set_ValueNoCheck (COLUMNNAME_SupplierApproval_Type, SupplierApproval_Type); } @Override public java.lang.String getSupplierApproval_Type() { return get_ValueAsString(COLUMNNAME_SupplierApproval_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_SupplierApproval.java
1
请完成以下Java代码
public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); } /** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestTypeUpdates.java
1
请完成以下Java代码
public class Order { private String transactionId; private List<String> orderItemIds; private Payment payment; public Order(String transactionId, List<String> orderItemIds, Payment payment) { this.transactionId = transactionId; this.orderItemIds = orderItemIds; this.payment = payment; } public Order() { } public String getTransactionId() { return transactionId; }
public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public List<String> getOrderItemIds() { return orderItemIds; } public void setOrderItemIds(List<String> orderItemIds) { this.orderItemIds = orderItemIds; } public Payment getPayment() { return payment; } public void setPayment(Payment payment) { this.payment = payment; } }
repos\tutorials-master\mapstruct-3\src\main\java\com\baeldung\entity\Order.java
1
请完成以下Java代码
public void updateBPartnerLocation(final ContactPerson contactPerson, BPartnerLocationId bpLocationId) { contactPerson.toBuilder() .bpLocationId(bpLocationId) .build(); save(contactPerson); } public Set<ContactPerson> getByBPartnerLocationId(@NonNull final BPartnerLocationId bpLocationId) { return queryBL .createQueryBuilder(I_MKTG_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_ContactPerson.COLUMN_C_BPartner_Location_ID, bpLocationId.getRepoId()) .create() .stream() .map(ContactPersonRepository::toContactPerson) .collect(ImmutableSet.toImmutableSet());
} public Set<ContactPerson> getByUserId(@NonNull final UserId userId) { return queryBL .createQueryBuilder(I_MKTG_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_ContactPerson.COLUMN_AD_User_ID, userId.getRepoId()) .create() .stream() .map(ContactPersonRepository::toContactPerson) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\ContactPersonRepository.java
1
请完成以下Java代码
public VariableProvider variableProvider() { return new ContextVariableWrapper(variableContext); } }; Either either = feelEngine.evalExpression(expression, context); if (either instanceof Right) { Right right = (Right) either; return (T) right.value(); } else { Left left = (Left) either; Failure failure = (Failure) left.value(); String message = failure.message(); throw LOGGER.evaluationException(message); } } public boolean evaluateSimpleUnaryTests(String expression, String inputVariable, VariableContext variableContext) { Map inputVariableMap = new Map.Map1(INPUT_VARIABLE_NAME, inputVariable); StaticVariableProvider inputVariableContext = new StaticVariableProvider(inputVariableMap); ContextVariableWrapper contextVariableWrapper = new ContextVariableWrapper(variableContext); CustomContext context = new CustomContext() { public VariableProvider variableProvider() { return new CompositeVariableProvider(toScalaList(inputVariableContext, contextVariableWrapper)); } }; Either either = feelEngine.evalUnaryTests(expression, context); if (either instanceof Right) { Right right = (Right) either; Object value = right.value(); return BoxesRunTime.unboxToBoolean(value); } else { Left left = (Left) either; Failure failure = (Failure) left.value(); String message = failure.message(); throw LOGGER.evaluationException(message); } } protected List<CustomValueMapper> getValueMappers() {
SpinValueMapperFactory spinValueMapperFactory = new SpinValueMapperFactory(); CustomValueMapper javaValueMapper = new JavaValueMapper(); CustomValueMapper spinValueMapper = spinValueMapperFactory.createInstance(); if (spinValueMapper != null) { return toScalaList(javaValueMapper, spinValueMapper); } else { return toScalaList(javaValueMapper); } } @SafeVarargs protected final <T> List<T> toScalaList(T... elements) { java.util.List<T> listAsJava = Arrays.asList(elements); return toList(listAsJava); } protected <T> List<T> toList(java.util.List list) { return ListHasAsScala(list).asScala().toList(); } protected org.camunda.feel.FeelEngine buildFeelEngine(CustomFunctionTransformer transformer, CompositeValueMapper valueMapper) { return new Builder() .functionProvider(transformer) .valueMapper(valueMapper) .enableExternalFunctions(false) .build(); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\ScalaFeelEngine.java
1
请完成以下Java代码
private CurrencyId getCurrencyIdByCurrencyISO(@NonNull final String currencyISO) { final CurrencyCode convertedToCurrencyCode = CurrencyCode.ofThreeLetterCode(currencyISO); return currencyRepository.getCurrencyIdByCurrencyCode(convertedToCurrencyCode); } @NonNull private BPartnerBankAccountId getBPartnerBankAccountId(@NonNull final BPartnerId bPartnerId) { final I_C_BP_BankAccount sourceBPartnerBankAccount = bankAccountDAO.retrieveDefaultBankAccountInTrx(bPartnerId) .orElseThrow(() -> new AdempiereException("No BPartnerBankAccount found for BPartnerId") .appendParametersToMessage() .setParameter("BPartnerId", bPartnerId)); return BPartnerBankAccountId.ofRepoId(BPartnerId.toRepoId(bPartnerId), sourceBPartnerBankAccount.getC_BP_BankAccount_ID()); } @NonNull private DocTypeId getDocTypeIdByType( @NonNull final String type, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { final DocTypeQuery docTypeQuery = DocTypeQuery.builder() .docBaseType(type) .adClientId(clientId.getRepoId()) .adOrgId(orgId.getRepoId()) .build(); return docTypeDAO.getDocTypeId(docTypeQuery); } private BPartnerQuery buildBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier) { final IdentifierString.Type type = bpartnerIdentifier.getType(); final BPartnerQuery query; switch (type) { case METASFRESH_ID: query = BPartnerQuery.builder() .bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId)) .build(); break; case EXTERNAL_ID: query = BPartnerQuery.builder() .externalId(bpartnerIdentifier.asExternalId()) .build(); break; case GLN: query = BPartnerQuery.builder() .gln(bpartnerIdentifier.asGLN()) .build(); break; case VALUE: query = BPartnerQuery.builder() .bpartnerValue(bpartnerIdentifier.asValue())
.build(); break; default: throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier); } return query; } @VisibleForTesting public String buildDocumentNo(@NonNull final DocTypeId docTypeId) { final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class); final String documentNo = documentNoFactory.forDocType(docTypeId.getRepoId(), /* useDefiniteSequence */false) .setClientId(Env.getClientId()) .setFailOnError(true) .build(); if (documentNo == null) { throw new AdempiereException("Cannot fetch documentNo for " + docTypeId); } return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\remittanceadvice\impl\CreateRemittanceAdviceService.java
1
请在Spring Boot框架中完成以下Java代码
static BeanMetadataElement getClientRegistrationRepository(Element element) { String clientRegistrationRepositoryRef = element.getAttribute(ATT_CLIENT_REGISTRATION_REPOSITORY_REF); if (StringUtils.hasLength(clientRegistrationRepositoryRef)) { return new RuntimeBeanReference(clientRegistrationRepositoryRef); } return new RuntimeBeanReference(ClientRegistrationRepository.class); } static BeanMetadataElement getAuthorizedClientRepository(Element element) { String authorizedClientRepositoryRef = element.getAttribute(ATT_AUTHORIZED_CLIENT_REPOSITORY_REF); if (StringUtils.hasLength(authorizedClientRepositoryRef)) { return new RuntimeBeanReference(authorizedClientRepositoryRef); } return null; } static BeanMetadataElement getAuthorizedClientService(Element element) { String authorizedClientServiceRef = element.getAttribute(ATT_AUTHORIZED_CLIENT_SERVICE_REF); if (StringUtils.hasLength(authorizedClientServiceRef)) { return new RuntimeBeanReference(authorizedClientServiceRef); } return null; }
static BeanDefinition createDefaultAuthorizedClientRepository(BeanMetadataElement clientRegistrationRepository, BeanMetadataElement authorizedClientService) { if (authorizedClientService == null) { authorizedClientService = BeanDefinitionBuilder .rootBeanDefinition("org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService") .addConstructorArgValue(clientRegistrationRepository) .getBeanDefinition(); } return BeanDefinitionBuilder.rootBeanDefinition( "org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository") .addConstructorArgValue(authorizedClientService) .getBeanDefinition(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ClientBeanDefinitionParserUtils.java
2
请在Spring Boot框架中完成以下Java代码
public String getDocumentID() { return documentID; } /** * Sets the value of the documentID property. * * @param value * allowed object is * {@link String } * */ public void setDocumentID(String value) { this.documentID = value; } /** * The type of the referenced document. E.g., order, despatch advice, etc. * * @return * possible object is * {@link DocumentTypeType } * */ public DocumentTypeType getDocumentType() { return documentType; } /** * Sets the value of the documentType property. * * @param value * allowed object is * {@link DocumentTypeType } * */ public void setDocumentType(DocumentTypeType value) { this.documentType = value; } /** * In case a certain position in a document shall be referenced, this element may be used. * * @return * possible object is * {@link String } * */ public String getDocumentPositionNumber() { return documentPositionNumber; } /** * Sets the value of the documentPositionNumber property. * * @param value * allowed object is * {@link String } * */ public void setDocumentPositionNumber(String value) { this.documentPositionNumber = value; } /** * Reference date of the document. Typcially this element refers to the document date of the preceding document. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getReferenceDate() { return referenceDate; }
/** * Sets the value of the referenceDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setReferenceDate(XMLGregorianCalendar value) { this.referenceDate = value; } /** * An optional description in free-text or a specification of the reference type for the DocumentType 'DocumentReference'. * * @return * possible object is * {@link DescriptionType } * */ public DescriptionType getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link DescriptionType } * */ public void setDescription(DescriptionType value) { this.description = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DocumentReferenceType.java
2
请在Spring Boot框架中完成以下Java代码
public class UserService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; /** * Get user by id. * * @return Returns user */ public User getUser(UUID id) { return userRepository.findById(id).orElseThrow(() -> new NoSuchElementException("user not found.")); } /** * Get user by username. * * @return Returns user */ public User getUser(String username) { return userRepository.findByUsername(username).orElseThrow(() -> new NoSuchElementException("user not found.")); } /** * Register a new user in the system. * * @param registry User registration information * @return Returns the registered user */ @SuppressWarnings("UnusedReturnValue") public User signup(UserRegistry registry) { if (userRepository.existsBy(registry.email(), registry.username())) { throw new IllegalArgumentException("email or username is already exists."); } var requester = new User(registry); requester.encryptPassword(passwordEncoder, registry.password()); return userRepository.save(requester); } /** * Login to the system.
* * @param email users email * @param password users password * @return Returns the logged-in user */ public User login(String email, String password) { if (email == null || email.isBlank()) { throw new IllegalArgumentException("email is required."); } if (password == null || password.isBlank()) { throw new IllegalArgumentException("password is required."); } return userRepository .findByEmail(email) .filter(user -> passwordEncoder.matches(password, user.getPassword())) .orElseThrow(() -> new IllegalArgumentException("invalid email or password.")); } /** * Update user information. * * @param userId The user who requested the update * @param email users email * @param username users username * @param password users password * @param bio users bio * @param imageUrl users imageUrl * @return Returns the updated user */ public User updateUserDetails( UUID userId, String email, String username, String password, String bio, String imageUrl) { if (userId == null) { throw new IllegalArgumentException("user id is required."); } return userRepository.updateUserDetails(userId, passwordEncoder, email, username, password, bio, imageUrl); } }
repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\UserService.java
2
请完成以下Java代码
public List<I_M_Package> retrievePackagesForShipment(final I_M_InOut shipment) { Check.assumeNotNull(shipment, "shipment not null"); return queryBL.createQueryBuilder(I_M_Package.class, shipment) .addEqualsFilter(org.compiere.model.I_M_Package.COLUMNNAME_M_InOut_ID, shipment.getM_InOut_ID()) .create() .list(I_M_Package.class); } @Override public Collection<PackageId> retainPackageIdsWithHUs(final Collection<PackageId> packageIds) { if (Check.isEmpty(packageIds)) { return Collections.emptyList(); } return queryBL.createQueryBuilder(I_M_Package_HU.class) .addInArrayFilter(I_M_Package_HU.COLUMNNAME_M_Package_ID, packageIds) .create() .listDistinct(I_M_Package_HU.COLUMNNAME_M_Package_ID, PackageId.class); } @Override public I_M_Package retrievePackage(final I_M_HU hu) {
final List<I_M_Package> mpackages = retrievePackages(hu, ITrx.TRXNAME_ThreadInherited); if (mpackages.isEmpty()) { return null; } else if (mpackages.size() > 1) { Check.errorIf(true, HUException.class, "More than one package was found for HU." + "\n@M_HU_ID@: {}" + "\n@M_Package_ID@: {}", hu, mpackages); return mpackages.get(0); // in case the system is configured to just log } else { return mpackages.get(0); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPackageDAO.java
1
请完成以下Java代码
protected Object getProcessVariable(InjectionPoint ip) { String processVariableName = getVariableName(ip); if (logger.isLoggable(Level.FINE)) { logger.fine("Getting process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "]."); } return businessProcess.getVariable(processVariableName); } /** * @since 7.3 */ @Produces @ProcessVariableTyped protected TypedValue getProcessVariableTyped(InjectionPoint ip) { String processVariableName = getVariableTypedName(ip); if (logger.isLoggable(Level.FINE)) { logger.fine("Getting typed process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "]."); } return businessProcess.getVariableTyped(processVariableName); } @Produces @Named protected Map<String, Object> processVariables() { return processVariableMap; } /** * @since 7.3 */ @Produces @Named protected VariableMap processVariableMap() { return processVariableMap; } protected String getVariableLocalName(InjectionPoint ip) { String variableName = ip.getAnnotated().getAnnotation(ProcessVariableLocal.class).value(); if (variableName.length() == 0) { variableName = ip.getMember().getName(); } return variableName; } protected String getVariableLocalTypedName(InjectionPoint ip) { String variableName = ip.getAnnotated().getAnnotation(ProcessVariableLocalTyped.class).value(); if (variableName.length() == 0) { variableName = ip.getMember().getName(); } return variableName; } @Produces @ProcessVariableLocal protected Object getProcessVariableLocal(InjectionPoint ip) { String processVariableName = getVariableLocalName(ip); if (logger.isLoggable(Level.FINE)) { logger.fine("Getting local process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "]."); } return businessProcess.getVariableLocal(processVariableName); } /**
* @since 7.3 */ @Produces @ProcessVariableLocalTyped protected TypedValue getProcessVariableLocalTyped(InjectionPoint ip) { String processVariableName = getVariableLocalTypedName(ip); if (logger.isLoggable(Level.FINE)) { logger.fine("Getting local typed process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "]."); } return businessProcess.getVariableLocalTyped(processVariableName); } @Produces @Named protected Map<String, Object> processVariablesLocal() { return processVariableLocalMap; } /** * @since 7.3 */ @Produces @Named protected VariableMap processVariableMapLocal() { return processVariableLocalMap; } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\ProcessVariables.java
1
请完成以下Java代码
public String login() { return "login page."; } /** * 登录请求 * @param username * @return */ @RequestMapping("/login/submit") public String loginSubmit(@RequestParam("username") String username) { if (StringUtils.isNotBlank(username)) { httpSession.setAttribute("username", username); return "/index"; } return "/login"; } /** * 首页 * @return */
@ResponseBody @RequestMapping("/index") public String index() { log.info("session id: {}", httpSession.getId()); return "index page."; } /** * 退出登录 * @return */ @RequestMapping("/logout") public String logout() { httpSession.invalidate(); return "/login"; } }
repos\spring-boot-best-practice-master\spring-boot-session\src\main\java\cn\javastack\springboot\session\IndexController.java
1
请在Spring Boot框架中完成以下Java代码
public static class LegacyVelocityConfiguration { @Bean @ConditionalOnMissingBean org.mybatis.scripting.velocity.Driver velocityLanguageDriver() { return new org.mybatis.scripting.velocity.Driver(); } } /** * Configuration class for mybatis-velocity 2.1.x or above. */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ VelocityLanguageDriver.class, VelocityLanguageDriverConfig.class }) public static class VelocityConfiguration { @Bean @ConditionalOnMissingBean VelocityLanguageDriver velocityLanguageDriver(VelocityLanguageDriverConfig config) { return new VelocityLanguageDriver(config); } @Bean @ConditionalOnMissingBean @ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".velocity") public VelocityLanguageDriverConfig velocityLanguageDriverConfig() { return VelocityLanguageDriverConfig.newInstance(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ThymeleafLanguageDriver.class) public static class ThymeleafConfiguration { @Bean @ConditionalOnMissingBean ThymeleafLanguageDriver thymeleafLanguageDriver(ThymeleafLanguageDriverConfig config) { return new ThymeleafLanguageDriver(config); }
@Bean @ConditionalOnMissingBean @ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf") public ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() { return ThymeleafLanguageDriverConfig.newInstance(); } // This class provides to avoid the https://github.com/spring-projects/spring-boot/issues/21626 as workaround. @SuppressWarnings("unused") private static class MetadataThymeleafLanguageDriverConfig extends ThymeleafLanguageDriverConfig { @ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf.dialect") @Override public DialectConfig getDialect() { return super.getDialect(); } @ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf.template-file") @Override public TemplateFileConfig getTemplateFile() { return super.getTemplateFile(); } } } }
repos\spring-boot-starter-master\mybatis-spring-boot-autoconfigure\src\main\java\org\mybatis\spring\boot\autoconfigure\MybatisLanguageDriverAutoConfiguration.java
2
请完成以下Java代码
public abstract class AbstractRequestInvocation<T> implements ConnectorInvocation { protected T target; protected int currentIndex; protected List<ConnectorRequestInterceptor> interceptorChain; protected ConnectorRequest<?> request; protected AbstractRequestInvocation(T target, ConnectorRequest<?> request, List<ConnectorRequestInterceptor> interceptorChain) { this.target = target; this.request = request; this.interceptorChain = interceptorChain; currentIndex = -1; } public T getTarget() { return target; }
public ConnectorRequest<?> getRequest() { return request; } public Object proceed() throws Exception { currentIndex++; if (interceptorChain.size() > currentIndex) { return interceptorChain.get(currentIndex).handleInvocation(this); } else { return invokeTarget(); } } public abstract Object invokeTarget() throws Exception; }
repos\camunda-bpm-platform-master\connect\core\src\main\java\org\camunda\connect\impl\AbstractRequestInvocation.java
1
请完成以下Spring Boot application配置
# Spring Boot application.properties to configure the Inline Caching Example Application spring.application.name=InlineCachingApplication spring.data.gemfire.cache.log-level=${gemfir
e.log-level:error} spring.jpa.hibernate.ddl-auto=none spring.jpa.show-sql=false
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline\src\main\resources\application.properties
2
请完成以下Java代码
public int getAPI_Request_Audit_ID() { return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID); } @Override public void setAPI_Response_Audit_ID (final int API_Response_Audit_ID) { if (API_Response_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, API_Response_Audit_ID); } @Override public int getAPI_Response_Audit_ID() { return get_ValueAsInt(COLUMNNAME_API_Response_Audit_ID); } @Override public void setBody (final @Nullable java.lang.String Body) { set_Value (COLUMNNAME_Body, Body); } @Override public java.lang.String getBody() { return get_ValueAsString(COLUMNNAME_Body); } @Override public void setHttpCode (final @Nullable java.lang.String HttpCode) { set_Value (COLUMNNAME_HttpCode, HttpCode); } @Override public java.lang.String getHttpCode()
{ return get_ValueAsString(COLUMNNAME_HttpCode); } @Override public void setHttpHeaders (final @Nullable java.lang.String HttpHeaders) { set_Value (COLUMNNAME_HttpHeaders, HttpHeaders); } @Override public java.lang.String getHttpHeaders() { return get_ValueAsString(COLUMNNAME_HttpHeaders); } @Override public void setTime (final @Nullable java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Response_Audit.java
1
请在Spring Boot框架中完成以下Java代码
public class SessionConfig { private static final Logger logger = LogManager.getLogger(SessionConfig.class); private static final String BEANNAME_SessionScheduledExecutorService = "sessionScheduledExecutorService"; @Value("${metasfresh.session.checkExpiredSessionsRateInMinutes:10}") private int checkExpiredSessionsRateInMinutes; @Bean public SessionRepository<MapSession> sessionRepository( final SessionProperties properties, final ApplicationEventPublisher applicationEventPublisher) { final FixedMapSessionRepository sessionRepository = FixedMapSessionRepository.builder() .applicationEventPublisher(applicationEventPublisher) .defaultMaxInactiveInterval(properties.getTimeout()) .build(); logger.info("Using session repository: {}", sessionRepository); if (checkExpiredSessionsRateInMinutes > 0) { final ScheduledExecutorService scheduledExecutor = sessionScheduledExecutorService(); scheduledExecutor.scheduleAtFixedRate(
sessionRepository::purgeExpiredSessionsNoFail, // command, don't fail because on failure the task won't be re-scheduled so it's game over checkExpiredSessionsRateInMinutes, // initialDelay checkExpiredSessionsRateInMinutes, // period TimeUnit.MINUTES // timeUnit ); logger.info("Checking expired sessions each {} minutes", checkExpiredSessionsRateInMinutes); } return sessionRepository; } @Bean(BEANNAME_SessionScheduledExecutorService) public ScheduledExecutorService sessionScheduledExecutorService() { return Executors.newScheduledThreadPool( 1, // corePoolSize CustomizableThreadFactory.builder() .setDaemon(true) .setThreadNamePrefix(SessionConfig.class.getName()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\SessionConfig.java
2
请完成以下Java代码
public OAuth2AccessToken getToken() { return token; } public void setToken(OAuth2AccessToken token) { this.token = token; } public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return null; } @Override public boolean isAccountNonExpired() { return true; }
@Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectUserDetails.java
1
请完成以下Java代码
public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.matcher = requestMatcher; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.matcher.matches(request)) { filterChain.doFilter(request, response); return; } SecurityContext context = this.securityContextHolderStrategy.getContext(); ImmutablePublicKeyCredentialRequestOptionsRequest optionsRequest = new ImmutablePublicKeyCredentialRequestOptionsRequest( context.getAuthentication()); PublicKeyCredentialRequestOptions credentialRequestOptions = this.rpOptions .createCredentialRequestOptions(optionsRequest); this.requestOptionsRepository.save(request, response, credentialRequestOptions); response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.converter.write(credentialRequestOptions, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response)); } /** * Sets the {@link PublicKeyCredentialRequestOptionsRepository} to use.
* @param requestOptionsRepository the * {@link PublicKeyCredentialRequestOptionsRepository} to use. Cannot be null. */ public void setRequestOptionsRepository(PublicKeyCredentialRequestOptionsRepository requestOptionsRepository) { Assert.notNull(requestOptionsRepository, "requestOptionsRepository cannot be null"); this.requestOptionsRepository = requestOptionsRepository; } /** * Sets the {@link HttpMessageConverter} to use. * @param converter the {@link HttpMessageConverter} to use. Cannot be null. */ public void setConverter(HttpMessageConverter<Object> converter) { Assert.notNull(converter, "converter cannot be null"); this.converter = converter; } /** * Sets the {@link SecurityContextHolderStrategy} to use. * @param securityContextHolderStrategy the {@link SecurityContextHolderStrategy} to * use. Cannot be null. */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\PublicKeyCredentialRequestOptionsFilter.java
1
请完成以下Java代码
public class LoginParam { /** * 用户名 */ @ApiModelProperty(value = "用户名", name = "username", example = "admin", required = true) private String username; /** * 密码 */ @ApiModelProperty(value = "密码", name = "password", example = "123456", required = true) private String password; /** * Application ID */ @ApiModelProperty(value = "Application ID", name = "appid", example = "com.xncoding.xzpay", required = false) private String appid; /** * IMEI码 */ @ApiModelProperty(value = "IMEI码", name = "imei", example = "TUYIUOIU234234YUII", required = false) private String imei; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\LoginParam.java
1
请完成以下Java代码
public I_M_HU_Item retrieveParentItem(final I_M_HU hu) { return getDelegate(hu).retrieveParentItem(hu); } @Override public void setParentItem(final I_M_HU hu, final I_M_HU_Item parentItem) { // TODO: shall we check if HU and parentItem have the same trxName getDelegate(hu).setParentItem(hu, parentItem); } @Override public List<I_M_HU> retrieveIncludedHUs(final I_M_HU_Item item) { return getDelegate(item).retrieveIncludedHUs(item); } @Override public List<I_M_HU_Item> retrieveItems(final I_M_HU hu) { return getDelegate(hu).retrieveItems(hu); } @Override public Optional<I_M_HU_Item> retrieveItem(final I_M_HU hu, final I_M_HU_PI_Item piItem) { return getDelegate(hu).retrieveItem(hu, piItem); } @Override public I_M_HU_Item createHUItem(final I_M_HU hu, final I_M_HU_PI_Item piItem) { return getDelegate(hu).createHUItem(hu, piItem); }
@Override public I_M_HU_Item createAggregateHUItem(@NonNull final I_M_HU hu) { return getDelegate(hu).createAggregateHUItem(hu); } @Override public I_M_HU_Item createChildHUItem(@NonNull final I_M_HU hu) { return getDelegate(hu).createChildHUItem(hu); } @Override public I_M_HU_Item retrieveAggregatedItemOrNull(I_M_HU hu) { return getDelegate(hu).retrieveAggregatedItemOrNull(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CachedIfInTransactionHUAndItemsDAO.java
1
请完成以下Java代码
public final class CompositeTabCallout implements ITabCallout { public static final Builder builder() { return new Builder(); } private final List<ITabCallout> tabCallouts; private CompositeTabCallout(final List<ITabCallout> tabCallouts) { super(); this.tabCallouts = ImmutableList.copyOf(tabCallouts); } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(tabCallouts) .toString(); } @Override public void onIgnore(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onIgnore(calloutRecord); } } @Override public void onNew(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onNew(calloutRecord); } } @Override public void onSave(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onSave(calloutRecord); } } @Override public void onDelete(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onDelete(calloutRecord); } } @Override public void onRefresh(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onRefresh(calloutRecord);
} } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onRefreshAll(calloutRecord); } } @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onAfterQuery(calloutRecord); } } public static final class Builder { private final List<ITabCallout> tabCalloutsAll = new ArrayList<>(); private Builder() { super(); } public ITabCallout build() { if (tabCalloutsAll.isEmpty()) { return ITabCallout.NULL; } else if (tabCalloutsAll.size() == 1) { return tabCalloutsAll.get(0); } else { return new CompositeTabCallout(tabCalloutsAll); } } public Builder addTabCallout(final ITabCallout tabCallout) { Check.assumeNotNull(tabCallout, "tabCallout not null"); if (tabCalloutsAll.contains(tabCallout)) { return this; } tabCalloutsAll.add(tabCallout); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\impl\CompositeTabCallout.java
1
请完成以下Java代码
final class OriginTrackedFieldError extends FieldError implements OriginProvider { private final @Nullable Origin origin; private OriginTrackedFieldError(FieldError fieldError, @Nullable Origin origin) { super(fieldError.getObjectName(), fieldError.getField(), fieldError.getRejectedValue(), fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), fieldError.getDefaultMessage()); this.origin = origin; } @Override public @Nullable Origin getOrigin() { return this.origin; }
@Override public String toString() { if (this.origin == null) { return super.toString(); } return super.toString() + "; origin " + this.origin; } @Contract("!null, _ -> !null") static @Nullable FieldError of(@Nullable FieldError fieldError, @Nullable Origin origin) { if (fieldError == null || origin == null) { return fieldError; } return new OriginTrackedFieldError(fieldError, origin); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\validation\OriginTrackedFieldError.java
1
请在Spring Boot框架中完成以下Java代码
public String getIndex() { return "comparison/index"; } @GetMapping("/login") public String showLoginPage() { return "comparison/login"; } @PostMapping("/login") public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword()); try { subject.login(token); } catch (AuthenticationException ae) { logger.error(ae.getMessage()); attr.addFlashAttribute("error", "Invalid Credentials"); return "redirect:/login"; } } return "redirect:/home"; } @GetMapping("/home") public String getMeHome(Model model) { addUserAttributes(model); return "comparison/home"; } @GetMapping("/admin") public String adminOnly(Model model) { addUserAttributes(model); Subject currentUser = SecurityUtils.getSubject(); if (currentUser.hasRole("ADMIN")) { model.addAttribute("adminContent", "only admin can view this"); } return "comparison/home"; } @PostMapping("/logout") public String logout() {
Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/"; } private void addUserAttributes(Model model) { Subject currentUser = SecurityUtils.getSubject(); String permission = ""; if (currentUser.hasRole("ADMIN")) { model.addAttribute("role", "ADMIN"); } else if (currentUser.hasRole("USER")) { model.addAttribute("role", "USER"); } if (currentUser.isPermitted("READ")) { permission = permission + " READ"; } if (currentUser.isPermitted("WRITE")) { permission = permission + " WRITE"; } model.addAttribute("username", currentUser.getPrincipal()); model.addAttribute("permission", permission); } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\shiro\controllers\ShiroController.java
2
请完成以下Java代码
private String getResAccessUrl(StorePath storePath) { String fileUrl = FastDFSConstants.HTTP_PRODOCOL + "://" + FastDFSConstants.RES_HOST + "/" + storePath.getFullPath(); return fileUrl; } /** * 删除文件 * @param fileUrl 文件访问地址 * @return */ public void deleteFile(String fileUrl) { if (StringUtils.isEmpty(fileUrl)) { return; } try { StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); } catch (FdfsUnsupportStorePathException e) { log.warn(e.getMessage()); } } // 除了FastDFSClientWrapper类中用到的api,客户端提供的api还有很多,可根据自身的业务需求,将其它接口也添加到工具类中即可。 // 上传文件,并添加文件元数据 //StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet); // 获取文件元数据 //Set<MateData> getMetadata(String groupName, String path); // 上传图片并同时生成一个缩略图 //StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet); // 。。。 }
repos\springboot-demo-master\fastdfs\src\main\java\com\et\fastdfs\util\FastDFSClientWrapper.java
1
请完成以下Java代码
public ValueType getType() { return type; } public void setEncoding(String encoding) { this.encoding = encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding.name(); } @Override public Charset getEncodingAsCharset() { if (encoding == null) { return null; } return Charset.forName(encoding); } @Override public String getEncoding() { return encoding; } /** * Get the byte array directly without wrapping it inside a stream to evade * not needed wrapping. This method is intended for the internal API, which * needs the byte array anyways. */ public byte[] getByteArray() {
return value; } @Override public String toString() { return "FileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", isTransient=" + isTransient + "]"; } @Override public boolean isTransient() { return isTransient; } public void setTransient(boolean isTransient) { this.isTransient = isTransient; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\FileValueImpl.java
1
请完成以下Java代码
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setESR_Control_Amount (final BigDecimal ESR_Control_Amount) { set_Value (COLUMNNAME_ESR_Control_Amount, ESR_Control_Amount); } @Override public BigDecimal getESR_Control_Amount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Amount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setESR_Control_Trx_Qty (final @Nullable BigDecimal ESR_Control_Trx_Qty) { set_Value (COLUMNNAME_ESR_Control_Trx_Qty, ESR_Control_Trx_Qty); } @Override public BigDecimal getESR_Control_Trx_Qty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Trx_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setESR_ImportFile_ID (final int ESR_ImportFile_ID) { if (ESR_ImportFile_ID < 1) set_ValueNoCheck (COLUMNNAME_ESR_ImportFile_ID, null); else set_ValueNoCheck (COLUMNNAME_ESR_ImportFile_ID, ESR_ImportFile_ID); } @Override public int getESR_ImportFile_ID() { return get_ValueAsInt(COLUMNNAME_ESR_ImportFile_ID); } @Override public de.metas.payment.esr.model.I_ESR_Import getESR_Import() { return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class); } @Override public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import) { set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import); } @Override public void setESR_Import_ID (final int ESR_Import_ID) { if (ESR_Import_ID < 1) set_Value (COLUMNNAME_ESR_Import_ID, null); else set_Value (COLUMNNAME_ESR_Import_ID, ESR_Import_ID); } @Override public int getESR_Import_ID() {
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID); } @Override public void setFileName (final @Nullable java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); } @Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportFile.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-consumer # Spring 应用名 cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 service: ${spring.appli
cation.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.name}。 server: port: 28080 # 服务器端口。默认为 8080
repos\SpringBoot-Labs-master\labx-01-spring-cloud-alibaba-nacos-discovery\labx-01-sca-nacos-discovery-demo01-consumer\src\main\resources\application.yaml
2
请完成以下Java代码
public static Set<Access> values() { return ALL_ACCESSES; } @NonNull String name; @NonNull String code; private Access(@NonNull final String name, final @NotNull String code) { Check.assumeNotEmpty(name, "name not empty"); this.name = name; this.code = code; } @Override public String toString() { return getName(); }
@Override @JsonValue public @NotNull String getCode() { return code; } public boolean isReadOnly() { return READ.equals(this); } public boolean isReadWrite() { return WRITE.equals(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\Access.java
1
请在Spring Boot框架中完成以下Java代码
public void setKeepAliveSeconds(int keepAliveSeconds) { AsyncExecutor.keepAliveSeconds = keepAliveSeconds; } @Value("${task.pool.queue-capacity}") public void setQueueCapacity(int queueCapacity) { AsyncExecutor.queueCapacity = queueCapacity; } /** * 自定义线程池,用法 @Async * @return Executor */ @Override public Executor getAsyncExecutor() { // 自定义工厂 ThreadFactory factory = r -> new Thread(r, "el-async-" + new AtomicInteger(1).getAndIncrement()); // 自定义线程池 return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueCapacity), factory,
new ThreadPoolExecutor.CallerRunsPolicy()); } /** * 自定义线程池,用法,注入到类中使用 * private ThreadPoolTaskExecutor taskExecutor; * @return ThreadPoolTaskExecutor */ @Bean("taskAsync") public ThreadPoolTaskExecutor taskAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(4); executor.setQueueCapacity(20); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("el-task-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\AsyncExecutor.java
2
请完成以下Java代码
public String getSummary() { final StringBuilder sb = new StringBuilder(); sb.append(getDocumentNo()); // - User sb.append(" - ").append(getUserName()); // : Total Lines = 123.00 sb.append(": ").append(Msg.translate(getCtx(), "TotalLines")).append("=").append(getTotalLines()); // - Description if (getDescription() != null && getDescription().length() > 0) { sb.append(" - ").append(getDescription()); } return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateDoc()); } @Override public String getProcessMsg() { return m_processMsg; } @Override public int getDoc_User_ID() { return getAD_User_ID(); } @Override public int getC_Currency_ID()
{ final I_M_PriceList pl = Services.get(IPriceListDAO.class).getById(getM_PriceList_ID()); return pl.getC_Currency_ID(); } /** * Get Document Approval Amount * * @return amount */ @Override public BigDecimal getApprovalAmt() { return getTotalLines(); } private String getUserName() { return Services.get(IUserDAO.class).retrieveUserOrNull(getCtx(), getAD_User_ID()).getName(); } /** * @return true if CO, CL or RE */ public boolean isComplete() { final String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequisition.java
1
请完成以下Java代码
public class ClassLoaderFileURLStreamHandler extends URLStreamHandler { private final ClassLoaderFile file; public ClassLoaderFileURLStreamHandler(ClassLoaderFile file) { this.file = file; } @Override protected URLConnection openConnection(URL url) throws IOException { return new Connection(url); } private class Connection extends URLConnection { Connection(URL url) { super(url); } @Override
public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { byte[] contents = ClassLoaderFileURLStreamHandler.this.file.getContents(); Assert.state(contents != null, "'contents' must not be null"); return new ByteArrayInputStream(contents); } @Override public long getLastModified() { return ClassLoaderFileURLStreamHandler.this.file.getLastModified(); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFileURLStreamHandler.java
1
请完成以下Java代码
public OrderAndLineId execute() { final OrderAndLineId orderAndLineId = OrderAndLineId.ofNullable(orderCost.getOrderId(), orderCost.getCreatedOrderLineId()); final I_C_OrderLine orderLine = orderAndLineId != null ? orderBL.getLineById(orderAndLineId) : orderBL.createOrderLine(getOrder()); if (productId != null) { orderBL.setProductId(orderLine, productId, true); } orderLine.setQtyEntered(BigDecimal.ONE); orderLine.setQtyOrdered(BigDecimal.ONE); orderLine.setIsManualPrice(true); orderLine.setIsPriceEditable(false); final Money costAmountConv = convertToOrderCurrency(orderCost.getCostAmount()); orderLine.setPriceEntered(costAmountConv.toBigDecimal()); orderLine.setPriceActual(costAmountConv.toBigDecimal()); orderLine.setIsManualDiscount(true); orderLine.setDiscount(BigDecimal.ZERO); orderBL.save(orderLine);
return OrderAndLineId.ofRepoIds(orderLine.getC_Order_ID(), orderLine.getC_OrderLine_ID()); } private I_C_Order getOrder() { if (_order == null) { _order = orderBL.getById(orderCost.getOrderId()); } return _order; } private Money convertToOrderCurrency(final Money amt) { final I_C_Order order = getOrder(); final CurrencyId orderCurrencyId = CurrencyId.ofRepoId(order.getC_Currency_ID()); final CurrencyConversionContext conversionCtx = orderBL.getCurrencyConversionContext(order); return moneyService.convertMoneyToCurrency(amt, orderCurrencyId, conversionCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\CreateOrUpdateOrderLineFromOrderCostCommand.java
1
请完成以下Java代码
public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final PickingSlotQuery query) { return pickingSlotDAO.retrievePickingSlotIdAndCaptions(query); } @Override public QRCodePDFResource createQRCodesPDF(@NonNull final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions) { Check.assumeNotEmpty(pickingSlotIdAndCaptions, "pickingSlotIdAndCaptions is not empty"); final ImmutableList<PrintableQRCode> qrCodes = pickingSlotIdAndCaptions.stream() .map(PickingSlotQRCode::ofPickingSlotIdAndCaption) .map(PickingSlotQRCode::toPrintableQRCode) .collect(ImmutableList.toImmutableList()); final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class); return globalQRCodeService.createPDF(qrCodes); } @Override public boolean isAvailableForAnyBPartner(@NonNull final PickingSlotId pickingSlotId)
{ return isAvailableForAnyBPartner(pickingSlotDAO.getById(pickingSlotId)); } @NonNull public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getById(pickingSlotId); } @Override public boolean isPickingRackSystem(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.isPickingRackSystem(pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotBL.java
1
请在Spring Boot框架中完成以下Java代码
private QueryBuilder createQueryBuilder(String keyword, String... fieldNames){ // 构造查询条件,使用标准分词器. return QueryBuilders.multiMatchQuery(keyword,fieldNames) // matchQuery(),单字段搜索 .analyzer("ik_max_word") .operator(Operator.OR); } /** * 构造高亮器 * @auther: zhoudong * @date: 2018/12/18 10:44 */ private HighlightBuilder createHighlightBuilder(String... fieldNames){ // 设置高亮,使用默认的highlighter高亮器 HighlightBuilder highlightBuilder = new HighlightBuilder() // .field("productName") .preTags("<span style='color:red'>") .postTags("</span>"); // 设置高亮字段 for (String fieldName: fieldNames) highlightBuilder.field(fieldName); return highlightBuilder; } /** * 处理高亮结果 * @auther: zhoudong * @date: 2018/12/18 10:48 */
private List<Map<String,Object>> getHitList(SearchHits hits){ List<Map<String,Object>> list = new ArrayList<>(); Map<String,Object> map; for(SearchHit searchHit : hits){ map = new HashMap<>(); // 处理源数据 map.put("source",searchHit.getSourceAsMap()); // 处理高亮数据 Map<String,Object> hitMap = new HashMap<>(); searchHit.getHighlightFields().forEach((k,v) -> { String hight = ""; for(Text text : v.getFragments()) hight += text.string(); hitMap.put(v.getName(),hight); }); map.put("highlight",hitMap); list.add(map); } return list; } @Override public void deleteIndex(String indexName) { elasticsearchTemplate.deleteIndex(indexName); } }
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\service\impl\BaseSearchServiceImpl.java
2
请完成以下Java代码
public class SponsorNoAutoCompleter extends FieldAutoCompleter { public SponsorNoAutoCompleter(JTextComponent comp) { super(comp); } @Override protected String getSelectSQL(String search, int caretPosition, List<Object> params) { if (caretPosition > 0 && caretPosition < search.length()) { search = new StringBuffer(search).insert(caretPosition, "%").toString(); } String searchSQL = StringUtils.stripDiacritics(search.toUpperCase()); if (!searchSQL.endsWith("%")) { searchSQL += "%"; } final DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); final String sql_strRep = "sp.SponsorNo || ' - VP - ' || bp.name"; final String sql = "SELECT sp.SponsorNo, bp.Name, sp.C_Sponsor_ID, " + sql_strRep + " as string_rep" + " FROM C_Sponsor_Salesrep ssr" + " LEFT JOIN C_Sponsor sp ON (ssr.C_Sponsor_ID = sp.C_Sponsor_ID)" + " LEFT JOIN C_BPartner bp ON (ssr.C_BPartner_ID = bp.C_BPartner_ID)" + " WHERE (sp.SponsorNo LIKE ?" + " OR upper(bp.Name) LIKE ?)" + " AND '" + df.format(Env.getContextAsDate(Env.getCtx(), "#Date")) + "' BETWEEN ssr.Validfrom AND ssr.Validto" + " ORDER BY sp.SponsorNo"
; params.add(searchSQL); // SponsorNo params.add(searchSQL); // Name // return sql; } @Override protected Object fetchUserObject(ResultSet rs) throws SQLException { int sponsorID = rs.getInt("C_Sponsor_ID"); String sponsorNo = rs.getString("SponsorNo"); String name = rs.getString("Name"); SponsorNoObject o = new SponsorNoObject(sponsorID, sponsorNo, name); o.setStringRepresentation(rs.getString("string_rep")); return o; } @Override protected boolean isMatching(Object userObject, String search) { // return super.isMatching(userObject, search); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\SponsorNoAutoCompleter.java
1
请在Spring Boot框架中完成以下Java代码
public class EDIDocOutBoundLogService { private final IDocOutboundDAO docOutboundDAO = Services.get(IDocOutboundDAO.class); /** * @param recordReference if this in an {@link I_C_Invoice}, then set the {@code C_Doc_Outbound_Log.EDI_ExportStatus} of all referencing log records to the invoice's current status. * @return changed log record or {@code null} */ public Optional<I_C_Doc_Outbound_Log> setEdiExportStatusFromInvoiceRecord(@NonNull final TableRecordReference recordReference) { if (!I_C_Invoice.Table_Name.equals(recordReference.getTableName())) { return Optional.empty(); } final I_C_Doc_Outbound_Log logRecord = create(docOutboundDAO.retrieveLog(recordReference), I_C_Doc_Outbound_Log.class); if (logRecord != null) { logRecord.setEDI_ExportStatus(getEDIExportStatusFromInvoiceRecord(recordReference)); } return Optional.ofNullable(logRecord); } @Nullable public String getEDIExportStatusFromInvoiceRecord(final @NonNull TableRecordReference recordReference) { if (!I_C_Invoice.Table_Name.equals(recordReference.getTableName())) { return null;
} final I_C_Invoice invoiceRecord = recordReference.getModel(I_C_Invoice.class); return invoiceRecord.getEDI_ExportStatus(); } public I_C_Doc_Outbound_Log retreiveById(@NonNull final DocOutboundLogId docOutboundLogId) { return load(docOutboundLogId, I_C_Doc_Outbound_Log.class); } public I_C_Invoice retreiveById(@NonNull final InvoiceId invoiceId) { return load(invoiceId, I_C_Invoice.class); } public void save(@NonNull final de.metas.edi.model.I_C_Doc_Outbound_Log docOutboundLog) { InterfaceWrapperHelper.save(docOutboundLog); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\EDIDocOutBoundLogService.java
2
请在Spring Boot框架中完成以下Java代码
public MobileApplication getById(@NonNull final MobileApplicationId id) { return applications.getById(id); } public void logout(@NonNull final IUserRolePermissions permissions) { final UserId userId = permissions.getUserId(); final MobileApplicationPermissions mobileApplicationPermissions = permissions.getMobileApplicationPermissions(); applications.stream() .filter(application -> hasAccess(application.getApplicationId(), mobileApplicationPermissions)) .forEach(application -> { try { application.logout(userId); } catch (Exception ex) { logger.warn("Application {} failed to logout. Skipped", application, ex); }
}); } private boolean hasAccess(@NonNull final MobileApplicationId applicationId, @NonNull final MobileApplicationPermissions permissions) { final MobileApplicationRepoId repoId = applicationInfoRepository.getById(applicationId).getRepoId(); return permissions.isAllowAccess(repoId); } private boolean hasActionAccess(@NonNull final MobileApplicationId applicationId, @NonNull String actionInternalName, final MobileApplicationPermissions permissions) { final MobileApplicationInfo applicationInfo = applicationInfoRepository.getById(applicationId); final MobileApplicationActionId actionId = applicationInfo.getActionIdByInternalName(actionInternalName).orElse(null); if (actionId == null) { return false; } return permissions.isAllowAction(applicationInfo.getRepoId(), actionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\application\service\MobileApplicationService.java
2
请完成以下Java代码
public void updatePrinterTrayMatching(@NonNull final I_AD_Printer_Matching printerMatching) { final IPrintingDAO dao = Services.get(IPrintingDAO.class); final HardwarePrinterId printerID = HardwarePrinterId.ofRepoId(printerMatching.getAD_PrinterHW_ID()); final List<I_AD_PrinterHW_MediaTray> hwTrays = dao.retrieveMediaTrays(printerID); final List<I_AD_PrinterTray_Matching> existingPrinterTrayMatchings = dao.retrievePrinterTrayMatchings(printerMatching); final I_AD_PrinterHW_MediaTray defaultHWTray = hwTrays.isEmpty() ? null : hwTrays.get(0); if (defaultHWTray == null) { // the new HW printer has no tray // delete existing tray matchings; for (final I_AD_PrinterTray_Matching trayMatching : existingPrinterTrayMatchings) { delete(trayMatching); } } else if (existingPrinterTrayMatchings.isEmpty() && defaultHWTray != null) { // the old HW printer didn't have a tray, but the new one does // create a new matching for every logical tray final LogicalPrinterId printerId = LogicalPrinterId.ofRepoId(printerMatching.getAD_Printer_ID()); for (final I_AD_Printer_Tray logicalTray : dao.retrieveTrays(printerId)) { final I_AD_PrinterTray_Matching trayMatching = newInstance(I_AD_PrinterTray_Matching.class, printerMatching); trayMatching.setAD_Printer_Matching(printerMatching); trayMatching.setAD_Printer_Tray(logicalTray); trayMatching.setAD_PrinterHW_MediaTray(defaultHWTray);
save(trayMatching); } } else { final I_AD_Printer printer = load(printerMatching.getAD_Printer_ID(), I_AD_Printer.class); Check.assumeNotNull(defaultHWTray, "{} has at least one tray", printer); Check.assume(!existingPrinterTrayMatchings.isEmpty(), "{} has at least one tray matching", printerMatching); for (final I_AD_PrinterTray_Matching trayMatching : existingPrinterTrayMatchings) { trayMatching.setAD_PrinterHW_MediaTray(defaultHWTray); save(trayMatching); } } } @Override public boolean isAttachToPrintPackagePrinter(@NonNull final I_AD_PrinterHW printerHW) { return X_AD_PrinterHW.OUTPUTTYPE_Attach.equals(printerHW.getOutputType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrinterBL.java
1
请完成以下Java代码
public class ArticleTitle { @Column(nullable = false) private String title; @Column(nullable = false) private String slug; public static ArticleTitle of(String title) { return new ArticleTitle(title, slugFromTitle(title)); } private ArticleTitle(String title, String slug) { this.title = title; this.slug = slug; } protected ArticleTitle() { } private static String slugFromTitle(String title) { return title.toLowerCase() .replaceAll("\\$,'\"|\\s|\\.|\\?", "-") .replaceAll("-{2,}", "-") .replaceAll("(^-)|(-$)", ""); } public String getSlug() { return slug; }
public String getTitle() { return title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArticleTitle that = (ArticleTitle) o; return slug.equals(that.slug); } @Override public int hashCode() { return Objects.hash(slug); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\ArticleTitle.java
1
请完成以下Java代码
Set<String> getColumnNames() { return map.keySet(); } @NonNull public Cell getCell(@NonNull final String columnName) { final Cell value = map.get(columnName); return value != null ? value : Cell.NULL; } public boolean isBlankColumn(final String columnName) { final Cell cell = getCell(columnName); return cell.isBlank(); } public int getColumnWidth(final String columnName) { final Cell cell = getCell(columnName); return cell.getWidth(); } public String getCellValue(@NonNull final String columnName) { final Cell cell = getCell(columnName); return cell.getAsString(); }
public void put(@NonNull final String columnName, @NonNull final Cell value) { map.put(columnName, value); } public void put(@NonNull final String columnName, @Nullable final Object valueObj) { map.put(columnName, Cell.ofNullable(valueObj)); } public void putAll(@NonNull final Map<String, ?> map) { map.forEach((columnName, value) -> this.map.put(columnName, Cell.ofNullable(value))); } public boolean containsColumn(final String columnName) { return map.containsKey(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Row.java
1
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { Context .getCommandContext() .getDbEntityManager() .delete(this); } @Override public String toString() { return this.getClass().getSimpleName()
+ "[activityInstanceId=" + activityInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", id=" + id + ", tenantId=" + tenantId + ", userOperationId=" + userOperationId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDetailEventEntity.java
1
请完成以下Java代码
public final class QualityInvoiceLineGroupByTypeComparator implements Comparator<IQualityInvoiceLineGroup> { /** * Maps {@link QualityInvoiceLineGroupType} to it's sorting priority. */ private final Map<QualityInvoiceLineGroupType, Integer> type2index = new HashMap<>(); /** Index to be used when type was not found */ private final static int INDEX_NotFound = 10000000; public QualityInvoiceLineGroupByTypeComparator(final QualityInvoiceLineGroupType... inspectionLineTypes) { this(Arrays.asList(inspectionLineTypes)); } public QualityInvoiceLineGroupByTypeComparator(final List<QualityInvoiceLineGroupType> inspectionLineTypes) { super(); Check.assumeNotEmpty(inspectionLineTypes, "inspectionLineTypes not empty"); // // Build type to priority index map for (int index = 0; index < inspectionLineTypes.size(); index++) { final QualityInvoiceLineGroupType type = inspectionLineTypes.get(index); Check.assumeNotNull(type, "type not null"); final Integer indexOld = type2index.put(type, index); if (indexOld != null) { throw new IllegalArgumentException("Duplicate type " + type + " found in " + inspectionLineTypes); } } } @Override public int compare(final IQualityInvoiceLineGroup line1, final IQualityInvoiceLineGroup line2) { final int index1 = getIndex(line1); final int index2 = getIndex(line2); return index1 - index2; } private final int getIndex(final IQualityInvoiceLineGroup line) { Check.assumeNotNull(line, "line not null"); final QualityInvoiceLineGroupType type = line.getQualityInvoiceLineGroupType(); final Integer index = type2index.get(type); if (index == null) { return INDEX_NotFound; } return index; }
private final boolean hasType(final QualityInvoiceLineGroupType type) { return type2index.containsKey(type); } /** * Remove from given lines those which their type is not specified in our list. * * NOTE: we assume the list is read-write. * * @param groups */ public void filter(final List<IQualityInvoiceLineGroup> groups) { for (final Iterator<IQualityInvoiceLineGroup> it = groups.iterator(); it.hasNext();) { final IQualityInvoiceLineGroup group = it.next(); final QualityInvoiceLineGroupType type = group.getQualityInvoiceLineGroupType(); if (!hasType(type)) { it.remove(); } } } /** * Sort given lines with this comparator. * * NOTE: we assume the list is read-write. * * @param lines */ public void sort(final List<IQualityInvoiceLineGroup> lines) { Collections.sort(lines, this); } /** * Remove from given lines those which their type is not specified in our list. Then sort the result. * * NOTE: we assume the list is read-write. * * @param lines */ public void filterAndSort(final List<IQualityInvoiceLineGroup> lines) { filter(lines); sort(lines); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\QualityInvoiceLineGroupByTypeComparator.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableListMultimap<BPartnerId, I_C_BP_BankAccount> getAllByBPartnerIds(@NonNull final Collection<BPartnerId> bpartnerIds) { if (bpartnerIds.isEmpty()) { return ImmutableListMultimap.of(); } return queryBL.createQueryBuilderOutOfTrx(I_C_BP_BankAccount.class) .addInArrayFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, bpartnerIds) .create() .stream() .collect(ImmutableListMultimap.toImmutableListMultimap( record -> BPartnerId.ofRepoId(record.getC_BPartner_ID()), record -> record)); } @Override public List<BPartnerBankAccount> getBpartnerBankAccount(final BankAccountQuery query) { final IQueryBuilder<I_C_BP_BankAccount> queryBuilder = queryBL.createQueryBuilder(I_C_BP_BankAccount.class) .addOnlyActiveRecordsFilter() .orderByDescending(I_C_BP_BankAccount.COLUMNNAME_IsDefault); // DESC (Y, then N) if (query.getBPartnerId() != null) { queryBuilder.addEqualsFilter(org.compiere.model.I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, query.getBPartnerId()); } else if (query.getInvoiceId() != null) { queryBuilder.addInSubQueryFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, I_C_Invoice.COLUMNNAME_C_BPartner_ID, queryBL.createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_C_Invoice_ID, query.getInvoiceId()) .create()); } final Collection<BPBankAcctUse> bankAcctUses = query.getBpBankAcctUses(); if (bankAcctUses != null && !bankAcctUses.isEmpty()) { queryBuilder.addInArrayFilter(I_C_BP_BankAccount.COLUMNNAME_BPBankAcctUse, bankAcctUses); } if (query.isContainsQRIBAN()) { queryBuilder.addNotNull(I_C_BP_BankAccount.COLUMNNAME_QR_IBAN); } queryBuilder.orderBy(I_C_BP_BankAccount.COLUMN_C_BP_BankAccount_ID); return queryBuilder.create() .stream() .map(this::of)
.collect(ImmutableList.toImmutableList()); } @NonNull private BPartnerBankAccount of(@NonNull final I_C_BP_BankAccount record) { return BPartnerBankAccount.builder() .id(BPartnerBankAccountId.ofRepoId(record.getC_BPartner_ID(), record.getC_BP_BankAccount_ID())) .currencyId(CurrencyId.ofRepoId(record.getC_Currency_ID())) .active(record.isActive()) .orgMappingId(OrgMappingId.ofRepoIdOrNull(record.getAD_Org_Mapping_ID())) .iban(record.getIBAN()) .qrIban(record.getQR_IBAN()) .bankId(BankId.ofRepoIdOrNull(record.getC_Bank_ID())) .accountName(record.getA_Name()) .accountStreet(record.getA_Street()) .accountZip(record.getA_Zip()) .accountCity(record.getA_City()) .accountCountry(record.getA_Country()) //.changeLog() .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPBankAccountDAO.java
2
请完成以下Java代码
private XMLPatientAddress createXmlPatientAddress(@NonNull final PatientAddressType patient) { final XMLPatientAddress.XMLPatientAddressBuilder patientAddressBuilder = XMLPatientAddress.builder(); if (patient.getPerson() != null) { patientAddressBuilder.person(createXmlPersonType(patient.getPerson())); } return patientAddressBuilder.build(); } private XMLPersonType createXmlPersonType(@NonNull final PersonType person) { return XMLPersonType.builder() .familyName(person.getFamilyname()) .givenName(person.getGivenname()) .build(); } private XmlRejected createXmlRejected(@NonNull final RejectedType rejected) { final XmlRejectedBuilder rejectedBuilder = XmlRejected.builder(); rejectedBuilder.explanation(rejected.getExplanation()) .statusIn(rejected.getStatusIn()) .statusOut(rejected.getStatusOut()); if (rejected.getError() != null && !rejected.getError().isEmpty()) { rejectedBuilder.errors(createXmlErrors(rejected.getError())); } return rejectedBuilder.build(); }
private List<XmlError> createXmlErrors(@NonNull final List<ErrorType> error) { final ImmutableList.Builder<XmlError> errorsBuilder = ImmutableList.builder(); for (final ErrorType errorType : error) { final XmlError xmlError = XmlError .builder() .code(errorType.getCode()) .errorValue(errorType.getErrorValue()) .recordId(errorType.getRecordId()) .text(errorType.getText()) .validValue(errorType.getValidValue()) .build(); errorsBuilder.add(xmlError); } return errorsBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Invoice440ToCrossVersionModelTool.java
1
请完成以下Java代码
public void setIsArchived (final boolean IsArchived) { set_Value (COLUMNNAME_IsArchived, IsArchived); } @Override public boolean isArchived() { return get_ValueAsBoolean(COLUMNNAME_IsArchived); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); }
@Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setTitleShort (final @Nullable java.lang.String TitleShort) { set_Value (COLUMNNAME_TitleShort, TitleShort); } @Override public java.lang.String getTitleShort() { return get_ValueAsString(COLUMNNAME_TitleShort); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_Alberta.java
1
请完成以下Java代码
protected String doIt() { final I_C_Location location = getSelectedLocationOrFirstAvailable(); final DocumentFilter filter = createAreaSearchFilter(location); final IView view = createViewWithFilter(filter); getResult().setWebuiViewToOpen( ProcessExecutionResult.WebuiViewToOpen.builder() .viewId(view.getViewId().toJson()) .target(ProcessExecutionResult.ViewOpenTarget.NewBrowserTab) .build()); return MSG_OK; } private IView createViewWithFilter(final DocumentFilter filter) { final WindowId windowId = getWindowId(); return viewsRepo.createView(CreateViewRequest.builder(windowId) .setFilters(DocumentFilterList.of(filter)) .build()); } @NonNull private WindowId getWindowId() { return WindowId.of(getProcessInfo().getAdWindowId().getRepoId()); } @NonNull private DocumentFilter createAreaSearchFilter(final I_C_Location location) { final DocumentEntityDescriptor entityDescriptor = documentCollection.getDocumentEntityDescriptor(getWindowId()); final GeoLocationDocumentQuery query = createGeoLocationQuery(location); return geoLocationDocumentService.createDocumentFilter(entityDescriptor, query); }
private GeoLocationDocumentQuery createGeoLocationQuery(final I_C_Location location) { final CountryId countryId = CountryId.ofRepoId(location.getC_Country_ID()); final ITranslatableString countryName = countriesRepo.getCountryNameById(countryId); return GeoLocationDocumentQuery.builder() .country(IntegerLookupValue.of(countryId, countryName)) .address1(location.getAddress1()) .city(location.getCity()) .postal(location.getPostal()) .distanceInKm(distanceInKm) .visitorsAddress(visitorsAddress) .build(); } private I_C_Location getSelectedLocationOrFirstAvailable() { final Set<Integer> bpLocationIds = getSelectedIncludedRecordIds(I_C_BPartner_Location.class); if (!bpLocationIds.isEmpty()) { // retrieve the selected location final LocationId locationId = bpartnersRepo.getBPartnerLocationAndCaptureIdInTrx(BPartnerLocationId.ofRepoId(getRecord_ID(), bpLocationIds.iterator().next())).getLocationCaptureId(); return locationsRepo.getById(locationId); } else { // retrieve the first bpartner location available final List<I_C_BPartner_Location> partnerLocations = bpartnersRepo.retrieveBPartnerLocations(BPartnerId.ofRepoId(getRecord_ID())); if (!partnerLocations.isEmpty()) { return locationsRepo.getById(LocationId.ofRepoId(partnerLocations.get(0).getC_Location_ID())); } } throw new AdempiereException("@NotFound@ @C_Location_ID@"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\location\geocoding\process\C_BPartner_Window_AreaSearchProcess.java
1
请完成以下Java代码
public void assertNoHUAssignments(final org.eevolution.model.I_PP_Cost_Collector cc) { Services.get(IHUAssignmentDAO.class).assertNoHUAssignmentsForModel(cc); } /** * @return assigned top level HUs (i.e. the HUs which were assigned to original cost collector). */ @Override public List<I_M_HU> getTopLevelHUs(final org.eevolution.model.I_PP_Cost_Collector cc) { final IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class); return huAssignmentDAO.retrieveTopLevelHUsForModel(cc); } @Override public void restoreTopLevelHUs(final I_PP_Cost_Collector costCollector) { Check.assumeNotNull(costCollector, "costCollector not null"); // // Retrieve the HUs which were assigned to original cost collector final List<I_M_HU> hus = getTopLevelHUs(costCollector); if (hus.isEmpty()) { return; }
// // Get the snapshot ID. // Make sure it exists, else we would not be able to restore the HUs. final String snapshotId = costCollector.getSnapshot_UUID(); if (Check.isEmpty(snapshotId, true)) { throw new HUException("@NotFound@ @Snapshot_UUID@ (" + costCollector + ")"); } final IContextAware context = InterfaceWrapperHelper.getContextAware(costCollector); Services.get(IHUSnapshotDAO.class).restoreHUs() .setContext(context) .setSnapshotId(snapshotId) .setDateTrx(costCollector.getMovementDate()) .setReferencedModel(costCollector) .addModels(hus) .restoreFromSnapshot(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPCostCollectorBL.java
1
请完成以下Java代码
static MetricsClientMeters newClientMetricsMeters(MeterRegistry registry) { MetricsClientMeters.Builder builder = MetricsClientMeters.newBuilder(); builder.setAttemptCounter(Counter.builder(CLIENT_ATTEMPT_STARTED) .description( "The total number of RPC attempts started from the client side, including " + "those that have not completed.") .withRegistry(registry)); builder.setSentMessageSizeDistribution(DistributionSummary.builder( CLIENT_ATTEMPT_SENT_COMPRESSED_MESSAGE_SIZE) .description("Compressed message bytes sent per client call attempt") .baseUnit(BaseUnits.BYTES) .serviceLevelObjectives(DEFAULT_SIZE_BUCKETS) .withRegistry(registry)); builder.setReceivedMessageSizeDistribution(DistributionSummary.builder( CLIENT_ATTEMPT_RECEIVED_COMPRESSED_MESSAGE_SIZE) .description("Compressed message bytes received per call attempt") .baseUnit(BaseUnits.BYTES) .serviceLevelObjectives(DEFAULT_SIZE_BUCKETS)
.withRegistry(registry)); builder.setClientAttemptDuration(Timer.builder(CLIENT_ATTEMPT_DURATION) .description("Time taken to complete a client call attempt") .serviceLevelObjectives(DEFAULT_LATENCY_BUCKETS) .withRegistry(registry)); builder.setClientCallDuration(Timer.builder(CLIENT_CALL_DURATION) .description("Time taken by gRPC to complete an RPC from application's perspective") .serviceLevelObjectives(DEFAULT_LATENCY_BUCKETS) .withRegistry(registry)); return builder.build(); } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientInstruments.java
1
请完成以下Java代码
private I_M_Product getM_Product() { final IProductionMaterial productionMaterial = getProductionMaterialOrNull(); if (productionMaterial != null) { return productionMaterial.getM_Product(); } else { return null; // N/A } } @Override public final IQualityInspectionLineBuilder setQty(final BigDecimal qty) { _qty = qty; _qtySet = true; return this; } /** * Gets Quantity to set in report. * * NOTE: returned value is not affected by {@link #isNegateQty()}. * * @return quantity */ protected final BigDecimal getQtyToSet() { BigDecimal qty; if (_qtySet) { qty = _qty; } else { final IProductionMaterial productionMaterial = getProductionMaterial(); qty = productionMaterial.getQty(); } return qty; } @Override public final IQualityInspectionLineBuilder setNegateQty(final boolean negateQty) { _negateQty = negateQty; return this; } protected final boolean isNegateQty() { return _negateQty; } @Override public final IQualityInspectionLineBuilder setQtyProjected(final BigDecimal qtyProjected) { _qtyProjected = qtyProjected; _qtyProjectedSet = true; return this; } protected boolean isQtyProjectedSet() { return _qtyProjectedSet; } protected BigDecimal getQtyProjected() { return _qtyProjected; } @Override public final IQualityInspectionLineBuilder setC_UOM(final I_C_UOM uom) { _uom = uom; _uomSet = true; return this; } protected final I_C_UOM getC_UOM() { if (_uomSet) { return _uom; }
else { final IProductionMaterial productionMaterial = getProductionMaterial(); return productionMaterial.getC_UOM(); } } @Override public final IQualityInspectionLineBuilder setPercentage(final BigDecimal percentage) { _percentage = percentage; return this; } private BigDecimal getPercentage() { return _percentage; } @Override public final IQualityInspectionLineBuilder setName(final String name) { _name = name; return this; } protected final String getName() { return _name; } private IHandlingUnitsInfo getHandlingUnitsInfoToSet() { if (_handlingUnitsInfoSet) { return _handlingUnitsInfo; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfo = handlingUnitsInfo; _handlingUnitsInfoSet = true; return this; } private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet() { if (_handlingUnitsInfoProjectedSet) { return _handlingUnitsInfoProjected; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfoProjected = handlingUnitsInfo; _handlingUnitsInfoProjectedSet = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java
1
请完成以下Java代码
public static Set<ProductBOMId> ofRepoIds(final Collection<Integer> repoIds) { return repoIds.stream() .filter(repoId -> repoId != null && repoId > 0) .map(ProductBOMId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } public static int toRepoId(@Nullable final ProductBOMId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals( @Nullable final ProductBOMId o1, @Nullable final ProductBOMId o2)
{ return Objects.equals(o1, o2); } private ProductBOMId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Product_BOM_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\ProductBOMId.java
1
请完成以下Java代码
public boolean isClusterMode() { return clusterMode; } public FlowRuleEntity setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; return this; } public ClusterFlowConfig getClusterConfig() { return clusterConfig; } public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) { this.clusterConfig = clusterConfig; return this; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public FlowRule toRule() { FlowRule flowRule = new FlowRule();
flowRule.setCount(this.count); flowRule.setGrade(this.grade); flowRule.setResource(this.resource); flowRule.setLimitApp(this.limitApp); flowRule.setRefResource(this.refResource); flowRule.setStrategy(this.strategy); if (this.controlBehavior != null) { flowRule.setControlBehavior(controlBehavior); } if (this.warmUpPeriodSec != null) { flowRule.setWarmUpPeriodSec(warmUpPeriodSec); } if (this.maxQueueingTimeMs != null) { flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); } flowRule.setClusterMode(clusterMode); flowRule.setClusterConfig(clusterConfig); return flowRule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java
1
请完成以下Java代码
protected boolean beforeSave(boolean newRecord) { if (!isInstanceAttribute()) setIsInstanceAttribute(true); return true; } // beforeSave @Override protected boolean afterSave(boolean newRecord, boolean success) { // Set Instance Attribute if (!isInstanceAttribute()) { String sql = "UPDATE M_AttributeSet mas" + " SET IsInstanceAttribute='Y' " + "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID() + " AND IsInstanceAttribute='N'" + " AND (EXISTS (SELECT * FROM M_AttributeUse mau" + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) " + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID" + " AND mau.IsActive='Y' AND ma.IsActive='Y'" + " AND ma.IsInstanceAttribute='Y')" + ")"; int no = DB.executeUpdateAndThrowExceptionOnFail(sql, get_TrxName()); if (no != 0) { log.warn("Set Instance Attribute"); setIsInstanceAttribute(true); }
} // Reset Instance Attribute if (isInstanceAttribute()) { String sql = "UPDATE M_AttributeSet mas" + " SET IsInstanceAttribute='N' " + "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID() + " AND IsInstanceAttribute='Y'" + " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau" + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) " + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID" + " AND mau.IsActive='Y' AND ma.IsActive='Y'" + " AND ma.IsInstanceAttribute='Y')"; int no = DB.executeUpdateAndThrowExceptionOnFail(sql, get_TrxName()); if (no != 0) { log.warn("Reset Instance Attribute"); setIsInstanceAttribute(false); } } return success; } // afterSave } // MAttributeSet
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAttributeSet.java
1
请完成以下Java代码
public static List<String> usingOrElse(Optional<String> obj) { List<String> arrayList = new ArrayList<>(); arrayList.add(obj.orElse("Hello, World!")); return arrayList; } public static List<String> usingOrElseGet(Optional<String> obj) { List<String> arrayList = new ArrayList<>(); arrayList.add(obj.orElseGet(() -> "Hello, World!")); return arrayList; } public static List<String> usingStream(Optional<String> obj) { List<String> arrayList = obj.stream() .collect(Collectors.toList()); return arrayList;
} public static List<String> usingStreamFilter(Optional<String> obj) { List<String> arrayList = obj.filter(e -> e.startsWith("H")) .stream() .collect(Collectors.toList()); return arrayList; } public static List<String> usingStreamFlatMap(Optional<List<String>> obj) { List<String> arrayList = obj.stream() .flatMap(List::stream) .collect(Collectors.toList()); return arrayList; } }
repos\tutorials-master\core-java-modules\core-java-collections-conversions-3\src\main\java\com\baeldung\optionaltoarraylist\OptionalToArrayListConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoryServiceImpl extends ServiceImpl implements HistoryService { public HistoryServiceImpl(ProcessEngineConfigurationImpl processEngineConfiguration) { super(processEngineConfiguration); } public HistoricProcessInstanceQuery createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(commandExecutor); } public HistoricActivityInstanceQuery createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(commandExecutor); } public HistoricTaskInstanceQuery createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(commandExecutor, processEngineConfiguration.getDatabaseType()); } public HistoricDetailQuery createHistoricDetailQuery() { return new HistoricDetailQueryImpl(commandExecutor); } @Override public NativeHistoricDetailQuery createNativeHistoricDetailQuery() { return new NativeHistoricDetailQueryImpl(commandExecutor); } public HistoricVariableInstanceQuery createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(commandExecutor); } @Override public NativeHistoricVariableInstanceQuery createNativeHistoricVariableInstanceQuery() { return new NativeHistoricVariableInstanceQueryImpl(commandExecutor); } public void deleteHistoricTaskInstance(String taskId) { commandExecutor.execute(new DeleteHistoricTaskInstanceCmd(taskId)); }
public void deleteHistoricProcessInstance(String processInstanceId) { commandExecutor.execute(new DeleteHistoricProcessInstanceCmd(processInstanceId)); } public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() { return new NativeHistoricProcessInstanceQueryImpl(commandExecutor); } public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() { return new NativeHistoricTaskInstanceQueryImpl(commandExecutor); } public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() { return new NativeHistoricActivityInstanceQueryImpl(commandExecutor); } @Override public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId)); } @Override public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null)); } @Override public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) { return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoryServiceImpl.java
2
请完成以下Java代码
public CaseFileItem getContext() { return contextRefAttribute.getReferenceTargetElement(this); } public void setContext(CaseFileItem caseFileItem) { contextRefAttribute.setReferenceTargetElement(this, caseFileItem); } public ConditionExpression getCondition() { return conditionChild.getChild(this); } public void setCondition(ConditionExpression condition) { conditionChild.setChild(this, condition); } public String getCamundaRepeatOnStandardEvent() { return camundaRepeatOnStandardEventAttribute.getValue(this); } public void setCamundaRepeatOnStandardEvent(String standardEvent) { camundaRepeatOnStandardEventAttribute.setValue(this, standardEvent); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(RepetitionRule.class, CMMN_ELEMENT_REPETITION_RULE) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<RepetitionRule>() { public RepetitionRule newInstance(ModelTypeInstanceContext instanceContext) { return new RepetitionRuleImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF) .idAttributeReference(CaseFileItem.class) .build(); /** Camunda extensions */ camundaRepeatOnStandardEventAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_REPEAT_ON_STANDARD_EVENT) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionChild = sequenceBuilder.element(ConditionExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\RepetitionRuleImpl.java
1
请完成以下Java代码
public BigDecimal getCUNetAmtNotApproved() { return _cuNetAmtNotApproved; } public BigDecimal getTotalNetAmt() { return _totalNetAmtApproved.add(_totalNetAmtNotApproved); } public BigDecimal getTotalNetAmt(final boolean isApprovedForInvoicing) { if (isApprovedForInvoicing) { return getTotalNetAmtApproved(); } else { return getTotalNetAmt(); } } public int getCountTotalToRecompute() { return countTotalToRecompute; } public Set<String> getCurrencySymbols() { return currencySymbols; } @Override public String toString() { return getSummaryMessage(); } /** * Keep in sync with {@link de.metas.ui.web.view.OrderCandidateViewHeaderPropertiesProvider#toViewHeaderProperties(de.metas.invoicecandidate.api.impl.InvoiceCandidatesAmtSelectionSummary)} */ public String getSummaryMessage() { final StringBuilder message = new StringBuilder(); message.append("@Netto@ (@ApprovalForInvoicing@): "); final BigDecimal totalNetAmtApproved = getTotalNetAmtApproved(); message.append(getAmountFormatted(totalNetAmtApproved)); final BigDecimal huNetAmtApproved = getHUNetAmtApproved(); message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtApproved)); final BigDecimal cuNetAmtApproved = getCUNetAmtApproved(); message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtApproved)); message.append(" | @Netto@ (@NotApprovedForInvoicing@): "); final BigDecimal totalNetAmtNotApproved = getTotalNetAmtNotApproved(); message.append(getAmountFormatted(totalNetAmtNotApproved)); final BigDecimal huNetAmtNotApproved = getHUNetAmtNotApproved(); message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtNotApproved));
final BigDecimal cuNetAmtNotApproved = getCUNetAmtNotApproved(); message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtNotApproved)); if (countTotalToRecompute > 0) { message.append(", @IsToRecompute@: "); message.append(countTotalToRecompute); } return message.toString(); } private String getAmountFormatted(final BigDecimal amt) { final DecimalFormat amountFormat = DisplayType.getNumberFormat(DisplayType.Amount); final StringBuilder amountFormatted = new StringBuilder(); amountFormatted.append(amountFormat.format(amt)); final boolean isSameCurrency = currencySymbols.size() == 1; String curSymbol = null; if (isSameCurrency) { curSymbol = currencySymbols.iterator().next(); amountFormatted.append(curSymbol); } return amountFormatted.toString(); } @Override public String getSummaryMessageTranslated(final Properties ctx) { final String message = getSummaryMessage(); final String messageTrl = Services.get(IMsgBL.class).parseTranslation(ctx, message); return messageTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\invoicecandidate\ui\spi\impl\HUInvoiceCandidatesSelectionSummaryInfo.java
1
请完成以下Java代码
public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public String getAssignee() { return assignee; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public Boolean getCanceled() { return canceled; } public Boolean getCompleteScope() { return completeScope; } public String getTenantId() { return tenantId; } public Date getRemovalTime() {
return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto, HistoricActivityInstance historicActivityInstance) { dto.id = historicActivityInstance.getId(); dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId(); dto.activityId = historicActivityInstance.getActivityId(); dto.activityName = historicActivityInstance.getActivityName(); dto.activityType = historicActivityInstance.getActivityType(); dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey(); dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId(); dto.processInstanceId = historicActivityInstance.getProcessInstanceId(); dto.executionId = historicActivityInstance.getExecutionId(); dto.taskId = historicActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId(); dto.assignee = historicActivityInstance.getAssignee(); dto.startTime = historicActivityInstance.getStartTime(); dto.endTime = historicActivityInstance.getEndTime(); dto.durationInMillis = historicActivityInstance.getDurationInMillis(); dto.canceled = historicActivityInstance.isCanceled(); dto.completeScope = historicActivityInstance.isCompleteScope(); dto.tenantId = historicActivityInstance.getTenantId(); dto.removalTime = historicActivityInstance.getRemovalTime(); dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityInstanceDto.java
1
请完成以下Java代码
public class HistoryEventProcessor { /** * The {@link HistoryEventCreator} interface which is used to interchange the implementation * of the creation of different HistoryEvents. */ public static class HistoryEventCreator { /** * Creates the {@link HistoryEvent} with the help off the given * {@link HistoryEventProducer}. * * @param producer the producer which is used for the creation * @return the created {@link HistoryEvent} */ public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return null; } public List<HistoryEvent> createHistoryEvents(HistoryEventProducer producer) { return Collections.emptyList(); } public void postHandleSingleHistoryEventCreated(HistoryEvent event) { return; } }
/** * Process an {@link HistoryEvent} and handle them directly after creation. * The {@link HistoryEvent} is created with the help of the given * {@link HistoryEventCreator} implementation. * * @param creator the creator is used to create the {@link HistoryEvent} which should be thrown */ public static void processHistoryEvents(HistoryEventCreator creator) { HistoryEventProducer historyEventProducer = Context.getProcessEngineConfiguration().getHistoryEventProducer(); HistoryEventHandler historyEventHandler = Context.getProcessEngineConfiguration().getHistoryEventHandler(); HistoryEvent singleEvent = creator.createHistoryEvent(historyEventProducer); if (singleEvent != null) { historyEventHandler.handleEvent(singleEvent); creator.postHandleSingleHistoryEventCreated(singleEvent); } List<HistoryEvent> eventList = creator.createHistoryEvents(historyEventProducer); historyEventHandler.handleEvents(eventList); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEventProcessor.java
1
请完成以下Java代码
private boolean update(@NonNull final IAttributeStorage huAttributes) { if (!huAttributes.hasAttribute(AttributeConstants.ATTR_MonthsUntilExpiry)) { return false; } final OptionalInt monthsUntilExpiry = computeMonthsUntilExpiry(huAttributes, today); final int monthsUntilExpiryOld = huAttributes.getValueAsInt(AttributeConstants.ATTR_MonthsUntilExpiry); if (monthsUntilExpiry.orElse(0) == monthsUntilExpiryOld) { return false; } huAttributes.setSaveOnChange(true); if (monthsUntilExpiry.isPresent()) { huAttributes.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, monthsUntilExpiry.getAsInt()); } else { huAttributes.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, null); } huAttributes.saveChangesIfNeeded(); return true; } static OptionalInt computeMonthsUntilExpiry(@NonNull final IAttributeStorage huAttributes, @NonNull final LocalDate today) { final LocalDate bestBeforeDate = huAttributes.getValueAsLocalDate(AttributeConstants.ATTR_BestBeforeDate); if (bestBeforeDate == null) {
return OptionalInt.empty(); } final int monthsUntilExpiry = (int)ChronoUnit.MONTHS.between(today, bestBeforeDate); return OptionalInt.of(monthsUntilExpiry); } private IAttributeStorage getHUAttributes(@NonNull final HuId huId, @NonNull final IHUContext huContext) { final I_M_HU hu = handlingUnitsBL.getById(huId); return huContext .getHUAttributeStorageFactory() .getAttributeStorage(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\UpdateMonthsUntilExpiryCommand.java
1
请完成以下Java代码
public int size() { return elementArray.length; } public float dot(Vector other) { float ret = 0.0f; for (int i = 0; i < size(); ++i) { ret += elementArray[i] * other.elementArray[i]; } return ret; } public float norm() { float ret = 0.0f; for (int i = 0; i < size(); ++i) { ret += elementArray[i] * elementArray[i]; } return (float) Math.sqrt(ret); } /** * 夹角的余弦<br> * 认为this和other都是单位向量,所以方法内部没有除以两者的模。 * * @param other * @return */ public float cosineForUnitVector(Vector other) { return dot(other); } /** * 夹角的余弦<br> * * @param other * @return */ public float cosine(Vector other) { return dot(other) / this.norm() / other.norm(); } public Vector minus(Vector other) { float[] result = new float[size()]; for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] - other.elementArray[i]; } return new Vector(result); } public Vector add(Vector other) { float[] result = new float[size()];
for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] + other.elementArray[i]; } return new Vector(result); } public Vector addToSelf(Vector other) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] + other.elementArray[i]; } return this; } public Vector divideToSelf(int n) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / n; } return this; } public Vector divideToSelf(float f) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / f; } return this; } /** * 自身归一化 * * @return */ public Vector normalize() { divideToSelf(norm()); return this; } public float[] getElementArray() { return elementArray; } public void setElementArray(float[] elementArray) { this.elementArray = elementArray; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } // Fetch books and authors including authors that have no registered books and books with no registered authors (JPQL) public List<AuthorNameBookTitle> fetchBooksAndAuthorsJpql() { return bookRepository.findBooksAndAuthorsJpql(); }
// Fetch books and authors including authors that have no registered books and books with no registered authors (SQL) public List<AuthorNameBookTitle> fetchBooksAndAuthorsSql() { return bookRepository.findBooksAndAuthorsSql(); } // Fetch authors and books including authors that have no registered books and books with no registered authors (JPQL) public List<AuthorNameBookTitle> fetchAuthorsAndBooksJpql() { return authorRepository.findAuthorsAndBooksJpql(); } // Fetch authors and books including authors that have no registered books and books with no registered authors (SQL) public List<AuthorNameBookTitle> fetchAuthorsAndBooksSql() { return authorRepository.findAuthorsAndBooksSql(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaFullJoins\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void failForMissingPricingConditions(final de.metas.adempiere.model.I_C_Order order) { final boolean mandatoryPricingConditions = isMandatoryPricingConditions(); if (!mandatoryPricingConditions) { return; } final List<I_C_OrderLine> orderLines = Services.get(IOrderDAO.class).retrieveOrderLines(order); final boolean existsOrderLineWithNoPricingConditions = orderLines .stream() .anyMatch(this::isPricingConditionsMissingButRequired); if (existsOrderLineWithNoPricingConditions) { throw new AdempiereException(MSG_NoPricingConditionsError) .setParameter("HowToDisablePricingConditionsCheck", "To disable it, please set " + SYSCONFIG_NoPriceConditionsColorName + " to `-`"); } } private boolean isMandatoryPricingConditions() { final ColorId noPriceConditionsColorId = getNoPriceConditionsColorId(); return noPriceConditionsColorId != null; } private boolean isPricingConditionsMissingButRequired(final I_C_OrderLine orderLine) { // Pricing conditions are not required for packing material line (task 3925) if (orderLine.isPackagingMaterial()) { return false; }
return hasPricingConditions(orderLine) == HasPricingConditions.NO; } private HasPricingConditions hasPricingConditions(final I_C_OrderLine orderLine) { if (orderLine.isTempPricingConditions()) { return HasPricingConditions.TEMPORARY; } else if (orderLine.getM_DiscountSchemaBreak_ID() > 0) { return HasPricingConditions.YES; } else { return HasPricingConditions.NO; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePricingConditions.java
1
请完成以下Java代码
private static TableRecordReference toTableRecordReference(final MatchInv matchInv) { return TableRecordReference.of(I_M_MatchInv.Table_Name, matchInv.getId()); } private void deleteFactAcct(final List<MatchInv> matchInvs) { for (final MatchInv matchInv : matchInvs) { if (matchInv.isPosted()) { MPeriod.testPeriodOpen(Env.getCtx(), Timestamp.from(matchInv.getDateAcct()), DocBaseType.MatchInvoice, matchInv.getOrgId().getRepoId()); factAcctDAO.deleteForRecordRef(toTableRecordReference(matchInv)); } } } private void unpostInvoiceIfNeeded(final List<MatchInv> matchInvs) { final HashSet<InvoiceId> invoiceIds = new HashSet<>();
for (final MatchInv matchInv : matchInvs) { // Reposting is required if a M_MatchInv was created for a purchase invoice. // ... because we book the matched quantity on InventoryClearing and on Expense the not matched quantity if (matchInv.getSoTrx().isPurchase()) { costDetailService.voidAndDeleteForDocument(CostingDocumentRef.ofMatchInvoiceId(matchInv.getId())); invoiceIds.add(matchInv.getInvoiceId()); } } invoiceBL.getByIds(invoiceIds) .forEach(Doc_Invoice::unpostIfNeeded); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\AcctMatchInvListener.java
1
请完成以下Java代码
public List<Address> getAddress() { return address; } public void setAddress(List<Address> address) { this.address = address; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() {
return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List<String> getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(List<String> phoneNumbers) { this.phoneNumbers = phoneNumbers; } }
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\xml\Person.java
1
请完成以下Java代码
public JobQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public JobQuery includeJobsWithoutTenantId() { this.includeJobsWithoutTenantId = true; return this; } //sorting ////////////////////////////////////////// public JobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } public JobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } public JobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } public JobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public JobQuery orderByProcessDefinitionId() { return orderBy(JobQueryProperty.PROCESS_DEFINITION_ID); } public JobQuery orderByProcessDefinitionKey() { return orderBy(JobQueryProperty.PROCESS_DEFINITION_KEY); } public JobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public JobQuery orderByJobPriority() { return orderBy(JobQueryProperty.PRIORITY); } public JobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } //results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobManager() .findJobCountByQueryCriteria(this); } @Override public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobManager() .findJobsByQueryCriteria(this, page); } @Override public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobManager()
.findDeploymentIdMappingsByQueryCriteria(this); } //getters ////////////////////////////////////////// public Set<String> getIds() { return ids; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getProcessInstanceId() { return processInstanceId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return ClockUtil.getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public boolean getAcquired() { return acquired; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisUtil { @Autowired private StringRedisTemplate stringRedisTemplate; /** * 分页获取指定格式key,使用 scan 命令代替 keys 命令,在大数据量的情况下可以提高查询效率 * * @param patternKey key格式 * @param currentPage 当前页码 * @param pageSize 每页条数 * @return 分页获取指定格式key */ public PageResult<String> findKeysForPage(String patternKey, int currentPage, int pageSize) { ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory(); RedisConnection rc = factory.getConnection(); Cursor<byte[]> cursor = rc.scan(options); List<String> result = Lists.newArrayList(); long tmpIndex = 0; int startIndex = (currentPage - 1) * pageSize; int end = currentPage * pageSize; while (cursor.hasNext()) { String key = new String(cursor.next()); if (tmpIndex >= startIndex && tmpIndex < end) { result.add(key); } tmpIndex++; } try { cursor.close(); RedisConnectionUtils.releaseConnection(rc, factory); } catch (Exception e) { log.warn("Redis连接关闭异常,", e); } return new PageResult<>(result, tmpIndex);
} /** * 删除 Redis 中的某个key * * @param key 键 */ public void delete(String key) { stringRedisTemplate.delete(key); } /** * 批量删除 Redis 中的某些key * * @param keys 键列表 */ public void delete(Collection<String> keys) { stringRedisTemplate.delete(keys); } }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\util\RedisUtil.java
2
请完成以下Java代码
public byte[] getCipherValue() { return cipherValue; } /** * Sets the value of the cipherValue property. * * @param value * allowed object is * byte[] */ public void setCipherValue(byte[] value) { this.cipherValue = value; } /** * Gets the value of the cipherReference property. * * @return * possible object is
* {@link CipherReferenceType } * */ public CipherReferenceType getCipherReference() { return cipherReference; } /** * Sets the value of the cipherReference property. * * @param value * allowed object is * {@link CipherReferenceType } * */ public void setCipherReference(CipherReferenceType value) { this.cipherReference = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CipherDataType.java
1
请完成以下Java代码
public class HeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<HeaderRoutePredicateFactory.Config> { /** * Header key. */ public static final String HEADER_KEY = "header"; /** * Regexp key. */ public static final String REGEXP_KEY = "regexp"; public HeaderRoutePredicateFactory() { super(Config.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(HEADER_KEY, REGEXP_KEY); } @Override public Predicate<ServerWebExchange> apply(Config config) { Pattern pattern = (StringUtils.hasText(config.regexp)) ? Pattern.compile(config.regexp) : null; return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { if (!StringUtils.hasText(config.header)) { return false; } List<String> values = exchange.getRequest().getHeaders().getValuesAsList(config.header); if (values.isEmpty()) { return false; } // values is now guaranteed to not be empty if (pattern != null) { // check if a header value matches for (int i = 0; i < values.size(); i++) { String value = values.get(i); if (pattern.asMatchPredicate().test(value)) { return true; } } return false; } // there is a value and since regexp is empty, we only check existence. return true; } @Override
public Object getConfig() { return config; } @Override public String toString() { return String.format("Header: %s regexp=%s", config.header, config.regexp); } }; } public static class Config { @NotEmpty private @Nullable String header; private @Nullable String regexp; public @Nullable String getHeader() { return header; } public Config setHeader(String header) { this.header = header; return this; } public @Nullable String getRegexp() { return regexp; } public Config setRegexp(@Nullable String regexp) { this.regexp = regexp; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HeaderRoutePredicateFactory.java
1
请完成以下Java代码
/* package */final class HUItemsLocalCache extends AbstractModelListCacheLocal<I_M_HU, I_M_HU_Item> { private final transient IQueryBL queryBL = Services.get(IQueryBL.class); private static final String DYNATTR_Instance = HUItemsLocalCache.class.getName(); public static final HUItemsLocalCache getCreate(final I_M_HU hu) { HUItemsLocalCache cache = InterfaceWrapperHelper.getDynAttribute(hu, DYNATTR_Instance); if (cache == null) { cache = new HUItemsLocalCache(hu); cache.setCacheDisabled(HUConstants.DEBUG_07504_Disable_HUItemsLocalCache); InterfaceWrapperHelper.setDynAttribute(hu, DYNATTR_Instance, cache); } return cache; } private HUItemsLocalCache(final I_M_HU hu) { super(hu); } @Override protected final Comparator<I_M_HU_Item> createItemsComparator() { return IHandlingUnitsDAO.HU_ITEMS_COMPARATOR; } /** * Retrieves a list of {@link I_M_HU_Item}s with ordering according to {@link #ITEM_TYPE_ORDERING}. */ @Override protected final List<I_M_HU_Item> retrieveItems(final IContextAware ctx, final I_M_HU hu) {
final IQueryBuilder<I_M_HU_Item> queryBuilder = queryBL.createQueryBuilder(I_M_HU_Item.class, ctx) .addEqualsFilter(I_M_HU_Item.COLUMN_M_HU_ID, hu.getM_HU_ID()) .addOnlyActiveRecordsFilter(); final List<I_M_HU_Item> items = queryBuilder .create() .list() .stream() .peek(item -> item.setM_HU(hu)) // Make sure item.getM_HU() will return our HU .sorted(createItemsComparator()) .collect(Collectors.toList()); return items; } @Override protected Object mkKey(final I_M_HU_Item item) { return item.getM_HU_Item_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUItemsLocalCache.java
1
请完成以下Java代码
public final class ConstantQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter { private static final ConstantQueryFilter<Object> TRUE = new ConstantQueryFilter<>(true); private static final ConstantQueryFilter<Object> FALSE = new ConstantQueryFilter<>(false); @SuppressWarnings("unchecked") public static <T> ConstantQueryFilter<T> of(final boolean value) { return (ConstantQueryFilter<T>)(value ? TRUE : FALSE); } /* package */static final String SQL_TRUE = "1=1"; /* package */static final String SQL_FALSE = "1=0"; private final boolean value; private ConstantQueryFilter(final boolean value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } @Override public String getSql()
{ return value ? SQL_TRUE : SQL_FALSE; } @Override public List<Object> getSqlParams(final Properties ctx) { return getSqlParams(); } public List<Object> getSqlParams() { return Collections.emptyList(); } @Override public boolean accept(final T model) { return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\ConstantQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class PP_Product_BOM { private final PPOrderCandidateDAO ppOrderCandidateDAO; private final IProductBOMDAO productBOMDAO = Services.get(IProductBOMDAO.class); private final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); private final IPPOrderDAO ppOrderDAO = Services.get(IPPOrderDAO.class); private final ITrxManager trxManager = Services.get(ITrxManager.class); public PP_Product_BOM(@NonNull final PPOrderCandidateDAO ppOrderCandidateDAO) { this.ppOrderCandidateDAO = ppOrderCandidateDAO; } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void onComplete(@NonNull final I_PP_Product_BOM productBOMRecord) { final Optional<I_PP_Product_BOM> previousBOMVersion = productBOMDAO.getPreviousVersion(productBOMRecord, DocStatus.Completed); if (!previousBOMVersion.isPresent()) { return; } if (!shouldUpdateExistingPPOrderCandidates(productBOMRecord, previousBOMVersion.get())) { return; } final ProductBOMId previousBOMVersionID = ProductBOMId.ofRepoId(previousBOMVersion.get().getPP_Product_BOM_ID()); trxManager.runAfterCommit(() -> updateBOMOnMatchingOrderCandidates(previousBOMVersionID, productBOMRecord)); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE }) public void onReactivate(@NonNull final I_PP_Product_BOM productBOMRecord)
{ final ProductBOMId productBOMId = ProductBOMId.ofRepoId(productBOMRecord.getPP_Product_BOM_ID()); if (isBOMInUse(productBOMId)) { throw new AdempiereException("Product BOM is already in use (linked to a manufacturing order or candidate). It cannot be reactivated!") .appendParametersToMessage() .setParameter("productBOMId", productBOMId); } } private boolean isBOMInUse(@NonNull final ProductBOMId productBOMId) { return !EmptyUtil.isEmpty(ppOrderCandidateDAO.getByProductBOMId(productBOMId)) || !EmptyUtil.isEmpty(ppOrderDAO.getByProductBOMId(productBOMId)); } private void updateBOMOnMatchingOrderCandidates( @NonNull final ProductBOMId previousBOMVersionID, @NonNull final I_PP_Product_BOM productBOMRecord) { ppOrderCandidateDAO.getByProductBOMId(previousBOMVersionID) .stream() .filter(ppOrderCandidate -> PPOrderCandidateService.canAssignBOMVersion(ppOrderCandidate, productBOMRecord)) .peek(ppOrderCandidate -> ppOrderCandidate.setPP_Product_BOM_ID(productBOMRecord.getPP_Product_BOM_ID())) .forEach(ppOrderCandidateDAO::save); } private boolean shouldUpdateExistingPPOrderCandidates(@NonNull final I_PP_Product_BOM currentVersion, @NonNull final I_PP_Product_BOM oldVersion) { final AttributeSetInstanceId orderLineCandidateASIId = AttributeSetInstanceId.ofRepoIdOrNull(currentVersion.getM_AttributeSetInstance_ID()); final AttributeSetInstanceId productBOMLineASIId = AttributeSetInstanceId.ofRepoIdOrNull(oldVersion.getM_AttributeSetInstance_ID()); return asiBL.nullSafeASIEquals(orderLineCandidateASIId, productBOMLineASIId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\interceptor\PP_Product_BOM.java
2
请完成以下Java代码
public void setIsDefaultSO (boolean IsDefaultSO) { set_Value (COLUMNNAME_IsDefaultSO, Boolean.valueOf(IsDefaultSO)); } /** Get Standard (Verkauf). @return Default value for sales transactions */ @Override public boolean isDefaultSO () { Object oo = get_Value(COLUMNNAME_IsDefaultSO); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name.
@param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_Aggregation.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * AD_Language AD_Reference_ID=106 * Reference name: AD_Language */ public static final int AD_LANGUAGE_AD_Reference_ID=106; @Override public void setAD_Language (final java.lang.String AD_Language) { set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language); } @Override public java.lang.String getAD_Language() { return get_ValueAsString(COLUMNNAME_AD_Language); } @Override public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID) { if (C_CostClassification_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CostClassification_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID); } @Override public int getC_CostClassification_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID); } @Override
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CostClassification_Category_Trl.java
1
请完成以下Java代码
private int getMinimalWarnIntervalInDays(@NonNull final AbstractHUAttributeStorage huAttributeStorage) { int expiryWarningLeadTimeDays = Integer.MAX_VALUE; final List<IHUProductStorage> productStorages = Services .get(IHandlingUnitsBL.class) .getStorageFactory() .getStorage(huAttributeStorage.getM_HU()) .getProductStorages(); for (final IHUProductStorage productStorage : productStorages) { final I_M_Product productRecord = productDAO.getById(productStorage.getProductId()); final int currentDays; if (productRecord.getGuaranteeDaysMin() > 0) { currentDays = productRecord.getGuaranteeDaysMin(); } else { if (productRecord.getGuaranteeMonths() != null && !productRecord.getGuaranteeMonths().isEmpty()) {
currentDays = productDAO.getGuaranteeMonthsInDays(ProductId.ofRepoId(productRecord.getM_Product_ID())); } else { final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(productRecord.getM_Product_Category_ID()); final I_M_Product_Category productCategoryRecord = productDAO.getProductCategoryById(productCategoryId); currentDays = productCategoryRecord.getGuaranteeDaysMin(); } } expiryWarningLeadTimeDays = Integer.min(currentDays, expiryWarningLeadTimeDays); } if (expiryWarningLeadTimeDays == Integer.MAX_VALUE) { expiryWarningLeadTimeDays = 0; } return expiryWarningLeadTimeDays; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\ExpiredAttributeStorageListener.java
1
请完成以下Java代码
public class MarketDataSource implements Iterator<MarketData> { private final LinkedList<MarketData> dataQueue = new LinkedList<>(); public MarketDataSource() { // adding some test data into queue this.dataQueue.addAll(Arrays.asList(MarketData.builder() .amount(1) .market(Market.NASDAQ) .symbol("AAPL") .price(134.12) .currency(Currency.USD) .build(), MarketData.builder() .amount(2) .market(Market.NYSE) .symbol("IBM") .price(128.99) .currency(Currency.USD) .build(), MarketData.builder() .amount(1) .market(Market.NASDAQ) .symbol("AXP") .price(34.87)
.currency(Currency.EUR) .build())); } @Override public boolean hasNext() { return !this.dataQueue.isEmpty(); } @Override public MarketData next() { final MarketData data = this.dataQueue.pop(); this.dataQueue.add(data); return data; } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketDataSource.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setIsDynamic (final boolean IsDynamic) { set_Value (COLUMNNAME_IsDynamic, IsDynamic); } @Override public boolean isDynamic() { return get_ValueAsBoolean(COLUMNNAME_IsDynamic); } @Override public void setIsPickingRackSystem (final boolean IsPickingRackSystem) { set_Value (COLUMNNAME_IsPickingRackSystem, IsPickingRackSystem); } @Override public boolean isPickingRackSystem() { return get_ValueAsBoolean(COLUMNNAME_IsPickingRackSystem); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); } @Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID)
{ if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setPickingSlot (final java.lang.String PickingSlot) { set_Value (COLUMNNAME_PickingSlot, PickingSlot); } @Override public java.lang.String getPickingSlot() { return get_ValueAsString(COLUMNNAME_PickingSlot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_PickingSlot.java
1
请完成以下Java代码
public String value() { return attributeNode.getValue(); } public SpinXmlAttribute value(String value) { if (value == null) { throw LOG.unableToSetAttributeValueToNull(namespace(), name()); } attributeNode.setValue(value); return this; } public SpinXmlElement remove() { Element ownerElement = attributeNode.getOwnerElement(); ownerElement.removeAttributeNode(attributeNode); return dataFormat.createElementWrapper(ownerElement); } public String toString() { return value(); } public void writeToWriter(Writer writer) { try { writer.write(toString());
} catch (IOException e) { throw LOG.unableToWriteAttribute(this, e); } } public <C> C mapTo(Class<C> javaClass) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(this, javaClass); } public <C> C mapTo(String javaClass) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(this, javaClass); } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlAttribute.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomAccessDecisionManager implements AccessDecisionManager { /** * Override the decide method, in which it is judged whether the currently logged in user has the role information required for the current request URL. If not, an AccessDeniedException is thrown, otherwise nothing is done. * * @param auth Information about the currently logged in user * @param object FilterInvocationObject, you can get the current request object * @param ca FilterInvocationSecurityMetadataSource The return value of the getAttributes method in is the role required by the current request URL */ @Override public void decide(Authentication auth, Object object, Collection<ConfigAttribute> ca) { Collection<? extends GrantedAuthority> auths = auth.getAuthorities(); for (ConfigAttribute configAttribute : ca) { /* * If the required role is ROLE_LOGIN, it means that the currently requested URL can be accessed after the user logs in. * If auth is an instance of UsernamePasswordAuthenticationToken, it means that the current user has logged in and the method ends here, otherwise it enters the normal judgment process. */ if ("ROLE_LOGIN".equals(configAttribute.getAttribute()) && auth instanceof UsernamePasswordAuthenticationToken) { return; } for (GrantedAuthority authority : auths) { // If the current user has the role required by the current request, the method ends
if (configAttribute.getAttribute().equals(authority.getAuthority())) { return; } } } throw new AccessDeniedException("no permission"); } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return true; } }
repos\springboot-demo-master\security\src\main\java\com\et\security\config\CustomAccessDecisionManager.java
2
请完成以下Java代码
public class CacheKeyGenerator { /* for testing */ static final String KEY_SEPARATOR = ";"; private static final byte[] KEY_SEPARATOR_BYTES = KEY_SEPARATOR.getBytes(); private final ThreadLocal<MessageDigest> messageDigest; /* for testing */ static final List<KeyValueGenerator> DEFAULT_KEY_VALUE_GENERATORS = List.of( new UriKeyValueGenerator(), new HeaderKeyValueGenerator(HttpHeaders.AUTHORIZATION, KEY_SEPARATOR), new CookiesKeyValueGenerator(KEY_SEPARATOR)); public CacheKeyGenerator() { messageDigest = ThreadLocal.withInitial(() -> { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error creating CacheKeyGenerator", e); } }); } public String generateMetadataKey(ServerHttpRequest request, String... varyHeaders) { return "META_" + generateKey(request, varyHeaders); } public String generateKey(ServerHttpRequest request, String... varyHeaders) { return generateKey(request, varyHeaders != null ? Arrays.asList(varyHeaders) : Collections.emptyList()); } public String generateKey(ServerHttpRequest request, List<String> varyHeaders) { byte[] rawKey = generateRawKey(request, varyHeaders); byte[] digest = messageDigest.get().digest(rawKey); return Base64.getEncoder().encodeToString(digest); }
private Stream<KeyValueGenerator> getKeyValueGenerators(List<String> varyHeaders) { return Stream.concat(DEFAULT_KEY_VALUE_GENERATORS.stream(), varyHeaders.stream().sorted().map(header -> new HeaderKeyValueGenerator(header, ","))); } private byte[] generateRawKey(ServerHttpRequest request, List<String> varyHeaders) { Stream<KeyValueGenerator> keyValueGenerators = getKeyValueGenerators(varyHeaders); final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); keyValueGenerators.map(generator -> generator.apply(request)).map(String::getBytes).forEach(bytes -> { byteOutputStream.writeBytes(bytes); byteOutputStream.writeBytes(KEY_SEPARATOR_BYTES); }); return byteOutputStream.toByteArray(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\keygenerator\CacheKeyGenerator.java
1
请完成以下Java代码
private static double div(int v1, int v2) { if (v2 == 0) return 0.0; return v1 / (double) v2; } /** * 安全除法 * @param v1 * @param v2 * @return */ private static double div(double v1, double v2) { if (v2 == 0) return 0.0; return v1 / v2; } @Override
public void save(DataOutputStream out) throws Exception { out.writeDouble(l1); out.writeDouble(l2); out.writeDouble(l3); tf.save(out); } @Override public boolean load(ByteArray byteArray) { l1 = byteArray.nextDouble(); l2 = byteArray.nextDouble(); l3 = byteArray.nextDouble(); tf.load(byteArray); return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\CharacterBasedGenerativeModel.java
1
请完成以下Java代码
public void setConfidentialType (java.lang.String ConfidentialType) { set_Value (COLUMNNAME_ConfidentialType, ConfidentialType); } /** Get Vertraulichkeit. @return Type of Confidentiality */ @Override public java.lang.String getConfidentialType () { return (java.lang.String)get_Value(COLUMNNAME_ConfidentialType); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * ModerationType AD_Reference_ID=395 * Reference name: CM_Chat ModerationType */ public static final int MODERATIONTYPE_AD_Reference_ID=395; /** Not moderated = N */ public static final String MODERATIONTYPE_NotModerated = "N"; /** Before Publishing = B */ public static final String MODERATIONTYPE_BeforePublishing = "B"; /** After Publishing = A */ public static final String MODERATIONTYPE_AfterPublishing = "A"; /** Set Moderation Type. @param ModerationType Type of moderation */ @Override public void setModerationType (java.lang.String ModerationType) { set_Value (COLUMNNAME_ModerationType, ModerationType); } /** Get Moderation Type.
@return Type of moderation */ @Override public java.lang.String getModerationType () { return (java.lang.String)get_Value(COLUMNNAME_ModerationType); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Chat.java
1
请完成以下Java代码
private void createLineFromCandidate(final I_C_Order newOrder, final SalesOrderLineCandidate candidate) { final ProductId productId = candidate.getBomProductId(); Check.assumeNotNull(productId, "Parameter productId is not null"); final BigDecimal price = candidate.getPrice(); final BigDecimal qty = candidate.getQty(); final UomId uomId = candidate.getUomId(); final I_C_OrderLine salesOrderLine = newInstance(I_C_OrderLine.class); salesOrderLine.setC_Order_ID(newOrder.getC_Order_ID()); orderLineBL.setOrder(salesOrderLine, newOrder); // salesOrderLine.setM_Product_ID(productId.getRepoId()); salesOrderLine.setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId()); // salesOrderLine.setC_UOM_ID(uomId.getRepoId()); salesOrderLine.setQtyEntered(qty); // salesOrderLine.setIsManualPrice(true); salesOrderLine.setPriceEntered(price); salesOrderLine.setPriceActual(price); // saveRecord(salesOrderLine); } private void copyQuotationLineToSalesOrder(final I_C_Order newOrder, final I_C_OrderLine fromQuotationLine) { final I_C_OrderLine salesOrderLine = InterfaceWrapperHelper.copy() .setFrom(fromQuotationLine) .setSkipCalculatedColumns(true) .copyToNew(I_C_OrderLine.class); salesOrderLine.setC_Order_ID(newOrder.getC_Order_ID()); orderLineBL.setOrder(salesOrderLine, newOrder); attributeSetInstanceBL.cloneASI(salesOrderLine, fromQuotationLine); saveRecord(salesOrderLine); } @Value @Builder private static class SalesOrderCandidate { @NonNull PriceListId priceListId; @NonNull ZonedDateTime datePromised; @NonNull I_C_Order fromQuotation; @NonNull ImmutableList<SalesOrderLineCandidate> lines; @NonNull ImmutableList<I_C_OrderLine> otherQuotationLinesToCopyDirectly; } @Data @Builder private static class SalesOrderLineCandidate { @Nullable
private ProductId bomProductId; private boolean addProductToPriceList; // // Quotation info: @NonNull private final GroupId quotationGroupId; @NonNull private final String quotationGroupName; @NonNull final OrgId orgId; @NonNull final ProductId quotationTemplateProductId; @NonNull final BigDecimal price; @NonNull final BigDecimal qty; @NonNull final UomId uomId; @NonNull final TaxCategoryId taxCategoryId; // // Additional quotation lines to copy directly @NonNull @Default private final ImmutableList<I_C_OrderLine> additionalQuotationLines = ImmutableList.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\CreateSalesOrderAndBOMsFromQuotationCommand.java
1
请完成以下Java代码
public void complete(ExternalTask externalTask, Map<String, Object> variables) { complete(externalTask, variables, null); } @Override public void complete(ExternalTask externalTask, Map<String, Object> variables, Map<String, Object> localVariables) { complete(externalTask.getId(), variables, localVariables); } public void complete(String externalTaskId, Map<String, Object> variables, Map<String, Object> localVariables) { try { engineClient.complete(externalTaskId, variables, localVariables); } catch (EngineClientException e) { throw LOG.handledEngineClientException("completing the external task", e); } } @Override public void handleFailure(ExternalTask externalTask, String errorMessage, String errorDetails, int retries, long retryTimeout) { handleFailure(externalTask.getId(), errorMessage, errorDetails, retries, retryTimeout); } @Override public void handleFailure(String externalTaskId, String errorMessage, String errorDetails, int retries, long retryTimeout) { handleFailure(externalTaskId, errorMessage, errorDetails, retries, retryTimeout, null, null); } @Override public void handleFailure(String externalTaskId, String errorMessage, String errorDetails, int retries, long retryTimeout, Map<String, Object> variables, Map<String, Object> locaclVariables) { try { engineClient.failure(externalTaskId, errorMessage, errorDetails, retries, retryTimeout, variables, locaclVariables); } catch (EngineClientException e) { throw LOG.handledEngineClientException("notifying a failure", e); } } @Override public void handleBpmnError(ExternalTask externalTask, String errorCode) { handleBpmnError(externalTask, errorCode, null, null);
} @Override public void handleBpmnError(ExternalTask externalTask, String errorCode, String errorMessage) { handleBpmnError(externalTask, errorCode, errorMessage, null); } @Override public void handleBpmnError(ExternalTask externalTask, String errorCode, String errorMessage, Map<String, Object> variables) { handleBpmnError(externalTask.getId(), errorCode, errorMessage, variables); } @Override public void handleBpmnError(String externalTaskId, String errorCode, String errorMessage, Map<String, Object> variables) { try { engineClient.bpmnError(externalTaskId, errorCode, errorMessage, variables); } catch (EngineClientException e) { throw LOG.handledEngineClientException("notifying a BPMN error", e); } } @Override public void extendLock(ExternalTask externalTask, long newDuration) { extendLock(externalTask.getId(), newDuration); } @Override public void extendLock(String externalTaskId, long newDuration) { try { engineClient.extendLock(externalTaskId, newDuration); } catch (EngineClientException e) { throw LOG.handledEngineClientException("extending lock", e); } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskServiceImpl.java
1
请完成以下Java代码
public class ShipmentLineNoInfo { private static final Logger logger = LogManager.getLogger(ShipmentLineNoInfo.class); private final Map<InOutLineId, Integer> shipmentLineIdToLineNo = new HashMap<>(); private final Multimap<Integer, InOutLineId> lineNoToShipmentLineId = MultimapBuilder.hashKeys().arrayListValues().build(); public boolean put(@NonNull final InOutLineId shipmentLineId, @NonNull final Integer lineNo) { if (lineNo <= 0) { logger.debug("Ignoring lineNo={} is associated with shipmentLineId={}; -> ignore, i.e. no collission; return true", lineNo, shipmentLineId); return true; } shipmentLineIdToLineNo.put(shipmentLineId, lineNo); lineNoToShipmentLineId.put(lineNo, shipmentLineId); if (lineNoToShipmentLineId.get(lineNo).size() > 1) { logger.debug("LineNo={} is associated with multiple shipmentLineIds={}; -> collision detected; return false", lineNo, lineNoToShipmentLineId.get(lineNo)); return false; } logger.debug("LineNo={} is associated only with shipmentLineId={} so far; -> no collision; return true", lineNo, shipmentLineId); return true; } public int getLineNoFor(@NonNull final InOutLineId shipmentLineId) { return coalesce(shipmentLineIdToLineNo.get(shipmentLineId), 0);
} public ImmutableList<InOutLineId> getShipmentLineIdsWithLineNoCollisions() { final ImmutableList.Builder<InOutLineId> result = ImmutableList.builder(); for (final Entry<Integer, Collection<InOutLineId>> entry : lineNoToShipmentLineId.asMap().entrySet()) { final Collection<InOutLineId> shipmentLineIds = entry.getValue(); if (shipmentLineIds.size() > 1) { result.addAll(shipmentLineIds); } } return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\spi\impl\ShipmentLineNoInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class Girl { @Id @GeneratedValue private Integer id; private String cupSize; private Integer age; public Girl() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; }
public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCupSize() { return cupSize; } public void setCupSize(String cupSize) { this.cupSize = cupSize; } }
repos\SpringBootLearning-master\firstspringboot-2h\src\main\java\com\forezp\Girl.java
2
请完成以下Java代码
public void afterNew(final I_DD_Order_Candidate record) { final DDOrderCandidateData data = toDDOrderCandidateData(record); final UserId userId = UserId.ofRepoId(record.getUpdatedBy()); materialEventService.enqueueEventAfterNextCommit(DDOrderCandidateCreatedEvent.of(data, userId)); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }) public void afterChange(final I_DD_Order_Candidate record) { final DDOrderCandidateData data = toDDOrderCandidateData(record); final UserId userId = UserId.ofRepoId(record.getUpdatedBy()); materialEventService.enqueueEventAfterNextCommit(DDOrderCandidateUpdatedEvent.of(data, userId)); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_DD_Order_Candidate record) { ddOrderCandidateAllocRepository.deleteByQuery(DeleteDDOrderCandidateAllocQuery.builder() .ddOrderCandidateId(DDOrderCandidateId.ofRepoId(record.getDD_Order_Candidate_ID())) .build());
final DDOrderCandidateData data = toDDOrderCandidateData(record); final UserId userId = UserId.ofRepoId(record.getUpdatedBy()); materialEventService.enqueueEventAfterNextCommit(DDOrderCandidateDeletedEvent.of(data, userId)); } private DDOrderCandidateData toDDOrderCandidateData(final I_DD_Order_Candidate record) { final DDOrderCandidate candidate = DDOrderCandidateRepository.fromRecord(record); return candidate.toDDOrderCandidateData() .fromWarehouseMinMaxDescriptor(getFromWarehouseMinMaxDescriptor(candidate)) .build(); } private MinMaxDescriptor getFromWarehouseMinMaxDescriptor(final DDOrderCandidate candidate) { return replenishInfoRepository.getBy(ReplenishInfo.Identifier.of(candidate.getSourceWarehouseId(), candidate.getSourceLocatorId(), candidate.getProductId())).toMinMaxDescriptor(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\interceptor\DD_Order_Candidate.java
1