instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public ProducerRecord<K, V> onSend(ProducerRecord<K, V> record) { ProducerRecord<K, V> interceptRecord = record; for (ProducerInterceptor<K, V> interceptor : this.delegates) { try { interceptRecord = interceptor.onSend(interceptRecord); } catch (Exception e) { // if exception thrown, log and continue calling other interceptors. if (record != null) { CompositeProducerInterceptor.this.logger.warn(e, () -> String.format("Error executing interceptor onSend callback for topic: %s, partition: %d", record.topic(), record.partition())); } else { CompositeProducerInterceptor.this.logger.warn(e, () -> "Error executing interceptor onSend callback: " + interceptor.toString()); } } } return interceptRecord; } @Override public void onAcknowledgement(RecordMetadata metadata, Exception exception) { for (ProducerInterceptor<K, V> interceptor : this.delegates) { try { interceptor.onAcknowledgement(metadata, exception); }
catch (Exception e) { // do not propagate interceptor exceptions, just log CompositeProducerInterceptor.this.logger.warn(e, () -> "Error executing interceptor onAcknowledgement callback: " + interceptor.toString()); } } } @Override public void close() { for (ProducerInterceptor<K, V> interceptor : this.delegates) { try { interceptor.close(); } catch (Exception e) { CompositeProducerInterceptor.this.logger.warn(e, () -> "Failed to close producer interceptor: " + interceptor.toString()); } } } @Override public void configure(Map<String, ?> configs) { this.delegates.forEach(delegate -> delegate.configure(configs)); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\CompositeProducerInterceptor.java
1
请完成以下Java代码
public LocalDateTime getSentAt() { return sentAt; } public void setSentAt(LocalDateTime sentAt) { this.sentAt = sentAt; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public InputMessage(String sender, String recipient, LocalDateTime sentAt, String message) { this.sender = sender; this.recipient = recipient; this.sentAt = sentAt; this.message = message; } @Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InputMessage message1 = (InputMessage) o; return Objects.equal(sender, message1.sender) && Objects.equal(recipient, message1.recipient) && Objects.equal(sentAt, message1.sentAt) && Objects.equal(message, message1.message); } @Override public int hashCode() { return Objects.hashCode(sender, recipient, sentAt, message); } }
repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\flink\model\InputMessage.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2") public String getDeploymentUrl() { return deploymentUrl; } public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; }
public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "oneChannel.channel") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneChannel.channel", value = "Contains the actual deployed channel definition JSON.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a channel definition for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\ChannelDefinitionResponse.java
2
请完成以下Java代码
protected <T> T get(String variableName) { BusinessProcess businessProcess = getBusinessProcess(); Object variable = businessProcess.getVariable(variableName); if (variable != null) { if (logger.isLoggable(Level.FINE)) { if(businessProcess.isAssociated()) { logger.fine("Getting instance of bean '" + variableName + "' from Execution[" + businessProcess.getExecutionId() + "]."); } else { logger.fine("Getting instance of bean '" + variableName + "' from transient bean store"); } } return (T) variable; } else { return null; } } @Override public <T> T get(Contextual<T> contextual, CreationalContext<T> arg1) { Bean<T> bean = (Bean<T>) contextual; String variableName = bean.getName(); T beanInstance = bean.create(arg1); return get(variableName, beanInstance); } protected <T> T get(String variableName, T beanInstance) { BusinessProcess businessProcess = getBusinessProcess(); Object variable = businessProcess.getVariable(variableName); if (variable != null) { if (logger.isLoggable(Level.FINE)) { if(businessProcess.isAssociated()) { logger.fine("Getting instance of bean '" + variableName + "' from Execution[" + businessProcess.getExecutionId() + "]."); } else { logger.fine("Getting instance of bean '" + variableName + "' from transient bean store");
} } return (T) variable; } else { if (logger.isLoggable(Level.FINE)) { if(businessProcess.isAssociated()) { logger.fine("Creating instance of bean '" + variableName + "' in business process context representing Execution[" + businessProcess.getExecutionId() + "]."); } else { logger.fine("Creating instance of bean '" + variableName + "' in transient bean store"); } } businessProcess.setVariable(variableName, beanInstance); return beanInstance; } } @Override public boolean isActive() { // we assume the business process is always 'active'. If no task/execution is // associated, temporary instances of @BusinessProcesScoped beans are cached in the // conversation / request return true; } protected BeanManager getBeanManager() { return beanManager; } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\BusinessProcessContext.java
1
请完成以下Java代码
public class BasicAuthenticationConverter implements AuthenticationConverter { public static final String AUTHENTICATION_SCHEME_BASIC = "Basic"; private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource; private Charset credentialsCharset = StandardCharsets.UTF_8; public BasicAuthenticationConverter() { this(new WebAuthenticationDetailsSource()); } public BasicAuthenticationConverter( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { this.authenticationDetailsSource = authenticationDetailsSource; } public Charset getCredentialsCharset() { return this.credentialsCharset; } public void setCredentialsCharset(Charset credentialsCharset) { this.credentialsCharset = credentialsCharset; } public AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() { return this.authenticationDetailsSource; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; } @Override public @Nullable UsernamePasswordAuthenticationToken convert(HttpServletRequest request) { String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null) {
return null; } header = header.trim(); if (!StringUtils.startsWithIgnoreCase(header, AUTHENTICATION_SCHEME_BASIC)) { return null; } if (header.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) { throw new BadCredentialsException("Empty basic authentication token"); } byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8); byte[] decoded = decode(base64Token); String token = new String(decoded, getCredentialsCharset(request)); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken .unauthenticated(token.substring(0, delim), token.substring(delim + 1)); result.setDetails(this.authenticationDetailsSource.buildDetails(request)); return result; } private byte[] decode(byte[] base64Token) { try { return Base64.getDecoder().decode(base64Token); } catch (IllegalArgumentException ex) { throw new BadCredentialsException("Failed to decode basic authentication token"); } } protected Charset getCredentialsCharset(HttpServletRequest request) { return getCredentialsCharset(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\www\BasicAuthenticationConverter.java
1
请完成以下Java代码
public void setPassword (final @Nullable java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public java.lang.String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setSMTPHost (final @Nullable java.lang.String SMTPHost) { set_Value (COLUMNNAME_SMTPHost, SMTPHost); } @Override public java.lang.String getSMTPHost() { return get_ValueAsString(COLUMNNAME_SMTPHost); } @Override public void setSMTPPort (final int SMTPPort) { set_Value (COLUMNNAME_SMTPPort, SMTPPort); } @Override public int getSMTPPort() { return get_ValueAsInt(COLUMNNAME_SMTPPort); } /**
* Type AD_Reference_ID=541904 * Reference name: AD_MailBox_Type */ public static final int TYPE_AD_Reference_ID=541904; /** SMTP = smtp */ public static final String TYPE_SMTP = "smtp"; /** MSGraph = msgraph */ public static final String TYPE_MSGraph = "msgraph"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java
1
请完成以下Java代码
public class ImportSysUserCache { private static final Map<String, Double> importSysUserMap = new HashMap<>(); /** * 获取导入的列 * * @param key * @param type user 用户 可扩展 * @return */ public static Double getImportSysUserMap(String key, String type) { if (importSysUserMap.containsKey(key + "__" + type)) { return importSysUserMap.get(key + "__" + type); } return 0.0; } /** * 设置导入缓存 *
* @param key 前村传过来的随机key * @param num 导入行数 * @param length 总长度 * @param type 导入类型 user 用户列表 */ public static void setImportSysUserMap(String key, int num, int length, String type) { double percent = (num * 100.0) / length; if(num == length){ percent = 100; } importSysUserMap.put(key + "__" + type, percent); } /** * 移除导入缓存 * * @param key */ public static void removeImportLowAppMap(String key) { importSysUserMap.remove(key); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\ImportSysUserCache.java
1
请完成以下Java代码
private final BPartnerId getBPartnerId() { return _bpartnerId; } public LUTUAssignBuilder setC_BPartner_Location_ID(final int bpartnerLocationId) { assertConfigurable(); _bpLocationId = bpartnerLocationId; return this; } private final int getC_BPartner_Location_ID() { return _bpLocationId; } public LUTUAssignBuilder setM_Locator(final I_M_Locator locator) { assertConfigurable(); _locatorId = LocatorId.ofRecordOrNull(locator); return this; } private LocatorId getLocatorId() {
Check.assumeNotNull(_locatorId, "_locatorId not null"); return _locatorId; } public LUTUAssignBuilder setHUStatus(final String huStatus) { assertConfigurable(); _huStatus = huStatus; return this; } private String getHUStatus() { Check.assumeNotEmpty(_huStatus, "_huStatus not empty"); return _huStatus; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUAssignBuilder.java
1
请在Spring Boot框架中完成以下Java代码
protected void initCaseInstanceService(ProcessEngineConfigurationImpl processEngineConfiguration) { processEngineConfiguration.setCaseInstanceService(new DefaultCaseInstanceService(cmmnEngineConfiguration)); } protected void initProcessInstanceStateChangedCallbacks(ProcessEngineConfigurationImpl processEngineConfiguration) { if (processEngineConfiguration.getProcessInstanceStateChangedCallbacks() == null) { processEngineConfiguration.setProcessInstanceStateChangedCallbacks(new HashMap<>()); } Map<String, List<RuntimeInstanceStateChangeCallback>> callbacks = processEngineConfiguration.getProcessInstanceStateChangedCallbacks(); if (!callbacks.containsKey(CallbackTypes.PLAN_ITEM_CHILD_PROCESS)) { callbacks.put(CallbackTypes.PLAN_ITEM_CHILD_PROCESS, new ArrayList<>()); } callbacks.get(CallbackTypes.PLAN_ITEM_CHILD_PROCESS).add(new ChildProcessInstanceStateChangeCallback(cmmnEngineConfiguration)); } @Override protected List<Class<? extends Entity>> getEntityInsertionOrder() { return EntityDependencyOrder.INSERT_ORDER; } @Override protected List<Class<? extends Entity>> getEntityDeletionOrder() { return EntityDependencyOrder.DELETE_ORDER;
} @Override protected CmmnEngine buildEngine() { if (cmmnEngineConfiguration == null) { throw new FlowableException("CmmnEngineConfiguration is required"); } return cmmnEngineConfiguration.buildCmmnEngine(); } public CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } public CmmnEngineConfigurator setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; return this; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine-configurator\src\main\java\org\flowable\cmmn\engine\configurator\CmmnEngineConfigurator.java
2
请完成以下Java代码
private static int getId(String word, HashMap<String, Integer> wordMap) { return getId(word, wordMap, -1); } private static int getId(String word, HashMap<String, Integer> wordMap, int defaultValue) { Integer id = wordMap.get(word); if (id == null) return defaultValue; return id; } public ArrayList<CompactTree> readStringData() throws IOException { ArrayList<CompactTree> treeSet = new ArrayList<CompactTree>(); String line; ArrayList<String> tags = new ArrayList<String>(); HashMap<Integer, Pair<Integer, String>> goldDependencies = new HashMap<Integer, Pair<Integer, String>>(); while ((line = fileReader.readLine()) != null) { line = line.trim(); if (line.length() == 0) { if (tags.size() >= 1) { CompactTree goldConfiguration = new CompactTree(goldDependencies, tags); treeSet.add(goldConfiguration); } tags = new ArrayList<String>(); goldDependencies = new HashMap<Integer, Pair<Integer, String>>(); } else { String[] splitLine = line.split("\t"); if (splitLine.length < 8) throw new IllegalArgumentException("wrong file format"); int wordIndex = Integer.parseInt(splitLine[0]); String pos = splitLine[3].trim(); tags.add(pos); int headIndex = Integer.parseInt(splitLine[6]);
String relation = splitLine[7]; if (headIndex == 0) { relation = "ROOT"; } if (pos.length() > 0) goldDependencies.put(wordIndex, new Pair<Integer, String>(headIndex, relation)); } } if (tags.size() > 0) { treeSet.add(new CompactTree(goldDependencies, tags)); } return treeSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\accessories\CoNLLReader.java
1
请完成以下Java代码
default boolean isParentLink() { return getDescriptor().isParentLink(); } /** Checks if this field was changed until it was saved. i.e. compares {@link #getValue()} with {@link #getInitialValue()}. */ boolean hasChangesToSave(); //@formatter:on //@formatter:off LogicExpressionResult getReadonly(); default boolean isAlwaysUpdateable() { return getDescriptor().isAlwaysUpdateable(); } // LogicExpressionResult getMandatory(); default boolean isMandatory() { return getMandatory().isTrue(); } // LogicExpressionResult getDisplayed(); // boolean isLookupValuesStale(); /** @return true if this field is public and will be published to API clients */ default boolean isPublicField() { return getDescriptor().hasCharacteristic(Characteristic.PublicField); } default boolean isAdvancedField() { return getDescriptor().hasCharacteristic(Characteristic.AdvancedField); } //@formatter:on //@formatter:off default Class<?> getValueClass() { return getDescriptor().getValueClass(); } /** @return field's current value */ @Nullable Object getValue(); @Nullable
Object getValueAsJsonObject(JSONOptions jsonOpts); boolean getValueAsBoolean(); int getValueAsInt(final int defaultValueWhenNull); DocumentZoomIntoInfo getZoomIntoInfo(); @Nullable <T> T getValueAs(@NonNull final Class<T> returnType); default Optional<BigDecimal> getValueAsBigDecimal() { return Optional.ofNullable(getValueAs(BigDecimal.class));} default <T extends RepoIdAware> Optional<T> getValueAsId(Class<T> idType) { return Optional.ofNullable(getValueAs(idType));} /** @return initial value / last saved value */ @Nullable Object getInitialValue(); /** @return old value (i.e. the value as it was when the document was checked out from repository/documents collection) */ @Nullable Object getOldValue(); //@formatter:on /** * @return field's valid state; never return null */ DocumentValidStatus getValidStatus(); /** * @return optional WindowId to be used when zooming into */ Optional<WindowId> getZoomIntoWindowId(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\IDocumentFieldView.java
1
请完成以下Java代码
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(time)); } @Override public void unlock() { sync.release(0); } @Override public Condition newCondition() { return sync.newCondition(); } public static void main(String[] args) { MutexLock lock = new MutexLock();
final User user = new User(); for (int i = 0; i < 100; i++) { new Thread(() -> { lock.lock(); try { user.setAge(user.getAge() + 1); System.out.println(user.getAge()); } finally { lock.unlock(); } }).start(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\MutexLock.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCustomer extends JsonCustomerBasicInfo { @NonNull @JsonProperty("id") String id; @Nullable @JsonProperty("defaultBillingAddressId") String defaultBillingAddressId; @Nullable @JsonProperty("defaultShippingAddressId") String defaultShippingAddressId; @Nullable @JsonProperty("groupId") String groupId; @Builder public JsonCustomer( @JsonProperty("id") final String id, @JsonProperty("defaultBillingAddressId") final String defaultBillingAddressId, @JsonProperty("defaultShippingAddressId") final String defaultShippingAddressId, @JsonProperty("groupId") final String groupId, @JsonProperty("firstName") final String firstName, @JsonProperty("lastName") final String lastName, @JsonProperty("company") final String company,
@JsonProperty("customerNumber") final String customerNumber, @JsonProperty("email") final String email, @JsonProperty("createdAt") final ZonedDateTime createdAt, @JsonProperty("updatedAt") final ZonedDateTime updatedAt, @JsonProperty("vatIds") final List<String> vatIds) { super(firstName, lastName, company, customerNumber, email, createdAt, updatedAt, vatIds); this.id = id; this.defaultBillingAddressId = defaultBillingAddressId; this.defaultShippingAddressId = defaultShippingAddressId; this.groupId = groupId; } @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "") static class JsonCustomerBuilder { } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\order\JsonCustomer.java
2
请完成以下Java代码
public ChildPK getChildPK() { return childPK; } public void setChildPK(ChildPK childPK) { this.childPK = childPK; } public Father getFather() { return father; } public void setFather(Father father) { this.father = father; } public Mother getMother() { return mother; } public void setMother(Mother mother) { this.mother = mother; } public String getName() { return name; } public void setName(String name) { this.name = name;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Child child = (Child) o; return Objects.equals(childPK, child.childPK) && Objects.equals(father, child.father) && Objects.equals(mother, child.mother) && Objects.equals(name, child.name); } @Override public int hashCode() { return Objects.hash(childPK, father, mother, name); } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\entity\Child.java
1
请完成以下Java代码
public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) { Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null"); this.authorizationFailureHandler = authorizationFailureHandler; } /** * The default implementation of the {@link #setContextAttributesMapper(Function) * contextAttributesMapper}. */ public static class DefaultContextAttributesMapper implements Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> { @Override public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest) { ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName()); // @formatter:off return Mono.justOrEmpty(serverWebExchange) .switchIfEmpty(currentServerWebExchangeMono) .flatMap((exchange) -> {
Map<String, Object> contextAttributes = Collections.emptyMap(); String scope = exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.SCOPE); if (StringUtils.hasText(scope)) { contextAttributes = new HashMap<>(); contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, StringUtils.delimitedListToStringArray(scope, " ")); } return Mono.just(contextAttributes); }) .defaultIfEmpty(Collections.emptyMap()); // @formatter:on } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\DefaultReactiveOAuth2AuthorizedClientManager.java
1
请完成以下Java代码
public String getBusinessKey() { return businessKey; } @Override public Map<String, String> getExtensionProperties() { return extensionProperties; } /** * Construct representation of locked ExternalTask from corresponding entity. * During mapping variables will be collected,during collection variables will not be deserialized * and scope will not be set to local. * * @see {@link org.camunda.bpm.engine.impl.core.variable.scope.AbstractVariableScope#collectVariables(VariableMapImpl, Collection, boolean, boolean)} * * @param externalTaskEntity - source persistent entity to use for fields * @param variablesToFetch - list of variable names to fetch, if null then all variables will be fetched * @param isLocal - if true only local variables will be collected * * @return object with all fields copied from the ExternalTaskEntity, error details fetched from the * database and variables attached */ public static LockedExternalTaskImpl fromEntity(ExternalTaskEntity externalTaskEntity, List<String> variablesToFetch, boolean isLocal, boolean deserializeVariables, boolean includeExtensionProperties) { LockedExternalTaskImpl result = new LockedExternalTaskImpl(); result.id = externalTaskEntity.getId(); result.topicName = externalTaskEntity.getTopicName(); result.workerId = externalTaskEntity.getWorkerId(); result.lockExpirationTime = externalTaskEntity.getLockExpirationTime(); result.createTime = externalTaskEntity.getCreateTime(); result.retries = externalTaskEntity.getRetries(); result.errorMessage = externalTaskEntity.getErrorMessage(); result.errorDetails = externalTaskEntity.getErrorDetails();
result.processInstanceId = externalTaskEntity.getProcessInstanceId(); result.executionId = externalTaskEntity.getExecutionId(); result.activityId = externalTaskEntity.getActivityId(); result.activityInstanceId = externalTaskEntity.getActivityInstanceId(); result.processDefinitionId = externalTaskEntity.getProcessDefinitionId(); result.processDefinitionKey = externalTaskEntity.getProcessDefinitionKey(); result.processDefinitionVersionTag = externalTaskEntity.getProcessDefinitionVersionTag(); result.tenantId = externalTaskEntity.getTenantId(); result.priority = externalTaskEntity.getPriority(); result.businessKey = externalTaskEntity.getBusinessKey(); ExecutionEntity execution = externalTaskEntity.getExecution(); result.variables = new VariableMapImpl(); execution.collectVariables(result.variables, variablesToFetch, isLocal, deserializeVariables); if(includeExtensionProperties) { result.extensionProperties = (Map<String, String>) execution.getActivity().getProperty(BpmnProperties.EXTENSION_PROPERTIES.getName()); } if(result.extensionProperties == null) { result.extensionProperties = Collections.emptyMap(); } return result; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\LockedExternalTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public TaxAddress postalCode(String postalCode) { this.postalCode = postalCode; return this; } /** * The postal code that can be used by sellers for tax purpose. Usually referred to as Zip codes in the US. * * @return postalCode **/ @javax.annotation.Nullable @ApiModelProperty(value = "The postal code that can be used by sellers for tax purpose. Usually referred to as Zip codes in the US.") public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public TaxAddress stateOrProvince(String stateOrProvince) { this.stateOrProvince = stateOrProvince; return this; } /** * The state name that can be used by sellers for tax purpose. * * @return stateOrProvince **/ @javax.annotation.Nullable @ApiModelProperty(value = "The state name that can be used by sellers for tax purpose.") public String getStateOrProvince() { return stateOrProvince; } public void setStateOrProvince(String stateOrProvince) { this.stateOrProvince = stateOrProvince; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) {
return false; } TaxAddress taxAddress = (TaxAddress)o; return Objects.equals(this.city, taxAddress.city) && Objects.equals(this.countryCode, taxAddress.countryCode) && Objects.equals(this.postalCode, taxAddress.postalCode) && Objects.equals(this.stateOrProvince, taxAddress.stateOrProvince); } @Override public int hashCode() { return Objects.hash(city, countryCode, postalCode, stateOrProvince); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TaxAddress {\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" stateOrProvince: ").append(toIndentedString(stateOrProvince)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\TaxAddress.java
2
请完成以下Java代码
public class DecisionLiteralExpressionEvaluationHandler implements DmnDecisionLogicEvaluationHandler { protected final ExpressionEvaluationHandler expressionEvaluationHandler; protected final String literalExpressionLanguage; public DecisionLiteralExpressionEvaluationHandler(DefaultDmnEngineConfiguration configuration) { expressionEvaluationHandler = new ExpressionEvaluationHandler(configuration); literalExpressionLanguage = configuration.getDefaultLiteralExpressionLanguage(); } @Override public DmnDecisionLogicEvaluationEvent evaluate(DmnDecision decision, VariableContext variableContext) { DmnDecisionLiteralExpressionEvaluationEventImpl evaluationResult = new DmnDecisionLiteralExpressionEvaluationEventImpl(); evaluationResult.setDecision(decision); evaluationResult.setExecutedDecisionElements(1); DmnDecisionLiteralExpressionImpl dmnDecisionLiteralExpression = (DmnDecisionLiteralExpressionImpl) decision.getDecisionLogic(); DmnVariableImpl variable = dmnDecisionLiteralExpression.getVariable(); DmnExpressionImpl expression = dmnDecisionLiteralExpression.getExpression(); Object evaluateExpression = evaluateLiteralExpression(expression, variableContext); TypedValue typedValue = variable.getTypeDefinition().transform(evaluateExpression); evaluationResult.setOutputValue(typedValue); evaluationResult.setOutputName(variable.getName()); return evaluationResult; } protected Object evaluateLiteralExpression(DmnExpressionImpl expression, VariableContext variableContext) { String expressionLanguage = expression.getExpressionLanguage();
if (expressionLanguage == null) { expressionLanguage = literalExpressionLanguage; } return expressionEvaluationHandler.evaluateExpression(expressionLanguage, expression, variableContext); } @Override public DmnDecisionResult generateDecisionResult(DmnDecisionLogicEvaluationEvent event) { DmnDecisionLiteralExpressionEvaluationEvent evaluationEvent = (DmnDecisionLiteralExpressionEvaluationEvent) event; DmnDecisionResultEntriesImpl result = new DmnDecisionResultEntriesImpl(); result.putValue(evaluationEvent.getOutputName(), evaluationEvent.getOutputValue()); return new DmnDecisionResultImpl(Collections.<DmnDecisionResultEntries> singletonList(result)); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\evaluation\DecisionLiteralExpressionEvaluationHandler.java
1
请完成以下Java代码
public static final class Affinity { private final ConnectionSettings.Affinity<? extends ConnectionBuilder> affinity; private Affinity(ConnectionSettings.Affinity<? extends ConnectionBuilder> affinity) { this.affinity = affinity; } public Affinity queue(String queue) { this.affinity.queue(queue); return this; } public Affinity operation(ConnectionSettings.Affinity.Operation operation) { this.affinity.operation(operation); return this; } public Affinity reuse(boolean reuse) { this.affinity.reuse(reuse); return this; } public Affinity strategy(ConnectionSettings.AffinityStrategy strategy) { this.affinity.strategy(strategy); return this; } } public static final class OAuth2 { private final OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings; private OAuth2(OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings) { this.oAuth2Settings = oAuth2Settings; } public OAuth2 tokenEndpointUri(String uri) { this.oAuth2Settings.tokenEndpointUri(uri); return this; } public OAuth2 clientId(String clientId) { this.oAuth2Settings.clientId(clientId); return this; } public OAuth2 clientSecret(String clientSecret) { this.oAuth2Settings.clientSecret(clientSecret); return this; } public OAuth2 grantType(String grantType) { this.oAuth2Settings.grantType(grantType);
return this; } public OAuth2 parameter(String name, String value) { this.oAuth2Settings.parameter(name, value); return this; } public OAuth2 shared(boolean shared) { this.oAuth2Settings.shared(shared); return this; } public OAuth2 sslContext(SSLContext sslContext) { this.oAuth2Settings.tls().sslContext(sslContext); return this; } } public static final class Recovery { private final ConnectionBuilder.RecoveryConfiguration recoveryConfiguration; private Recovery(ConnectionBuilder.RecoveryConfiguration recoveryConfiguration) { this.recoveryConfiguration = recoveryConfiguration; } public Recovery activated(boolean activated) { this.recoveryConfiguration.activated(activated); return this; } public Recovery backOffDelayPolicy(BackOffDelayPolicy backOffDelayPolicy) { this.recoveryConfiguration.backOffDelayPolicy(backOffDelayPolicy); return this; } public Recovery topology(boolean activated) { this.recoveryConfiguration.topology(activated); return this; } } }
repos\spring-amqp-main\spring-rabbitmq-client\src\main\java\org\springframework\amqp\rabbitmq\client\SingleAmqpConnectionFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipperExtensionType { @XmlElement(name = "ShipperExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact") protected at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType shipperExtension; @XmlElement(name = "ErpelShipperExtension") protected CustomType erpelShipperExtension; /** * Gets the value of the shipperExtension property. * * @return * possible object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType } * */ public at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType getShipperExtension() { return shipperExtension; } /** * Sets the value of the shipperExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType } * */ public void setShipperExtension(at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType value) { this.shipperExtension = value; } /** * Gets the value of the erpelShipperExtension property. * * @return * possible object is * {@link CustomType }
* */ public CustomType getErpelShipperExtension() { return erpelShipperExtension; } /** * Sets the value of the erpelShipperExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelShipperExtension(CustomType value) { this.erpelShipperExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\ShipperExtensionType.java
2
请完成以下Java代码
public static PaymentRule ofNullableCode(@Nullable final String code) { return code != null ? ofCode(code) : null; } public static Optional<PaymentRule> optionalOfCode(@Nullable final String code) { return Optional.ofNullable(ofNullableCode(code)); } public static PaymentRule ofCode(@NonNull final String code) { final PaymentRule type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + PaymentRule.class + " found for code: " + code); } return type; } @Nullable public static String toCodeOrNull(@Nullable final PaymentRule type) { return type != null ? type.getCode() : null; } private static final ImmutableMap<String, PaymentRule> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), PaymentRule::getCode); public boolean isCashOrCheck() { return isCash() || isCheck(); } public boolean isCash()
{ return this == Cash; } public boolean isCheck() { return this == Check; } public boolean isOnCredit() {return OnCredit.equals(this);} public boolean isPayPal() {return PayPal.equals(this);} public boolean isSettlement() {return Settlement.equals(this);} public boolean isDirectDebit() { return this == DirectDebit; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\PaymentRule.java
1
请完成以下Java代码
public class SelectionSort { public static void sortAscending(final int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minElementIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[minElementIndex] > arr[j]) { minElementIndex = j; } } if (minElementIndex != i) { int temp = arr[i]; arr[i] = arr[minElementIndex]; arr[minElementIndex] = temp; } } } public static void sortDescending(final int[] arr) { for (int i = 0; i < arr.length - 1; i++) {
int maxElementIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[maxElementIndex] < arr[j]) { maxElementIndex = j; } } if (maxElementIndex != i) { int temp = arr[i]; arr[i] = arr[maxElementIndex]; arr[maxElementIndex] = temp; } } } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\selectionsort\SelectionSort.java
1
请完成以下Java代码
public final IHUAttributesDAO getHUAttributesDAO() { Check.assumeNotNull(huAttributesDAO, "huAttributesDAO not null"); return huAttributesDAO; } @Override public final void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO) { this.huAttributesDAO = huAttributesDAO; } @Override public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO(); } @Override public IHUStorageFactory getHUStorageFactory() { Check.assumeNotNull(huStorageFactory, "IHUStorageFactory member of AbstractAttributeStorageFactory {} is not null", this); return huStorageFactory; } @Override public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory; }
@Override public String toString() { final ToStringHelper stringHelper = MoreObjects.toStringHelper(this); toString(stringHelper); return stringHelper.toString(); } protected void toString(final ToStringHelper stringHelper) { // nothing on this level } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractAttributeStorageFactory.java
1
请完成以下Java代码
private PickingCandidateIssueToBOMLine toPickingCandidateIssueToBOMLine(final I_M_Picking_Candidate_IssueToOrder record) { final I_C_UOM uom = uomsRepo.getById(record.getC_UOM_ID()); return PickingCandidateIssueToBOMLine.builder() .issueToOrderBOMLineId(PPOrderBOMLineId.ofRepoId(record.getPP_Order_BOMLine_ID())) .issueFromHUId(HuId.ofRepoId(record.getM_HU_ID())) .productId(ProductId.ofRepoId(record.getM_Product_ID())) .qtyToIssue(Quantity.of(record.getQtyToIssue(), uom)) .build(); } private void saveIssuesToBOMLine( @NonNull final PickingCandidateId pickingCandidateId, @NonNull final ImmutableList<PickingCandidateIssueToBOMLine> issuesToPickingOrder) { final HashMap<PickingCandidateIssueToBOMLineKey, I_M_Picking_Candidate_IssueToOrder> existingRecordsByKey = streamIssuesToBOMLineRecords(pickingCandidateId) .collect(GuavaCollectors.toHashMapByKey(PickingCandidateIssueToBOMLineKey::of)); for (final PickingCandidateIssueToBOMLine issue : issuesToPickingOrder) { final PickingCandidateIssueToBOMLineKey key = PickingCandidateIssueToBOMLineKey.of(issue); final I_M_Picking_Candidate_IssueToOrder existingRecord = existingRecordsByKey.remove(key); final I_M_Picking_Candidate_IssueToOrder record; if (existingRecord != null) { record = existingRecord; } else { record = newInstance(I_M_Picking_Candidate_IssueToOrder.class); } record.setIsActive(true); record.setM_Picking_Candidate_ID(pickingCandidateId.getRepoId()); record.setPP_Order_BOMLine_ID(issue.getIssueToOrderBOMLineId().getRepoId()); record.setM_HU_ID(issue.getIssueFromHUId().getRepoId()); record.setM_Product_ID(issue.getProductId().getRepoId()); record.setQtyToIssue(issue.getQtyToIssue().toBigDecimal()); record.setC_UOM_ID(issue.getQtyToIssue().getUomId().getRepoId()); saveRecord(record); } deleteAll(existingRecordsByKey.values());
} private Stream<I_M_Picking_Candidate_IssueToOrder> streamIssuesToBOMLineRecords(final PickingCandidateId pickingCandidateId) { return queryBL.createQueryBuilder(I_M_Picking_Candidate_IssueToOrder.class) .addEqualsFilter(I_M_Picking_Candidate_IssueToOrder.COLUMNNAME_M_Picking_Candidate_ID, pickingCandidateId) .create() .stream(); } private void deleteIssuesToBOMLine(@NonNull final Collection<PickingCandidateId> pickingCandidateIds) { if (pickingCandidateIds.isEmpty()) { return; } queryBL.createQueryBuilder(I_M_Picking_Candidate_IssueToOrder.class) .addInArrayFilter(I_M_Picking_Candidate_IssueToOrder.COLUMNNAME_M_Picking_Candidate_ID, pickingCandidateIds) .create() .delete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidateRepository.java
1
请完成以下Java代码
public void onMaterialTrackingASIChange(final I_M_ReceiptSchedule rs) { final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class); final IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class); // get the old and current material tracking (if any) and check if there was a change final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(rs.getM_AttributeSetInstance_ID()); final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId); // might be null final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID(); final I_M_ReceiptSchedule rsOld = InterfaceWrapperHelper.createOld(rs, I_M_ReceiptSchedule.class); final AttributeSetInstanceId asiOldId = AttributeSetInstanceId.ofRepoIdOrNone(rsOld.getM_AttributeSetInstance_ID()); final I_M_Material_Tracking materialTrackingOld = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiOldId); final int materialTrackingOldId = materialTrackingOld == null ? -1 : materialTrackingOld.getM_Material_Tracking_ID();
if (materialTrackingOldId == materialTrackingId) { return; // the M_Material_Tracking part of the ASI was not changed; nothing to do } // update the HUs that are still in the planning stage final List<I_M_HU> topLevelHUs = huAssignmentDAO.retrieveTopLevelHUsForModel(rs); for (final I_M_HU hu : topLevelHUs) { // we only want to update HUs that are still in the planning stage. For the others, this rs is not in charge anymore final IHUMaterialTrackingBL huMaterialTrackingBL = Services.get(IHUMaterialTrackingBL.class); huMaterialTrackingBL.updateHUAttributeRecursive(hu, materialTracking, X_M_HU.HUSTATUS_Planning); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\model\validator\M_ReceiptSchedule.java
1
请完成以下Java代码
public class EvaluateeValidationContext implements IValidationContext { private final Evaluatee evaluatee; public EvaluateeValidationContext(@NonNull final Evaluatee evaluatee) { this.evaluatee = evaluatee; } /** * @return null */ @Override public String getTableName() { return null; } @Override
public String get_ValueAsString(final String variableName) { return evaluatee.get_ValueAsString(variableName); } @Override public Integer get_ValueAsInt(final String variableName, final Integer defaultValue) { return evaluatee.get_ValueAsInt(variableName, defaultValue); } @Override public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue) { return evaluatee.get_ValueAsBoolean(variableName, defaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\EvaluateeValidationContext.java
1
请完成以下Java代码
public String asString() { return "graphql.outcome"; } }, /** * GraphQL {@link graphql.language.OperationDefinition.Operation Operation type}. */ OPERATION_TYPE { @Override public String asString() { return "graphql.operation.type"; } } } public enum ExecutionRequestHighCardinalityKeyNames implements KeyName { /** * GraphQL Operation name. */ OPERATION_NAME { @Override public String asString() { return "graphql.operation.name"; } }, /** * {@link graphql.execution.ExecutionId} of the GraphQL request. */ EXECUTION_ID { @Override public String asString() { return "graphql.execution.id"; } } } public enum DataFetcherLowCardinalityKeyNames implements KeyName { /** * Outcome of the GraphQL data fetching operation. */ OUTCOME { @Override public String asString() { return "graphql.outcome"; } }, /** * Name of the field being fetched. */ FIELD_NAME { @Override public String asString() { return "graphql.field.name"; } }, /** * Class name of the data fetching error. */ ERROR_TYPE { @Override public String asString() { return "graphql.error.type"; } } } public enum DataFetcherHighCardinalityKeyNames implements KeyName { /** * Path to the field being fetched. */ FIELD_PATH { @Override public String asString() { return "graphql.field.path"; } } } public enum DataLoaderLowCardinalityKeyNames implements KeyName { /** * Class name of the data fetching error. */ ERROR_TYPE { @Override public String asString() {
return "graphql.error.type"; } }, /** * {@link DataLoader#getName()} of the data loader. */ LOADER_NAME { @Override public String asString() { return "graphql.loader.name"; } }, /** * Outcome of the GraphQL data fetching operation. */ OUTCOME { @Override public String asString() { return "graphql.outcome"; } } } public enum DataLoaderHighCardinalityKeyNames implements KeyName { /** * Size of the list of elements returned by the data loading operation. */ LOADER_SIZE { @Override public String asString() { return "graphql.loader.size"; } } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\GraphQlObservationDocumentation.java
1
请完成以下Java代码
public class AuthenticationPayloadExchangeConverter implements PayloadExchangeAuthenticationConverter { private static final MimeType COMPOSITE_METADATA_MIME_TYPE = MimeTypeUtils .parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); private static final MimeType AUTHENTICATION_MIME_TYPE = MimeTypeUtils .parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); private final MetadataExtractor metadataExtractor = createDefaultExtractor(); @Override public Mono<Authentication> convert(PayloadExchange exchange) { return Mono .fromCallable(() -> this.metadataExtractor.extract(exchange.getPayload(), AuthenticationPayloadExchangeConverter.COMPOSITE_METADATA_MIME_TYPE)) .flatMap((metadata) -> Mono.justOrEmpty(authentication(metadata))); } private @Nullable Authentication authentication(Map<String, Object> metadata) { byte[] authenticationMetadata = (byte[]) metadata.get("authentication"); if (authenticationMetadata == null) { return null; } ByteBuf rawAuthentication = ByteBufAllocator.DEFAULT.buffer(); try { rawAuthentication.writeBytes(authenticationMetadata); if (!AuthMetadataCodec.isWellKnownAuthType(rawAuthentication)) { return null; } WellKnownAuthType wellKnownAuthType = AuthMetadataCodec.readWellKnownAuthType(rawAuthentication); if (WellKnownAuthType.SIMPLE.equals(wellKnownAuthType)) { return simple(rawAuthentication); } if (WellKnownAuthType.BEARER.equals(wellKnownAuthType)) { return bearer(rawAuthentication); } throw new IllegalArgumentException("Unknown Mime Type " + wellKnownAuthType);
} finally { rawAuthentication.release(); } } private Authentication simple(ByteBuf rawAuthentication) { ByteBuf rawUsername = AuthMetadataCodec.readUsername(rawAuthentication); String username = rawUsername.toString(StandardCharsets.UTF_8); ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication); String password = rawPassword.toString(StandardCharsets.UTF_8); return UsernamePasswordAuthenticationToken.unauthenticated(username, password); } private Authentication bearer(ByteBuf rawAuthentication) { char[] rawToken = AuthMetadataCodec.readBearerTokenAsCharArray(rawAuthentication); String token = new String(rawToken); return new BearerTokenAuthenticationToken(token); } private static MetadataExtractor createDefaultExtractor() { DefaultMetadataExtractor result = new DefaultMetadataExtractor(new ByteArrayDecoder()); result.metadataToExtract(AUTHENTICATION_MIME_TYPE, byte[].class, "authentication"); return result; } }
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\authentication\AuthenticationPayloadExchangeConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class Department { @Id @GeneratedValue private Long id; private String name; @OneToMany(mappedBy = "department") private List<Course> courses; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public List<Course> getCourses() { return courses; } public void setCourses(List<Course> courses) { this.courses = courses; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\jacksonlazyfields\model\Department.java
2
请完成以下Java代码
public static class PrinterHWMediaTray implements Serializable { /** * */ private static final long serialVersionUID = -1833627999553124042L; private String name; private String trayNumber; private String isDefault; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTrayNumber() { return trayNumber; } public void setTrayNumber(String trayNumber) { this.trayNumber = trayNumber; }
public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaTray [name=" + name + ", trayNumber=" + trayNumber + ", isDefault=" + isDefault + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrinterHW.java
1
请在Spring Boot框架中完成以下Java代码
public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter { @Value("${google.clientId}") private String clientId; @Value("${google.issuer}") private String issuer; @Value("${google.jwkUrl}") private String jwkUrl; public OAuth2RestOperations restTemplate; public OpenIdConnectFilter(String defaultFilterProcessesUrl) { super(defaultFilterProcessesUrl); setAuthenticationManager(new NoopAuthenticationManager()); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { OAuth2AccessToken accessToken; try { accessToken = restTemplate.getAccessToken(); } catch (final OAuth2Exception e) { throw new BadCredentialsException("Could not obtain access token", e); } try { final String idToken = accessToken.getAdditionalInformation().get("id_token").toString(); String kid = JwtHelper.headers(idToken) .get("kid"); final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid)); final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class); verifyClaims(authInfo); final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken); return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); } catch (final Exception e) { throw new BadCredentialsException("Could not obtain user details from token", e); } } public void verifyClaims(Map claims) { int exp = (int) claims.get("exp"); Date expireDate = new Date(exp * 1000L); Date now = new Date(); if (expireDate.before(now) || !claims.get("iss").equals(issuer) || !claims.get("aud").equals(clientId)) {
throw new RuntimeException("Invalid claims"); } } private RsaVerifier verifier(String kid) throws Exception { JwkProvider provider = new UrlJwkProvider(new URI(jwkUrl).toURL()); Jwk jwk = provider.get(kid); return new RsaVerifier((RSAPublicKey) jwk.getPublicKey()); } public void setRestTemplate(OAuth2RestTemplate restTemplate2) { restTemplate = restTemplate2; } private static class NoopAuthenticationManager implements AuthenticationManager { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager"); } } }
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectFilter.java
2
请完成以下Java代码
public class ArrayLifoStack<E> implements LifoStack<E> { private final Deque<E> deque = new ArrayDeque<>(); @Override public void push(E item) { deque.addFirst(item); } @Override public E pop() { return deque.removeFirst(); } @Override public E peek() { return deque.peekFirst(); } // implementing methods from the Collection interface @Override public int size() { return deque.size(); } @Override public boolean isEmpty() { return deque.isEmpty(); } @Override public boolean contains(Object o) { return deque.contains(o); } @Override public Iterator<E> iterator() { return deque.iterator(); } @Override public Object[] toArray() { return deque.toArray(); } @Override public <T> T[] toArray(T[] a) { return deque.toArray(a); } @Override public boolean add(E e) { return deque.add(e); } @Override
public boolean remove(Object o) { return deque.remove(o); } @Override public boolean containsAll(Collection<?> c) { return deque.containsAll(c); } @Override public boolean addAll(Collection<? extends E> c) { return deque.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return deque.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return deque.retainAll(c); } @Override public void clear() { deque.clear(); } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\dequestack\ArrayLifoStack.java
1
请完成以下Java代码
public Builder newContextForFetchingList() { return LookupDataSourceContext.builder(CONTEXT_LookupTableName) .setRequiredParameters(PARAMETERS); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { final int countryId = evalCtx.get_ValueAsInt(I_C_Location.COLUMNNAME_C_Country_ID, -1); if (countryId <= 0) { return LookupValuesPage.EMPTY; } // // Determine what we will filter final String filter = evalCtx.getFilter(); final boolean matchAll; final String filterUC; final int limit; final int offset = evalCtx.getOffset(0); if (filter == LookupDataSourceContext.FILTER_Any) { matchAll = true; filterUC = null; // N/A limit = evalCtx.getLimit(Integer.MAX_VALUE); } else if (Check.isEmpty(filter, true)) { return LookupValuesPage.EMPTY; } else { matchAll = false; filterUC = filter.trim().toUpperCase(); limit = evalCtx.getLimit(100); } // // Get, filter, return return getRegionLookupValues(countryId) .getValues() .stream() .filter(region -> matchAll || matchesFilter(region, filterUC))
.collect(LookupValuesList.collect()) .pageByOffsetAndLimit(offset, limit); } private boolean matchesFilter(final LookupValue region, final String filterUC) { final String displayName = region.getDisplayName(); if (Check.isEmpty(displayName)) { return false; } final String displayNameUC = displayName.trim().toUpperCase(); return displayNameUC.contains(filterUC); } private LookupValuesList getRegionLookupValues(final int countryId) { return regionsByCountryId.getOrLoad(countryId, () -> retrieveRegionLookupValues(countryId)); } private LookupValuesList retrieveRegionLookupValues(final int countryId) { return Services.get(ICountryDAO.class) .retrieveRegions(Env.getCtx(), countryId) .stream() .map(this::createLookupValue) .collect(LookupValuesList.collect()); } private IntegerLookupValue createLookupValue(final I_C_Region regionRecord) { return IntegerLookupValue.of(regionRecord.getC_Region_ID(), regionRecord.getName()); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRegionLookupDescriptor.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { if (isJobReacquired(commandContext)) { // skip failed listener if job has been already re-acquired LOG.debugFailedJobListenerSkipped(jobFailureCollector.getJobId()); return null; } initTotalRetries(commandContext); logJobFailure(commandContext); FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory(); String jobId = jobFailureCollector.getJobId(); Command<Object> cmd = failedJobCommandFactory.getCommand(jobId, jobFailureCollector.getFailure()); commandExecutor.execute(new FailedJobListenerCmd(jobId, cmd)); return null; } protected boolean isJobReacquired(CommandContext commandContext) { // if persisted job's lockExpirationTime is different, then it's been already re-acquired JobEntity persistedJob = commandContext.getJobManager().findJobById(jobFailureCollector.getJobId()); JobEntity job = jobFailureCollector.getJob(); if (persistedJob == null || persistedJob.getLockExpirationTime() == null) { return false; } return !persistedJob.getLockExpirationTime().equals(job.getLockExpirationTime()); } private void initTotalRetries(CommandContext commandContext) { totalRetries = commandContext.getProcessEngineConfiguration().getFailedJobListenerMaxRetries(); } protected void fireHistoricJobFailedEvt(JobEntity job) { CommandContext commandContext = Context.getCommandContext(); // the given job failed and a rollback happened, // that's why we have to increment the job // sequence counter once again job.incrementSequenceCounter(); commandContext .getHistoricJobLogManager() .fireJobFailedEvent(job, jobFailureCollector.getFailure()); } protected void logJobFailure(CommandContext commandContext) { if (commandContext.getProcessEngineConfiguration().isMetricsEnabled()) {
commandContext.getProcessEngineConfiguration() .getMetricsRegistry() .markOccurrence(Metrics.JOB_FAILED); } } public void incrementCountRetries() { this.countRetries++; } public int getRetriesLeft() { return Math.max(0, totalRetries - countRetries); } protected class FailedJobListenerCmd implements Command<Void> { protected String jobId; protected Command<Object> cmd; public FailedJobListenerCmd(String jobId, Command<Object> cmd) { this.jobId = jobId; this.cmd = cmd; } @Override public Void execute(CommandContext commandContext) { JobEntity job = commandContext .getJobManager() .findJobById(jobId); if (job != null) { job.setFailedActivityId(jobFailureCollector.getFailedActivityId()); fireHistoricJobFailedEvt(job); cmd.execute(commandContext); } else { LOG.debugFailedJobNotFound(jobId); } return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\FailedJobListener.java
1
请完成以下Java代码
public int getM_Product_Order_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Order_ID); } @Override public void setPercentOfBasePoints (final @Nullable BigDecimal PercentOfBasePoints) { set_ValueNoCheck (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); } @Override public BigDecimal getPercentOfBasePoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Forecasted (final @Nullable BigDecimal PointsBase_Forecasted) { set_ValueNoCheck (COLUMNNAME_PointsBase_Forecasted, PointsBase_Forecasted); } @Override public BigDecimal getPointsBase_Forecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Forecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiceable (final @Nullable BigDecimal PointsBase_Invoiceable) { set_ValueNoCheck (COLUMNNAME_PointsBase_Invoiceable, PointsBase_Invoiceable); } @Override public BigDecimal getPointsBase_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiced (final @Nullable BigDecimal PointsBase_Invoiced) { set_ValueNoCheck (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced); } @Override public BigDecimal getPointsBase_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setPointsSum_Settled (final @Nullable BigDecimal PointsSum_Settled) { set_ValueNoCheck (COLUMNNAME_PointsSum_Settled, PointsSum_Settled); } @Override public BigDecimal getPointsSum_Settled() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_ToSettle (final @Nullable BigDecimal PointsSum_ToSettle) { set_ValueNoCheck (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle); } @Override public BigDecimal getPointsSum_ToSettle() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Overview_V.java
1
请完成以下Java代码
public boolean isUser() { return userId != null; } public boolean isGroup() { return groupId != null; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserId() { return userId; } public void setUserId(String userId) { if (this.groupId != null && userId != null) { throw new ActivitiException("Cannot assign a userId to a task assignment that already has a groupId"); } this.userId = userId; } public String getGroupId() { return groupId; }
public void setGroupId(String groupId) { if (this.userId != null && groupId != null) { throw new ActivitiException("Cannot assign a groupId to a task assignment that already has a userId"); } this.groupId = groupId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public byte[] getDetails() { return this.details; } public void setDetails(byte[] details) { this.details = details; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityImpl.java
1
请完成以下Java代码
public class HitPolicyPriority extends AbstractHitPolicy implements ComposeDecisionResultBehavior { @Override public String getHitPolicyName() { return HitPolicy.PRIORITY.getValue(); } @Override public void composeDecisionResults(final ELExecutionContext executionContext) { List<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values()); // sort on predefined list(s) of output values ruleResults.sort(new Comparator<Object>() { boolean noOutputValuesPresent = true; @SuppressWarnings("unchecked") @Override public int compare(Object o1, Object o2) { CompareToBuilder compareToBuilder = new CompareToBuilder(); for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) { List<Object> outputValues = entry.getValue(); if (outputValues != null && !outputValues.isEmpty()) { noOutputValuesPresent = false; compareToBuilder.append(((Map<String, Object>) o1).get(entry.getKey()), ((Map<String, Object>) o2).get(entry.getKey()), new OutputOrderComparator<>(outputValues.toArray(new Comparable[outputValues.size()]))); } } if (!noOutputValuesPresent) { return compareToBuilder.toComparison(); } else {
if (CommandContextUtil.getDmnEngineConfiguration().isStrictMode()) { throw new FlowableException(String.format("HitPolicy %s violated; no output values present.", getHitPolicyName())); } else { executionContext.getAuditContainer().setValidationMessage( String.format("HitPolicy %s violated; no output values present. Setting first valid result as final result.", getHitPolicyName())); } return 0; } } }); if (!ruleResults.isEmpty()) { executionContext.getAuditContainer().addDecisionResultObject(ruleResults.get(0)); } } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyPriority.java
1
请完成以下Java代码
public class X_C_CountryArea extends org.compiere.model.PO implements I_C_CountryArea, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 371014192L; /** Standard Constructor */ public X_C_CountryArea (Properties ctx, int C_CountryArea_ID, String trxName) { super (ctx, C_CountryArea_ID, trxName); /** if (C_CountryArea_ID == 0) { setC_CountryArea_ID (0); setName (null); setValue (null); } */ } /** Load Constructor */ public X_C_CountryArea (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Country Area. @param C_CountryArea_ID Country Area */ @Override public void setC_CountryArea_ID (int C_CountryArea_ID) { if (C_CountryArea_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, Integer.valueOf(C_CountryArea_ID)); } /** Get Country Area. @return Country Area */ @Override public int getC_CountryArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name)
{ set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CountryArea.java
1
请完成以下Java代码
public void setParameter(Object parameter) { this.parameter = parameter; } public void setDatabaseType(String databaseType) { this.databaseType = databaseType; } public String getDatabaseType() { return databaseType; } public AuthorizationCheck getAuthCheck() { return authCheck; } public void setAuthCheck(AuthorizationCheck authCheck) { this.authCheck = authCheck;
} public TenantCheck getTenantCheck() { return tenantCheck; } public void setTenantCheck(TenantCheck tenantCheck) { this.tenantCheck = tenantCheck; } public List<QueryOrderingProperty> getOrderingProperties() { return orderingProperties; } public void setOrderingProperties(List<QueryOrderingProperty> orderingProperties) { this.orderingProperties = orderingProperties; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\ListQueryParameterObject.java
1
请完成以下Java代码
public class AddCommentCmd implements Command<Comment> { protected String taskId; protected String processInstanceId; protected String type; protected String message; public AddCommentCmd(String taskId, String processInstanceId, String message) { this.taskId = taskId; this.processInstanceId = processInstanceId; this.message = message; } public AddCommentCmd(String taskId, String processInstanceId, String type, String message) { this.taskId = taskId; this.processInstanceId = processInstanceId; this.type = type; this.message = message; } @Override public Comment execute(CommandContext commandContext) { // Validate task if (taskId != null) { TaskEntity task = commandContext.getTaskEntityManager().findTaskById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class); } if (task.isSuspended()) { throw new ActivitiException(getSuspendedTaskException()); } } if (processInstanceId != null) { ExecutionEntity execution = commandContext.getExecutionEntityManager().findExecutionById(processInstanceId); if (execution == null) { throw new ActivitiObjectNotFoundException("execution " + processInstanceId + " doesn't exist", Execution.class); } if (execution.isSuspended()) { throw new ActivitiException(getSuspendedExceptionMessage()); } } String userId = Authentication.getAuthenticatedUserId(); CommentEntity comment = new CommentEntity();
comment.setUserId(userId); comment.setType((type == null) ? CommentEntity.TYPE_COMMENT : type); comment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime()); comment.setTaskId(taskId); comment.setProcessInstanceId(processInstanceId); comment.setAction(Event.ACTION_ADD_COMMENT); String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } comment.setMessage(eventMessage); comment.setFullMessage(message); commandContext .getCommentEntityManager() .insert(comment); return comment; } protected String getSuspendedTaskException() { return "Cannot add a comment to a suspended task"; } protected String getSuspendedExceptionMessage() { return "Cannot add a comment to a suspended execution"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\AddCommentCmd.java
1
请在Spring Boot框架中完成以下Java代码
public List<VariableInstance> findVariableInstancesByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findVariableInstancesByNativeQuery(parameterMap); } @Override public long findVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findVariableInstanceCountByNativeQuery(parameterMap); } @Override public void delete(VariableInstanceEntity entity, boolean fireDeleteEvent) { super.delete(entity, false); ByteArrayRef byteArrayRef = entity.getByteArrayRef(); if (byteArrayRef != null) { byteArrayRef.delete(serviceConfiguration.getEngineName()); } entity.setDeleted(true); } @Override public void deleteVariablesByTaskId(String taskId) { dataManager.deleteVariablesByTaskId(taskId); } @Override
public void deleteVariablesByExecutionId(String executionId) { dataManager.deleteVariablesByExecutionId(executionId); } @Override public void deleteByScopeIdAndScopeType(String scopeId, String scopeType) { dataManager.deleteByScopeIdAndScopeType(scopeId, scopeType); } @Override public void deleteByScopeIdAndScopeTypes(String scopeId, Collection<String> scopeTypes) { dataManager.deleteByScopeIdAndScopeTypes(scopeId, scopeTypes); } @Override public void deleteBySubScopeIdAndScopeTypes(String subScopeId, Collection<String> scopeTypes) { dataManager.deleteBySubScopeIdAndScopeTypes(subScopeId, scopeTypes); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInstanceEntityManagerImpl.java
2
请完成以下Java代码
public class ByteArrayOtherStream extends ByteArrayStream { InputStream is; public ByteArrayOtherStream(byte[] bytes, int bufferSize) { super(bytes, bufferSize); } public ByteArrayOtherStream(byte[] bytes, int bufferSize, InputStream is) { super(bytes, bufferSize); this.is = is; } public static ByteArrayOtherStream createByteArrayOtherStream(String path) { try { InputStream is = HanLP.Config.IOAdapter == null ? new FileInputStream(path) : HanLP.Config.IOAdapter.open(path); return createByteArrayOtherStream(is); } catch (Exception e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); return null; } } public static ByteArrayOtherStream createByteArrayOtherStream(InputStream is) throws IOException { if (is == null) return null; int size = is.available(); size = Math.max(102400, size); // 有些网络InputStream实现会返回0,直到read的时候才知道到底是不是0 int bufferSize = Math.min(1048576, size); // 最终缓冲区在100KB到1MB之间 byte[] bytes = new byte[bufferSize]; if (IOUtil.readBytesFromOtherInputStream(is, bytes) == 0) { throw new IOException("读取了空文件,或参数InputStream已经到了文件尾部"); } return new ByteArrayOtherStream(bytes, bufferSize, is); } @Override protected void ensureAvailableBytes(int size) { if (offset + size > bufferSize) { try
{ int wantedBytes = offset + size - bufferSize; // 实际只需要这么多 wantedBytes = Math.max(wantedBytes, is.available()); // 如果非阻塞IO能读到更多,那越多越好 wantedBytes = Math.min(wantedBytes, offset); // 但不能超过脏区的大小 byte[] bytes = new byte[wantedBytes]; int readBytes = IOUtil.readBytesFromOtherInputStream(is, bytes); assert readBytes > 0 : "已到达文件尾部!"; System.arraycopy(this.bytes, offset, this.bytes, offset - wantedBytes, bufferSize - offset); System.arraycopy(bytes, 0, this.bytes, bufferSize - wantedBytes, wantedBytes); offset -= wantedBytes; } catch (IOException e) { throw new RuntimeException(e); } } } @Override public void close() { super.close(); if (is == null) { return; } try { is.close(); } catch (IOException e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayOtherStream.java
1
请完成以下Java代码
public EventDeploymentQuery orderByDeploymentName() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_NAME); } @Override public EventDeploymentQuery orderByTenantId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_TENANT_ID); } // results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getDeploymentEntityManager(commandContext).findDeploymentCountByQueryCriteria(this); } @Override public List<EventDeployment> executeList(CommandContext commandContext) { return CommandContextUtil.getDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this); } // getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; }
public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getEventDefinitionKey() { return eventDefinitionKey; } public String getEventDefinitionKeyLike() { return eventDefinitionKeyLike; } public String getParentDeploymentId() { return parentDeploymentId; } public String getParentDeploymentIdLike() { return parentDeploymentIdLike; } public String getChannelDefinitionKey() { return channelDefinitionKey; } public String getChannelDefinitionKeyLike() { return channelDefinitionKeyLike; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDeploymentQueryImpl.java
1
请完成以下Java代码
public PlanItemDefinition getDefinition() { return definitionRefAttribute.getReferenceTargetElement(this); } public void setDefinition(PlanItemDefinition definition) { definitionRefAttribute.setReferenceTargetElement(this, definition); } public ItemControl getItemControl() { return itemControlChild.getChild(this); } public void setItemControl(ItemControl itemControl) { itemControlChild.setChild(this, itemControl); } public Collection<EntryCriterion> getEntryCriterions() { return entryCriterionCollection.get(this); } public Collection<ExitCriterion> getExitCriterions() { return exitCriterionCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DiscretionaryItem.class, CMMN_ELEMENT_DISCRETIONARY_ITEM) .namespaceUri(CMMN11_NS) .extendsType(TableItem.class) .instanceProvider(new ModelTypeInstanceProvider<DiscretionaryItem>() { public DiscretionaryItem newInstance(ModelTypeInstanceContext instanceContext) { return new DiscretionaryItemImpl(instanceContext); }
}); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .idAttributeReference(PlanItemDefinition.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); itemControlChild = sequenceBuilder.element(ItemControl.class) .build(); entryCriterionCollection = sequenceBuilder.elementCollection(EntryCriterion.class) .build(); exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DiscretionaryItemImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Chapter implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "chapter_title") private String title; @Column(name = "chapter_pages") private int pages; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "book_id") private Book book; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book;
} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Chapter) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseTriggers\src\main\java\com\bookstore\entity\Chapter.java
2
请完成以下Java代码
public class TomcatEmbeddedWebappClassLoader extends ParallelWebappClassLoader { private static final Log logger = LogFactory.getLog(TomcatEmbeddedWebappClassLoader.class); static { if (!JreCompat.isGraalAvailable()) { ClassLoader.registerAsParallelCapable(); } } public TomcatEmbeddedWebappClassLoader() { } public TomcatEmbeddedWebappClassLoader(@Nullable ClassLoader parent) { super(parent); } @Override public @Nullable URL findResource(String name) { return null; } @Override public Enumeration<URL> findResources(String name) throws IOException { return Collections.emptyEnumeration(); } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (JreCompat.isGraalAvailable() ? this : getClassLoadingLock(name)) { Class<?> result = findExistingLoadedClass(name); result = (result != null) ? result : doLoadClass(name); if (result == null) { throw new ClassNotFoundException(name); } return resolveIfNecessary(result, resolve); } } private @Nullable Class<?> findExistingLoadedClass(String name) { Class<?> resultClass = findLoadedClass0(name); resultClass = (resultClass != null || JreCompat.isGraalAvailable()) ? resultClass : findLoadedClass(name); return resultClass; }
private @Nullable Class<?> doLoadClass(String name) { if ((this.delegate || filter(name, true))) { Class<?> result = loadFromParent(name); return (result != null) ? result : findClassIgnoringNotFound(name); } Class<?> result = findClassIgnoringNotFound(name); return (result != null) ? result : loadFromParent(name); } private Class<?> resolveIfNecessary(Class<?> resultClass, boolean resolve) { if (resolve) { resolveClass(resultClass); } return (resultClass); } @Override protected void addURL(URL url) { // Ignore URLs added by the Tomcat 8 implementation (see gh-919) if (logger.isTraceEnabled()) { logger.trace("Ignoring request to add " + url + " to the tomcat classloader"); } } private @Nullable Class<?> loadFromParent(String name) { if (this.parent == null) { return null; } try { return Class.forName(name, false, this.parent); } catch (ClassNotFoundException ex) { return null; } } private @Nullable Class<?> findClassIgnoringNotFound(String name) { try { return findClass(name); } catch (ClassNotFoundException ex) { return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\TomcatEmbeddedWebappClassLoader.java
1
请完成以下Java代码
public void setAuthenticationManager(AuthenticationManager newManager) { this.authenticationManager = newManager; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } /** * Only {@code AuthorizationFailureEvent} will be published. If you set this property * to {@code true}, {@code AuthorizedEvent}s will also be published. * @param publishAuthorizationSuccess default value is {@code false} */ public void setPublishAuthorizationSuccess(boolean publishAuthorizationSuccess) { this.publishAuthorizationSuccess = publishAuthorizationSuccess; } /** * By rejecting public invocations (and setting this property to <tt>true</tt>), * essentially you are ensuring that every secure object invocation advised by * <code>AbstractSecurityInterceptor</code> has a configuration attribute defined. * This is useful to ensure a "fail safe" mode where undeclared secure objects will be * rejected and configuration omissions detected early. An * <tt>IllegalArgumentException</tt> will be thrown by the * <tt>AbstractSecurityInterceptor</tt> if you set this property to <tt>true</tt> and * an attempt is made to invoke a secure object that has no configuration attributes. * @param rejectPublicInvocations set to <code>true</code> to reject invocations of * secure objects that have no configuration attributes (by default it is * <code>false</code> which treats undeclared secure objects as "public" or * unauthorized). */
public void setRejectPublicInvocations(boolean rejectPublicInvocations) { this.rejectPublicInvocations = rejectPublicInvocations; } public void setRunAsManager(RunAsManager runAsManager) { this.runAsManager = runAsManager; } public void setValidateConfigAttributes(boolean validateConfigAttributes) { this.validateConfigAttributes = validateConfigAttributes; } private void publishEvent(ApplicationEvent event) { if (this.eventPublisher != null) { this.eventPublisher.publishEvent(event); } } private static class NoOpAuthenticationManager implements AuthenticationManager { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { throw new AuthenticationServiceException("Cannot authenticate " + authentication); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AbstractSecurityInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public class PushProductsRoute extends RouteBuilder { public static final String PUSH_PRODUCTS = "Alberta-pushProducts"; public static final String PROCESS_PRODUCT_ROUTE_ID = "Alberta-pushProduct"; public static final String RETRIEVE_PRODUCTS_PROCESSOR_ID = "GetProductsFromMetasfreshProcessor"; public static final String PREPARE_ARTICLE_PROCESSOR_ID = "PrepareArticleProcessor"; public static final String PUSH_ARTICLE_PROCESSOR_ID = "PushArticleProcessor"; private final ProcessLogger processLogger; public PushProductsRoute(final ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void configure() { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(StaticEndpointBuilders.direct(MF_ERROR_ROUTE_ID)); //@formatter:off // this EP's name is matching the JsonExternalSystemRequest's ExternalSystem and Command from(StaticEndpointBuilders.direct(PUSH_PRODUCTS)) .routeId(PUSH_PRODUCTS) .log("Route invoked") .streamCache("true") .process(new RetrieveProductsProcessor()).id(RETRIEVE_PRODUCTS_PROCESSOR_ID) .to(StaticEndpointBuilders.direct(MF_GET_PRODUCTS_ROUTE_ID)) .unmarshal(setupJacksonDataFormatFor(getContext(), JsonGetProductsResponse.class)) .process(this::processProductsResponseFromMF) .choice() .when(body().isNull()) .log(LoggingLevel.INFO, "Nothing to do! No products pulled from MF!") .otherwise() .split(body())
.to(StaticEndpointBuilders.direct(PROCESS_PRODUCT_ROUTE_ID)) .end() .endChoice() .process((exchange) -> processLogger.logMessage( PUSH_PRODUCTS + " route finalized work!" + Instant.now(), exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class))); from(StaticEndpointBuilders.direct(PROCESS_PRODUCT_ROUTE_ID)) .routeId(PROCESS_PRODUCT_ROUTE_ID) .log("Route invoked") .process(new PrepareAlbertaArticlesProcessor()).id(PREPARE_ARTICLE_PROCESSOR_ID) .process(new PushArticlesProcessor()).id(PUSH_ARTICLE_PROCESSOR_ID) .choice() .when(bodyAs(JsonRequestExternalReferenceUpsert.class).isNull()) .log(LoggingLevel.INFO, "Nothing to do! No JsonRequestExternalReferenceUpsert found!") .otherwise() .to("{{" + ExternalSystemCamelConstants.MF_UPSERT_EXTERNALREFERENCE_CAMEL_URI + "}}") .endChoice(); //@formatter:on } private void processProductsResponseFromMF(@NonNull final Exchange exchange) { final JsonGetProductsResponse response = exchange.getIn().getBody(JsonGetProductsResponse.class); final List<JsonProduct> products = (response != null && !CollectionUtils.isEmpty(response.getProducts())) ? response.getProducts() : null; exchange.getIn().setBody(products); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\product\PushProductsRoute.java
2
请完成以下Java代码
public void setAssignedMoneyAmount (java.math.BigDecimal AssignedMoneyAmount) { set_ValueNoCheck (COLUMNNAME_AssignedMoneyAmount, AssignedMoneyAmount); } /** Get Zugeordneter Geldbetrag. @return Zugeordneter Geldbetrag, in der Währung des Vertrags-Rechnungskandidaten. */ @Override public java.math.BigDecimal getAssignedMoneyAmount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedMoneyAmount); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zugeordnete Menge. @param AssignedQuantity Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes */ @Override public void setAssignedQuantity (java.math.BigDecimal AssignedQuantity) { set_ValueNoCheck (COLUMNNAME_AssignedQuantity, AssignedQuantity); } /** Get Zugeordnete Menge. @return Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes */ @Override public java.math.BigDecimal getAssignedQuantity () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedQuantity); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public de.metas.contracts.model.I_C_Flatrate_RefundConfig getC_Flatrate_RefundConfig() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class); } @Override public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig) { set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig); } /** Set C_Flatrate_RefundConfig. @param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */ @Override public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID) { if (C_Flatrate_RefundConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID)); } /** Get C_Flatrate_RefundConfig.
@return C_Flatrate_RefundConfig */ @Override public int getC_Flatrate_RefundConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) { if (C_Invoice_Candidate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java
1
请完成以下Java代码
public final Quantity getQtyInStockingUOM() { final I_C_UOM productUOM = Services.get(IProductBL.class).getStockUOM(getProductId()); return getQty(productUOM); } @Override public BigDecimal getQtyCapacity() { return capacityTotal.toBigDecimal(); } @Override public IAllocationRequest addQty(final IAllocationRequest request) { throw new AdempiereException("Adding Qty is not supported on this level"); } @Override public IAllocationRequest removeQty(final IAllocationRequest request) { throw new AdempiereException("Removing Qty is not supported on this level"); } /** * Returns always false because negative storages are not supported (see {@link #removeQty(IAllocationRequest)}) * * @return false */ @Override public boolean isAllowNegativeStorage() { return false; }
@Override public void markStaled() { // nothing, so far, itemStorage is always database coupled, no in memory values } @Override public boolean isEmpty() { return huStorage.isEmpty(getProductId()); } @Override public I_M_HU getM_HU() { return huStorage.getM_HU(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUProductStorage.java
1
请完成以下Java代码
public static List<String> readGZipFile(String filePath) throws IOException { List<String> lines = new ArrayList<>(); try (InputStream inputStream = new FileInputStream(filePath); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { String line; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } } return lines; } public static List<String> findInZipFile(String filePath, String toFind) throws IOException { try (InputStream inputStream = new FileInputStream(filePath); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { return bufferedReader.lines().filter(line -> line.contains(toFind)).collect(toList()); } } public static void useContentsOfZipFile(String filePath, Consumer<Stream<String>> consumer) throws IOException { try (InputStream inputStream = new FileInputStream(filePath); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { consumer.accept(bufferedReader.lines()); } } }
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\usinggzipInputstream\Main.java
1
请完成以下Java代码
protected final I_M_ShipmentSchedule getDocumentLineModel() { return (I_M_ShipmentSchedule)super.getDocumentLineModel(); } @Override protected final void createAllocation( final I_M_HU luHU, final I_M_HU tuHU, final I_M_HU vhu, final StockQtyAndUOMQty qtyToAllocate, final boolean deleteOldTUAllocations) { // nothing for now } @Override protected final void deleteAllocations(final Collection<I_M_HU> husToUnassign)
{ final I_M_ShipmentSchedule shipmentSchedule = getDocumentLineModel(); for (final I_M_HU hu : husToUnassign) { huShipmentScheduleBL.unallocateTU(shipmentSchedule, hu, getTrxName()); } } @Override protected final void deleteAllocations() { // nothing for now } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\ShipmentScheduleHUAllocations.java
1
请完成以下Java代码
public ReferredDocumentType2 getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link ReferredDocumentType2 } * */ public void setTp(ReferredDocumentType2 value) { this.tp = value; } /** * Gets the value of the nb property. * * @return * possible object is * {@link String } * */ public String getNb() { return nb; } /** * Sets the value of the nb property. * * @param value * allowed object is
* {@link String } * */ public void setNb(String value) { this.nb = value; } /** * Gets the value of the rltdDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRltdDt() { return rltdDt; } /** * Sets the value of the rltdDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRltdDt(XMLGregorianCalendar value) { this.rltdDt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ReferredDocumentInformation3.java
1
请完成以下Java代码
public Integer getFilterType() { return filterType; } public void setFilterType(Integer filterType) { this.filterType = filterType; } public Integer getSearchType() { return searchType; } public void setSearchType(Integer searchType) { this.searchType = searchType; } public Integer getRelatedStatus() { return relatedStatus; } public void setRelatedStatus(Integer relatedStatus) { this.relatedStatus = relatedStatus; } public Integer getHandAddStatus() { return handAddStatus; } public void setHandAddStatus(Integer handAddStatus) { this.handAddStatus = handAddStatus; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", selectType=").append(selectType); sb.append(", inputType=").append(inputType); sb.append(", inputList=").append(inputList); sb.append(", sort=").append(sort); sb.append(", filterType=").append(filterType); sb.append(", searchType=").append(searchType); sb.append(", relatedStatus=").append(relatedStatus); sb.append(", handAddStatus=").append(handAddStatus); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttribute.java
1
请完成以下Java代码
public ProcessEngineException transformResourceException(String name, Throwable cause) { return new ProcessEngineException(exceptionMessage("001", "Could not transform resource '{}'.", name), cause); } public ProcessEngineException parseProcessException(String name, Throwable cause) { return new ProcessEngineException(exceptionMessage("002", "Error while parsing process of resource '{}'.", name), cause); } public void ignoredSentryWithMissingCondition(String id) { logInfo( "003", "Sentry with id '{}' will be ignored. Reason: Neither ifPart nor onParts are defined with a condition.", id ); } public void ignoredSentryWithInvalidParts(String id) { logInfo("004", "Sentry with id '{}' will be ignored. Reason: ifPart and all onParts are not valid.", id); } public void ignoredUnsupportedAttribute(String attribute, String element, String id) { logInfo( "005", "The attribute '{}' based on the element '{}' of the sentry with id '{}' is not supported and will be ignored.", attribute, element, id ); } public void multipleIgnoredConditions(String id) { logInfo( "006", "The ifPart of the sentry with id '{}' has more than one condition. " +
"Only the first one will be used and the other conditions will be ignored.", id ); } public CmmnTransformException nonMatchingVariableEvents(String id) { return new CmmnTransformException(exceptionMessage( "007", "The variableOnPart of the sentry with id '{}' must have one valid variable event. ", id )); } public CmmnTransformException emptyVariableName(String id) { return new CmmnTransformException(exceptionMessage( "008", "The variableOnPart of the sentry with id '{}' must have variable name. ", id )); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransformerLogger.java
1
请完成以下Java代码
public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { return value instanceof CmmnAggregation; } @Override public boolean isReadOnly() { return true; } @Override public void setValue(Object value, ValueFields valueFields) { if (value instanceof CmmnAggregation) {
valueFields.setTextValue(((CmmnAggregation) value).getPlanItemInstanceId()); } else { valueFields.setTextValue(null); } } @Override public Object getValue(ValueFields valueFields) { CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { return CmmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), commandContext); } else { return cmmnEngineConfiguration.getCommandExecutor() .execute(context -> CmmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), context)); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\variable\CmmnAggregatedVariableType.java
1
请在Spring Boot框架中完成以下Java代码
static BeanMetadataElement getAuthenticationRequestResolver(Element element) { String authenticationRequestContextResolver = element.getAttribute(ATT_AUTHENTICATION_REQUEST_RESOLVER_REF); if (StringUtils.hasText(authenticationRequestContextResolver)) { return new RuntimeBeanReference(authenticationRequestContextResolver); } return null; } static BeanMetadataElement createDefaultAuthenticationRequestResolver( BeanMetadataElement relyingPartyRegistrationRepository) { BeanMetadataElement defaultRelyingPartyRegistrationResolver = BeanDefinitionBuilder .rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class) .addConstructorArgValue(relyingPartyRegistrationRepository) .getBeanDefinition(); if (USE_OPENSAML_5) { return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5AuthenticationRequestResolver.class) .addConstructorArgValue(defaultRelyingPartyRegistrationResolver) .getBeanDefinition(); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } static BeanDefinition createAuthenticationProvider() { if (USE_OPENSAML_5) { return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5AuthenticationProvider.class).getBeanDefinition(); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } static BeanMetadataElement getAuthenticationConverter(Element element) { String authenticationConverter = element.getAttribute(ATT_AUTHENTICATION_CONVERTER); if (StringUtils.hasText(authenticationConverter)) {
return new RuntimeBeanReference(authenticationConverter); } return null; } static BeanDefinition createDefaultAuthenticationConverter(BeanMetadataElement relyingPartyRegistrationRepository) { AbstractBeanDefinition resolver = BeanDefinitionBuilder .rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class) .addConstructorArgValue(relyingPartyRegistrationRepository) .getBeanDefinition(); return BeanDefinitionBuilder.rootBeanDefinition(Saml2AuthenticationTokenConverter.class) .addConstructorArgValue(resolver) .getBeanDefinition(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\Saml2LoginBeanDefinitionParserUtils.java
2
请在Spring Boot框架中完成以下Java代码
public void setDefaultPageSize(@Nullable Integer defaultPageSize) { this.defaultPageSize = defaultPageSize; } public @Nullable Integer getMaxPageSize() { return this.maxPageSize; } public void setMaxPageSize(@Nullable Integer maxPageSize) { this.maxPageSize = maxPageSize; } public @Nullable String getPageParamName() { return this.pageParamName; } public void setPageParamName(@Nullable String pageParamName) { this.pageParamName = pageParamName; } public @Nullable String getLimitParamName() { return this.limitParamName; } public void setLimitParamName(@Nullable String limitParamName) { this.limitParamName = limitParamName; } public @Nullable String getSortParamName() { return this.sortParamName; } public void setSortParamName(@Nullable String sortParamName) { this.sortParamName = sortParamName; } public RepositoryDetectionStrategies getDetectionStrategy() { return this.detectionStrategy; } public void setDetectionStrategy(RepositoryDetectionStrategies detectionStrategy) { this.detectionStrategy = detectionStrategy; } public @Nullable MediaType getDefaultMediaType() { return this.defaultMediaType; } public void setDefaultMediaType(@Nullable MediaType defaultMediaType) { this.defaultMediaType = defaultMediaType; } public @Nullable Boolean getReturnBodyOnCreate() { return this.returnBodyOnCreate; } public void setReturnBodyOnCreate(@Nullable Boolean returnBodyOnCreate) { this.returnBodyOnCreate = returnBodyOnCreate;
} public @Nullable Boolean getReturnBodyOnUpdate() { return this.returnBodyOnUpdate; } public void setReturnBodyOnUpdate(@Nullable Boolean returnBodyOnUpdate) { this.returnBodyOnUpdate = returnBodyOnUpdate; } public @Nullable Boolean getEnableEnumTranslation() { return this.enableEnumTranslation; } public void setEnableEnumTranslation(@Nullable Boolean enableEnumTranslation) { this.enableEnumTranslation = enableEnumTranslation; } public void applyTo(RepositoryRestConfiguration rest) { PropertyMapper map = PropertyMapper.get(); map.from(this::getBasePath).to(rest::setBasePath); map.from(this::getDefaultPageSize).to(rest::setDefaultPageSize); map.from(this::getMaxPageSize).to(rest::setMaxPageSize); map.from(this::getPageParamName).to(rest::setPageParamName); map.from(this::getLimitParamName).to(rest::setLimitParamName); map.from(this::getSortParamName).to(rest::setSortParamName); map.from(this::getDetectionStrategy).to(rest::setRepositoryDetectionStrategy); map.from(this::getDefaultMediaType).to(rest::setDefaultMediaType); map.from(this::getReturnBodyOnCreate).to(rest::setReturnBodyOnCreate); map.from(this::getReturnBodyOnUpdate).to(rest::setReturnBodyOnUpdate); map.from(this::getEnableEnumTranslation).to(rest::setEnableEnumTranslation); } }
repos\spring-boot-4.0.1\module\spring-boot-data-rest\src\main\java\org\springframework\boot\data\rest\autoconfigure\DataRestProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Queue syncRPCQueue() { return new Queue(QUEUE_SYNC_RPC); } @Bean public Queue asyncRPCQueue() { return new Queue(QUEUE_ASYNC_RPC); } @Bean public Queue fixedReplyRPCQueue() { return new Queue(QUEUE_ASYNC_RPC_WITH_FIXED_REPLY); } @Bean public Queue repliesQueue() { return new AnonymousQueue(); } @Bean public MessageConverter jsonMessageConverter(){ return new Jackson2JsonMessageConverter(); }
@Bean @Primary public SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setQueueNames(repliesQueue().getName()); return container; } @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(jsonMessageConverter()); return rabbitTemplate; } @Bean public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate template, SimpleMessageListenerContainer container) { return new AsyncRabbitTemplate(template, container); } }
repos\SpringBootBucket-master\springboot-rabbitmq-rpc\springboot-rabbitmq-rpc-client\src\main\java\com\xncoding\pos\config\RabbitConfig.java
2
请完成以下Java代码
public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public boolean isAllowCoreThreadTimeout() { return allowCoreThreadTimeout; } public void setAllowCoreThreadTimeout(boolean allowCoreThreadTimeout) { this.allowCoreThreadTimeout = allowCoreThreadTimeout; } public Duration getAwaitTerminationPeriod() { return awaitTerminationPeriod; } public void setAwaitTerminationPeriod(Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; }
public String getThreadPoolNamingPattern() { return threadPoolNamingPattern; } public void setThreadPoolNamingPattern(String threadPoolNamingPattern) { this.threadPoolNamingPattern = threadPoolNamingPattern; } public void setThreadNamePrefix(String prefix) { if (prefix == null) { this.threadPoolNamingPattern = "%d"; } else { this.threadPoolNamingPattern = prefix + "%d"; } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\async\AsyncTaskExecutorConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public class MysqlDatasourceConfig { // mysqldao扫描路径 static final String PACKAGE = "com.springboot.mysqldao"; // mybatis mapper扫描路径 static final String MAPPER_LOCATION = "classpath:mapper/mysql/*.xml"; @Primary @Bean(name = "mysqldatasource") @ConfigurationProperties("spring.datasource.druid.mysql") public DataSource mysqlDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "mysqlTransactionManager") @Primary
public DataSourceTransactionManager mysqlTransactionManager() { return new DataSourceTransactionManager(mysqlDataSource()); } @Bean(name = "mysqlSqlSessionFactory") @Primary public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqldatasource") DataSource dataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); //如果不使用xml的方式配置mapper,则可以省去下面这行mapper location的配置。 sessionFactory.setMapperLocations( new PathMatchingResourcePatternResolver().getResources(MysqlDatasourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); } }
repos\SpringAll-master\05.Spring-Boot-MyBatis-MultiDataSource\src\main\java\com\springboot\datasource\MysqlDatasourceConfig.java
2
请完成以下Java代码
public final I_M_Product getM_Product() { final ProductId productId = ProductId.ofRepoId(ppOrderBOMLine.getM_Product_ID()); return productBL.getById(productId); } @Override public BigDecimal getQty() { Quantity qtyDelivered = orderBOMBL.getQuantities(ppOrderBOMLine) .getQtyIssuedOrReceivedActual(); if (isCoOrByProduct) { qtyDelivered = qtyDelivered.negate(); } return qtyDelivered.toBigDecimal(); } @Override public final I_C_UOM getC_UOM() { return orderBOMBL.getBOMLineUOM(ppOrderBOMLine); } @Override public ProductionMaterialType getType() { return type; } @Override public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw) { ppOrderBOMLine.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw); } @Override public BigDecimal getQM_QtyDeliveredPercOfRaw() { return ppOrderBOMLine.getQM_QtyDeliveredPercOfRaw(); } @Override public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg) { ppOrderBOMLine.setQM_QtyDeliveredAvg(qtyDeliveredAvg); } @Override public BigDecimal getQM_QtyDeliveredAvg() { return ppOrderBOMLine.getQM_QtyDeliveredAvg(); } @Override public Object getModel() { return ppOrderBOMLine; } @Override public String getVariantGroup() { return ppOrderBOMLine.getVariantGroup(); }
@Override public BOMComponentType getComponentType() { return BOMComponentType.ofCode(ppOrderBOMLine.getComponentType()); } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { if (!_handlingUnitsInfoLoaded) { _handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrderBOMLine); _handlingUnitsInfoLoaded = true; } return _handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { return mainComponentProduct; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderBOMLineProductionMaterial.java
1
请在Spring Boot框架中完成以下Java代码
public class MybatisEntityLinkDataManager extends AbstractDataManager<EntityLinkEntity> implements EntityLinkDataManager { protected CachedEntityMatcher<EntityLinkEntity> entityLinksByScopeIdAndTypeMatcher = new EntityLinksByScopeIdAndTypeMatcher(); protected CachedEntityMatcher<EntityLinkEntity> entityLinksByRootScopeIdAndScopeTypeMatcher = new EntityLinksByRootScopeIdAndTypeMatcher(); protected EntityLinkServiceConfiguration entityLinkServiceConfiguration; public MybatisEntityLinkDataManager(EntityLinkServiceConfiguration entityLinkServiceConfiguration) { this.entityLinkServiceConfiguration = entityLinkServiceConfiguration; } @Override public Class<? extends EntityLinkEntity> getManagedEntityClass() { return EntityLinkEntityImpl.class; } @Override public EntityLinkEntity create() { return new EntityLinkEntityImpl(); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public List<EntityLink> findEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) { Map<String, String> parameters = new HashMap<>(); parameters.put("scopeId", scopeId); parameters.put("scopeType", scopeType); parameters.put("linkType", linkType); return (List) getList("selectEntityLinksWithSameRootScopeByScopeIdAndType", parameters); } @Override @SuppressWarnings("unchecked") public List<EntityLinkEntity> findEntityLinksByQuery(InternalEntityLinkQuery<EntityLinkEntity> query) {
return getList("selectEntityLinksByQuery", query, (CachedEntityMatcher<EntityLinkEntity>) query, true); } @Override @SuppressWarnings("unchecked") public EntityLinkEntity findEntityLinkByQuery(InternalEntityLinkQuery<EntityLinkEntity> query) { return getEntity("selectEntityLinksByQuery", query, (SingleCachedEntityMatcher<EntityLinkEntity>) query, true); } @Override public void deleteEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { Map<String, String> parameters = new HashMap<>(); parameters.put("scopeId", scopeId); parameters.put("scopeType", scopeType); bulkDelete("deleteEntityLinksByScopeIdAndScopeType", entityLinksByScopeIdAndTypeMatcher, parameters); } @Override public void deleteEntityLinksByRootScopeIdAndType(String scopeId, String scopeType) { Map<String, String> parameters = new HashMap<>(); parameters.put("rootScopeId", scopeId); parameters.put("rootScopeType", scopeType); bulkDelete("deleteEntityLinksByRootScopeIdAndRootScopeType", entityLinksByRootScopeIdAndScopeTypeMatcher, parameters); } @Override protected IdGenerator getIdGenerator() { return entityLinkServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\data\impl\MybatisEntityLinkDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public String getEndUserId() { return endUserId; } public void setEndUserId(String endUserId) { this.endUserId = endUserId; } @ApiModelProperty(example = "3") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "null") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @ApiModelProperty(example = "active") public String getState() { return state; } public void setState(String state) { this.state = state; } @ApiModelProperty(example = "123") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) {
this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请完成以下Java代码
public XMLGregorianCalendar getDt() { return dt; } /** * Sets the value of the dt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDt(XMLGregorianCalendar value) { this.dt = value; } /** * Gets the value of the dtTm property. * * @return * possible object is
* {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDtTm() { return dtTm; } /** * Sets the value of the dtTm property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDtTm(XMLGregorianCalendar value) { this.dtTm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DateAndDateTimeChoice.java
1
请完成以下Java代码
public Flux<InstanceEvent> events() { return eventStore.findAll(); } /** * Stream all instance events as Server-Sent Events (SSE). Returns a continuous stream * of instance events for real-time monitoring and UI updates. * @return flux of {@link ServerSentEvent} containing {@link InstanceEvent} */ @GetMapping(path = "/instances/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<InstanceEvent>> eventStream() { return Flux.from(eventStore).map((event) -> ServerSentEvent.builder(event).build()).mergeWith(ping()); } /** * Stream events for a specific instance as Server-Sent Events (SSE). Streams events * for the instance identified by its ID. Each event is delivered as an SSE message. * @param id the instance ID * @return flux of {@link ServerSentEvent} containing {@link Instance} */ @GetMapping(path = "/instances/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<Instance>> instanceStream(@PathVariable String id) { return Flux.from(eventStore) .filter((event) -> event.getInstance().equals(InstanceId.of(id))) .flatMap((event) -> registry.getInstance(event.getInstance())) .map((event) -> ServerSentEvent.builder(event).build()) .mergeWith(ping()); } /** * Returns a periodic Server-Sent Event (SSE) comment-only ping every 10 seconds. * <p> * This method is used to keep SSE connections alive for all event stream endpoints in * Spring Boot Admin. The ping event is sent as a comment (": ping") and does not * contain any data payload. <br> * <b>Why?</b> Many proxies, firewalls, and browsers may close idle HTTP connections. * The ping event provides regular activity on the stream, ensuring the connection * remains open even when no instance events are emitted. <br>
* <b>Technical details:</b> * <ul> * <li>Interval: 10 seconds</li> * <li>Format: SSE comment-only event</li> * <li>Applies to: All event stream endpoints (e.g., /instances/events, * /instances/{id} with Accept: text/event-stream)</li> * </ul> * </p> * @param <T> the type of event data (unused for ping) * @return flux of ServerSentEvent representing periodic ping comments */ @SuppressWarnings("unchecked") private static <T> Flux<ServerSentEvent<T>> ping() { return (Flux<ServerSentEvent<T>>) (Flux) PING_FLUX; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\InstancesController.java
1
请完成以下Java代码
public TbMsgBuilder copyMetaData(TbMsgMetaData metaData) { this.metaData = metaData.copy(); return this; } public TbMsgBuilder dataType(TbMsgDataType dataType) { this.dataType = dataType; return this; } public TbMsgBuilder data(String data) { this.data = data; return this; } public TbMsgBuilder ruleChainId(RuleChainId ruleChainId) { this.ruleChainId = ruleChainId; return this; } public TbMsgBuilder ruleNodeId(RuleNodeId ruleNodeId) { this.ruleNodeId = ruleNodeId; return this; } public TbMsgBuilder resetRuleNodeId() { return ruleNodeId(null); } public TbMsgBuilder correlationId(UUID correlationId) { this.correlationId = correlationId; return this; } public TbMsgBuilder partition(Integer partition) { this.partition = partition; return this; } public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds); return this; } public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) { this.ctx = ctx; return this;
} public TbMsgBuilder callback(TbMsgCallback callback) { this.callback = callback; return this; } public TbMsg build() { return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback); } public String toString() { return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts + ", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator + ", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType + ", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId + ", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds + ", ctx=" + this.ctx + ", callback=" + this.callback + ")"; } } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java
1
请完成以下Java代码
public class ValuePreferenceContextEditorAction extends AbstractContextMenuAction { @Override public String getName() { return ValuePreference.NAME; } @Override public String getIcon() { return "VPreference16"; } @Override public boolean isAvailable() { return true; } @Override public boolean isRunnable() { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); if (gridField == null) { return false; } if (!Env.getUserRolePermissions().isShowPreference()) {
return false; } return true; } @Override public void run() { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); if (gridField == null) { return ; } ValuePreference.start (gridField, editor.getValue(), editor.getDisplay()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\ValuePreferenceContextEditorAction.java
1
请完成以下Java代码
public synchronized Enumeration<Object> elements() { // TODO: implement for GridField values too return ctx.elements(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { // TODO: implement for GridField values too return ctx.entrySet(); } @Override public synchronized boolean isEmpty() { return false; } @Override public synchronized Enumeration<Object> keys() { // TODO: implement for GridField values too return ctx.keys(); } @Override public Set<Object> keySet() { // TODO: implement for GridField values too return ctx.keySet(); } @Override public synchronized Object put(Object key, Object value) { if (gridTab == null) throw new IllegalStateException("Method not supported (gridTab is null)"); if (gridTab.getCurrentRow() != row) { return ctx.put(key, value); } String columnName = getColumnName(key); if (columnName == null) { return ctx.put(key, value); } GridField field = gridTab.getField(columnName); if (field == null) { return ctx.put(key, value); } Object valueOld = field.getValue(); field.setValue(value, false); // inserting=false return valueOld; }
@Override public synchronized void putAll(Map<? extends Object, ? extends Object> t) { for (Map.Entry<? extends Object, ? extends Object> e : t.entrySet()) put(e.getKey(), e.getValue()); } @Override public synchronized Object remove(Object key) { // TODO: implement for GridField values too return ctx.remove(key); } @Override public synchronized int size() { // TODO: implement for GridField values too return ctx.size(); } @Override public synchronized String toString() { // TODO: implement for GridField values too return ctx.toString(); } @Override public Collection<Object> values() { return ctx.values(); } @Override public String getProperty(String key) { // I need to override this method, because Properties.getProperty method // is calling super.get() instead of get() Object oval = get(key); return oval == null ? null : oval.toString(); } @Override public String get_ValueAsString(String variableName) { final int windowNo = getWindowNo(); final int tabNo = getTabNo(); // Check value at Tab level, fallback to Window level final String value = Env.getContext(this, windowNo, tabNo, variableName, Scope.Window); return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\GridRowCtx.java
1
请在Spring Boot框架中完成以下Java代码
public List<I_AD_InfoColumn> retrieveDisplayedColumns(final I_AD_InfoWindow infoWindow) { final List<I_AD_InfoColumn> list = new ArrayList<I_AD_InfoColumn>(); for (final I_AD_InfoColumn infoColumn : retrieveInfoColumns(infoWindow)) { if (!infoColumn.isActive()) { continue; } if (!infoColumn.isDisplayed()) { continue; } list.add(infoColumn); } Collections.sort(list, new Comparator<I_AD_InfoColumn>() { @Override public int compare(final I_AD_InfoColumn o1, final I_AD_InfoColumn o2) { return o1.getSeqNo() - o2.getSeqNo(); } }); return list; } @Override @Cached(cacheName = I_AD_InfoWindow.Table_Name + "#by#" + I_AD_InfoWindow.COLUMNNAME_ShowInMenu) public List<I_AD_InfoWindow> retrieveInfoWindowsInMenu(@CacheCtx final Properties ctx)
{ return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_InfoWindow.class, ctx, ITrx.TRXNAME_None) .addCompareFilter(I_AD_InfoWindow.COLUMNNAME_AD_InfoWindow_ID, CompareQueryFilter.Operator.NOT_EQUAL, 540008) // FIXME: hardcoded "Info Partner" .addCompareFilter(I_AD_InfoWindow.COLUMNNAME_AD_InfoWindow_ID, CompareQueryFilter.Operator.NOT_EQUAL, 540009) // FIXME: hardcoded "Info Product" .addEqualsFilter(I_AD_InfoWindow.COLUMNNAME_IsActive, true) .addEqualsFilter(I_AD_InfoWindow.COLUMNNAME_ShowInMenu, true) .addOnlyContextClientOrSystem() // .orderBy() .addColumn(I_AD_InfoWindow.COLUMNNAME_AD_InfoWindow_ID) .endOrderBy() // .create() .list(I_AD_InfoWindow.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\ADInfoWindowDAO.java
2
请完成以下Java代码
public void calloutOnTableIdChanged(final I_AD_Tab tab) { if (tab.getAD_Table_ID() > 0) { final IADTableDAO adTablesRepo = Services.get(IADTableDAO.class); final IADElementDAO adElementsRepo = Services.get(IADElementDAO.class); final String tableName = adTablesRepo.retrieveTableName(tab.getAD_Table_ID()); tab.setInternalName(tableName); final AdElementId adElementId = adElementsRepo.getADElementIdByColumnNameOrNull(tableName + "_ID"); if (adElementId != null) { tab.setAD_Element_ID(adElementId.getRepoId()); updateTabFromElement(tab); } } } @CalloutMethod(columnNames = I_AD_Tab.COLUMNNAME_AD_Element_ID) public void calloutOnElementIdChanged(final I_AD_Tab tab) { updateTabFromElement(tab); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_AD_Tab.COLUMNNAME_AD_Element_ID) public void onBeforeTabSave_WhenElementIdChanged(final I_AD_Tab tab) { updateTabFromElement(tab); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_AD_Tab.COLUMNNAME_AD_Element_ID) public void onAfterTabSave_WhenElementIdChanged(final I_AD_Tab tab) { updateTranslationsForElement(tab); recreateElementLinkForTab(tab); } private void updateTabFromElement(final I_AD_Tab tab) { final IADElementDAO adElementDAO = Services.get(IADElementDAO.class); final I_AD_Element tabElement = adElementDAO.getById(tab.getAD_Element_ID()); if (tabElement == null) { // nothing to do. It was not yet set return; }
tab.setName(tabElement.getName()); tab.setDescription(tabElement.getDescription()); tab.setHelp(tabElement.getHelp()); tab.setCommitWarning(tabElement.getCommitWarning()); tab.setEntityType(tab.getAD_Window().getEntityType()); } private void recreateElementLinkForTab(final I_AD_Tab tab) { final AdTabId adTabId = AdTabId.ofRepoIdOrNull(tab.getAD_Tab_ID()); if (adTabId != null) { final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.createADElementLinkForTabId(adTabId); } } private void updateTranslationsForElement(final I_AD_Tab tab) { if (!IElementTranslationBL.DYNATTR_AD_Tab_UpdateTranslations.getValue(tab, true)) { // do not copy translations from element to tab return; } final AdElementId tabElementId = AdElementId.ofRepoIdOrNull(tab.getAD_Element_ID()); if (tabElementId == null) { // nothing to do. It was not yet set return; } Services.get(IElementTranslationBL.class).updateTabTranslationsFromElement(tabElementId); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void onBeforeTabDelete(final I_AD_Tab tab) { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final AdTabId adTabId = AdTabId.ofRepoId(tab.getAD_Tab_ID()); adWindowDAO.deleteFieldsByTabId(adTabId); adWindowDAO.deleteUISectionsByTabId(adTabId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\tab\model\interceptor\AD_Tab.java
1
请在Spring Boot框架中完成以下Java代码
void init(HttpSecurity httpSecurity) { AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils .getAuthorizationServerSettings(httpSecurity); String oidcProviderConfigurationEndpointUri = authorizationServerSettings.isMultipleIssuersAllowed() ? "/**/.well-known/openid-configuration" : "/.well-known/openid-configuration"; this.requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, oidcProviderConfigurationEndpointUri); } @Override void configure(HttpSecurity httpSecurity) { OidcProviderConfigurationEndpointFilter oidcProviderConfigurationEndpointFilter = new OidcProviderConfigurationEndpointFilter(); Consumer<OidcProviderConfiguration.Builder> providerConfigurationCustomizer = getProviderConfigurationCustomizer(); if (providerConfigurationCustomizer != null) { oidcProviderConfigurationEndpointFilter.setProviderConfigurationCustomizer(providerConfigurationCustomizer); } httpSecurity.addFilterBefore(postProcess(oidcProviderConfigurationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class); } private Consumer<OidcProviderConfiguration.Builder> getProviderConfigurationCustomizer() { Consumer<OidcProviderConfiguration.Builder> providerConfigurationCustomizer = null;
if (this.defaultProviderConfigurationCustomizer != null || this.providerConfigurationCustomizer != null) { if (this.defaultProviderConfigurationCustomizer != null) { providerConfigurationCustomizer = this.defaultProviderConfigurationCustomizer; } if (this.providerConfigurationCustomizer != null) { providerConfigurationCustomizer = (providerConfigurationCustomizer != null) ? providerConfigurationCustomizer.andThen(this.providerConfigurationCustomizer) : this.providerConfigurationCustomizer; } } return providerConfigurationCustomizer; } @Override RequestMatcher getRequestMatcher() { return this.requestMatcher; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OidcProviderConfigurationEndpointConfigurer.java
2
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Password Info. @param PasswordInfo Password Info */ public void setPasswordInfo (String PasswordInfo) { set_Value (COLUMNNAME_PasswordInfo, PasswordInfo); } /** Get Password Info. @return Password Info */ public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port);
if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor.java
1
请在Spring Boot框架中完成以下Java代码
public AuthorizationManagerRequestMatcherRegistry access( AuthorizationManager<? super RequestAuthorizationContext> manager) { Assert.notNull(manager, "manager cannot be null"); return (this.not) ? AuthorizeHttpRequestsConfigurer.this.addMapping(this.matchers, AuthorizationManagers.not(manager)) : AuthorizeHttpRequestsConfigurer.this.addMapping(this.matchers, manager); } /** * An object that allows configuring {@link RequestMatcher}s with URI path * variables * * @author Taehong Kim * @since 6.3 */ public final class AuthorizedUrlVariable { private final String variable; private AuthorizedUrlVariable(String variable) { this.variable = variable; } /** * Compares the value of a path variable in the URI with an `Authentication` * attribute * <p> * For example, <pre>
* requestMatchers("/user/{username}").hasVariable("username").equalTo(Authentication::getName)); * </pre> * @param function a function to get value from {@link Authentication}. * @return the {@link AuthorizationManagerRequestMatcherRegistry} for further * customization. */ public AuthorizationManagerRequestMatcherRegistry equalTo(Function<Authentication, String> function) { return access((auth, requestContext) -> { String value = requestContext.getVariables().get(this.variable); return new AuthorizationDecision(function.apply(auth.get()).equals(value)); }); } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AuthorizeHttpRequestsConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public static Options of(Option... options) { Assert.notNull(options, "'options' must not be null"); if (options.length == 0) { return NONE; } return new Options(EnumSet.copyOf(Arrays.asList(options))); } } /** * Option flags that can be applied. */ public enum Option { /** * Ignore all imports properties from the source. */
IGNORE_IMPORTS, /** * Ignore all profile activation and include properties. * @since 2.4.3 */ IGNORE_PROFILES, /** * Indicates that the source is "profile specific" and should be included after * profile specific sibling imports. * @since 2.4.5 */ PROFILE_SPECIFIC } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigData.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Date getCreateTime() { return createTime;
} public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", icon=").append(icon); sb.append(", email=").append(email); sb.append(", nickName=").append(nickName); sb.append(", note=").append(note); sb.append(", createTime=").append(createTime); sb.append(", loginTime=").append(loginTime); sb.append(", status=").append(status); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java
1
请完成以下Java代码
public void setDocumentName (final @Nullable java.lang.String DocumentName) { set_ValueNoCheck (COLUMNNAME_DocumentName, DocumentName); } @Override public java.lang.String getDocumentName() { return get_ValueAsString(COLUMNNAME_DocumentName); } @Override public void setDocumentNo (final @Nullable java.lang.String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setPIName (final @Nullable java.lang.String PIName)
{ set_ValueNoCheck (COLUMNNAME_PIName, PIName); } @Override public java.lang.String getPIName() { return get_ValueAsString(COLUMNNAME_PIName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_ValueNoCheck (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Instance_Properties_v.java
1
请在Spring Boot框架中完成以下Java代码
public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(mailServerHost); mailSender.setPort(mailServerPort); mailSender.setUsername(mailServerUsername); mailSender.setPassword(mailServerPassword); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", mailServerAuth); props.put("mail.smtp.starttls.enable", mailServerStartTls); props.put("mail.debug", "true"); return mailSender;
} @Bean public SimpleMailMessage templateSimpleMessage() { SimpleMailMessage message = new SimpleMailMessage(); message.setText("This is the test email template for your email:\n%s\n"); return message; } @Bean public ResourceBundleMessageSource emailMessageSource() { final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("mailMessages"); return messageSource; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\mail\EmailConfiguration.java
2
请完成以下Java代码
public void onComplete(final I_C_Order order) { if (!callOrderService.isCallOrder(order)) { return; } final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order, I_C_OrderLine.class); for (final I_C_OrderLine callOrderLine : orderLines) { final FlatrateTermId callOrderContractId = callOrderContractService.validateCallOrderLine(callOrderLine, order); final UpsertCallOrderDetailRequest request = UpsertCallOrderDetailRequest.builder() .callOrderContractId(callOrderContractId) .orderLine(callOrderLine) .build(); callOrderService.handleCallOrderDetailUpsert(request); } }
@Override public void onReverse(final I_C_Order model) { throw new AdempiereException("Orders cannot be reversed!"); } @Override public void onReactivate(final I_C_Order order) { if (!callOrderService.isCallOrder(order)) { return; } final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID()); detailRepo.resetEnteredQtyForOrder(orderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\document\DocumentChangeHandler_Order.java
1
请完成以下Java代码
public Dimension getFromRecord(@NonNull final I_MD_Candidate record) { return Dimension.builder() .projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID())) .campaignId(record.getC_Campaign_ID()) .activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID())) .salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID())) .userElementString1(record.getUserElementString1()) .userElementString2(record.getUserElementString2()) .userElementString3(record.getUserElementString3()) .userElementString4(record.getUserElementString4()) .userElementString5(record.getUserElementString5()) .userElementString6(record.getUserElementString6()) .userElementString7(record.getUserElementString7()) .build(); }
@Override public void updateRecord(final I_MD_Candidate record, final Dimension from) { record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId())); record.setC_Campaign_ID(from.getCampaignId()); record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId())); record.setC_OrderSO_ID(OrderId.toRepoId(from.getSalesOrderId())); record.setUserElementString1(from.getUserElementString1()); record.setUserElementString2(from.getUserElementString2()); record.setUserElementString3(from.getUserElementString3()); record.setUserElementString4(from.getUserElementString4()); record.setUserElementString5(from.getUserElementString5()); record.setUserElementString6(from.getUserElementString6()); record.setUserElementString7(from.getUserElementString7()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\document\dimension\MDCandidateDimensionFactory.java
1
请完成以下Java代码
private boolean hasChangedSessionId() { return !getId().equals(this.originalSessionId); } private void save() { saveChangeSessionId(); saveDelta(); if (this.isNew) { this.isNew = false; } } private void saveChangeSessionId() { if (hasChangedSessionId()) { if (!this.isNew) { String originalSessionIdKey = getSessionKey(this.originalSessionId); String sessionIdKey = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, sessionIdKey); } this.originalSessionId = getId(); } }
private void saveDelta() { if (this.delta.isEmpty()) { return; } String key = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta)); RedisSessionRepository.this.sessionRedisOperations.expireAt(key, Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli()) .plusSeconds(getMaxInactiveInterval().getSeconds())); this.delta.clear(); } } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionRepository.java
1
请完成以下Java代码
public void setHost (final @Nullable java.lang.String Host) { set_ValueNoCheck (COLUMNNAME_Host, Host); } @Override public java.lang.String getHost() { return get_ValueAsString(COLUMNNAME_Host); } @Override public void setRabbitMQ_Message_Audit_ID (final int RabbitMQ_Message_Audit_ID) { if (RabbitMQ_Message_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, RabbitMQ_Message_Audit_ID); } @Override public int getRabbitMQ_Message_Audit_ID() { return get_ValueAsInt(COLUMNNAME_RabbitMQ_Message_Audit_ID); } @Override public void setRabbitMQ_QueueName (final @Nullable java.lang.String RabbitMQ_QueueName) { set_ValueNoCheck (COLUMNNAME_RabbitMQ_QueueName, RabbitMQ_QueueName); }
@Override public java.lang.String getRabbitMQ_QueueName() { return get_ValueAsString(COLUMNNAME_RabbitMQ_QueueName); } @Override public void setRelated_Event_UUID (final @Nullable java.lang.String Related_Event_UUID) { set_ValueNoCheck (COLUMNNAME_Related_Event_UUID, Related_Event_UUID); } @Override public java.lang.String getRelated_Event_UUID() { return get_ValueAsString(COLUMNNAME_Related_Event_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RabbitMQ_Message_Audit.java
1
请在Spring Boot框架中完成以下Java代码
public class GraphqlConfiguration { @Bean public PostDao postDao() { List<Post> posts = new ArrayList<>(); for (int postId = 0; postId < 10; ++postId) { for (int authorId = 0; authorId < 10; ++authorId) { Post post = new Post(); post.setId("Post" + authorId + postId); post.setTitle("Post " + authorId + ":" + postId); post.setCategory("Post category"); post.setText("Post " + postId + " + by author " + authorId); post.setAuthorId("Author" + authorId); posts.add(post); } } return new PostDao(posts);
} @Bean public AuthorDao authorDao() { List<Author> authors = new ArrayList<>(); for (int authorId = 0; authorId < 10; ++authorId) { Author author = new Author(); author.setId("Author" + authorId); author.setName("Author " + authorId); author.setThumbnail("http://example.com/authors/" + authorId); authors.add(author); } return new AuthorDao(authors); } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql\src\main\java\com\baeldung\graphql\intro\GraphqlConfiguration.java
2
请完成以下Java代码
public class DLM_Partition_Config_Reference { static final DLM_Partition_Config_Reference INSTANCE = new DLM_Partition_Config_Reference(); private DLM_Partition_Config_Reference() { } @CalloutMethod(columnNames = I_DLM_Partition_Config_Reference.COLUMNNAME_DLM_Referencing_Column_ID, skipIfCopying = true) public void updateTable(final I_DLM_Partition_Config_Reference ref) { if (ref.getDLM_Referencing_Column_ID() <= 0) { ref.setDLM_Referenced_Table_ID(0); return; } final I_AD_Column adColumn = ref.getDLM_Referencing_Column(); final int displayType = adColumn.getAD_Reference_ID(); if (!DisplayType.isLookup(displayType)) { return; } final ADReferenceService adReferenceService = ADReferenceService.get(); final ADRefTable tableRefInfo; final ReferenceId adReferenceValueId = ReferenceId.ofRepoIdOrNull(adColumn.getAD_Reference_Value_ID()); if (adReferenceService.isTableReference(adReferenceValueId)) { tableRefInfo = adReferenceService.retrieveTableRefInfo(adReferenceValueId); }
else { final String columnName = adColumn.getColumnName(); tableRefInfo = adReferenceService.getTableDirectRefInfo(columnName); } if (tableRefInfo == null) { // what we do further up is not very sophisticated. e.g. for "CreatedBy", we currently don't find the table name. // therefore, don't set the table to null since we don't know that there is no table for the given column // ref.setDLM_Referenced_Table_ID(0); return; } final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); ref.setDLM_Referenced_Table_ID(adTableDAO.retrieveTableId(tableRefInfo.getTableName())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\DLM_Partition_Config_Reference.java
1
请在Spring Boot框架中完成以下Java代码
private CandidatesQuery createCandidatesQuery(@NonNull final AbstractStockEstimateEvent event) { final StockChangeDetailQuery stockChangeDetailQuery = StockChangeDetailQuery.builder() .freshQuantityOnHandLineRepoId(event.getFreshQtyOnHandLineId()) .build(); return CandidatesQuery.builder() .businessCase(CandidateBusinessCase.STOCK_CHANGE) .materialDescriptorQuery(MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor())) .stockChangeDetailQuery(stockChangeDetailQuery) .build(); } @NonNull private CandidatesQuery createPreviousStockCandidatesQuery(@NonNull final AbstractStockEstimateEvent event) { final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor())
.toBuilder() .timeRangeEnd(DateAndSeqNo.builder() .date(event.getDate()) .operator(DateAndSeqNo.Operator.EXCLUSIVE) .build()) .build(); return CandidatesQuery.builder() .materialDescriptorQuery(materialDescriptorQuery) .type(CandidateType.STOCK) .matchExactStorageAttributesKey(true) .parentId(CandidateId.UNSPECIFIED) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\stockchange\StockEstimateEventService.java
2
请在Spring Boot框架中完成以下Java代码
JwtAuthenticationConverter getJwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); PropertyMapper map = PropertyMapper.get(); map.from(this.properties.getAuthorityPrefix()).to(grantedAuthoritiesConverter::setAuthorityPrefix); map.from(this.properties.getAuthoritiesClaimDelimiter()) .to(grantedAuthoritiesConverter::setAuthoritiesClaimDelimiter); map.from(this.properties.getAuthoritiesClaimName()) .to(grantedAuthoritiesConverter::setAuthoritiesClaimName); JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); map.from(this.properties.getPrincipalClaimName()).to(jwtAuthenticationConverter::setPrincipalClaimName); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); return jwtAuthenticationConverter; } } private static class JwtConverterPropertiesCondition extends AnyNestedCondition { JwtConverterPropertiesCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authority-prefix")
static class OnAuthorityPrefix { } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.principal-claim-name") static class OnPrincipalClaimName { } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-name") static class OnAuthoritiesClaimName { } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\servlet\OAuth2ResourceServerJwtConfiguration.java
2
请完成以下Java代码
public java.lang.String getAD_WF_Responsible_Name () { return (java.lang.String)get_Value(COLUMNNAME_AD_WF_Responsible_Name); } /** Set Document Responsible. @param C_Doc_Responsible_ID Document Responsible */ @Override public void setC_Doc_Responsible_ID (int C_Doc_Responsible_ID) { if (C_Doc_Responsible_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, Integer.valueOf(C_Doc_Responsible_ID)); } /** Get Document Responsible. @return Document Responsible */ @Override public int getC_Doc_Responsible_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Doc_Responsible_ID); if (ii == null) return 0; return ii.intValue(); } /** 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.swat\de.metas.swat.base\src\main\java-gen\de\metas\workflow\model\X_C_Doc_Responsible.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<SysDictVo>> getDictListByLowAppId(HttpServletRequest request){ String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request)); List<SysDictVo> list = sysDictService.getDictListByLowAppId(lowAppId); return Result.ok(list); } /** * 添加字典 * @param sysDictVo * @param request * @return */ @PostMapping("/addDictByLowAppId") public Result<String> addDictByLowAppId(@RequestBody SysDictVo sysDictVo,HttpServletRequest request){ String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request));
String tenantId = oConvertUtils.getString(TokenUtils.getTenantIdByRequest(request)); sysDictVo.setLowAppId(lowAppId); sysDictVo.setTenantId(oConvertUtils.getInteger(tenantId, null)); sysDictService.addDictByLowAppId(sysDictVo); return Result.ok("添加成功"); } @PutMapping("/editDictByLowAppId") public Result<String> editDictByLowAppId(@RequestBody SysDictVo sysDictVo,HttpServletRequest request){ String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request)); sysDictVo.setLowAppId(lowAppId); sysDictService.editDictByLowAppId(sysDictVo); return Result.ok("编辑成功"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDictController.java
2
请完成以下Java代码
public class JExcelHelper { public Map<Integer, List<String>> readJExcel(String fileLocation) throws IOException, BiffException { Map<Integer, List<String>> data = new HashMap<>(); Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); Sheet sheet = workbook.getSheet(0); int rows = sheet.getRows(); int columns = sheet.getColumns(); for (int i = 0; i < rows; i++) { data.put(i, new ArrayList<String>()); for (int j = 0; j < columns; j++) { data.get(i).add(sheet.getCell(j, i).getContents()); } } return data; } public void writeJExcel() throws IOException, WriteException { WritableWorkbook workbook = null; try { File currDir = new File("."); String path = currDir.getAbsolutePath(); String fileLocation = path.substring(0, path.length() - 1) + "temp.xls"; workbook = Workbook.createWorkbook(new File(fileLocation)); WritableSheet sheet = workbook.createSheet("Sheet 1", 0); WritableCellFormat headerFormat = new WritableCellFormat();
WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD); headerFormat.setFont(font); headerFormat.setBackground(Colour.LIGHT_BLUE); headerFormat.setWrap(true); Label headerLabel = new Label(0, 0, "Name", headerFormat); sheet.setColumnView(0, 60); sheet.addCell(headerLabel); headerLabel = new Label(1, 0, "Age", headerFormat); sheet.setColumnView(0, 40); sheet.addCell(headerLabel); WritableCellFormat cellFormat = new WritableCellFormat(); cellFormat.setWrap(true); Label cellLabel = new Label(0, 2, "John Smith", cellFormat); sheet.addCell(cellLabel); Number cellNumber = new Number(1, 2, 20, cellFormat); sheet.addCell(cellNumber); workbook.write(); } finally { if (workbook != null) { workbook.close(); } } } }
repos\tutorials-master\apache-poi\src\main\java\com\baeldung\jexcel\JExcelHelper.java
1
请完成以下Java代码
public String getId() { return id; } public AppClusterServerStateWrapVO setId(String id) { this.id = id; return this; } public String getIp() { return ip; } public AppClusterServerStateWrapVO setIp(String ip) { this.ip = ip; return this; } public Integer getPort() { return port; } public AppClusterServerStateWrapVO setPort(Integer port) { this.port = port; return this; } public Boolean getBelongToApp() { return belongToApp; } public AppClusterServerStateWrapVO setBelongToApp(Boolean belongToApp) { this.belongToApp = belongToApp; return this; } public Integer getConnectedCount() { return connectedCount; }
public AppClusterServerStateWrapVO setConnectedCount(Integer connectedCount) { this.connectedCount = connectedCount; return this; } public ClusterServerStateVO getState() { return state; } public AppClusterServerStateWrapVO setState(ClusterServerStateVO state) { this.state = state; return this; } @Override public String toString() { return "AppClusterServerStateWrapVO{" + "id='" + id + '\'' + ", ip='" + ip + '\'' + ", port='" + port + '\'' + ", belongToApp=" + belongToApp + ", state=" + state + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\AppClusterServerStateWrapVO.java
1
请完成以下Java代码
public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public int getXmlLineNumber() { return xmlLineNumber; } public void setXmlLineNumber(int xmlLineNumber) { this.xmlLineNumber = xmlLineNumber; } public int getXmlColumnNumber() { return xmlColumnNumber; } public void setXmlColumnNumber(int xmlColumnNumber) { this.xmlColumnNumber = xmlColumnNumber; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } public boolean isWarning() { return isWarning; } public void setWarning(boolean isWarning) { this.isWarning = isWarning; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("[Validation set: '").append(validatorSetName).append("' | Problem: '").append(problem).append("'] : "); strb.append(defaultDescription); strb.append(" - [Extra info : "); boolean extraInfoAlreadyPresent = false; if (processDefinitionId != null) { strb.append("processDefinitionId = ").append(processDefinitionId); extraInfoAlreadyPresent = true; } if (processDefinitionName != null) { if (extraInfoAlreadyPresent) {
strb.append(" | "); } strb.append("processDefinitionName = ").append(processDefinitionName).append(" | "); extraInfoAlreadyPresent = true; } if (activityId != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("id = ").append(activityId).append(" | "); extraInfoAlreadyPresent = true; } if (activityName != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("activityName = ").append(activityName).append(" | "); extraInfoAlreadyPresent = true; } strb.append("]"); if (xmlLineNumber > 0 && xmlColumnNumber > 0) { strb.append(" ( line: ").append(xmlLineNumber).append(", column: ").append(xmlColumnNumber).append(")"); } return strb.toString(); } }
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\ValidationError.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult add(@PathVariable Long couponId) { memberCouponService.add(couponId); return CommonResult.success(null,"领取成功"); } @ApiOperation("获取会员优惠券历史列表") @ApiImplicitParam(name = "useStatus", value = "优惠券筛选类型:0->未使用;1->已使用;2->已过期", allowableValues = "0,1,2", paramType = "query", dataType = "integer") @RequestMapping(value = "/listHistory", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsCouponHistory>> listHistory(@RequestParam(value = "useStatus", required = false) Integer useStatus) { List<SmsCouponHistory> couponHistoryList = memberCouponService.listHistory(useStatus); return CommonResult.success(couponHistoryList); } @ApiOperation("获取会员优惠券列表") @ApiImplicitParam(name = "useStatus", value = "优惠券筛选类型:0->未使用;1->已使用;2->已过期", allowableValues = "0,1,2", paramType = "query", dataType = "integer") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsCoupon>> list(@RequestParam(value = "useStatus", required = false) Integer useStatus) { List<SmsCoupon> couponList = memberCouponService.list(useStatus); return CommonResult.success(couponList); } @ApiOperation("获取登录会员购物车的相关优惠券") @ApiImplicitParam(name = "type", value = "使用可用:0->不可用;1->可用", defaultValue = "1", allowableValues = "0,1", paramType = "path", dataType = "integer")
@RequestMapping(value = "/list/cart/{type}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsCouponHistoryDetail>> listCart(@PathVariable Integer type) { List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(memberService.getCurrentMember().getId(), null); List<SmsCouponHistoryDetail> couponHistoryList = memberCouponService.listCart(cartPromotionItemList, type); return CommonResult.success(couponHistoryList); } @ApiOperation("获取当前商品相关优惠券") @RequestMapping(value = "/listByProduct/{productId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsCoupon>> listByProduct(@PathVariable Long productId) { List<SmsCoupon> couponHistoryList = memberCouponService.listByProduct(productId); return CommonResult.success(couponHistoryList); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\UmsMemberCouponController.java
2
请完成以下Java代码
public boolean contains(final ITableRecordReference tableRecordReference) { final Set<ITableRecordReference> records = tableName2Record.get(mkKey(tableRecordReference)); if (records == null) { return false; } return records.contains(tableRecordReference); } private String mkKey(final ITableRecordReference tableRecordReference) { return tableRecordReference.getTableName(); } @Override public Map<Integer, Set<ITableRecordReference>> getDlmPartitionId2Record() { return ImmutableMap.copyOf(dlmPartitionId2Record); } @Override public Map<String, Collection<ITableRecordReference>> getTableName2Record() { final Map<String, Collection<ITableRecordReference>> result = new HashMap<>(); tableName2Record.entrySet().forEach(e -> { result.put(e.getKey(), e.getValue()); }); return result; } @Override public int size() { return size; } @Override public boolean isQueueEmpty() { final boolean iteratorEmpty = !iterator.hasNext(); return iteratorEmpty && queueItemsToProcess.isEmpty(); } @Override public ITableRecordReference nextFromQueue() { final WorkQueue result = nextFromQueue0(); if (result.getDLM_Partition_Workqueue_ID() > 0) { queueItemsToDelete.add(result); } return result.getTableRecordReference(); } private WorkQueue nextFromQueue0() { if (iterator.hasNext()) { // once we get the record from the queue, we also add it to our result
final WorkQueue next = iterator.next(); final ITableRecordReference tableRecordReference = next.getTableRecordReference(); final IDLMAware model = tableRecordReference.getModel(ctxAware, IDLMAware.class); add0(tableRecordReference, model.getDLM_Partition_ID(), true); return next; } return queueItemsToProcess.removeFirst(); } @Override public List<WorkQueue> getQueueRecordsToStore() { return queueItemsToProcess; } @Override public List<WorkQueue> getQueueRecordsToDelete() { return queueItemsToDelete; } /** * @return the {@link Partition} from the last invokation of {@link #clearAfterPartitionStored(Partition)}, or an empty partition. */ @Override public Partition getPartition() { return partition; } @Override public void registerHandler(IIterateResultHandler handler) { handlerSupport.registerListener(handler); } @Override public List<IIterateResultHandler> getRegisteredHandlers() { return handlerSupport.getRegisteredHandlers(); } @Override public boolean isHandlerSignaledToStop() { return handlerSupport.isHandlerSignaledToStop(); } @Override public String toString() { return "IterateResult [queueItemsToProcess.size()=" + queueItemsToProcess.size() + ", queueItemsToDelete.size()=" + queueItemsToDelete.size() + ", size=" + size + ", tableName2Record.size()=" + tableName2Record.size() + ", dlmPartitionId2Record.size()=" + dlmPartitionId2Record.size() + ", iterator=" + iterator + ", ctxAware=" + ctxAware + ", partition=" + partition + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\CreatePartitionIterateResult.java
1
请完成以下Java代码
protected boolean beforeSave (boolean newRecord) { if (isSummary()) { setMediaType(null); setAD_Image_ID(0); } return true; } // beforeSave /** * After Save. * Insert * - create tree * @param newRecord insert * @param success save success * @return true if saved */ @Override protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (newRecord) { StringBuffer sb = new StringBuffer ("INSERT INTO AD_TreeNodeCMM " + "(AD_Client_ID,AD_Org_ID, IsActive,Created,CreatedBy,Updated,UpdatedBy, " + "AD_Tree_ID, Node_ID, Parent_ID, SeqNo) " + "VALUES (") .append(getAD_Client_ID()).append(",0, 'Y', now(), 0, now(), 0,") .append(getAD_Tree_ID()).append(",").append(get_ID()) .append(", 0, 999)"); int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName()); if (no > 0) log.debug("#" + no + " - TreeType=CMM"); else log.warn("#" + no + " - TreeType=CMM"); return no > 0; } return success; } // afterSave /** * After Delete * @param success * @return deleted */ @Override protected boolean afterDelete (boolean success) { if (!success) return success; // StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMM ") .append(" WHERE Node_ID=").append(get_IDOld()) .append(" AND AD_Tree_ID=").append(getAD_Tree_ID());
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName()); if (no > 0) log.debug("#" + no + " - TreeType=CMM"); else log.warn("#" + no + " - TreeType=CMM"); return no > 0; } // afterDelete /** * Get File Name * @return file name return ID */ public String getFileName() { return get_ID() + getExtension(); } // getFileName /** * Get Extension with . * @return extension */ public String getExtension() { String mt = getMediaType(); if (MEDIATYPE_ApplicationPdf.equals(mt)) return ".pdf"; if (MEDIATYPE_ImageGif.equals(mt)) return ".gif"; if (MEDIATYPE_ImageJpeg.equals(mt)) return ".jpg"; if (MEDIATYPE_ImagePng.equals(mt)) return ".png"; if (MEDIATYPE_TextCss.equals(mt)) return ".css"; // Unknown return ".dat"; } // getExtension /** * Get Image * @return image or null */ public MImage getImage() { if (getAD_Image_ID() != 0) return MImage.get(getCtx(), getAD_Image_ID()); return null; } // getImage } // MMedia
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMedia.java
1
请完成以下Java代码
public void setTrgtCcy(String value) { this.trgtCcy = value; } /** * Gets the value of the unitCcy property. * * @return * possible object is * {@link String } * */ public String getUnitCcy() { return unitCcy; } /** * Sets the value of the unitCcy property. * * @param value * allowed object is * {@link String } * */ public void setUnitCcy(String value) { this.unitCcy = value; } /** * Gets the value of the xchgRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getXchgRate() { return xchgRate; } /** * Sets the value of the xchgRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setXchgRate(BigDecimal value) { this.xchgRate = value; } /** * Gets the value of the ctrctId property. * * @return * possible object is * {@link String } * */ public String getCtrctId() { return ctrctId; }
/** * Sets the value of the ctrctId property. * * @param value * allowed object is * {@link String } * */ public void setCtrctId(String value) { this.ctrctId = value; } /** * Gets the value of the qtnDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getQtnDt() { return qtnDt; } /** * Sets the value of the qtnDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setQtnDt(XMLGregorianCalendar value) { this.qtnDt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CurrencyExchange5.java
1
请完成以下Java代码
private Iterator<I_C_Printing_Queue> retrievePrintingQueueItems() { final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); queueQuery.setRequiredAccess(Access.WRITE); if (p_FilterBySelectedQueueItems) { final PInstanceId selectionId = getPinstanceId(); createWindowSelectionId(selectionId); queueQuery.setOnlyAD_PInstance_ID(selectionId); } if (p_FilterByProcessedQueueItems != null) { queueQuery.setFilterByProcessedQueueItems(p_FilterByProcessedQueueItems); } queueQuery.setModelTableId(p_AD_Table_ID); queueQuery.setModelFromRecordId(p_Record_ID); queueQuery.setModelToRecordId(p_Record_ID_To); if (!Check.isEmpty(p_WhereClause, true)) { final ISqlQueryFilter modelFilter = TypedSqlQueryFilter.of(p_WhereClause); queueQuery.setModelFilter(modelFilter); } loggable.addLog("Queue query: {}", queueQuery); final IQuery<I_C_Printing_Queue> query = printingDAO.createQuery(getCtx(), queueQuery, ITrx.TRXNAME_None); query.setOption(IQuery.OPTION_IteratorBufferSize, null); // use standard IteratorBufferSize if (log.isInfoEnabled())
{ loggable.addLog("The query matches {} C_Printing_Queue records; query={}",query.count(), query); } return query.iterate(I_C_Printing_Queue.class); } private int createWindowSelectionId(final PInstanceId selectionId) { final IQueryFilter<I_C_Printing_Queue> processQueryFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQuery<I_C_Printing_Queue> query = queryBL .createQueryBuilder(I_C_Printing_Queue.class, getCtx(), ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .filter(processQueryFilter) .create() .setRequiredAccess(Access.WRITE) .setClient_ID(); final int count = query.createSelection(selectionId); Loggables.withLogger(logger, Level.DEBUG).addLog("Restricting C_Printing_Queue records to selection of {} items; query={}", count, query); return count; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Printing_Queue_ReEnqueue.java
1
请完成以下Java代码
public class Person { private Long id; private String name; private Integer age; private String address; public Person() { super(); } public Person(Long id, String name, Integer age, String address) { this.id = id; this.name = name; this.age = age; this.address = address; } public Person(String name, Integer age) { this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]"; } }
repos\spring-boot-student-master\spring-boot-student-export\src\main\java\com\xiaolyuh\entity\Person.java
1
请完成以下Java代码
public class TenantPackModel { /** * 租户Id */ private Integer tenantId; /** * 产品包编码 */ private String packCode; /** * 产品包ID */ private String packId; /** * 产品包名称 */ private String packName; /** * 产品包 权限信息 */ private List<TenantPackAuth> authList; /** * 产品包 用户列表
*/ private List<TenantPackUser> userList; /** * 状态 正常状态1 申请状态0 */ private Integer packUserStatus; public Integer getPackUserStatus(){ if(packUserStatus==null){ return 1; } return packUserStatus; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\tenant\TenantPackModel.java
1
请完成以下Java代码
public void setM_Warehouse_Dest_ID (int M_Warehouse_Dest_ID) { if (M_Warehouse_Dest_ID < 1) set_Value (COLUMNNAME_M_Warehouse_Dest_ID, null); else set_Value (COLUMNNAME_M_Warehouse_Dest_ID, Integer.valueOf(M_Warehouse_Dest_ID)); } /** Get Ziel-Lager. @return Ziel-Lager */ public int getM_Warehouse_Dest_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Dest_ID); if (ii == null) return 0; return ii.intValue(); } /** * Set Verarbeitet. * * @param Processed * Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ public void setProcessed(boolean Processed) { set_Value(COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** * Get Verarbeitet. * * @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ public boolean isProcessed() { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTree.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { // @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String firstName; private String lastName; public long getId() { return id; } public void setId(long id) { this.id = id; } 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; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringJerseySimple\src\main\java\spring\jersey\domain\Customer.java
2