instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) { this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive; } public boolean isUseAlternativeNames() { return this.useAlternativeNames; } public void setUseAlternativeNames(boolean useAlternativeNames) { this.useAlternativeNames = useAlternativeNames; } public boolean isAllowTrailingComma() { return this.allowTrailingComma; } public void setAllowTrailingComma(boolean allowTrailingComma) { this.allowTrailingComma = allowTrailingComma; } public boolean isAllowComments() { return this.allowComments; } public void setAllowComments(boolean allowComments) { this.allowComments = allowComments;
} /** * Enum representing strategies for JSON property naming. The values correspond to * {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot * be directly referenced. */ public enum JsonNamingStrategy { /** * Snake case strategy. */ SNAKE_CASE, /** * Kebab case strategy. */ KEBAB_CASE } }
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
2
请完成以下Java代码
public static <K, V> Map<K, V> fillMissingKeys(@NonNull final Map<K, V> map, @NonNull final Collection<K> keys, @NonNull final V defaultValue) { if (keys.isEmpty()) { return map; } LinkedHashMap<K, V> result = null; for (K key : keys) { if (!map.containsKey(key)) { if (result == null) { result = new LinkedHashMap<>(map.size() + keys.size()); result.putAll(map); } result.put(key, defaultValue); } } return result == null ? map : result; } public <K, V> ImmutableMap<K, V> merge(@NonNull final ImmutableMap<K, V> map, K key, V value, BinaryOperator<V> remappingFunction) { if (map.isEmpty()) { return ImmutableMap.of(key, value); } final ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder(); boolean added = false; boolean changed = false; for (Map.Entry<K, V> entry : map.entrySet()) { if (!added && Objects.equals(key, entry.getKey())) { final V valueOld = entry.getValue(); final V valueNew = remappingFunction.apply(valueOld, value); mapBuilder.put(key, valueNew); added = true;
if (!Objects.equals(valueOld, valueNew)) { changed = true; } } else { mapBuilder.put(entry.getKey(), entry.getValue()); } } if (!added) { mapBuilder.put(key, value); changed = true; } if (!changed) { return map; } return mapBuilder.build(); } public static <T> ImmutableList<T> removeIf(@NonNull ImmutableList<T> list, @NonNull Predicate<T> predicate) { if (list.isEmpty()) {return list;} final ImmutableList<T> result = list.stream() .filter(item -> !predicate.test(item)) .collect(ImmutableList.toImmutableList()); return list.size() == result.size() ? list : result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\CollectionUtils.java
1
请完成以下Java代码
public class AssignmentImpl extends BaseElementImpl implements Assignment { protected static ChildElement<From> fromChild; protected static ChildElement<To> toChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Assignment.class, BPMN_ELEMENT_ASSIGNMENT) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<Assignment>() { public Assignment newInstance(ModelTypeInstanceContext instanceContext) { return new AssignmentImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); fromChild = sequenceBuilder.element(From.class) .required() .build(); toChild = sequenceBuilder.element(To.class) .required() .build(); typeBuilder.build(); } public AssignmentImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); }
public From getFrom() { return fromChild.getChild(this); } public void setFrom(From from) { fromChild.setChild(this, from); } public To getTo() { return toChild.getChild(this); } public void setTo(To to) { toChild.setChild(this, to); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\AssignmentImpl.java
1
请完成以下Java代码
public boolean isAllowAnyProduct() { return allowAnyProduct; } @Override public void setAllowAnyProduct(final boolean allowAnyProduct) { this.allowAnyProduct = allowAnyProduct; } @Override public String getHU_UnitType() { return huUnitType; } @Override public void setHU_UnitType(final String huUnitType) { this.huUnitType = huUnitType; } @Override public boolean isAllowVirtualPI() { return allowVirtualPI; } @Override public void setAllowVirtualPI(final boolean allowVirtualPI) { this.allowVirtualPI = allowVirtualPI; } @Override public void setOneConfigurationPerPI(final boolean oneConfigurationPerPI) { this.oneConfigurationPerPI = oneConfigurationPerPI; } @Override public boolean isOneConfigurationPerPI() { return oneConfigurationPerPI; } @Override public boolean isAllowDifferentCapacities() { return allowDifferentCapacities; } @Override public void setAllowDifferentCapacities(final boolean allowDifferentCapacities) { this.allowDifferentCapacities = allowDifferentCapacities; } @Override
public boolean isAllowInfiniteCapacity() { return allowInfiniteCapacity; } @Override public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity) { this.allowInfiniteCapacity = allowInfiniteCapacity; } @Override public boolean isAllowAnyPartner() { return allowAnyPartner; } @Override public void setAllowAnyPartner(final boolean allowAnyPartner) { this.allowAnyPartner = allowAnyPartner; } @Override public int getM_Product_Packaging_ID() { return packagingProductId; } @Override public void setM_Product_Packaging_ID(final int packagingProductId) { this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
1
请完成以下Java代码
public PropertySource<?> getPropertySource() { return this.propertySource; } /** * Return the property name that was used when obtaining the original value from the * {@link #getPropertySource() property source}. * @return the origin property name */ public String getPropertyName() { return this.propertyName; } /** * Return the actual origin for the source if known. * @return the actual source origin * @since 3.2.8 */ @Override public @Nullable Origin getOrigin() { return this.origin; } @Override public @Nullable Origin getParent() { return (this.origin != null) ? this.origin.getParent() : null;
} @Override public String toString() { return (this.origin != null) ? this.origin.toString() : "\"" + this.propertyName + "\" from property source \"" + this.propertySource.getName() + "\""; } /** * Get an {@link Origin} for the given {@link PropertySource} and * {@code propertyName}. Will either return an {@link OriginLookup} result or a * {@link PropertySourceOrigin}. * @param propertySource the origin property source * @param name the property name * @return the property origin */ public static Origin get(PropertySource<?> propertySource, String name) { Origin origin = OriginLookup.getOrigin(propertySource, name); return (origin instanceof PropertySourceOrigin) ? origin : new PropertySourceOrigin(propertySource, name, origin); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\origin\PropertySourceOrigin.java
1
请在Spring Boot框架中完成以下Java代码
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } @Bean
public SessionDAO sessionDAO() { MemorySessionDAO sessionDAO = new MemorySessionDAO(); return sessionDAO; } @Bean public SessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); Collection<SessionListener> listeners = new ArrayList<SessionListener>(); listeners.add(new ShiroSessionListener()); sessionManager.setSessionListeners(listeners); sessionManager.setSessionDAO(sessionDAO()); return sessionManager; } }
repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\config\ShiroConfig.java
2
请在Spring Boot框架中完成以下Java代码
final void addMapping(UrlMapping urlMapping) { this.unmappedMatchers = null; this.urlMappings.add(urlMapping); } /** * Marks the {@link RequestMatcher}'s as unmapped and then calls * {@link #chainRequestMatchersInternal(List)}. * @param requestMatchers the {@link RequestMatcher} instances that were created * @return the chained Object for the subclass which allows association of something * else to the {@link RequestMatcher} */ @Override protected final C chainRequestMatchers(List<RequestMatcher> requestMatchers) { this.unmappedMatchers = requestMatchers; return chainRequestMatchersInternal(requestMatchers); } /** * Subclasses should implement this method for returning the object that is chained to * the creation of the {@link RequestMatcher} instances. * @param requestMatchers the {@link RequestMatcher} instances that were created * @return the chained Object for the subclass which allows association of something * else to the {@link RequestMatcher} */ protected abstract C chainRequestMatchersInternal(List<RequestMatcher> requestMatchers); /** * Adds a {@link UrlMapping} added by subclasses in * {@link #chainRequestMatchers(java.util.List)} at a particular index. * @param index the index to add a {@link UrlMapping} * @param urlMapping {@link UrlMapping} the mapping to add */ final void addMapping(int index, UrlMapping urlMapping) { this.urlMappings.add(index, urlMapping); } /** * Creates the mapping of {@link RequestMatcher} to {@link Collection} of * {@link ConfigAttribute} instances * @return the mapping of {@link RequestMatcher} to {@link Collection} of * {@link ConfigAttribute} instances. Cannot be null. */ final LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> createRequestMap() { Assert.state(this.unmappedMatchers == null, () -> "An incomplete mapping was found for " + this.unmappedMatchers + ". Try completing it with something like requestUrls().<something>.hasRole('USER')"); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); for (UrlMapping mapping : getUrlMappings()) { RequestMatcher matcher = mapping.getRequestMatcher(); Collection<ConfigAttribute> configAttrs = mapping.getConfigAttrs(); requestMap.put(matcher, configAttrs); } return requestMap; }
/** * A mapping of {@link RequestMatcher} to {@link Collection} of * {@link ConfigAttribute} instances */ static final class UrlMapping { private final RequestMatcher requestMatcher; private final Collection<ConfigAttribute> configAttrs; UrlMapping(RequestMatcher requestMatcher, Collection<ConfigAttribute> configAttrs) { this.requestMatcher = requestMatcher; this.configAttrs = configAttrs; } RequestMatcher getRequestMatcher() { return this.requestMatcher; } Collection<ConfigAttribute> getConfigAttrs() { return this.configAttrs; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractConfigAttributeRequestMatcherRegistry.java
2
请完成以下Java代码
public void addAuthResolutionForPathsContaining(@NonNull final String containing, @NonNull final AuthResolution resolution) { final PathMatcher matcher = PathMatcher.builder() .containing(containing) .resolution(resolution) .build(); matchers.add(matcher); logger.info("Added path authentication resolution matcher: {}", matcher); } public Optional<AuthResolution> getAuthResolution(@NonNull final HttpServletRequest httpRequest) { if (matchers.isEmpty()) { return Optional.empty(); } final String path = httpRequest.getServletPath(); if (path == null) { return Optional.empty(); }
return matchers.stream() .filter(matcher -> matcher.isMatching(path)) .map(PathMatcher::getResolution) .findFirst(); } @Value @Builder private static class PathMatcher { @NonNull String containing; @NonNull AuthResolution resolution; public boolean isMatching(final String path) {return path.contains(containing);} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenFilterConfiguration.java
1
请完成以下Java代码
public boolean getParameterAsBool(final String parameterName) { return values.getParameterAsBool(parameterName); } @Nullable @Override public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue) { return values.getParameterAsBoolean(parameterName, defaultValue); } @Override public Timestamp getParameterAsTimestamp(final String parameterName) { return values.getParameterAsTimestamp(parameterName); } @Override public BigDecimal getParameterAsBigDecimal(final String parameterName) { return values.getParameterAsBigDecimal(parameterName); } @Override public Object getParameter_ToAsObject(final String parameterName) { return valuesTo.getParameterAsObject(parameterName); } @Override public String getParameter_ToAsString(final String parameterName) { return valuesTo.getParameterAsString(parameterName); } @Override public int getParameter_ToAsInt(final String parameterName, final int defaultValue) { return valuesTo.getParameterAsInt(parameterName, defaultValue); } @Override public boolean getParameter_ToAsBool(final String parameterName) { return valuesTo.getParameterAsBool(parameterName); } @Override public Timestamp getParameter_ToAsTimestamp(final String parameterName) { return valuesTo.getParameterAsTimestamp(parameterName); }
@Override public BigDecimal getParameter_ToAsBigDecimal(final String parameterName) { return valuesTo.getParameterAsBigDecimal(parameterName); } @Override public LocalDate getParameterAsLocalDate(String parameterName) { return values.getParameterAsLocalDate(parameterName); } @Override public LocalDate getParameter_ToAsLocalDate(String parameterName) { return valuesTo.getParameterAsLocalDate(parameterName); } @Override public ZonedDateTime getParameterAsZonedDateTime(String parameterName) { return values.getParameterAsZonedDateTime(parameterName); } @Nullable @Override public Instant getParameterAsInstant(final String parameterName) { return values.getParameterAsInstant(parameterName); } @Override public ZonedDateTime getParameter_ToAsZonedDateTime(String parameterName) { return valuesTo.getParameterAsZonedDateTime(parameterName); } @Override public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { return values.getParameterAsEnum(parameterName, enumType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\RangeAwareParams.java
1
请完成以下Java代码
private boolean isPicked() { return PICKED.equals(this); } private boolean isToBePicked() { return TO_BE_PICKED.equals(this); } public boolean isPickRejected() { return WILL_NOT_BE_PICKED.equals(this); } private boolean isPacked() { return PACKED.equals(this); } public boolean isEligibleForPicking() { return isToBePicked() || isPickRejected(); } public boolean isEligibleForRejectPicking() {
return !isPickRejected(); } public boolean isEligibleForPacking() { return !isPickRejected(); } public boolean isEligibleForReview() { return isPicked() || isPacked() || isPickRejected(); } public boolean isEligibleForProcessing() { return isPacked() || isPickRejected(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidatePickStatus.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_WF_Block_ID (final int AD_WF_Block_ID) { if (AD_WF_Block_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Block_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Block_ID, AD_WF_Block_ID); } @Override public int getAD_WF_Block_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Block_ID); } @Override public void setAD_Workflow_ID (final int AD_Workflow_ID) { if (AD_Workflow_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); } @Override public int getAD_Workflow_ID()
{ return get_ValueAsInt(COLUMNNAME_AD_Workflow_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Block.java
1
请完成以下Java代码
public int getStateCode() { return stateCode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + stateCode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass())
return false; SuspensionStateImpl other = (SuspensionStateImpl) obj; if (stateCode != other.stateCode) return false; return true; } @Override public String toString() { return name; } @Override public String getName() { return name; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\SuspensionState.java
1
请在Spring Boot框架中完成以下Java代码
public Long getId() { return id; } /** * 设置id属性的值。 * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * 获取name属性的值。 * * @return * possible object is
* {@link String } * */ public String getName() { return name; } /** * 设置name属性的值。 * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\User.java
2
请完成以下Java代码
public void setPassword(String password) { this.password = password; } /** * <p>Setter for the field <code>saltGenerator</code>.</p> * * @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object */ public void setSaltGenerator(SaltGenerator saltGenerator) { this.saltGenerator = saltGenerator; } /** * <p>Setter for the field <code>iterations</code>.</p>
* * @param iterations a int */ public void setIterations(int iterations) { this.iterations = iterations; } /** * <p>Setter for the field <code>algorithm</code>.</p> * * @param algorithm a {@link java.lang.String} object */ public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimplePBEByteEncryptor.java
1
请在Spring Boot框架中完成以下Java代码
private EsProductRelatedInfo convertProductRelatedInfo(SearchHits<EsProduct> response) { EsProductRelatedInfo productRelatedInfo = new EsProductRelatedInfo(); Map<String, Aggregation> aggregationMap = ((Aggregations)response.getAggregations().aggregations()).asMap(); //设置品牌 Aggregation brandNames = aggregationMap.get("brandNames"); List<String> brandNameList = new ArrayList<>(); for(int i = 0; i<((Terms) brandNames).getBuckets().size(); i++){ brandNameList.add(((Terms) brandNames).getBuckets().get(i).getKeyAsString()); } productRelatedInfo.setBrandNames(brandNameList); //设置分类 Aggregation productCategoryNames = aggregationMap.get("productCategoryNames"); List<String> productCategoryNameList = new ArrayList<>(); for(int i=0;i<((Terms) productCategoryNames).getBuckets().size();i++){ productCategoryNameList.add(((Terms) productCategoryNames).getBuckets().get(i).getKeyAsString()); } productRelatedInfo.setProductCategoryNames(productCategoryNameList); //设置参数 Aggregation productAttrs = aggregationMap.get("allAttrValues"); List<? extends Terms.Bucket> attrIds = ((ParsedLongTerms) ((ParsedFilter) ((ParsedNested) productAttrs).getAggregations().get("productAttrs")).getAggregations().get("attrIds")).getBuckets();
List<EsProductRelatedInfo.ProductAttr> attrList = new ArrayList<>(); for (Terms.Bucket attrId : attrIds) { EsProductRelatedInfo.ProductAttr attr = new EsProductRelatedInfo.ProductAttr(); attr.setAttrId((Long) attrId.getKey()); List<String> attrValueList = new ArrayList<>(); List<? extends Terms.Bucket> attrValues = ((ParsedStringTerms) attrId.getAggregations().get("attrValues")).getBuckets(); List<? extends Terms.Bucket> attrNames = ((ParsedStringTerms) attrId.getAggregations().get("attrNames")).getBuckets(); for (Terms.Bucket attrValue : attrValues) { attrValueList.add(attrValue.getKeyAsString()); } attr.setAttrValues(attrValueList); if(!CollectionUtils.isEmpty(attrNames)){ String attrName = attrNames.get(0).getKeyAsString(); attr.setAttrName(attrName); } attrList.add(attr); } productRelatedInfo.setProductAttrs(attrList); return productRelatedInfo; } }
repos\mall-master\mall-search\src\main\java\com\macro\mall\search\service\impl\EsProductServiceImpl.java
2
请完成以下Java代码
private static String extractProductName(@Nullable final ProductId productId) { if (productId == null) { return "<none>"; } return Services.get(IProductBL.class).getProductValueAndName(productId); } private static String extractUOMSymbol(@Nullable final UomId uomId) { if (uomId == null) { return "<none>"; } try
{ final I_C_UOM uom = Services.get(IUOMDAO.class).getById(uomId); if (uom == null) { return "<" + uomId.getRepoId() + ">"; } return uom.getUOMSymbol(); } catch (final Exception ex) { return "<" + uomId.getRepoId() + ">"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\exceptions\NoUOMConversionException.java
1
请完成以下Java代码
public void removedObserveRelation(ObserveRelation relation) { } } private void sendOtaData(CoapExchange exchange) { String idStr = exchange.getRequestOptions().getUriPath().get(exchange.getRequestOptions().getUriPath().size() - 1 ); UUID currentId = UUID.fromString(idStr); Response response = new Response(CoAP.ResponseCode.CONTENT); byte[] otaData = this.getOtaData(currentId); if (otaData != null && otaData.length > 0) { log.debug("Read ota data (length): [{}]", otaData.length); response.setPayload(otaData); if (exchange.getRequestOptions().getBlock2() != null) { int szx = exchange.getRequestOptions().getBlock2().getSzx(); int chunkSize = exchange.getRequestOptions().getBlock2().getSize();
boolean lastFlag = otaData.length <= chunkSize; response.getOptions().setBlock2(szx, lastFlag, 0); log.trace("With block2 Send currentId: [{}], length: [{}], chunkSize [{}], szx [{}], moreFlag [{}]", currentId, otaData.length, chunkSize, szx, lastFlag); } else { log.trace("With block1 Send currentId: [{}], length: [{}], ", currentId, otaData.length); } exchange.respond(response); } else { log.trace("Ota packaged currentId: [{}] is not found.", currentId); } } private byte[] getOtaData(UUID currentId) { return otaPackageDataCache.get(currentId.toString()); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mTransportCoapResource.java
1
请完成以下Java代码
public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Object... recordIds) { return ofColumnNameAndRecordIds(columnName, Arrays.asList(recordIds)); } @Nullable public static RecordsToAlwaysIncludeSql mergeOrNull(@Nullable final Collection<RecordsToAlwaysIncludeSql> collection) { if (collection == null || collection.isEmpty()) { return null; } else if (collection.size() == 1) { return collection.iterator().next(); } else {
return SqlAndParams.orNullables( collection.stream() .filter(Objects::nonNull) .map(RecordsToAlwaysIncludeSql::toSqlAndParams) .collect(ImmutableSet.toImmutableSet())) .map(RecordsToAlwaysIncludeSql::new) .orElse(null); } } public SqlAndParams toSqlAndParams() { return sqlAndParams; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\FilterSql.java
1
请在Spring Boot框架中完成以下Java代码
public ShiroRealm shiroRealm(){ ShiroRealm shiroRealm = new ShiroRealm(); return shiroRealm; } /** * cookie对象 * @return */ public SimpleCookie rememberMeCookie() { // 设置cookie名称,对应login.html页面的<input type="checkbox" name="rememberMe"/> SimpleCookie cookie = new SimpleCookie("rememberMe"); // 设置cookie的过期时间,单位为秒,这里为一天 cookie.setMaxAge(86400); return cookie;
} /** * cookie管理对象 * @return */ public CookieRememberMeManager rememberMeManager() { CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); // rememberMe cookie加密的密钥 cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag==")); return cookieRememberMeManager; } }
repos\SpringAll-master\12.Spring-Boot-Shiro-RememberMe\src\main\java\com\springboot\config\ShiroConfig.java
2
请完成以下Java代码
public String getAssigneeId() { return assigneeId; } public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } public String getInitiatorVariableName() { return initiatorVariableName; } public void setInitiatorVariableName(String initiatorVariableName) { this.initiatorVariableName = initiatorVariableName; } public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } public String getPredefinedProcessInstanceId() { return predefinedProcessInstanceId; } public void setPredefinedProcessInstanceId(String predefinedProcessInstanceId) { this.predefinedProcessInstanceId = predefinedProcessInstanceId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\StartProcessInstanceBeforeContext.java
1
请完成以下Java代码
public BigDecimal getAlreadyInvoicedNetSum(final I_M_Material_Tracking materialTracking) { final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); final List<I_C_Invoice> invoices = materialTrackingDAO.retrieveReferences(materialTracking, I_C_Invoice.class); BigDecimal result = BigDecimal.ZERO; for (final I_C_Invoice invoice : invoices) { final DocStatus invoiceDocStatus = DocStatus.ofCode(invoice.getDocStatus()); if(!invoiceDocStatus.isCompletedOrClosed()) { continue; }
// note: completed/closed implies that a C_DocType is set. final I_C_DocType docType = docTypeDAO.getById(invoice.getC_DocType_ID()); final String docSubType = docType.getDocSubType(); if (!IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_DownPayment.equals(docSubType) && !IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement.equals(docSubType)) { continue; } result = result.add(invoice.getTotalLines()); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InvoicedSumProvider.java
1
请完成以下Java代码
public int getM_InOutLineConfirm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLineConfirm_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ 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; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); }
/** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Scrapped Quantity. @param ScrappedQty The Quantity scrapped due to QA issues */ public void setScrappedQty (BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Scrapped Quantity. @return The Quantity scrapped due to QA issues */ public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_InOutLineConfirm.java
1
请完成以下Java代码
private <T> T executePost(final String path, final Map<String, String> params, final Object request, final Class<T> responseClass) { final URL url = getURL(path, params); final PostMethod httpPost = new PostMethod(url.toString()); final byte[] data = beanEncoder.encode(request); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; InputStream in = null; try { result = executeHttpPost(httpPost); in = httpPost.getResponseBodyAsStream(); if (result != 200) { final String errorMsg = in == null ? "code " + result : IOStreamUtils.toString(in); throw new AdempiereException("Error " + result + " while posting on " + url + ": " + errorMsg); } if (responseClass != null) { final T response = beanEncoder.decodeStream(in, responseClass); return response; } } catch (final Exception e) { throw new AdempiereException(e); } finally { IOStreamUtils.close(in); in = null;
} return null; } private int executeHttpPost(final PostMethod httpPost) throws HttpException, IOException { final int result = httpclient.executeMethod(httpPost); RestHttpArchiveEndpoint.logger.trace("Result code: {}", result); // final DefaultMethodRetryHandler retryHandler = new DefaultMethodRetryHandler(); // retryHandler.setRetryCount(3); // httpPost.setMethodRetryHandler(retryHandler); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\RestHttpArchiveEndpoint.java
1
请完成以下Java代码
private void setAutoTaxType(final I_GL_JournalLine glJournalLine) { final boolean drAutoTax = isAutoTaxAccount(glJournalLine.getAccount_DR()); final boolean crAutoTax = isAutoTaxAccount(glJournalLine.getAccount_CR()); // // We can activate tax accounting only for one side if (drAutoTax && crAutoTax) { throw new AdempiereException("@" + MSG_AutoTaxAccountDrCrNotAllowed + "@"); } final boolean taxRecord = drAutoTax || crAutoTax; // // Tax accounting can be allowed only if in a new transaction final boolean isPartialTrx = !glJournalLine.isAllowAccountDR() || !glJournalLine.isAllowAccountCR(); if (taxRecord && isPartialTrx) { throw new AdempiereException("@" + MSG_AutoTaxNotAllowedOnPartialTrx + "@"); } // // Set AutoTaxaAcount flags glJournalLine.setDR_AutoTaxAccount(drAutoTax); glJournalLine.setCR_AutoTaxAccount(crAutoTax); // // Update journal line type final String type = taxRecord ? X_GL_JournalLine.TYPE_Tax : X_GL_JournalLine.TYPE_Normal; glJournalLine.setType(type); } private ITaxAccountable asTaxAccountable(final I_GL_JournalLine glJournalLine, final boolean accountSignDR) { final IGLJournalLineBL glJournalLineBL = Services.get(IGLJournalLineBL.class);
return glJournalLineBL.asTaxAccountable(glJournalLine, accountSignDR); } private boolean isAutoTaxAccount(final I_C_ValidCombination accountVC) { if (accountVC == null) { return false; } final I_C_ElementValue account = accountVC.getAccount(); if (account == null) { return false; } return account.isAutoTaxAccount(); } private boolean isAutoTax(final I_GL_JournalLine glJournalLine) { return glJournalLine.isDR_AutoTaxAccount() || glJournalLine.isCR_AutoTaxAccount(); } @Nullable private AccountConceptualName suggestAccountConceptualName(@NonNull final AccountId accountId) { final ElementValueId elementValueId = accountDAO.getElementValueIdByAccountId(accountId); final ElementValue elementValue = elementValueRepository.getById(elementValueId); return elementValue.getAccountConceptualName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_JournalLine.java
1
请完成以下Java代码
public IntermediateThrowSignalEventActivityBehavior createIntermediateThrowSignalEventActivityBehavior(ThrowEvent throwEvent, Signal signal, EventSubscriptionDeclaration eventSubscriptionDeclaration) { return new IntermediateThrowSignalEventActivityBehavior(throwEvent, signal, eventSubscriptionDeclaration); } @Override public IntermediateThrowCompensationEventActivityBehavior createIntermediateThrowCompensationEventActivityBehavior(ThrowEvent throwEvent, CompensateEventDefinition compensateEventDefinition) { return new IntermediateThrowCompensationEventActivityBehavior(compensateEventDefinition); } // End events @Override public NoneEndEventActivityBehavior createNoneEndEventActivityBehavior(EndEvent endEvent) { return new NoneEndEventActivityBehavior(); } @Override public ErrorEndEventActivityBehavior createErrorEndEventActivityBehavior(EndEvent endEvent, ErrorEventDefinition errorEventDefinition) { return new ErrorEndEventActivityBehavior(errorEventDefinition.getErrorCode()); } @Override public CancelEndEventActivityBehavior createCancelEndEventActivityBehavior(EndEvent endEvent) { return new CancelEndEventActivityBehavior(); }
@Override public TerminateEndEventActivityBehavior createTerminateEndEventActivityBehavior(EndEvent endEvent) { return new TerminateEndEventActivityBehavior(endEvent); } // Boundary Events @Override public BoundaryEventActivityBehavior createBoundaryEventActivityBehavior(BoundaryEvent boundaryEvent, boolean interrupting, ActivityImpl activity) { return new BoundaryEventActivityBehavior(interrupting, activity.getId()); } @Override public CancelBoundaryEventActivityBehavior createCancelBoundaryEventActivityBehavior(CancelEventDefinition cancelEventDefinition) { return new CancelBoundaryEventActivityBehavior(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
1
请在Spring Boot框架中完成以下Java代码
public List<DataPoint> findByAccountName(String accountName) { Assert.hasLength(accountName); return repository.findByIdAccount(accountName); } /** * {@inheritDoc} */ @Override public DataPoint save(String accountName, Account account) { Instant instant = LocalDate.now().atStartOfDay() .atZone(ZoneId.systemDefault()).toInstant(); DataPointId pointId = new DataPointId(accountName, Date.from(instant)); Set<ItemMetric> incomes = account.getIncomes().stream() .map(this::createItemMetric) .collect(Collectors.toSet()); Set<ItemMetric> expenses = account.getExpenses().stream() .map(this::createItemMetric) .collect(Collectors.toSet()); Map<StatisticMetric, BigDecimal> statistics = createStatisticMetrics(incomes, expenses, account.getSaving()); DataPoint dataPoint = new DataPoint(); dataPoint.setId(pointId); dataPoint.setIncomes(incomes); dataPoint.setExpenses(expenses); dataPoint.setStatistics(statistics); dataPoint.setRates(ratesService.getCurrentRates()); log.debug("new datapoint has been created: {}", pointId); return repository.save(dataPoint);
} private Map<StatisticMetric, BigDecimal> createStatisticMetrics(Set<ItemMetric> incomes, Set<ItemMetric> expenses, Saving saving) { BigDecimal savingAmount = ratesService.convert(saving.getCurrency(), Currency.getBase(), saving.getAmount()); BigDecimal expensesAmount = expenses.stream() .map(ItemMetric::getAmount) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal incomesAmount = incomes.stream() .map(ItemMetric::getAmount) .reduce(BigDecimal.ZERO, BigDecimal::add); return ImmutableMap.of( StatisticMetric.EXPENSES_AMOUNT, expensesAmount, StatisticMetric.INCOMES_AMOUNT, incomesAmount, StatisticMetric.SAVING_AMOUNT, savingAmount ); } /** * Normalizes given item amount to {@link Currency#getBase()} currency with * {@link TimePeriod#getBase()} time period */ private ItemMetric createItemMetric(Item item) { BigDecimal amount = ratesService .convert(item.getCurrency(), Currency.getBase(), item.getAmount()) .divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP); return new ItemMetric(item.getTitle(), amount); } }
repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\service\StatisticsServiceImpl.java
2
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Product Key. @param ProductValue Key of the Product */ public void setProductValue (String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Product Key. @return Key of the Product */ public String getProductValue () { return (String)get_Value(COLUMNNAME_ProductValue); } /** Set Valid from.
@param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set UOM Code. @param X12DE355 UOM EDI X12 Code */ public void setX12DE355 (String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } /** Get UOM Code. @return UOM EDI X12 Code */ public String getX12DE355 () { return (String)get_Value(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java
1
请完成以下Java代码
public static Optional<AccountId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final AccountId id) { return id != null ? id.getRepoId() : -1; } int repoId; private AccountId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_ValidCombination_ID"); }
@Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals( @Nullable final AccountId id1, @Nullable final AccountId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountId.java
1
请完成以下Java代码
public class MusicAlbum { @Id private String id; private String name; private String artist; public MusicAlbum() { } public MusicAlbum(String name, String artist) { super(); this.name = name; this.artist = artist; } public String getId() { return id; }
public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\collection\name\data\MusicAlbum.java
1
请完成以下Java代码
public class GenericProperties { private Map<String, Object> properties = new HashMap<>(); private boolean ignoreUnknownFields; public Map<String, Object> getProperties() { return properties; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } public boolean isIgnoreUnknownFields() { return ignoreUnknownFields;
} public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } @Override public String toString() { return joinOn(this.getClass()) .add("properties=" + properties) .add("ignoreUnknownFields=" + ignoreUnknownFields) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\GenericProperties.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String userName() { return get(InfluxProperties::getUserName, InfluxConfig.super::userName); } @Override public @Nullable String password() { return get(InfluxProperties::getPassword, InfluxConfig.super::password); } @Override public @Nullable String retentionPolicy() { return get(InfluxProperties::getRetentionPolicy, InfluxConfig.super::retentionPolicy); } @Override public @Nullable Integer retentionReplicationFactor() { return get(InfluxProperties::getRetentionReplicationFactor, InfluxConfig.super::retentionReplicationFactor); } @Override public @Nullable String retentionDuration() { return get(InfluxProperties::getRetentionDuration, InfluxConfig.super::retentionDuration); } @Override public @Nullable String retentionShardDuration() { return get(InfluxProperties::getRetentionShardDuration, InfluxConfig.super::retentionShardDuration); } @Override public String uri() { return obtain(InfluxProperties::getUri, InfluxConfig.super::uri); } @Override public boolean compressed() { return obtain(InfluxProperties::isCompressed, InfluxConfig.super::compressed); } @Override public boolean autoCreateDb() { return obtain(InfluxProperties::isAutoCreateDb, InfluxConfig.super::autoCreateDb); } @Override
public InfluxApiVersion apiVersion() { return obtain(InfluxProperties::getApiVersion, InfluxConfig.super::apiVersion); } @Override public @Nullable String org() { return get(InfluxProperties::getOrg, InfluxConfig.super::org); } @Override public String bucket() { return obtain(InfluxProperties::getBucket, InfluxConfig.super::bucket); } @Override public @Nullable String token() { return get(InfluxProperties::getToken, InfluxConfig.super::token); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxPropertiesConfigAdapter.java
2
请完成以下Java代码
public void logJsonException(Exception e) { logDebug( "030", "Exception while parsing JSON: {}", e.getMessage(), e); } public void logAccessExternalSchemaNotSupported(Exception e) { logDebug( "031", "Could not restrict external schema access. " + "This indicates that this is not supported by your JAXP implementation: {}", e.getMessage()); } public void logMissingPropertiesFile(String file) { logWarn("032", "Could not find the '{}' file on the classpath. " + "If you have removed it, please restore it.", file); } public ProcessEngineException exceptionDuringFormParsing(String cause, String resourceName) { return new ProcessEngineException( exceptionMessage("033", "Could not parse Camunda Form resource {}. Cause: {}", resourceName, cause)); } public void debugCouldNotResolveCallableElement(
String callingProcessDefinitionId, String activityId, Throwable cause) { logDebug("046", "Could not resolve a callable element for activity {} in process {}. Reason: {}", activityId, callingProcessDefinitionId, cause.getMessage()); } public ProcessEngineException exceptionWhileSettingXxeProcessing(Throwable cause) { return new ProcessEngineException(exceptionMessage( "047", "Exception while configuring XXE processing: {}", cause.getMessage()), cause); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EngineUtilLogger.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingJobBPartnerService { @NonNull private final BPartnerBL bpartnerBL; @NonNull private final IDocumentLocationBL documentLocationBL; public String getBPartnerName(@Nullable final BPartnerId bpartnerId) { return bpartnerBL.getBPartnerName(bpartnerId); } public Map<BPartnerId, String> getBPartnerNames(@NonNull final Set<BPartnerId> bpartnerIds) { return bpartnerBL.getBPartnerNames(bpartnerIds); } public ShipmentAllocationBestBeforePolicy getBestBeforePolicy(@NonNull final BPartnerId bpartnerId) { return bpartnerBL.getBestBeforePolicy(bpartnerId); } public Set<DocumentLocation> getDocumentLocations(@NonNull final Set<BPartnerLocationId> bpartnerLocationIds) { return documentLocationBL.getDocumentLocations(bpartnerLocationIds); }
public I_C_BPartner_Location getBPartnerLocationByIdEvenInactive(final @NonNull BPartnerLocationId id) { return bpartnerBL.getBPartnerLocationByIdEvenInactive(id); } public List<I_C_BPartner_Location> getBPartnerLocationsByIds(final Set<BPartnerLocationId> ids) { return bpartnerBL.getBPartnerLocationsByIds(ids); } public RenderedAddressProvider newRenderedAddressProvider() { return documentLocationBL.newRenderedAddressProvider(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\bpartner\PickingJobBPartnerService.java
2
请完成以下Java代码
public class MHRPeriod extends X_HR_Period { /** * */ private static final long serialVersionUID = -7787966459848200539L; private static CCache<Integer, MHRPeriod> s_cache = new CCache<Integer, MHRPeriod>(Table_Name, 20); public static MHRPeriod get(Properties ctx, int HR_Period_ID) { if (HR_Period_ID <= 0) { return null; } // MHRPeriod period = s_cache.get(HR_Period_ID); if (period != null) { return period; } // Try Load period = new MHRPeriod(ctx, HR_Period_ID, null); if (period.get_ID() == HR_Period_ID) { s_cache.put(HR_Period_ID, period);
} else { period = null; } return period; } public MHRPeriod(Properties ctx, int HR_Period_ID, String trxName) { super(ctx, HR_Period_ID, trxName); } public MHRPeriod(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRPeriod.java
1
请完成以下Java代码
private HalVariableValue link(HalRelation relation, String resourcePath, String resourceId, String variablesPath) { if (resourcePath.startsWith("/")) { // trim leading / because otherwise it will be encode as %2F (see CAM-3091) resourcePath = resourcePath.substring(1); } this.linker.createLink(relation, resourcePath, resourceId, variablesPath, this.name); return this; } public static HalVariableValue fromVariableInstance(VariableInstance variableInstance) { HalVariableValue dto = new HalVariableValue(); VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(variableInstance.getTypedValue()); dto.name = variableInstance.getName(); dto.value = variableValueDto.getValue(); dto.type = variableValueDto.getType(); dto.valueInfo = variableValueDto.getValueInfo(); return dto;
} public String getName() { return name; } public Object getValue() { return value; } public String getType() { return type; } public Map<String, Object> getValueInfo() { return valueInfo; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalVariableValue.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } final Pointcut other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } // we use PointCut in a sorted set, so equals has to be consistent with compareTo() if (compareTo(other) == 0) { return true; } return false; }; /** * Compares this instance with the given {@link Pointcut} by comparing their. * <ul> * <li>TableName</li> * <li>Method's name</li> * <li>Method's declaring class name</li> * </ul> * * @task https://metasfresh.atlassian.net/browse/FRESH-318 */ @Override
public int compareTo(final Pointcut o) { return ComparisonChain.start() .compare(getTableName(), o.getTableName()) .compare(getMethod() == null ? null : getMethod().getDeclaringClass().getName(), o.getMethod() == null ? null : o.getMethod().getDeclaringClass().getName()) .compare(getMethod() == null ? null : getMethod().getName(), o.getMethod() == null ? null : o.getMethod().getName()) .compare(getMethod() == null ? null : getMethod().getName(), o.getMethod() == null ? null : o.getMethod().getName()) .result(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\Pointcut.java
1
请完成以下Spring Boot application配置
server: context-path: /web spring: datasource: druid: # 数据库访问配置, 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:ORCL username: test password: 123456 # 连接池配置 initial-size: 5 min-idle: 5 max-active: 20 # 连接等待超时时间 max-wait: 30000 # 配置检测可以关闭的空闲连接间隔时间 time-between-eviction-runs-millis: 60000 # 配置连接在池中的最小生存时间 min-evictable-idle-time-millis: 300000 validation-query: select '1' from dual test-while-idle: true test-on-borrow: false test-on-return: false # 打开PSCache,并且指定每个连接上PSCache的大小 pool-prepared-statements: true max-open-prepared-statements: 20 max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙 filters: stat,wall # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔 aop-patterns: com.springboot.servie.* # WebStatFilter配置 web-stat-filter: enabled: true # 添加过滤规则 url-pattern: /* # 忽略过滤的格式 exclusions: '*.js,*.gif,*.j
pg,*.png,*.css,*.ico,/druid/*' # StatViewServlet配置 stat-view-servlet: enabled: true # 访问路径为/druid时,跳转到StatViewServlet url-pattern: /druid/* # 是否能够重置数据 reset-enable: false # 需要账号密码才能访问控制台 login-username: druid login-password: druid123 # IP白名单 # allow: 127.0.0.1 # IP黑名单(共同存在时,deny优先于allow) # deny: 192.168.1.218 # 配置StatFilter filter: stat: log-slow-sql: true
repos\SpringAll-master\03.Spring-Boot-MyBatis\src\main\resources\application.yml
2
请完成以下Java代码
public @Nullable String getVersion() { return get("version"); } /** * Return the timestamp of the build or {@code null}. * <p> * If the original value could not be parsed properly, it is still available with the * {@code time} key. * @return the build time * @see #get(String) */ public @Nullable Instant getTime() { return getInstant("time"); } private static Properties processEntries(Properties properties) { coerceDate(properties, "time"); return properties; } private static void coerceDate(Properties properties, String key) { String value = properties.getProperty(key); if (value != null) { try { String updatedValue = String .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); properties.setProperty(key, updatedValue); }
catch (DateTimeException ex) { // Ignore and store the original value } } } static class BuildPropertiesRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("META-INF/build-info.properties"); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\BuildProperties.java
1
请完成以下Java代码
private void createAndLinkElementsForWindows() { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final IADElementDAO adElementsRepo = Services.get(IADElementDAO.class); final Set<AdWindowId> windowIdsWithMissingADElements = adWindowDAO.retrieveWindowIdsWithMissingADElements(); for (final AdWindowId windowId : windowIdsWithMissingADElements) { final I_AD_Window window = adWindowDAO.getWindowByIdInTrx(windowId); final AdElementId elementId = adElementsRepo.createNewElement(CreateADElementRequest.builder() .name(window.getName()) .printName(window.getName()) .description(window.getDescription()) .help(window.getHelp()) .build()); updateElementTranslationsFromWindow(elementId, windowId); DYNATTR_AD_Window_UpdateTranslations.setValue(window, false); window.setAD_Element_ID(elementId.getRepoId()); save(window); } } private void createAndLinkElementsForMenus() { final IADMenuDAO adMenuDAO = Services.get(IADMenuDAO.class);
final IADElementDAO adElementsRepo = Services.get(IADElementDAO.class); final Set<AdMenuId> menuIdsWithMissingADElements = adMenuDAO.retrieveMenuIdsWithMissingADElements(); for (final AdMenuId menuId : menuIdsWithMissingADElements) { final I_AD_Menu menu = adMenuDAO.getById(menuId); final AdElementId elementId = adElementsRepo.createNewElement(CreateADElementRequest.builder() .name(menu.getName()) .printName(menu.getName()) .description(menu.getDescription()) .webuiNameBrowse(menu.getWEBUI_NameBrowse()) .webuiNameNew(menu.getWEBUI_NameNew()) .webuiNameNewBreadcrumb(menu.getWEBUI_NameNewBreadcrumb()).build()); updateElementTranslationsFromMenu(elementId, menuId); DYNATTR_AD_Menu_UpdateTranslations.setValue(menu, false); menu.setAD_Element_ID(elementId.getRepoId()); save(menu); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\translation\api\impl\ElementTranslationBL.java
1
请完成以下Java代码
private FAOpenItemsHandler getHandler(@Nullable final AccountConceptualName accountConceptualName, @NonNull String docTableName) { if (accountConceptualName != null) { final FAOpenItemsHandler handler = handlersByKey.get(FAOpenItemsHandlerMatchingKey.of(accountConceptualName, docTableName)); if (handler != null) { return handler; } } return genericOIHandler; } public int processScheduled() { final int batchSize = getProcessingBatchSize(); final Stopwatch stopwatch = Stopwatch.createStarted(); final int count = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, "SELECT de_metas_acct.fact_acct_openItems_to_update_process(p_BatchSize:=?)", batchSize); stopwatch.stop(); logger.debug("Processed {} records in {} (batchSize={})", count, stopwatch, batchSize); return count; } private int getProcessingBatchSize() { final int batchSize = sysConfigBL.getIntValue(SYSCONFIG_ProcessingBatchSize, -1); return batchSize > 0 ? batchSize : DEFAULT_ProcessingBatchSize; } public void fireGLJournalCompleted(final SAPGLJournal glJournal)
{ for (SAPGLJournalLine line : glJournal.getLines()) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { continue; } handlersByKey.values() .stream() .distinct() .forEach(handler -> handler.onGLJournalLineCompleted(line)); } } public void fireGLJournalReactivated(final SAPGLJournal glJournal) { for (SAPGLJournalLine line : glJournal.getLines()) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { continue; } handlersByKey.values().forEach(handler -> handler.onGLJournalLineReactivated(line)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\FAOpenItemsService.java
1
请完成以下Java代码
public class DefaultManagementMBeanAssembler implements ManagementMBeanAssembler { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultManagementMBeanAssembler.class); protected final MBeanInfoAssembler assembler; public DefaultManagementMBeanAssembler() { this.assembler = new MBeanInfoAssembler(); } @Override public ModelMBean assemble(Object obj, ObjectName name) throws JMException { ModelMBeanInfo mbi = null; // use the default provided mbean which has been annotated with JMX annotations LOGGER.trace("Assembling MBeanInfo for: {} from @ManagedResource object: {}", name, obj); mbi = assembler.getMBeanInfo(obj, null, name.toString()); if (mbi == null) { return null;
} RequiredModelMBean mbean = new RequiredModelMBean(mbi); try { mbean.setManagedResource(obj, "ObjectReference"); } catch (InvalidTargetObjectTypeException e) { throw new JMException(e.getMessage()); } // Allows the managed object to send notifications if (obj instanceof NotificationSenderAware) { ((NotificationSenderAware) obj).setNotificationSender(new NotificationSenderAdapter(mbean)); } return mbean; } }
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\DefaultManagementMBeanAssembler.java
1
请完成以下Java代码
public IReturnsInOutProducer setM_Warehouse(final I_M_Warehouse warehouse) { assertConfigurable(); _warehouse = warehouse; return this; } private final int getM_Warehouse_ID_ToUse() { if (_warehouse != null) { return _warehouse.getM_Warehouse_ID(); } return -1; } @Override public IReturnsInOutProducer setMovementDate(final Date movementDate) { Check.assumeNotNull(movementDate, "movementDate not null"); _movementDate = movementDate; return this; } protected final Timestamp getMovementDateToUse() { if (_movementDate != null) { return TimeUtil.asTimestamp(_movementDate); }
final Properties ctx = getCtx(); final Timestamp movementDate = Env.getDate(ctx); // use Login date (08306) return movementDate; } @Override public IReturnsInOutProducer setC_Order(final I_C_Order order) { assertConfigurable(); _order = order; return this; } protected I_C_Order getC_Order() { return _order; } @Override public IReturnsInOutProducer dontComplete() { _complete = false; return this; } protected boolean isComplete() { return _complete; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\AbstractReturnsInOutProducer.java
1
请完成以下Java代码
public void executeHandler(RestartProcessInstancesBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { String processDefinitionId = batchConfiguration.getProcessDefinitionId(); RestartProcessInstanceBuilderImpl builder = new RestartProcessInstanceBuilderImpl(processDefinitionId); builder.processInstanceIds(batchConfiguration.getIds()); builder.setInstructions(batchConfiguration.getInstructions()); if (batchConfiguration.isInitialVariables()) { builder.initialSetOfVariables(); } if (batchConfiguration.isSkipCustomListeners()) { builder.skipCustomListeners(); } if (batchConfiguration.isWithoutBusinessKey()) { builder.withoutBusinessKey(); } if (batchConfiguration.isSkipIoMappings()) { builder.skipIoMappings();
} CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration() .getCommandExecutorTxRequired(); commandContext.executeWithOperationLogPrevented( new RestartProcessInstancesCmd(commandExecutor, builder)); } @Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected RestartProcessInstancesBatchConfiguration createJobConfiguration(RestartProcessInstancesBatchConfiguration configuration, List<String> processIdsForJob) { return new RestartProcessInstancesBatchConfiguration(processIdsForJob, configuration.getInstructions(), configuration.getProcessDefinitionId(), configuration.isInitialVariables(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings(), configuration.isWithoutBusinessKey()); } @Override protected RestartProcessInstancesBatchConfigurationJsonConverter getJsonConverterInstance() { return RestartProcessInstancesBatchConfigurationJsonConverter.INSTANCE; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstancesJobHandler.java
1
请完成以下Java代码
private void markAsError(final String errorMsg, final String sqlWhereClause) { final String sql = "UPDATE " + I_I_Request.Table_Name + " i " + "\n SET " + COLUMNNAME_I_IsImported + "=?, " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||? " + "\n WHERE " + sqlWhereClause; final Object[] sqlParams = new Object[] { X_I_Request.I_ISIMPORTED_ImportFailed, errorMsg + "; " }; DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams, ITrx.TRXNAME_ThreadInherited); } @Override public I_I_Request retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { final PO po = TableModelLoader.instance.getPO(ctx, I_I_Request.Table_Name, rs, ITrx.TRXNAME_ThreadInherited); return InterfaceWrapperHelper.create(po, I_I_Request.class); } /* * @param isInsertOnly ignored. This import is only for updates. */ @Override protected ImportRecordResult importRecord( final @NonNull IMutable<Object> state_NOTUSED, final @NonNull I_I_Request importRecord, final boolean isInsertOnly_NOTUSED) { // // Create a new request final I_R_Request request = InterfaceWrapperHelper.newInstance(I_R_Request.class, importRecord); request.setAD_Org_ID(importRecord.getAD_Org_ID()); // // BPartner { int bpartnerId = importRecord.getC_BPartner_ID(); if (bpartnerId <= 0) { throw new AdempiereException("BPartner not found"); } request.setC_BPartner_ID(bpartnerId); } // // request type { int requesTypeId = importRecord.getR_RequestType_ID(); if (requesTypeId <= 0) {
throw new AdempiereException("Request Type not found"); } request.setR_RequestType_ID(requesTypeId); } // // status { int statusId = importRecord.getR_Status_ID(); if (statusId <= 0) { throw new AdempiereException("Status not found"); } request.setR_Status_ID(statusId); } // // set data from the other fields request.setDateTrx(importRecord.getDateTrx()); request.setDateNextAction(importRecord.getDateNextAction()); request.setSummary(importRecord.getSummary()); request.setDocumentNo(importRecord.getDocumentNo()); int userid = Env.getAD_User_ID(getCtx()); request.setSalesRep_ID(userid); // InterfaceWrapperHelper.save(request); // // Link back the request to current import record importRecord.setR_Request(request); // return ImportRecordResult.Inserted; } @Override protected void markImported(final I_I_Request importRecord) { importRecord.setI_IsImported(X_I_Request.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\request\impexp\RequestImportProcess.java
1
请完成以下Java代码
public UpdateJobDefinitionSuspensionStateBuilderImpl processDefinitionTenantId(String tenantId) { ensureNotNull("tenantId", tenantId); this.processDefinitionTenantId = tenantId; this.isProcessDefinitionTenantIdSet = true; return this; } @Override public UpdateJobDefinitionSuspensionStateBuilderImpl includeJobs(boolean includeJobs) { this.includeJobs = includeJobs; return this; } @Override public UpdateJobDefinitionSuspensionStateBuilderImpl executionDate(Date executionDate) { this.executionDate = executionDate; return this; } @Override public void activate() { validateParameters(); ActivateJobDefinitionCmd command = new ActivateJobDefinitionCmd(this); commandExecutor.execute(command); } @Override public void suspend() { validateParameters(); SuspendJobDefinitionCmd command = new SuspendJobDefinitionCmd(this); commandExecutor.execute(command); } protected void validateParameters() { ensureOnlyOneNotNull("Need to specify either a job definition id, a process definition id or a process definition key.", jobDefinitionId, processDefinitionId, processDefinitionKey); if (isProcessDefinitionTenantIdSet && (jobDefinitionId != null || processDefinitionId != null)) { throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey(); } ensureNotNull("commandExecutor", commandExecutor); }
public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionTenantId() { return processDefinitionTenantId; } public boolean isProcessDefinitionTenantIdSet() { return isProcessDefinitionTenantIdSet; } public String getJobDefinitionId() { return jobDefinitionId; } public boolean isIncludeJobs() { return includeJobs; } public Date getExecutionDate() { return executionDate; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\UpdateJobDefinitionSuspensionStateBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public String getExecutionId() { return executionId; }
public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceResponse.java
2
请完成以下Java代码
private <T> T restrictQuery( SecurityPoliciesRestrictionApplier<T> restrictionApplier, SecurityPolicyAccess securityPolicyAccess ) { if (!arePoliciesDefined()) { return restrictionApplier.allowAll(); } Set<String> keys = definitionKeysAllowedForApplicationPolicy(securityPolicyAccess); if (keys != null && !keys.isEmpty()) { if (keys.contains(getSecurityPoliciesProperties().getWildcard())) { return restrictionApplier.allowAll(); } return restrictionApplier.restrictToKeys(keys); } //policies are in place but if we've got here then none for this user if (!getSecurityPoliciesProperties().getPolicies().isEmpty()) { return restrictionApplier.denyAll(); } return restrictionApplier.allowAll(); }
public boolean canWrite(String processDefinitionKey) { return hasPermission(processDefinitionKey, SecurityPolicyAccess.WRITE, applicationName); } public boolean canRead(String processDefinitionKey) { return ( hasPermission(processDefinitionKey, SecurityPolicyAccess.READ, applicationName) || hasPermission(processDefinitionKey, SecurityPolicyAccess.WRITE, applicationName) ); } protected boolean anEntryInSetStartsKey(Set<String> keys, String processDefinitionKey) { for (String key : keys) { //override the base class with exact matching as startsWith is only preferable for audit where id might be used that would start with key if (processDefinitionKey.equalsIgnoreCase(key)) { return true; } } return false; } }
repos\Activiti-develop\activiti-core-common\activiti-spring-security-policies\src\main\java\org\activiti\core\common\spring\security\policies\ProcessSecurityPoliciesManagerImpl.java
1
请完成以下Java代码
public Collection<Todo> findAll() { return repo.findAll().stream() .map(mapper::map) .collect(toList()); } /** * Durchsucht die Todos nach einer ID. * * @param id die ID * @return das Suchergebnis */ public Optional<Todo> findById(long id) { return repo.findById(id) .map(mapper::map); } /** * Fügt ein Item in den Datenbestand hinzu. Dabei wird eine ID generiert. * * @param item das anzulegende Item (ohne ID) * @return das gespeicherte Item (mit ID) * @throws IllegalArgumentException wenn das Item null oder die ID bereits belegt ist */ public Todo create(Todo item) { if (null == item || null != item.id()) { throw new IllegalArgumentException("item must exist without any id"); } return mapper.map(repo.save(mapper.map(item))); } /** * Aktualisiert ein Item im Datenbestand. * * @param item das zu ändernde Item mit ID * @throws IllegalArgumentException * wenn das Item oder dessen ID nicht belegt ist
* @throws NotFoundException * wenn das Element mit der ID nicht gefunden wird */ public void update(Todo item) { if (null == item || null == item.id()) { throw new IllegalArgumentException("item must exist with an id"); } // remove separat, um nicht neue Einträge hinzuzufügen (put allein würde auch ersetzen) if (repo.existsById(item.id())) { repo.save(mapper.map(item)); } else { throw new NotFoundException(); } } /** * Entfernt ein Item aus dem Datenbestand. * * @param id die ID des zu löschenden Items * @throws NotFoundException * wenn das Element mit der ID nicht gefunden wird */ public void delete(long id) { if (repo.existsById(id)) { repo.deleteById(id); } else { throw new NotFoundException(); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\sample\control\TodosService.java
1
请完成以下Java代码
public class ProductMap { private String name; private String category; private Map<String, Object> details; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category;
} public void setCategory(String category) { this.category = category; } public Map<String, Object> getDetails() { return details; } public void setDetails(Map<String, Object> details) { this.details = details; } }
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\dynamicobject\ProductMap.java
1
请完成以下Java代码
class ArrayBinder extends IndexedElementsBinder<Object> { ArrayBinder(Context context) { super(context); } @Override protected @Nullable Object bindAggregate(ConfigurationPropertyName name, Bindable<?> target, AggregateElementBinder elementBinder) { IndexedCollectionSupplier result = new IndexedCollectionSupplier(ArrayList::new); ResolvableType aggregateType = target.getType(); ResolvableType elementType = target.getType().getComponentType(); bindIndexed(name, target, elementBinder, aggregateType, elementType, result); if (result.wasSupplied()) { List<Object> list = (List<Object>) result.get();
Object array = Array.newInstance(elementType.resolve(), list.size()); for (int i = 0; i < list.size(); i++) { Array.set(array, i, list.get(i)); } return array; } return null; } @Override protected Object merge(Supplier<Object> existing, Object additional) { return additional; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\ArrayBinder.java
1
请完成以下Java代码
public void updateTypeOfDestCountry(@NonNull final I_C_Tax tax) { final CountryId toCountryId = CountryId.ofRepoIdOrNull(tax.getTo_Country_ID()); if (toCountryId == null) { final OrgId orgId = OrgId.ofRepoId(tax.getAD_Org_ID()); if (orgId.isAny()) { tax.setTypeOfDestCountry(WITHIN_COUNTRY_AREA.getCode()); } } else { if (tax.getC_Country_ID() == tax.getTo_Country_ID()) { tax.setTypeOfDestCountry(DOMESTIC.getCode()); } else { final String countryCode = countryDAO.retrieveCountryCode2ByCountryId(toCountryId); final boolean isEULocation = countryAreaBL.isMemberOf(Env.getCtx(), ICountryAreaBL.COUNTRYAREAKEY_EU, countryCode, tax.getUpdated()); final TypeOfDestCountry typeOfDestCountry = isEULocation ? WITHIN_COUNTRY_AREA : OUTSIDE_COUNTRY_AREA; tax.setTypeOfDestCountry(typeOfDestCountry.getCode()); } } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Tax.COLUMNNAME_TypeOfDestCountry }) public void updateToCountryId(@NonNull final I_C_Tax tax) { final TypeOfDestCountry typeOfDestCountry = TypeOfDestCountry.ofNullableCode(tax.getTypeOfDestCountry()); final int countryId = tax.getC_Country_ID(); final int toCountryIdRepoId = tax.getTo_Country_ID(); if ((DOMESTIC.equals(typeOfDestCountry) && countryId != toCountryIdRepoId) || (countryId == toCountryIdRepoId && !DOMESTIC.equals(typeOfDestCountry))) { tax.setTo_Country_ID(0); }
else { final CountryId toCountryId = CountryId.ofRepoIdOrNull(toCountryIdRepoId); if (toCountryId != null) { final String countryCode = countryDAO.retrieveCountryCode2ByCountryId(toCountryId); final boolean isEULocation = countryAreaBL.isMemberOf(Env.getCtx(), ICountryAreaBL.COUNTRYAREAKEY_EU, countryCode, Env.getDate()); if ((isEULocation && !WITHIN_COUNTRY_AREA.equals(typeOfDestCountry)) || (!isEULocation && OUTSIDE_COUNTRY_AREA.equals(typeOfDestCountry))) { tax.setTo_Country_ID(0); } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\interceptor\C_Tax.java
1
请完成以下Java代码
public List<Account> getAccounts(){ return accountDao.all(); } @RequestMapping(value = "/{id}",method = RequestMethod.GET) public Account getAccountById(@PathVariable("id") int id){ return accountDao.unique(id); } @RequestMapping(value = "",method = RequestMethod.GET) public Account getAccountById(@RequestParam("name") String name){ return accountDao.selectAccountByName(name); } @RequestMapping(value = "/{id}",method = RequestMethod.PUT) public String updateAccount(@PathVariable("id")int id , @RequestParam(value = "name",required = true)String name, @RequestParam(value = "money" ,required = true)double money){ Account account=new Account(); account.setMoney(money); account.setName(name); account.setId(id); int t=accountDao.updateById(account); if(t==1){ return account.toString(); }else { return "fail"; } }
@RequestMapping(value = "",method = RequestMethod.POST) public String postAccount( @RequestParam(value = "name")String name, @RequestParam(value = "money" )double money) { Account account = new Account(); account.setMoney(money); account.setName(name); KeyHolder t = accountDao.insertReturnKey(account); if (t.getInt() > 0) { return account.toString(); } else { return "fail"; } } }
repos\SpringBootLearning-master\springboot-beatlsql\src\main\java\com\forezp\web\AccountController.java
1
请完成以下Java代码
public void setCity (final @Nullable java.lang.String City) { set_Value (COLUMNNAME_City, City); } @Override public java.lang.String getCity() { return get_ValueAsString(COLUMNNAME_City); } @Override public void setFirstname (final @Nullable java.lang.String Firstname) { set_Value (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return get_ValueAsString(COLUMNNAME_Firstname); } @Override public void setIsCompany (final boolean IsCompany) { set_ValueNoCheck (COLUMNNAME_IsCompany, IsCompany); } @Override public boolean isCompany() { return get_ValueAsBoolean(COLUMNNAME_IsCompany); } @Override public void setLastname (final @Nullable java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return get_ValueAsString(COLUMNNAME_Lastname); }
@Override public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Adv_Search_v.java
1
请完成以下Java代码
public void setTags (final @Nullable java.lang.String Tags) { set_Value (COLUMNNAME_Tags, Tags); } @Override public java.lang.String getTags() { return get_ValueAsString(COLUMNNAME_Tags); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Local File-URL = LU */ public static final String TYPE_LocalFile_URL = "LU"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override
public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry.java
1
请完成以下Java代码
public Extension newInstance(ModelTypeInstanceContext instanceContext) { return new ExtensionImpl(instanceContext); } }); // TODO: qname reference extension definition definitionAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DEFINITION) .build(); mustUnderstandAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_MUST_UNDERSTAND) .defaultValue(false) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); documentationCollection = sequenceBuilder.elementCollection(Documentation.class) .build(); typeBuilder.build(); } public ExtensionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); }
public String getDefinition() { return definitionAttribute.getValue(this); } public void setDefinition(String Definition) { definitionAttribute.setValue(this, Definition); } public boolean mustUnderstand() { return mustUnderstandAttribute.getValue(this); } public void setMustUnderstand(boolean mustUnderstand) { mustUnderstandAttribute.setValue(this, mustUnderstand); } public Collection<Documentation> getDocumentations() { return documentationCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ExtensionImpl.java
1
请完成以下Java代码
protected static String buildInfoString(final I_C_RfQ rfq) { return Services.get(IRfqBL.class).getSummary(rfq); } protected static String buildInfoString(final I_C_RfQLine rfqLine) { if (rfqLine == null) { return "?"; } final I_C_RfQ rfq = rfqLine.getC_RfQ(); return new StringBuilder() .append(buildInfoString(rfq)) .append(", @Line@ ").append(rfqLine.getLine()) .toString(); } protected static String buildInfoString(final I_C_RfQResponse rfqResponse) { return Services.get(IRfqBL.class).getSummary(rfqResponse); } protected static String buildInfoString(final I_C_RfQResponseLine rfqResponseLine) { if (rfqResponseLine == null)
{ return "?"; } return new StringBuilder() .append(buildInfoString(rfqResponseLine.getC_RfQResponse())) .append(", @Line@ ").append(rfqResponseLine.getLine()) .toString(); } protected static String buildInfoString(final I_C_RfQResponseLineQty rfqResponseLineQty) { if (rfqResponseLineQty == null) { return "?"; } return new StringBuilder() .append(buildInfoString(rfqResponseLineQty.getC_RfQResponseLine())) .append(", @Qty@=").append(rfqResponseLineQty.getQtyPromised()) .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\exceptions\RfQException.java
1
请完成以下Java代码
public void updateLUTUConfigurationFromDocumentLine(final I_M_HU_LUTU_Configuration lutuConfiguration, final I_M_ReceiptSchedule documentLine) { Check.assumeNotNull(lutuConfiguration, "lutuConfiguration not null"); Check.assumeNotNull(documentLine, "documentLine not null"); // // Set BPartner / Location to be used final int bpartnerId = receiptScheduleBL.getC_BPartner_Effective_ID(documentLine); final int bpartnerLocationId = receiptScheduleBL.getC_BPartner_Location_Effective_ID(documentLine); lutuConfiguration.setC_BPartner_ID(bpartnerId); lutuConfiguration.setC_BPartner_Location_ID(bpartnerLocationId); // // Set Locator final LocatorId locatorId = receiptScheduleBL.getLocatorEffectiveId(documentLine); lutuConfiguration.setM_Locator_ID(locatorId.getRepoId()); //
// Set HUStatus=Planning because receipt schedules are always about planning lutuConfiguration.setHUStatus(X_M_HU.HUSTATUS_Planning); } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product(final I_M_ReceiptSchedule receiptSchedule) { final I_M_HU_PI_Item_Product tuPIItemProduct = receiptSchedule.getM_HU_PI_Item_Product(); if (tuPIItemProduct != null && tuPIItemProduct.getM_HU_PI_Item_Product_ID() > 0) { return tuPIItemProduct; } // // Fallback: return Virtual PI item final Properties ctx = InterfaceWrapperHelper.getCtx(receiptSchedule); return hupiItemProductDAO.retrieveVirtualPIMaterialItemProduct(ctx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleDocumentLUTUConfigurationHandler.java
1
请完成以下Java代码
protected boolean isEmptyFile(URL url) { InputStream inputStream = null; try { inputStream = url.openStream(); return inputStream.available() == 0; } catch (IOException e) { throw new ProcessEngineException("Could not open stream for " + url, e); } finally { IoUtil.closeSilently(inputStream); } } protected ProcessesXml parseProcessesXml(URL url) {
final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser(); ProcessesXml processesXml = processesXmlParser.createParse() .sourceUrl(url) .execute() .getProcessesXml(); return processesXml; } public void undeploy(DeploymentUnit context) { } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessesXmlProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<Class<? extends DDOrderDocStatusChangedEvent>> getHandledEventType() { return ImmutableList.of(DDOrderDocStatusChangedEvent.class); } @Override public void handleEvent(@NonNull final DDOrderDocStatusChangedEvent ddOrderChangedDocStatusEvent) { final List<Candidate> candidatesForDDOrderId = DDOrderUtil .retrieveCandidatesForDDOrderId( candidateRepositoryRetrieval, ddOrderChangedDocStatusEvent.getDdOrderId()); Check.errorIf(candidatesForDDOrderId.isEmpty(), "No Candidates found for PP_Order_ID={} ", ddOrderChangedDocStatusEvent.getDdOrderId()); final DocStatus newDocStatusFromEvent = ddOrderChangedDocStatusEvent.getNewDocStatus(); final List<Candidate> updatedCandidatesToPersist = new ArrayList<>(); for (final Candidate candidateForDDOrderId : candidatesForDDOrderId) { final BigDecimal newQuantity = computeNewQuantity(newDocStatusFromEvent, candidateForDDOrderId); final DistributionDetail distributionDetail = // DistributionDetail.cast(candidateForDDOrderId.getBusinessCaseDetail()); final Candidate updatedCandidateToPersist = candidateForDDOrderId.toBuilder() // .status(newCandidateStatus) .materialDescriptor(candidateForDDOrderId.getMaterialDescriptor().withQuantity(newQuantity)) .businessCaseDetail(distributionDetail.toBuilder().ddOrderDocStatus(newDocStatusFromEvent).build()) .build();
updatedCandidatesToPersist.add(updatedCandidateToPersist); } updatedCandidatesToPersist.forEach(candidateChangeService::onCandidateNewOrChange); } private BigDecimal computeNewQuantity( @NonNull final DocStatus newDocStatusFromEvent, @NonNull final Candidate candidateForDDOrderId) { final BigDecimal newQuantity; if (newDocStatusFromEvent.isClosed()) { // Take the "actualQty" instead of max(actual, planned) newQuantity = candidateForDDOrderId.computeActualQty(); } else { // take the max(actual, planned) final BigDecimal plannedQty = candidateForDDOrderId.getBusinessCaseDetail().getQty(); newQuantity = candidateForDDOrderId.computeActualQty().max(plannedQty); } return newQuantity; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderDocStatusChangedHandler.java
2
请完成以下Java代码
public class Trade { private String securityID; private int quantity; private double price; public Trade(String securityID, int quantity, double price) { this.securityID = securityID; this.quantity = quantity; this.price = price; } public String getSecurityID() { return securityID; } public void setSecurityID(String securityID) { this.securityID = securityID;
} public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
repos\tutorials-master\mapstruct-2\src\main\java\com\baeldung\context\entity\Trade.java
1
请完成以下Java代码
public static void writeStringToFile(String content, String filePath) { BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath))); outputStream.write(content.getBytes()); outputStream.flush(); } catch (Exception e) { throw new ActivitiException("Couldn't write file " + filePath, e); } finally { IoUtil.closeSilently(outputStream); } } /** * Closes the given stream. The same as calling {@link InputStream#close()}, but errors while closing are silently ignored. */ public static void closeSilently(InputStream inputStream) { try { if (inputStream != null) { inputStream.close(); }
} catch (IOException ignore) { // Exception is silently ignored } } /** * Closes the given stream. The same as calling {@link OutputStream#close()} , but errors while closing are silently ignored. */ public static void closeSilently(OutputStream outputStream) { try { if (outputStream != null) { outputStream.close(); } } catch (IOException ignore) { // Exception is silently ignored } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\IoUtil.java
1
请完成以下Java代码
public boolean isAuditSuccess() { return this.auditSuccess; } @Override public boolean isGranting() { return this.granting; } void setAuditFailure(boolean auditFailure) { this.auditFailure = auditFailure; } void setAuditSuccess(boolean auditSuccess) { this.auditSuccess = auditSuccess; } void setPermission(Permission permission) { Assert.notNull(permission, "Permission required"); this.permission = permission;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AccessControlEntryImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("granting: ").append(this.granting).append("; "); sb.append("sid: ").append(this.sid).append("; "); sb.append("permission: ").append(this.permission).append("; "); sb.append("auditSuccess: ").append(this.auditSuccess).append("; "); sb.append("auditFailure: ").append(this.auditFailure); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AccessControlEntryImpl.java
1
请完成以下Java代码
public class HelloWorldExecutor implements Executor { @Override public void registered(ExecutorDriver driver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) { } @Override public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) { } @Override public void disconnected(ExecutorDriver driver) { } @Override public void launchTask(ExecutorDriver driver, TaskInfo task) { Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) .setState(Protos.TaskState.TASK_RUNNING).build(); driver.sendStatusUpdate(status); String myStatus = "Hello Framework"; driver.sendFrameworkMessage(myStatus.getBytes()); System.out.println("Hello World!!!"); status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) .setState(Protos.TaskState.TASK_FINISHED).build(); driver.sendStatusUpdate(status);
} @Override public void killTask(ExecutorDriver driver, Protos.TaskID taskId) { } @Override public void frameworkMessage(ExecutorDriver driver, byte[] data) { } @Override public void shutdown(ExecutorDriver driver) { } @Override public void error(ExecutorDriver driver, String message) { } public static void main(String[] args) { MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor()); System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1); } }
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\mesos\executors\HelloWorldExecutor.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Notiz. @param Note Optional additional user defined information */ @Override public void setNote (java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Notiz. @return Optional additional user defined information */ @Override public java.lang.String getNote () { return (java.lang.String)get_Value(COLUMNNAME_Note); } /** Set Notiz Header. @param NoteHeader Optional weitere Information für ein Dokument */ @Override public void setNoteHeader (java.lang.String NoteHeader) {
set_Value (COLUMNNAME_NoteHeader, NoteHeader); } /** Get Notiz Header. @return Optional weitere Information für ein Dokument */ @Override public java.lang.String getNoteHeader () { return (java.lang.String)get_Value(COLUMNNAME_NoteHeader); } /** Set Drucktext. @param PrintName The label text to be printed on a document or correspondence. */ @Override public void setPrintName (java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } /** Get Drucktext. @return The label text to be printed on a document or correspondence. */ @Override public java.lang.String getPrintName () { return (java.lang.String)get_Value(COLUMNNAME_PrintName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningLevel.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Authentication Token. @param AuthToken Authentication Token */ @Override public void setAuthToken (java.lang.String AuthToken) { set_Value (COLUMNNAME_AuthToken, AuthToken); } /** Get Authentication Token. @return Authentication Token */ @Override public java.lang.String getAuthToken () { return (java.lang.String)get_Value(COLUMNNAME_AuthToken);
} /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_AuthToken.java
1
请完成以下Java代码
public class MHRMovement extends X_HR_Movement { /** * */ private static final long serialVersionUID = 6705848510397126140L; /** * Standard Constructor * @param ctx context * @param HR_Concept_ID * @param trxName */ public MHRMovement (Properties ctx, int HR_Movement_ID, String trxName) { super (ctx, HR_Movement_ID, trxName); } /** * Load Constructor * @param ctx context * @param rs result set * @param trxName */ public MHRMovement (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } public MHRMovement (MHRProcess proc, I_HR_Concept concept) { this(proc.getCtx(), 0, proc.get_TrxName()); // Process this.setHR_Process_ID(proc.getHR_Process_ID()); // Concept this.setHR_Concept_Category_ID(concept.getHR_Concept_Category_ID()); this.setHR_Concept_ID(concept.getHR_Concept_ID()); this.setColumnType(concept.getColumnType()); } public void addAmount(BigDecimal amount) { setAmount(getAmount().add(amount == null ? Env.ZERO : amount)); } public void addQty(BigDecimal qty) { setQty(getAmount().add(qty == null ? Env.ZERO : qty)); } /**
* @return true if all movement values (Amount, Qty, Text) are empty */ public boolean isEmpty() { return getQty().signum() == 0 && getAmount().signum() == 0 && Check.isEmpty(getTextMsg()); } /** * According to the concept type, it's saved in the column specified for the purpose * @param columnType column type (see MHRConcept.COLUMNTYPE_*) * @param value */ public void setColumnValue(Object value) { final String columnType = getColumnType(); if (MHRConcept.COLUMNTYPE_Quantity.equals(columnType)) { BigDecimal qty = new BigDecimal(value.toString()); setQty(qty); setAmount(Env.ZERO); } else if(MHRConcept.COLUMNTYPE_Amount.equals(columnType)) { BigDecimal amount = new BigDecimal(value.toString()); setAmount(amount); setQty(Env.ZERO); } else if(MHRConcept.COLUMNTYPE_Text.equals(columnType)) { setTextMsg(value.toString().trim()); } else if(MHRConcept.COLUMNTYPE_Date.equals(columnType)) { if (value instanceof Timestamp) { setServiceDate((Timestamp)value); } else { setServiceDate(Timestamp.valueOf(value.toString().trim().substring(0, 10)+ " 00:00:00.0")); } } else { throw new AdempiereException("@NotSupported@ @ColumnType@ - "+columnType); } } } // HRMovement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRMovement.java
1
请完成以下Java代码
public void setClusterNodes(String clusterNodes) { this.clusterNodes = ClusterNodes.of(clusterNodes); } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setClientTransportSniff(Boolean clientTransportSniff) { this.clientTransportSniff = clientTransportSniff; } public String getClientNodesSamplerInterval() { return clientNodesSamplerInterval; } public void setClientNodesSamplerInterval(String clientNodesSamplerInterval) { this.clientNodesSamplerInterval = clientNodesSamplerInterval; }
public String getClientPingTimeout() { return clientPingTimeout; } public void setClientPingTimeout(String clientPingTimeout) { this.clientPingTimeout = clientPingTimeout; } public Boolean getClientIgnoreClusterName() { return clientIgnoreClusterName; } public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) { this.clientIgnoreClusterName = clientIgnoreClusterName; } public void setProperties(Properties properties) { this.properties = properties; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-elasticsearch\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\spring\TracingTransportClientFactoryBean.java
1
请完成以下Java代码
public void setM_HU_PI_Item_Product_ID(final int piItemProductId) { setPiItemProductId(HUPIItemProductId.ofRepoIdOrNull(piItemProductId)); } @Override @Deprecated public int getM_AttributeSetInstance_ID() { return AttributeSetInstanceId.toRepoId(getAsiId()); } @Override @Deprecated public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { setAsiId(AttributeSetInstanceId.ofRepoIdOrNull(M_AttributeSetInstance_ID)); } @Override @Deprecated public int getC_BPartner_ID() { return BPartnerId.toRepoId(getBpartnerId());
} @Override @Deprecated public void setC_BPartner_ID(final int bpartnerId) { setBpartnerId(BPartnerId.ofRepoIdOrNull(bpartnerId)); } @Override public Optional<BigDecimal> getQtyCUsPerTU() { return Optional.ofNullable(qtyCUsPerTU); } @Override public void setQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { this.qtyCUsPerTU = qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\PlainHUPackingAware.java
1
请完成以下Java代码
public class DeliveryDayAllocableInterceptor extends AbstractModelInterceptor { private final IDeliveryDayCreateHandler handler; private final String modelTableName; public DeliveryDayAllocableInterceptor(@NonNull final IDeliveryDayCreateHandler handler) { this.handler = handler; this.modelTableName = handler.getModelTableName(); Check.assumeNotNull(modelTableName, "modelTableName not null"); } @Override public String toString() { return "DeliveryDayAllocableInterceptor [modelTableName=" + modelTableName + ", handler=" + handler + "]"; } public final String getModelTableName() { return modelTableName; } @Override protected void onInit(final IModelValidationEngine engine, final I_AD_Client client) { engine.addModelChange(modelTableName, this); } @Override public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception { if (!changeType.isAfter()) { return; } // // Model was created on changed if (changeType.isNewOrChange()) { createOrUpdateAllocation(model); } // // Model was deleted else if (changeType.isDelete()) { deleteAllocation(model); }
} private void createOrUpdateAllocation(final Object model) { final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable); if (deliveryDayAlloc == null) { // Case: no delivery day allocation was found and no delivery day on which we could allocate was found return; } deliveryDayBL.getDeliveryDayHandlers() .updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable); InterfaceWrapperHelper.save(deliveryDayAlloc); } private void deleteAllocation(Object model) { final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayDAO.retrieveDeliveryDayAllocForModel(context, deliveryDayAllocable); if (deliveryDayAlloc != null) { InterfaceWrapperHelper.delete(deliveryDayAlloc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\DeliveryDayAllocableInterceptor.java
1
请完成以下Java代码
private static class ShipmentCandidateExportException extends AdempiereException { public ShipmentCandidateExportException(final String message) { super(message); } } private void setAdditionalContactFields( @NonNull final JsonCustomerBuilder customerBuilder, @NonNull final OrderAndLineId orderAndLineId) { final I_C_Order orderRecord = orderDAO.getById(orderAndLineId.getOrderId()); customerBuilder .contactEmail(orderRecord.getEMail()) .contactName(orderRecord.getBPartnerName()) .contactPhone(orderRecord.getPhone()); logger.debug("Exporting effective contactEmail={}, contactName={}, contactPhone={} from the orderId={}", orderRecord.getEMail(), orderRecord.getBPartnerName(), orderRecord.getPhone(), orderAndLineId.getOrderId()); } private void setAdditionalContactFields( @NonNull final JsonCustomerBuilder customerBuilder, @NonNull final BPartnerLocation bPartnerLocation) { customerBuilder .contactEmail(bPartnerLocation.getEmail()) .contactName(bPartnerLocation.getBpartnerName()) .contactPhone(bPartnerLocation.getPhone()); logger.debug("Exporting effective contactEmail={}, contactName={}, contactPhone={} from the bPartnerLocationId={}",
bPartnerLocation.getEmail(), bPartnerLocation.getBpartnerName(), bPartnerLocation.getPhone(), bPartnerLocation.getId()); } private void setAdditionalContactFieldsForOxidOrder( @NonNull final ShipmentSchedule shipmentSchedule, @NonNull final BPartnerComposite composite, @NonNull final JsonCustomerBuilder customerBuilder, @Nullable final BPartnerContactId contactId) { if (contactId == null) { return; } final BPartnerContact contact = composite.extractContact(contactId) .orElseThrow(() -> new ShipmentCandidateExportException("Unable to get the contact info from bPartnerComposite!") .appendParametersToMessage() .setParameter("composite.C_BPartner_ID", composite.getBpartner().getId()) .setParameter("AD_User_ID", contactId)); customerBuilder .contactEmail(oxidAdaptor.getContactEmail(shipmentSchedule, composite)) .contactName(contact.getName()) .contactPhone(contact.getPhone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\ShipmentCandidateAPIService.java
1
请完成以下Java代码
public class DeltaLake { public static SparkSession createSession() { return SparkSession.builder() .appName("DeltaLake") .master("local[*]") .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") .getOrCreate(); } public static String preparePeopleTable(SparkSession spark) { try { String tablePath = Files.createTempDirectory("delta-table-").toAbsolutePath().toString(); Dataset<Row> data = spark.createDataFrame( java.util.Arrays.asList( new Person(1, "Alice"), new Person(2, "Bob") ), Person.class ); data.write().format("delta").mode("overwrite").save(tablePath); spark.sql("DROP TABLE IF EXISTS people"); spark.sql("CREATE TABLE IF NOT EXISTS people USING DELTA LOCATION '" + tablePath + "'"); return tablePath; } catch (Exception e) { throw new RuntimeException(e); } } public static void cleanupPeopleTable(SparkSession spark) { spark.sql("DROP TABLE IF EXISTS people"); } public static void stopSession(SparkSession spark) { if (spark != null) {
spark.stop(); } } public static class Person implements Serializable { private int id; private String name; public Person() {} public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
repos\tutorials-master\apache-spark-2\src\main\java\com\baeldung\delta\DeltaLake.java
1
请完成以下Java代码
private void onInvoke() { final long millisNow = SystemTime.millis(); intervalLastInvoke = new BigDecimal(millisNow - millisLastInvoke.get()); millisLastInvoke.set(millisNow); invokeCount.addAndGet(1); updateInvokeRate(); } private void updateInvokeRate() { // getting local copies to ensure that the values we work with aren't changed by other threads // while this method executes final BigDecimal intervalLastInvokeLocal = this.intervalLastInvoke; final long invokeCountLocal = invokeCount.get(); if (invokeCountLocal < 2) { // need at least two 'plusOne()' invocations to get a rate invokeRate = BigDecimal.ZERO; } else if (intervalLastInvokeLocal.signum() == 0) { // omit division by zero invokeRate = new BigDecimal(Long.MAX_VALUE); } else { invokeRate = new BigDecimal("1000") .setScale(2, BigDecimal.ROUND_HALF_UP) .divide(intervalLastInvokeLocal, RoundingMode.HALF_UP) .abs(); // be tolerant against intervalLastChange < 0 } }
@Override public long getInvokeCount() { return invokeCount.get(); } @Override public BigDecimal getInvokeRate() { return invokeRate; } @Override public long getGauge() { return gauge.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\api\impl\Meter.java
1
请完成以下Java代码
public class CoNllLine { /** * 十个值 */ public String[] value = new String[10]; /** * 第一个值化为id */ public int id; public CoNllLine(String... args) { int length = Math.min(args.length, value.length); for (int i = 0; i < length; ++i) {
value[i] = args[i]; } id = Integer.parseInt(value[0]); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); for (String value : this.value) { sb.append(value); sb.append('\t'); } return sb.deleteCharAt(sb.length() - 1).toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\CoNllLine.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthInitResultVo implements Serializable { private static final long serialVersionUID = 3312403855750120397L; /** * 订单金额 */ private BigDecimal orderAmount; /** * 产品名称 */ private String productName; /** * 商户名称 */ private String merchantName; /** * 商户号 */ private String merchantNo; /** * 商户订单号 */ private String merchantOrderNo; /** * */ private String payKey; /** * 支付方式列表 */ private Map<String, PayTypeEnum> payTypeEnumMap; /** * 订单状态 */ private TradeStatusEnum tradeStatus = TradeStatusEnum.WAITING_PAYMENT; /** * 是否鉴权 */ private boolean isAuth = false; public BigDecimal getOrderAmount() { return orderAmount; } public void setOrderAmount(BigDecimal orderAmount) { this.orderAmount = orderAmount; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getMerchantName() { return merchantName;
} public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public String getMerchantNo() { return merchantNo; } public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo; } public String getMerchantOrderNo() { return merchantOrderNo; } public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo; } public String getPayKey() { return payKey; } public void setPayKey(String payKey) { this.payKey = payKey; } public TradeStatusEnum getTradeStatus() { return tradeStatus; } public void setTradeStatus(TradeStatusEnum tradeStatus) { this.tradeStatus = tradeStatus; } public boolean isAuth() { return isAuth; } public void setAuth(boolean auth) { isAuth = auth; } public Map<String, PayTypeEnum> getPayTypeEnumMap() { return payTypeEnumMap; } public void setPayTypeEnumMap(Map<String, PayTypeEnum> payTypeEnumMap) { this.payTypeEnumMap = payTypeEnumMap; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthInitResultVo.java
2
请完成以下Java代码
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { log.info("服务器收到消息:{}", msg.text()); // 获取用户ID,关联channel JSONObject jsonObject = JSONUtil.parseObj(msg.text()); String uid = jsonObject.getStr("uid"); NettyConfig.getChannelMap().put(uid, ctx.channel()); // 将用户ID作为自定义属性加入到channel中,方便随时channel中获取用户ID AttributeKey<String> key = AttributeKey.valueOf("userId"); ctx.channel().attr(key).setIfAbsent(uid); // 回复消息 ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器收到消息啦")); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { log.info("用户下线了:{}", ctx.channel().id().asLongText()); // 删除通道 NettyConfig.getChannelGroup().remove(ctx.channel()); removeUserId(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.info("异常:{}", cause.getMessage());
// 删除通道 NettyConfig.getChannelGroup().remove(ctx.channel()); removeUserId(ctx); ctx.close(); } /** * 删除用户与channel的对应关系 */ private void removeUserId(ChannelHandlerContext ctx) { AttributeKey<String> key = AttributeKey.valueOf("userId"); String userId = ctx.channel().attr(key).get(); NettyConfig.getChannelMap().remove(userId); } }
repos\springboot-demo-master\netty\src\main\java\com\et\netty\handler\WebSocketHandler.java
1
请完成以下Java代码
public class OptionalToArrayListConverter { public static List<String> usingIfPresent(Optional<String> obj) { List<String> arrayList = new ArrayList<>(); obj.ifPresent(arrayList::add); return arrayList; } public static List<String> usingOrElse(Optional<String> obj) { List<String> arrayList = new ArrayList<>(); arrayList.add(obj.orElse("Hello, World!")); return arrayList; } public static List<String> usingOrElseGet(Optional<String> obj) { List<String> arrayList = new ArrayList<>(); arrayList.add(obj.orElseGet(() -> "Hello, World!")); return arrayList; } public static List<String> usingStream(Optional<String> obj) { List<String> arrayList = obj.stream() .collect(Collectors.toList()); return arrayList;
} public static List<String> usingStreamFilter(Optional<String> obj) { List<String> arrayList = obj.filter(e -> e.startsWith("H")) .stream() .collect(Collectors.toList()); return arrayList; } public static List<String> usingStreamFlatMap(Optional<List<String>> obj) { List<String> arrayList = obj.stream() .flatMap(List::stream) .collect(Collectors.toList()); return arrayList; } }
repos\tutorials-master\core-java-modules\core-java-collections-conversions-3\src\main\java\com\baeldung\optionaltoarraylist\OptionalToArrayListConverter.java
1
请完成以下Java代码
public X509Certificate signCSR(PKCS10CertificationRequest inputCSR, PrivateKey caPrivate, KeyPair pair) throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder() .find(sigAlgId); AsymmetricKeyParameter foo = PrivateKeyFactory.createKey(caPrivate .getEncoded()); SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pair .getPublic().getEncoded()); X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder( new X500Name("CN=issuer"), new BigInteger("1"), new Date( System.currentTimeMillis()), new Date( System.currentTimeMillis() + 30L * 365 * 24 * 60 * 60 * 1000), inputCSR.getSubject(), keyInfo); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(foo); X509CertificateHolder holder = myCertificateGenerator.build(sigGen); Certificate eeX509CertificateStructure = holder.toASN1Structure(); CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded()); X509Certificate theCert = (X509Certificate) cf.generateCertificate(is1);
is1.close(); return theCert; } public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair(); } public static PKCS10CertificationRequest generateCSR(KeyPair pair) throws OperatorCreationException { PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder( new X500Principal("CN=Requested Test Certificate"), pair.getPublic()); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(pair.getPrivate()); return p10Builder.build(signer); } }
repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\bouncycastle\SignCSRBouncyCastle.java
1
请完成以下Java代码
protected UserDetails loadUserDetails(final Assertion assertion) { List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String attribute : this.attributes) { Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value != null) { if (value instanceof List) { for (Object o : (List<?>) value) { grantedAuthorities.add(createSimpleGrantedAuthority(o)); } } else { grantedAuthorities.add(createSimpleGrantedAuthority(value)); } } } return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities);
} private SimpleGrantedAuthority createSimpleGrantedAuthority(Object o) { return new SimpleGrantedAuthority( this.convertToUpperCase ? o.toString().toUpperCase(Locale.ROOT) : o.toString()); } /** * Converts the returned attribute values to uppercase values. * @param convertToUpperCase true if it should convert, false otherwise. */ public void setConvertToUpperCase(final boolean convertToUpperCase) { this.convertToUpperCase = convertToUpperCase; } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\userdetails\GrantedAuthorityFromAssertionAttributesUserDetailsService.java
1
请在Spring Boot框架中完成以下Java代码
public class SpelLogical { @Value("#{250 > 200 && 200 < 4000}") private boolean and; @Value("#{250 > 200 and 200 < 4000}") private boolean andAlphabetic; @Value("#{400 > 300 || 150 < 100}") private boolean or; @Value("#{400 > 300 or 150 < 100}") private boolean orAlphabetic; @Value("#{!true}") private boolean not; @Value("#{not true}") private boolean notAlphabetic; public boolean isAnd() { return and; } public void setAnd(boolean and) { this.and = and; } public boolean isAndAlphabetic() { return andAlphabetic; } public void setAndAlphabetic(boolean andAlphabetic) { this.andAlphabetic = andAlphabetic; } public boolean isOr() { return or; } public void setOr(boolean or) { this.or = or; } public boolean isOrAlphabetic() { return orAlphabetic;
} public void setOrAlphabetic(boolean orAlphabetic) { this.orAlphabetic = orAlphabetic; } public boolean isNot() { return not; } public void setNot(boolean not) { this.not = not; } public boolean isNotAlphabetic() { return notAlphabetic; } public void setNotAlphabetic(boolean notAlphabetic) { this.notAlphabetic = notAlphabetic; } @Override public String toString() { return "SpelLogical{" + "and=" + and + ", andAlphabetic=" + andAlphabetic + ", or=" + or + ", orAlphabetic=" + orAlphabetic + ", not=" + not + ", notAlphabetic=" + notAlphabetic + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelLogical.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests(authorize -> authorize.antMatchers("/index", "/login") .permitAll() .antMatchers("/home", "/logout") .authenticated() .antMatchers("/admin/**") .hasRole("ADMIN")) .formLogin(formLogin -> formLogin.loginPage("/login") .failureUrl("/login-error")); return http.build(); } @Bean public InMemoryUserDetailsManager userDetailsService() throws Exception { UserDetails jerry = User.withUsername("Jerry") .password(passwordEncoder().encode("password"))
.authorities("READ", "WRITE") .roles("ADMIN") .build(); UserDetails tom = User.withUsername("Tom") .password(passwordEncoder().encode("password")) .authorities("READ") .roles("USER") .build(); return new InMemoryUserDetailsManager(jerry, tom); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\springsecurity\config\SecurityConfig.java
2
请完成以下Java代码
/* package */ final class ConstantTranslatableString implements ITranslatableString { @NonNull static ConstantTranslatableString of(@Nullable final String value) { final boolean anyLanguage = false; return of(value, anyLanguage); } @NonNull static ITranslatableString anyLanguage(@Nullable final String value) { final boolean anyLanguage = true; return of(value, anyLanguage); } @NonNull static ConstantTranslatableString of(@Nullable final String value, final boolean anyLanguage) { if (value == null || value.isEmpty()) { return EMPTY; } else if (" ".equals(value)) { return SPACE; } else { return new ConstantTranslatableString(value, anyLanguage); } } static final ConstantTranslatableString EMPTY = new ConstantTranslatableString("", true); private static final ConstantTranslatableString SPACE = new ConstantTranslatableString(" ", true); private final String value; private final boolean anyLanguage; private ConstantTranslatableString(@NonNull final String value, final boolean anyLanguage) {
this.value = value; this.anyLanguage = anyLanguage; } @Override @Deprecated public String toString() { return value; } @Override public String translate(final String adLanguage) { return value; } @Override public String getDefaultValue() { return value; } @Override public Set<String> getAD_Languages() { return ImmutableSet.of(); } @Override public boolean isTranslatedTo(final String adLanguage) { return anyLanguage; } @JsonIgnore // needed for snapshot testing public boolean isEmpty() {return value.isEmpty();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ConstantTranslatableString.java
1
请在Spring Boot框架中完成以下Java代码
public class GetStudentDetailsResponse { @XmlElement(name = "StudentDetails", required = true) protected StudentDetails studentDetails; /** * Gets the value of the studentDetails property. * * @return * possible object is * {@link StudentDetails } * */ public StudentDetails getStudentDetails() { return studentDetails;
} /** * Sets the value of the studentDetails property. * * @param value * allowed object is * {@link StudentDetails } * */ public void setStudentDetails(StudentDetails value) { this.studentDetails = value; } }
repos\spring-boot-examples-master\spring-boot-tutorial-soap-web-services\src\main\java\com\in28minutes\students\GetStudentDetailsResponse.java
2
请在Spring Boot框架中完成以下Java代码
public DateSequenceGenerator createDateSequenceGenerator( @NonNull final PhonecallSchemaVersion schemaVersion, @NonNull final LocalDate validFrom, @NonNull final LocalDate validTo) { final Frequency frequency = schemaVersion.getFrequency(); if (frequency == null) { return null; } final OnNonBussinessDay onNonBusinessDay = schemaRepo.extractOnNonBussinessDayOrNull(schemaVersion); return DateSequenceGenerator.builder() .dateFrom(validFrom) .dateTo(validTo) .shifter(createDateShifter(frequency, onNonBusinessDay)) .frequency(frequency) .build(); } private static IDateShifter createDateShifter(final Frequency frequency, final OnNonBussinessDay onNonBusinessDay) { final IBusinessDayMatcher businessDayMatcher = createBusinessDayMatcher(frequency, onNonBusinessDay); return BusinessDayShifter.builder() .businessDayMatcher(businessDayMatcher) .onNonBussinessDay(onNonBusinessDay != null ? onNonBusinessDay : OnNonBussinessDay.Cancel) .build(); } public static IBusinessDayMatcher createBusinessDayMatcher(final Frequency frequency, final OnNonBussinessDay onNonBusinessDay) {
final ICalendarBL calendarBL = Services.get(ICalendarBL.class); // // If user explicitly asked for a set of week days, don't consider them non-business days by default if (frequency.isWeekly() && frequency.isOnlySomeDaysOfTheWeek() && onNonBusinessDay == null) { return calendarBL.createBusinessDayMatcherExcluding(frequency.getOnlyDaysOfWeek()); } else { return calendarBL.createBusinessDayMatcherExcluding(ImmutableSet.of()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\service\PhonecallScheduleService.java
2
请完成以下Java代码
protected String stripBpmnFileSuffix(String bpmnFileResource) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (bpmnFileResource.endsWith(suffix)) { return bpmnFileResource.substring(0, bpmnFileResource.length() - suffix.length()); } } return bpmnFileResource; } protected void createResource(String name, byte[] bytes, DeploymentEntity deploymentEntity) { ResourceEntity resource = new ResourceEntity(); resource.setName(name); resource.setBytes(bytes); resource.setDeploymentId(deploymentEntity.getId()); // Mark the resource as 'generated' resource.setGenerated(true); Context .getCommandContext() .getDbSqlSession() .insert(resource); } protected boolean isBpmnResource(String resourceName) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (resourceName.endsWith(suffix)) { return true; } } return false; } public ExpressionManager getExpressionManager() {
return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请完成以下Java代码
public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Role Notification Group. @param AD_Role_NotificationGroup_ID Role Notification Group */ @Override public void setAD_Role_NotificationGroup_ID (int AD_Role_NotificationGroup_ID) { if (AD_Role_NotificationGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Role_NotificationGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_NotificationGroup_ID, Integer.valueOf(AD_Role_NotificationGroup_ID)); } /** Get Role Notification Group. @return Role Notification Group */ @Override public int getAD_Role_NotificationGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_NotificationGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * NotificationType AD_Reference_ID=344
* Reference name: AD_User NotificationType */ public static final int NOTIFICATIONTYPE_AD_Reference_ID=344; /** EMail = E */ public static final String NOTIFICATIONTYPE_EMail = "E"; /** Notice = N */ public static final String NOTIFICATIONTYPE_Notice = "N"; /** None = X */ public static final String NOTIFICATIONTYPE_None = "X"; /** EMailPlusNotice = B */ public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B"; /** NotifyUserInCharge = O */ public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O"; /** Set Benachrichtigungs-Art. @param NotificationType Art der Benachrichtigung */ @Override public void setNotificationType (java.lang.String NotificationType) { set_Value (COLUMNNAME_NotificationType, NotificationType); } /** Get Benachrichtigungs-Art. @return Art der Benachrichtigung */ @Override public java.lang.String getNotificationType () { return (java.lang.String)get_Value(COLUMNNAME_NotificationType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_NotificationGroup.java
1
请完成以下Java代码
public void setOnSaturday (boolean OnSaturday) { set_Value (COLUMNNAME_OnSaturday, Boolean.valueOf(OnSaturday)); } /** Get Samstag. @return Samstags verfügbar */ @Override public boolean isOnSaturday () { Object oo = get_Value(COLUMNNAME_OnSaturday); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sonntag. @param OnSunday Sonntags verfügbar */ @Override public void setOnSunday (boolean OnSunday) { set_Value (COLUMNNAME_OnSunday, Boolean.valueOf(OnSunday)); } /** Get Sonntag. @return Sonntags verfügbar */ @Override public boolean isOnSunday () { Object oo = get_Value(COLUMNNAME_OnSunday); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Donnerstag. @param OnThursday Donnerstags verfügbar */ @Override public void setOnThursday (boolean OnThursday) { set_Value (COLUMNNAME_OnThursday, Boolean.valueOf(OnThursday)); } /** Get Donnerstag. @return Donnerstags verfügbar */ @Override public boolean isOnThursday () { Object oo = get_Value(COLUMNNAME_OnThursday); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Dienstag. @param OnTuesday Dienstags verfügbar */ @Override public void setOnTuesday (boolean OnTuesday) { set_Value (COLUMNNAME_OnTuesday, Boolean.valueOf(OnTuesday)); } /** Get Dienstag. @return Dienstags verfügbar */ @Override public boolean isOnTuesday () { Object oo = get_Value(COLUMNNAME_OnTuesday); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set Mittwoch. @param OnWednesday Mittwochs verfügbar */ @Override public void setOnWednesday (boolean OnWednesday) { set_Value (COLUMNNAME_OnWednesday, Boolean.valueOf(OnWednesday)); } /** Get Mittwoch. @return Mittwochs verfügbar */ @Override public boolean isOnWednesday () { Object oo = get_Value(COLUMNNAME_OnWednesday); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schema_Version.java
1
请完成以下Java代码
public abstract class FeatureMap implements IStringIdMap, ICacheAble { public abstract int size(); public int[] allLabels() { return tagSet.allTags(); } public int bosTag() { return tagSet.size(); } public TagSet tagSet; /** * 是否允许新增特征 */ public boolean mutable; public FeatureMap(TagSet tagSet) { this(tagSet, false); } public FeatureMap(TagSet tagSet, boolean mutable) { this.tagSet = tagSet; this.mutable = mutable; } public abstract Set<Map.Entry<String, Integer>> entrySet(); public FeatureMap(boolean mutable) { this.mutable = mutable; } public FeatureMap() { this(false); } @Override public void save(DataOutputStream out) throws IOException { tagSet.save(out); out.writeInt(size()); for (Map.Entry<String, Integer> entry : entrySet()) { out.writeUTF(entry.getKey()); } }
@Override public boolean load(ByteArray byteArray) { loadTagSet(byteArray); int size = byteArray.nextInt(); for (int i = 0; i < size; i++) { idOf(byteArray.nextUTF()); } return true; } protected final void loadTagSet(ByteArray byteArray) { TaskType type = TaskType.values()[byteArray.nextInt()]; switch (type) { case CWS: tagSet = new CWSTagSet(); break; case POS: tagSet = new POSTagSet(); break; case NER: tagSet = new NERTagSet(); break; case CLASSIFICATION: tagSet = new TagSet(TaskType.CLASSIFICATION); break; } tagSet.load(byteArray); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\FeatureMap.java
1
请完成以下Java代码
public void onSearch(boolean triggeredFromSearchField) { if (triggeredFromSearchField && findPanel.getTotalRecords() <= 0) { return; } dispose(); }; @Override public void onCancel() { dispose(); }; @Override public void onOpenAsNewRecord() { dispose(); }; }; Find(final FindPanelBuilder builder) { super(builder.getParentFrame(), Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Find") + ": " + builder.getTitle(), true // modal=true ); findPanel = builder.buildFindPanel(); // metas: tsa: begin if (findPanel.isDisposed()) { this.dispose(); return; } findPanel.setActionListener(findPanelActionListener); // Set panel size // NOTE: we are setting such a big width because the table from advanced panel shall be displayed nicely. final int findPanelHeight = AdempierePLAF.getInt(FindPanelUI.KEY_Dialog_Height, FindPanelUI.DEFAULT_Dialog_Height); findPanel.setPreferredSize(new Dimension(950, findPanelHeight)); setIconImage(Images.getImage2("Find24")); this.setContentPane(findPanel); // teo_sarca, [ 1670847 ] Find dialog: closing and canceling need same // functionality this.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { findPanel.requestFocus(); } @Override public void windowClosing(WindowEvent e) { findPanel.doCancel();
} }); AEnv.showCenterWindow(builder.getParentFrame(), this); } // Find @Override public void dispose() { findPanel.dispose(); removeAll(); super.dispose(); } // dispose /************************************************************************** * Get Query - Retrieve result * * @return String representation of query */ public MQuery getQuery() { return findPanel.getQuery(); } // getQuery /** * @return true if cancel button pressed */ public boolean isCancel() { return findPanel.isCancel(); } } // Find
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\Find.java
1
请完成以下Java代码
protected void prepareSocket(SSLSocket socket) { String hostname = socket.getInetAddress() .getHostName(); if (hostname.endsWith("internal.system.com")) { socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }); } else { socket.setEnabledProtocols(new String[] { "TLSv1.3" }); } } }; HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(sslsf) .build(); return HttpClients.custom() .setConnectionManager(connManager) .build(); } // To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar public static CloseableHttpClient setViaSystemProperties() { return HttpClients.createSystem(); // Alternatively: //return HttpClients.custom().useSystemProperties().build(); } public static void main(String[] args) throws IOException { try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } } }
repos\tutorials-master\apache-httpclient-2\src\main\java\com\baeldung\tlsversion\ClientTlsVersionExamples.java
1
请完成以下Java代码
public final Border getBorder(final String name, final Border defaultBorder) { Border border = UIManager.getBorder(buildUIDefaultsKey(name)); if (border == null && uiSubClassID != null) { border = UIManager.getBorder(name); } if (border == null) { border = defaultBorder; } return border; } private final String buildUIDefaultsKey(final String name) { return buildUIDefaultsKey(uiSubClassID, name); } private static final String buildUIDefaultsKey(final String uiSubClassID, final String name) { if (uiSubClassID == null) { return name; } else { return uiSubClassID + "." + name; } } public boolean getBoolean(final String name, final boolean defaultValue) { Object value = UIManager.getDefaults().get(buildUIDefaultsKey(name)); if (value instanceof Boolean) { return (boolean)value; } if (uiSubClassID != null) { value = UIManager.getDefaults().get(name); if (value instanceof Boolean) { return (boolean)value; } } return defaultValue; } /** * Convert all keys from given UI defaults key-value list by applying the <code>uiSubClassID</code> prefix to them. * * @param uiSubClassID * @param keyValueList
* @return converted <code>keyValueList</code> */ public static final Object[] applyUISubClassID(final String uiSubClassID, final Object[] keyValueList) { if (keyValueList == null || keyValueList.length <= 0) { return keyValueList; } Check.assumeNotEmpty(uiSubClassID, "uiSubClassID not empty"); final Object[] keyValueListConverted = new Object[keyValueList.length]; for (int i = 0, max = keyValueList.length; i < max; i += 2) { final Object keyOrig = keyValueList[i]; final Object value = keyValueList[i + 1]; final Object key; if (keyOrig instanceof String) { key = buildUIDefaultsKey(uiSubClassID, (String)keyOrig); } else { key = keyOrig; } keyValueListConverted[i] = key; keyValueListConverted[i + 1] = value; } return keyValueListConverted; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UISubClassIDHelper.java
1
请完成以下Java代码
private static void errorIfQueryValueNotEmpty( @NonNull final String field, @Nullable final Collection<?> value, @NonNull final HUTraceEventQuery query) { if (!Check.isEmpty(value)) { final String message = StringUtils.formatMessage("The given HUTraceEventQuery already has {}={}", field, value); throw new AdempiereException(message).setParameter("HUTraceEventQuery", query); } } private static void errorIfQueryValueNotNull( @NonNull final String field, final Object value, @NonNull final HUTraceEventQuery query) { if (value != null) { final String message = StringUtils.formatMessage("The given HUTraceEventQuery already has {}={}", field, value); throw new AdempiereException(message).setParameter("HUTraceEventQuery", query); } } private static void errorfIfNotEqualsOperator(@NonNull final DocumentFilterParam parameter) { if (!Operator.EQUAL.equals(parameter.getOperator())) { final String message = StringUtils.formatMessage("The given DocumentFilterParam needs to have an EQUAL operator, but has {}", parameter.getOperator()); throw new AdempiereException(message).setParameter("DocumentFilterParam", parameter); } } private static HuId extractHuId(@NonNull final DocumentFilterParam parameter) { return HuId.ofRepoIdOrNull(extractInt(parameter)); } private static ImmutableSet<HuId> extractHuIds(@NonNull final DocumentFilterParam parameter) { final HuId huId = extractHuId(parameter); return huId != null ? ImmutableSet.of(huId) : ImmutableSet.of(); } private static int extractInt(@NonNull final DocumentFilterParam parameter) { final Object value = Check.assumeNotNull(parameter.getValue(), "Given paramter may not have a null value; parameter={}", parameter); if (value instanceof LookupValue) { final LookupValue lookupValue = (LookupValue)value; return lookupValue.getIdAsInt(); } else if (value instanceof Integer)
{ return (Integer)value; } else { throw new AdempiereException("Unable to extract an integer ID from parameter=" + parameter); } } private static String extractString(@NonNull final DocumentFilterParam parameter) { final Object value = Check.assumeNotNull(parameter.getValue(), "Given paramter may not have a null value; parameter={}", parameter); if (value instanceof LookupValue) { final LookupValue lookupValue = (LookupValue)value; return lookupValue.getIdAsString(); } else if (value instanceof String) { return (String)value; } throw Check.fail("Unable to extract a String from parameter={}", parameter); } private static Boolean extractBoolean(@NonNull final DocumentFilterParam parameter) { final Object value = Check.assumeNotNull(parameter.getValue(), "Given parameter may not have a null value; parameter={}", parameter); if (value instanceof Boolean) { return (Boolean)value; } throw Check.fail("Unable to extract a Boolean from parameter={}", parameter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\trace\HuTraceQueryCreator.java
1
请完成以下Java代码
public static <T> Optional<QtyAvailableStatus> computeOfLines( @NonNull final Collection<T> lines, @NonNull final Function<T, QtyAvailableStatus> getStatusFunc) { if (lines.isEmpty()) { return Optional.empty(); } boolean hasNotAvailableProducts = false; boolean hasFullyAvailableProducts = false; for (final T line : lines) { @Nullable final QtyAvailableStatus lineStatus = getStatusFunc.apply(line); if (lineStatus == null) { return Optional.empty(); } switch (lineStatus) { case NOT_AVAILABLE: hasNotAvailableProducts = true; break;
case PARTIALLY_AVAILABLE: return Optional.of(QtyAvailableStatus.PARTIALLY_AVAILABLE); case FULLY_AVAILABLE: hasFullyAvailableProducts = true; break; default: throw new AdempiereException("Unknown QtyAvailableStatus: " + lineStatus); } } if (hasFullyAvailableProducts) { return hasNotAvailableProducts ? Optional.of(QtyAvailableStatus.PARTIALLY_AVAILABLE) : Optional.of(QtyAvailableStatus.FULLY_AVAILABLE); } else { return Optional.of(QtyAvailableStatus.NOT_AVAILABLE); } } public boolean isPartialOrFullyAvailable() {return this == PARTIALLY_AVAILABLE || this == FULLY_AVAILABLE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\QtyAvailableStatus.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Item getM_HU_Item() { return get_ValueAsPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class); } @Override public void setM_HU_Item(final de.metas.handlingunits.model.I_M_HU_Item M_HU_Item) { set_ValueFromPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, M_HU_Item); } @Override public void setM_HU_Item_ID (final int M_HU_Item_ID) { if (M_HU_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, M_HU_Item_ID); } @Override public int getM_HU_Item_ID()
{ return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID); } @Override public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID) { if (M_HU_Item_Storage_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID); } @Override public int getM_HU_Item_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); 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_Item_Storage.java
1
请完成以下Java代码
public class PortScanner { private static final int poolSize = 10; private static final int timeOut = 200; public void runPortScan(String ip, int nbrPortMaxToScan) throws IOException { ConcurrentLinkedQueue openPorts = new ConcurrentLinkedQueue<>(); ExecutorService executorService = Executors.newFixedThreadPool(poolSize); AtomicInteger port = new AtomicInteger(0); while (port.get() < nbrPortMaxToScan) { final int currentPort = port.getAndIncrement(); executorService.submit(() -> { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(ip, currentPort), timeOut); socket.close(); openPorts.add(currentPort); System.out.println(ip + " ,port open: " + currentPort); } catch (IOException e) { // System.err.println(e); } }); } executorService.shutdown();
try { executorService.awaitTermination(10, TimeUnit.MINUTES); } catch (InterruptedException e) { throw new RuntimeException(e); } List openPortList = new ArrayList<>(); System.out.println("openPortsQueue: " + openPorts.size()); while (!openPorts.isEmpty()) { openPortList.add(openPorts.poll()); } openPortList.forEach(p -> System.out.println("port " + p + " is open")); } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\portscanner\PortScanner.java
1
请完成以下Java代码
private static void addPPOrderCandidateToGroup( @NonNull final Map<String, PPOrderCandidatesGroup> headerAgg2PPOrderCandGroup, @NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { if (headerAgg2PPOrderCandGroup.get(ppOrderCandidateToAllocate.getHeaderAggregationKey()) == null) { headerAgg2PPOrderCandGroup.put(ppOrderCandidateToAllocate.getHeaderAggregationKey(), PPOrderCandidatesGroup.of(ppOrderCandidateToAllocate)); } else { final PPOrderCandidatesGroup group = headerAgg2PPOrderCandGroup.get(ppOrderCandidateToAllocate.getHeaderAggregationKey()); group.addToGroup(ppOrderCandidateToAllocate); } } @Getter @EqualsAndHashCode private static class PPOrderCandidatesGroup { @Nullable private Integer groupSeqNo; @NonNull private final List<PPOrderCandidateToAllocate> ppOrderCandidateToAllocateList; private PPOrderCandidatesGroup(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { this.ppOrderCandidateToAllocateList = new ArrayList<>();
this.ppOrderCandidateToAllocateList.add(ppOrderCandidateToAllocate); this.groupSeqNo = ppOrderCandidateToAllocate.getPpOrderCandidate().getSeqNo() > 0 ? ppOrderCandidateToAllocate.getPpOrderCandidate().getSeqNo() : null; } @NonNull public static PPOrderCandidatesGroup of(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { return new PPOrderCandidatesGroup(ppOrderCandidateToAllocate); } public void addToGroup(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { ppOrderCandidateToAllocateList.add(ppOrderCandidateToAllocate); updateSeqNo(ppOrderCandidateToAllocate.getPpOrderCandidate().getSeqNo()); } private void updateSeqNo(final int newSeqNo) { if (newSeqNo <= 0 || (groupSeqNo != null && groupSeqNo <= newSeqNo)) { return; } this.groupSeqNo = newSeqNo; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\async\GeneratePPOrderFromPPOrderCandidate.java
1
请完成以下Java代码
public class Login { @Inject private Logger logger; @Inject private AlertManager alertManager; @InjectComponent private Form login; @Property private String email; @Property private String password; void onValidateFromLogin() {
if(email == null || password == null) { alertManager.error("Email/Password is null"); login.recordError("Validation failed"); } } Object onSuccessFromLogin() { alertManager.success("Welcome! Login Successful"); return Home.class; } void onFailureFromLogin() { alertManager.error("Please try again with correct credentials"); } }
repos\tutorials-master\web-modules\apache-tapestry\src\main\java\com\baeldung\tapestry\pages\Login.java
1
请完成以下Java代码
public class SwitchStatement { // Method 1: Assign grade using if-else public String assignGradeUsingIfElse(int score) { if (score >= 90) { return "Grade: A"; } else if (score >= 80) { return "Grade: B"; } else if (score >= 70) { return "Grade: C"; } else if (score >= 60) { return "Grade: D"; } return "Grade: F"; } // Method 2: Assign grade using switch with integer division public String assignGradeUsingRangesWithIntegerDivision(int score) { int range = score / 10;
switch (range) { case 10: case 9: return "Grade: A"; case 8: return "Grade: B"; case 7: return "Grade: C"; case 6: return "Grade: D"; default: return "Grade: F"; } } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-3\src\main\java\com\baeldung\switchstatement\SwitchStatement.java
1
请完成以下Java代码
public class ComposeFileWriter { /** * Write a {@linkplain ComposeFile compose.yaml} using the specified * {@linkplain IndentingWriter writer}. * @param writer the writer to use * @param compose the compose file to write */ public void writeTo(IndentingWriter writer, ComposeFile compose) { if (compose.services().isEmpty()) { writer.println("services: {}"); return; } writer.println("services:"); compose.services() .values() .sorted(Comparator.comparing(ComposeService::getName)) .forEach((service) -> writeService(writer, service)); } private void writeService(IndentingWriter writer, ComposeService service) { writer.indented(() -> { writer.println(service.getName() + ":"); writer.indented(() -> { writer.println("image: '%s:%s'".formatted(service.getImage(), service.getImageTag())); writerServiceEnvironment(writer, service.getEnvironment()); writerServiceLabels(writer, service.getLabels()); writerServicePorts(writer, service.getPorts()); writeServiceCommand(writer, service.getCommand()); }); }); } private void writerServiceEnvironment(IndentingWriter writer, Map<String, String> environment) { if (environment.isEmpty()) { return; } writer.println("environment:"); writer.indented(() -> { for (Map.Entry<String, String> env : environment.entrySet()) { writer.println("- '%s=%s'".formatted(env.getKey(), env.getValue())); } }); } private void writerServicePorts(IndentingWriter writer, Set<Integer> ports) { if (ports.isEmpty()) { return; } writer.println("ports:"); writer.indented(() -> { for (Integer port : ports) { writer.println("- '%d'".formatted(port));
} }); } private void writeServiceCommand(IndentingWriter writer, String command) { if (!StringUtils.hasText(command)) { return; } writer.println("command: '%s'".formatted(command)); } private void writerServiceLabels(IndentingWriter writer, Map<String, String> labels) { if (labels.isEmpty()) { return; } writer.println("labels:"); writer.indented(() -> { for (Map.Entry<String, String> label : labels.entrySet()) { writer.println("- \"%s=%s\"".formatted(label.getKey(), label.getValue())); } }); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeFileWriter.java
1
请完成以下Java代码
public class X_API_Response_Audit extends org.compiere.model.PO implements I_API_Response_Audit, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1611110786L; /** Standard Constructor */ public X_API_Response_Audit (final Properties ctx, final int API_Response_Audit_ID, @Nullable final String trxName) { super (ctx, API_Response_Audit_ID, trxName); } /** Load Constructor */ public X_API_Response_Audit (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_API_Request_Audit getAPI_Request_Audit() { return get_ValueAsPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class); } @Override public void setAPI_Request_Audit(final org.compiere.model.I_API_Request_Audit API_Request_Audit) { set_ValueFromPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class, API_Request_Audit); } @Override public void setAPI_Request_Audit_ID (final int API_Request_Audit_ID) { if (API_Request_Audit_ID < 1) set_Value (COLUMNNAME_API_Request_Audit_ID, null); else set_Value (COLUMNNAME_API_Request_Audit_ID, API_Request_Audit_ID); } @Override public int getAPI_Request_Audit_ID() { return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID); } @Override public void setAPI_Response_Audit_ID (final int API_Response_Audit_ID) { if (API_Response_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, API_Response_Audit_ID); } @Override public int getAPI_Response_Audit_ID() { return get_ValueAsInt(COLUMNNAME_API_Response_Audit_ID); } @Override public void setBody (final @Nullable java.lang.String Body) { set_Value (COLUMNNAME_Body, Body); } @Override public java.lang.String getBody() { return get_ValueAsString(COLUMNNAME_Body); } @Override
public void setHttpCode (final @Nullable java.lang.String HttpCode) { set_Value (COLUMNNAME_HttpCode, HttpCode); } @Override public java.lang.String getHttpCode() { return get_ValueAsString(COLUMNNAME_HttpCode); } @Override public void setHttpHeaders (final @Nullable java.lang.String HttpHeaders) { set_Value (COLUMNNAME_HttpHeaders, HttpHeaders); } @Override public java.lang.String getHttpHeaders() { return get_ValueAsString(COLUMNNAME_HttpHeaders); } @Override public void setTime (final @Nullable java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Response_Audit.java
1
请完成以下Java代码
public static IValidationRule ofNullableSqlWhereClause(@Nullable final String sqlWhereClause) { final String sqlWhereClauseNorm = StringUtils.trimBlankToNull(sqlWhereClause); if (sqlWhereClauseNorm == null) { return NullValidationRule.instance; } return ofSqlWhereClause(sqlWhereClauseNorm); } public static IValidationRule ofSqlWhereClause(@NonNull final String sqlWhereClause) { final String sqlWhereClauseNorm = StringUtils.trimBlankToNull(sqlWhereClause); if (sqlWhereClauseNorm == null) { throw new AdempiereException("sqlWhereClause cannot be blank"); } final IStringExpression sqlWhereClauseExpr = IStringExpression.compileOrDefault(sqlWhereClauseNorm, IStringExpression.NULL); return ofNullableSqlWhereClause(sqlWhereClauseExpr); } public static IValidationRule ofNullableSqlWhereClause(@Nullable final IStringExpression sqlWhereClauseExpr) { if (sqlWhereClauseExpr == null || sqlWhereClauseExpr.isNullExpression()) { return NullValidationRule.instance; }
return builder().prefilterWhereClause(sqlWhereClauseExpr).build(); } @Override public Set<String> getAllParameters() { return prefilterWhereClause.getParameterNames(); // NOTE: we are not checking post-filter params because that's always empty } @Override public boolean isImmutable() { return getAllParameters().isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\SQLValidationRule.java
1