instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static void setFixedTimeSource(@NonNull final String zonedDateTime) { setTimeSource(FixedTimeSource.ofZonedDateTime(ZonedDateTime.parse(zonedDateTime))); } public static long millis() { return getTimeSource().millis(); } public static ZoneId zoneId() { return getTimeSource().zoneId(); } public static GregorianCalendar asGregorianCalendar() { final GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(millis()); return cal; } public static Date asDate() { return new Date(millis()); } public static Timestamp asTimestamp() { return new Timestamp(millis()); } /** * Same as {@link #asTimestamp()} but the returned date will be truncated to DAY. */ public static Timestamp asDayTimestamp() { final GregorianCalendar cal = asGregorianCalendar(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Timestamp(cal.getTimeInMillis()); } public static Instant asInstant() { return Instant.ofEpochMilli(millis()); } public static LocalDateTime asLocalDateTime() { return asZonedDateTime().toLocalDateTime(); } @NonNull public static LocalDate asLocalDate() { return asLocalDate(zoneId()); } @NonNull
public static LocalDate asLocalDate(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId).toLocalDate(); } public static ZonedDateTime asZonedDateTime() { return asZonedDateTime(zoneId()); } public static ZonedDateTime asZonedDateTimeAtStartOfDay() { return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS); } public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId) .toLocalDate() .atTime(LocalTime.MAX) .atZone(zoneId); } public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId) { return asInstant().atZone(zoneId); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
1
请完成以下Java代码
public Mono<Map<String, Object>> handle(Map<String, Object> payload) { return handleInternal(payload).map(ExecutionGraphQlResponse::toMap); } /** * Handle a {@code Request-Stream} interaction. For subscriptions. * @param payload the decoded GraphQL request payload */ public Flux<Map<String, Object>> handleSubscription(Map<String, Object> payload) { return handleInternal(payload) .flatMapMany((response) -> { if (response.getData() instanceof Publisher) { Publisher<ExecutionResult> publisher = response.getData(); return Flux.from(publisher).map(ExecutionResult::toSpecification); } else if (response.isValid()) { return Flux.error(new InvalidException( "Expected a Publisher for a subscription operation. " + "This is either a server error or the operation is not a subscription"));
} String errorData = encodeErrors(response).toString(StandardCharsets.UTF_8); return Flux.error(new RejectedException(errorData)); }); } private Mono<RSocketGraphQlResponse> handleInternal(Map<String, Object> payload) { String requestId = this.idGenerator.generateId().toString(); return this.executionChain.next(new RSocketGraphQlRequest(payload, requestId, null)); } @SuppressWarnings("unchecked") private DataBuffer encodeErrors(RSocketGraphQlResponse response) { return ((Encoder<List<GraphQLError>>) this.jsonEncoder).encodeValue( response.getExecutionResult().getErrors(), DefaultDataBufferFactory.sharedInstance, LIST_TYPE, MimeTypeUtils.APPLICATION_JSON, null); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\GraphQlRSocketHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, String> headers() { return obtain(OtlpMetricsProperties::getHeaders, OtlpConfig.super::headers); } @Override public HistogramFlavor histogramFlavor() { return obtain(OtlpMetricsProperties::getHistogramFlavor, OtlpConfig.super::histogramFlavor); } @Override public Map<String, HistogramFlavor> histogramFlavorPerMeter() { return obtain(perMeter(Meter::getHistogramFlavor), OtlpConfig.super::histogramFlavorPerMeter); } @Override public Map<String, Integer> maxBucketsPerMeter() { return obtain(perMeter(Meter::getMaxBucketCount), OtlpConfig.super::maxBucketsPerMeter); } @Override public int maxScale() { return obtain(OtlpMetricsProperties::getMaxScale, OtlpConfig.super::maxScale); } @Override public int maxBucketCount() { return obtain(OtlpMetricsProperties::getMaxBucketCount, OtlpConfig.super::maxBucketCount); } @Override public TimeUnit baseTimeUnit() { return obtain(OtlpMetricsProperties::getBaseTimeUnit, OtlpConfig.super::baseTimeUnit);
} private <V> Getter<OtlpMetricsProperties, Map<String, V>> perMeter(Getter<Meter, V> getter) { return (properties) -> { if (CollectionUtils.isEmpty(properties.getMeter())) { return null; } Map<String, V> perMeter = new LinkedHashMap<>(); properties.getMeter().forEach((key, meterProperties) -> { V value = getter.get(meterProperties); if (value != null) { perMeter.put(key, value); } }); return (!perMeter.isEmpty()) ? perMeter : null; }; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsPropertiesConfigAdapter.java
2
请完成以下Java代码
public JavaType typeFromId(DatabindContext context, String id) throws IOException { DeserializationConfig config = (DeserializationConfig) context.getConfig(); JavaType result = this.delegate.typeFromId(context, id); String className = result.getRawClass().getName(); if (isInAllowlist(className)) { return result; } boolean isExplicitMixin = config.findMixInClassFor(result.getRawClass()) != null; if (isExplicitMixin) { return result; } JacksonAnnotation jacksonAnnotation = AnnotationUtils.findAnnotation(result.getRawClass(), JacksonAnnotation.class); if (jacksonAnnotation != null) { return result; } throw new IllegalArgumentException("The class with " + id + " and name of " + className + " is not in the allowlist. " + "If you believe this class is safe to deserialize, please provide an explicit mapping using Jackson annotations or by providing a Mixin. " + "If the serialization is only done by a trusted source, you can also enable default typing. " + "See https://github.com/spring-projects/spring-security/issues/4370 for details"); } private boolean isInAllowlist(String id) {
return ALLOWLIST_CLASS_NAMES.contains(id); } @Override public String getDescForKnownTypeIds() { return this.delegate.getDescForKnownTypeIds(); } @Override public JsonTypeInfo.Id getMechanism() { return this.delegate.getMechanism(); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\jackson2\SecurityJackson2Modules.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_A_Asset_Use[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Asset. @param A_Asset_ID Asset used internally or by customers */ public void setA_Asset_ID (int A_Asset_ID) { if (A_Asset_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Asset_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID)); } /** Get Asset. @return Asset used internally or by customers */ public int getA_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID); if (ii == null) return 0; return ii.intValue(); } /** Set A_Asset_Use_ID. @param A_Asset_Use_ID A_Asset_Use_ID */ public void setA_Asset_Use_ID (int A_Asset_Use_ID) { if (A_Asset_Use_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Asset_Use_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Asset_Use_ID, Integer.valueOf(A_Asset_Use_ID)); } /** Get A_Asset_Use_ID. @return A_Asset_Use_ID */ public int getA_Asset_Use_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Use_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Use_ID())); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description);
} /** Set UseDate. @param UseDate UseDate */ public void setUseDate (Timestamp UseDate) { set_Value (COLUMNNAME_UseDate, UseDate); } /** Get UseDate. @return UseDate */ public Timestamp getUseDate () { return (Timestamp)get_Value(COLUMNNAME_UseDate); } /** Set Use units. @param UseUnits Currently used units of the assets */ public void setUseUnits (int UseUnits) { set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits)); } /** Get Use units. @return Currently used units of the assets */ public int getUseUnits () { Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Use.java
1
请完成以下Java代码
static class IncidentStateImpl implements IncidentState { public final int stateCode; protected final String name; public IncidentStateImpl(int suspensionCode, String string) { this.stateCode = suspensionCode; this.name = string; } 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; IncidentStateImpl other = (IncidentStateImpl) obj; if (stateCode != other.stateCode) return false; return true; } @Override public String toString() { return name; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\history\IncidentState.java
1
请完成以下Java代码
public class MiscUtils { public static final Charset UTF8 = Charset.forName("UTF-8"); public static String missingProperty(String propertyName) { return "The " + propertyName + " property need to be set!"; } @SuppressWarnings("deprecation") public static HashFunction forName(String name) { switch (name) { case "murmur3_32": return Hashing.murmur3_32(); case "murmur3_128": return Hashing.murmur3_128(); case "crc32": return Hashing.crc32(); case "md5": return Hashing.md5(); default: throw new IllegalArgumentException("Can't find hash function with name " + name); } } public static String constructBaseUrl(HttpServletRequest request) { return String.format("%s://%s:%d", getScheme(request), getDomainName(request), getPort(request)); } public static String getScheme(HttpServletRequest request){ String scheme = request.getScheme(); String forwardedProto = request.getHeader("x-forwarded-proto"); if (forwardedProto != null) { scheme = forwardedProto; } return scheme; } public static String getDomainName(HttpServletRequest request){ return request.getServerName(); } public static String getDomainNameAndPort(HttpServletRequest request){ String domainName = getDomainName(request); String scheme = getScheme(request); int port = MiscUtils.getPort(request); if (needsPort(scheme, port)) { domainName += ":" + port;
} return domainName; } private static boolean needsPort(String scheme, int port) { boolean isHttpDefault = "http".equals(scheme.toLowerCase()) && port == 80; boolean isHttpsDefault = "https".equals(scheme.toLowerCase()) && port == 443; return !isHttpDefault && !isHttpsDefault; } public static int getPort(HttpServletRequest request){ String forwardedProto = request.getHeader("x-forwarded-proto"); int serverPort = request.getServerPort(); if (request.getHeader("x-forwarded-port") != null) { try { serverPort = request.getIntHeader("x-forwarded-port"); } catch (NumberFormatException e) { } } else if (forwardedProto != null) { switch (forwardedProto) { case "http": serverPort = 80; break; case "https": serverPort = 443; break; } } return serverPort; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\utils\MiscUtils.java
1
请在Spring Boot框架中完成以下Java代码
public List<AuthorityDto> buildPermissions(UserDto user) { String key = CacheKey.ROLE_AUTH + user.getId(); List<AuthorityDto> authorityDtos = redisUtils.getList(key, AuthorityDto.class); if (CollUtil.isEmpty(authorityDtos)) { Set<String> permissions = new HashSet<>(); // 如果是管理员直接返回 if (user.getIsAdmin()) { permissions.add("admin"); return permissions.stream().map(AuthorityDto::new) .collect(Collectors.toList()); } Set<Role> roles = roleRepository.findByUserId(user.getId()); permissions = roles.stream().flatMap(role -> role.getMenus().stream()) .map(Menu::getPermission) .filter(StringUtils::isNotBlank).collect(Collectors.toSet()); authorityDtos = permissions.stream().map(AuthorityDto::new) .collect(Collectors.toList()); redisUtils.set(key, authorityDtos, 1, TimeUnit.HOURS); } return authorityDtos; } @Override public void download(List<RoleDto> roles, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (RoleDto role : roles) { Map<String, Object> map = new LinkedHashMap<>(); map.put("角色名称", role.getName()); map.put("角色级别", role.getLevel()); map.put("描述", role.getDescription()); map.put("创建日期", role.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } @Override public void verification(Set<Long> ids) { if (userRepository.countByRoles(ids) > 0) { throw new BadRequestException("所选角色存在用户关联,请解除关联再试!"); } } @Override public List<Role> findInMenuId(List<Long> menuIds) {
return roleRepository.findInMenuId(menuIds); } /** * 清理缓存 * @param id / */ public void delCaches(Long id, List<User> users) { users = CollectionUtil.isEmpty(users) ? userRepository.findByRoleId(id) : users; if (CollectionUtil.isNotEmpty(users)) { users.forEach(item -> userCacheManager.cleanUserCache(item.getUsername())); Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet()); redisUtils.delByKeys(CacheKey.DATA_USER, userIds); redisUtils.delByKeys(CacheKey.MENU_USER, userIds); redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds); redisUtils.delByKeys(CacheKey.ROLE_USER, userIds); } redisUtils.del(CacheKey.ROLE_ID + id); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\RoleServiceImpl.java
2
请完成以下Java代码
public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article;
} public Magazine getMagazine() { return magazine; } public void setMagazine(Magazine magazine) { this.magazine = magazine; } @Override public String toString() { return "Review{" + "id=" + id + ", content=" + content + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootChooseOnlyOneAssociation\src\main\java\com\bookstore\entity\Review.java
1
请完成以下Java代码
protected final ProductsProposalView getById(final ViewId viewId) { final ProductsProposalView view = getByIdOrNull(viewId); if (view == null) { throw new EntityNotFoundException("View not found: " + viewId.toJson()); } return view; } @Override public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { beforeViewClose(viewId, closeAction); views.invalidate(viewId); views.cleanUp(); } protected void beforeViewClose(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { // nothing on this level } @Override public final Stream<IView> streamAllViews() { return Stream.empty(); }
@Override public final void invalidateView(final ViewId viewId) { final ProductsProposalView view = getById(viewId); view.invalidateAll(); } @lombok.Value(staticConstructor = "of") protected static class ViewLayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalViewFactoryTemplate.java
1
请完成以下Java代码
public void setC_TaxCategory_ID (final int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID); } @Override public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public void setCommodityCode (final @Nullable java.lang.String CommodityCode) { set_Value (COLUMNNAME_CommodityCode, CommodityCode); } @Override public java.lang.String getCommodityCode() { return get_ValueAsString(COLUMNNAME_CommodityCode); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setInternalName (final @Nullable java.lang.String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public java.lang.String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @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); } /** * ProductType AD_Reference_ID=270 * Reference name: M_Product_ProductType */ public static final int PRODUCTTYPE_AD_Reference_ID=270; /** Item = I */ public static final String PRODUCTTYPE_Item = "I"; /** Service = S */ public static final String PRODUCTTYPE_Service = "S";
/** Resource = R */ public static final String PRODUCTTYPE_Resource = "R"; /** ExpenseType = E */ public static final String PRODUCTTYPE_ExpenseType = "E"; /** Online = O */ public static final String PRODUCTTYPE_Online = "O"; /** FreightCost = F */ public static final String PRODUCTTYPE_FreightCost = "F"; @Override public void setProductType (final @Nullable java.lang.String ProductType) { set_Value (COLUMNNAME_ProductType, ProductType); } @Override public java.lang.String getProductType() { return get_ValueAsString(COLUMNNAME_ProductType); } /** * VATType AD_Reference_ID=540842 * Reference name: VATType */ public static final int VATTYPE_AD_Reference_ID=540842; /** RegularVAT = N */ public static final String VATTYPE_RegularVAT = "N"; /** ReducedVAT = R */ public static final String VATTYPE_ReducedVAT = "R"; /** TaxExempt = E */ public static final String VATTYPE_TaxExempt = "E"; @Override public void setVATType (final @Nullable java.lang.String VATType) { set_Value (COLUMNNAME_VATType, VATType); } @Override public java.lang.String getVATType() { return get_ValueAsString(COLUMNNAME_VATType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxCategory.java
1
请在Spring Boot框架中完成以下Java代码
public class TbTimeSeriesSubscription extends TbSubscription<TelemetrySubscriptionUpdate> { @Getter private final long queryTs; @Getter private final boolean allKeys; @Getter private final Map<String, Long> keyStates; @Getter private final long startTime; @Getter private final long endTime; @Getter private final boolean latestValues; @Builder public TbTimeSeriesSubscription(String serviceId, String sessionId, int subscriptionId, TenantId tenantId, EntityId entityId, BiConsumer<TbSubscription<TelemetrySubscriptionUpdate>, TelemetrySubscriptionUpdate> updateProcessor, long queryTs, boolean allKeys, Map<String, Long> keyStates, long startTime, long endTime, boolean latestValues) {
super(serviceId, sessionId, subscriptionId, tenantId, entityId, TbSubscriptionType.TIMESERIES, updateProcessor); this.queryTs = queryTs; this.allKeys = allKeys; this.keyStates = keyStates; this.startTime = startTime; this.endTime = endTime; this.latestValues = latestValues; } @Override public boolean equals(Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbTimeSeriesSubscription.java
2
请完成以下Java代码
public void setPayPal_Config_ID (final int PayPal_Config_ID) { if (PayPal_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_PayPal_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_PayPal_Config_ID, PayPal_Config_ID); } @Override public int getPayPal_Config_ID() { return get_ValueAsInt(COLUMNNAME_PayPal_Config_ID); } @Override public org.compiere.model.I_R_MailText getPayPal_PayerApprovalRequest_MailTemplate() { return get_ValueAsPO(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, org.compiere.model.I_R_MailText.class); } @Override public void setPayPal_PayerApprovalRequest_MailTemplate(final org.compiere.model.I_R_MailText PayPal_PayerApprovalRequest_MailTemplate) { set_ValueFromPO(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, org.compiere.model.I_R_MailText.class, PayPal_PayerApprovalRequest_MailTemplate); } @Override public void setPayPal_PayerApprovalRequest_MailTemplate_ID (final int PayPal_PayerApprovalRequest_MailTemplate_ID) { if (PayPal_PayerApprovalRequest_MailTemplate_ID < 1) set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, null); else set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, PayPal_PayerApprovalRequest_MailTemplate_ID); } @Override public int getPayPal_PayerApprovalRequest_MailTemplate_ID() { return get_ValueAsInt(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID); } @Override public void setPayPal_PaymentApprovedCallbackUrl (final @Nullable java.lang.String PayPal_PaymentApprovedCallbackUrl) { set_Value (COLUMNNAME_PayPal_PaymentApprovedCallbackUrl, PayPal_PaymentApprovedCallbackUrl);
} @Override public java.lang.String getPayPal_PaymentApprovedCallbackUrl() { return get_ValueAsString(COLUMNNAME_PayPal_PaymentApprovedCallbackUrl); } @Override public void setPayPal_Sandbox (final boolean PayPal_Sandbox) { set_Value (COLUMNNAME_PayPal_Sandbox, PayPal_Sandbox); } @Override public boolean isPayPal_Sandbox() { return get_ValueAsBoolean(COLUMNNAME_PayPal_Sandbox); } @Override public void setPayPal_WebUrl (final @Nullable java.lang.String PayPal_WebUrl) { set_Value (COLUMNNAME_PayPal_WebUrl, PayPal_WebUrl); } @Override public java.lang.String getPayPal_WebUrl() { return get_ValueAsString(COLUMNNAME_PayPal_WebUrl); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Config.java
1
请完成以下Java代码
Properties toProps() { Properties props = new Properties(); if (useConfluent) { props.put("ssl.endpoint.identification.algorithm", sslAlgorithm); props.put("sasl.mechanism", saslMechanism); props.put("sasl.jaas.config", saslConfig); props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol); } props.put(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG, requestTimeoutMs); props.putAll(PropertyUtils.getProps(otherInline)); if (other != null) { other.forEach(kv -> props.put(kv.getKey(), kv.getValue())); } configureSSL(props); return props; } void configureSSL(Properties props) { if (sslEnabled) { props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslTruststoreLocation); props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, sslTruststorePassword); props.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, sslKeystoreLocation); props.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, sslKeystorePassword); props.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, sslKeyPassword); } } /* * Temporary solution to avoid major code changes. * FIXME: use single instance of Kafka queue admin, don't create a separate one for each consumer/producer
* */ public KafkaAdmin getAdmin() { return kafkaAdmin; } protected Properties toAdminProps() { Properties props = toProps(); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, servers); props.put(AdminClientConfig.RETRIES_CONFIG, retries); return props; } private Map<String, List<TbProperty>> parseTopicPropertyList(String inlineProperties) { Map<String, List<String>> grouped = PropertyUtils.getGroupedProps(inlineProperties); Map<String, List<TbProperty>> result = new HashMap<>(); grouped.forEach((topic, entries) -> { Map<String, String> merged = new LinkedHashMap<>(); for (String entry : entries) { String[] kv = entry.split("=", 2); if (kv.length == 2) { merged.put(kv[0].trim(), kv[1].trim()); } } List<TbProperty> props = merged.entrySet().stream() .map(e -> new TbProperty(e.getKey(), e.getValue())) .toList(); result.put(topic, props); }); return result; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaSettings.java
1
请完成以下Java代码
private static void increaseFrequency(char c, Map<Character, int[]> storage) { int[] freq = storage.get(c); if (freq == null) { freq = new int[]{1}; storage.put(c, freq); } else { ++freq[0]; } } private float computeEntropy(Map<Character, int[]> storage) { float sum = 0; for (Map.Entry<Character, int[]> entry : storage.entrySet()) { float p = entry.getValue()[0] / (float) frequency; sum -= p * Math.log(p); } return sum; } void update(char left, char right) { ++frequency; increaseFrequency(left, this.left); increaseFrequency(right, this.right); } void computeProbabilityEntropy(int length) { p = frequency / (float) length; leftEntropy = computeEntropy(left); rightEntropy = computeEntropy(right); entropy = Math.min(leftEntropy, rightEntropy); }
void computeAggregation(Map<String, WordInfo> word_cands) { if (text.length() == 1) { aggregation = (float) Math.sqrt(p); return; } for (int i = 1; i < text.length(); ++i) { aggregation = Math.min(aggregation, p / word_cands.get(text.substring(0, i)).p / word_cands.get(text.substring(i)).p); } } @Override public String toString() { return text; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\WordInfo.java
1
请完成以下Java代码
public void load(String trxName) { Services.get(ITrxManager.class).run(trxName, new TrxRunnableAdapter() { @Override public void run(String innerTrxName) { try { load0(innerTrxName); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AdempiereException(e); } } }); } private void load0(String trxName) throws ParserConfigurationException, SAXException, IOException { this.objects = new ArrayList<Object>(); final IXMLHandlerFactory factory = Services.get(IXMLHandlerFactory.class); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setIgnoringElementContentWhitespace(true); final DocumentBuilder builder = dbf.newDocumentBuilder(); final InputSource source = getInputSource(); final Document doc = builder.parse(source); final NodeList nodes = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (!(nodes.item(i) instanceof Element)) { continue; } final Element element = (Element)nodes.item(i); final String name = element.getLocalName(); final Class<Object> beanClass = factory.getBeanClassByNodeName(name); if (beanClass == null) { addLog("Error: node is not handled: " + name); continue; } final IXMLHandler<Object> converter = factory.getHandler(beanClass); final Object bean = InterfaceWrapperHelper.create(ctx, beanClass, trxName); if (converter.fromXmlNode(bean, element)) { InterfaceWrapperHelper.save(bean); // make sure is saved objects.add(bean); }
} } private InputSource getInputSource() { if (fileName != null) { return new InputSource(fileName); } else if (inputStream != null) { return new InputSource(inputStream); } else { throw new AdempiereException("Cannot identify source"); } } private void addLog(String msg) { logger.info(msg); } public List<Object> getObjects() { if (objects == null) { return new ArrayList<Object>(); } return new ArrayList<Object>(this.objects); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\XMLLoader.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } public void displayAuthorsAndBooks() { List<Author> authors = authorRepository.findAll(); for (Author author : authors) { System.out.println("Author: " + author); System.out.println("No of books: " + author.getBooks().size() + ", " + author.getBooks()); } } public void displayAuthorsAndBooksByAge(int age) { List<Author> authors = authorRepository.findByAgeLessThanOrderByNameDesc(age); for (Author author : authors) { System.out.println("Author: " + author); System.out.println("No of books: " + author.getBooks().size() + ", " + author.getBooks()); } } public void displayAuthorsAndBooksByAgeWithSpec() { List<Author> authors = authorRepository.findAll(isAgeGt45()); for (Author author : authors) { System.out.println("Author: " + author); System.out.println("No of books: " + author.getBooks().size() + ", " + author.getBooks());
} } public void displayAuthorsAndBooksFetchAllAgeBetween20And40() { List<Author> authors = authorRepository.fetchAllAgeBetween20And40(); for (Author author : authors) { System.out.println("Author: " + author); System.out.println("No of books: " + author.getBooks().size() + ", " + author.getBooks()); } } public void displayBooksAndAuthors() { List<Book> books = bookRepository.findAll(); for (Book book : books) { System.out.println("Book: " + book); System.out.println("Author: " + book.getAuthor()); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootEntityGraphAttributePaths\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); try { writer = new BufferedWriter(new FileWriter(filePath)); } catch (IOException e) { logger.error("Failed to open a file for writing.", e); } } @Override public void execute(Tuple tuple) { int sumOfOperations = tuple.getIntegerByField("sumOfOperations"); long beginningTimestamp = tuple.getLongByField("beginningTimestamp"); long endTimestamp = tuple.getLongByField("endTimestamp"); if(sumOfOperations > 200) { AggregatedWindow aggregatedWindow = new AggregatedWindow(sumOfOperations, beginningTimestamp, endTimestamp); try { writer.write(objectMapper.writeValueAsString(aggregatedWindow)); writer.write("\n"); writer.flush(); } catch (IOException e) {
logger.error("Failed to write data to file.", e); } } } public FileWritingBolt(String filePath) { this.filePath = filePath; } @Override public void cleanup() { try { writer.close(); } catch (IOException e) { logger.error("Failed to close the writer!"); } } @Override public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { } }
repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\storm\bolt\FileWritingBolt.java
1
请完成以下Java代码
public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderId(newPPOrderId); } else if (newPPOrderId != null) { return ofPPOrderId(newPPOrderId); } else { return null; } } @Nullable public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { if (ppOrderRef != null) {
return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId); } else if (newPPOrderAndBOMLineId != null) { return ofPPOrderBOMLineId(newPPOrderAndBOMLineId); } else { return null; } } @Nullable public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java
1
请完成以下Java代码
private boolean isPricingConditionsApplicable( @Nullable final PricingConditionsId pricingConditionsId, @NonNull final LocalDate date, @NonNull final OrgId orgId) { if (pricingConditionsId == null) { return false; } final PricingConditions pricingConditions = pricingConditionsService.getPricingConditionsById(pricingConditionsId); if (!pricingConditions.isActive()) { return false; } final ZoneId timeZone = orgDAO.getTimeZone(orgId); final LocalDate validFrom = TimeUtil.asLocalDate(pricingConditions.getValidFrom(), timeZone); return date.isAfter(validFrom) || date.isEqual(validFrom) ; } private ImmutableAttributeSet getAttributes(final IPricingContext pricingCtx) { final IAttributeSetInstanceAware asiAware = pricingCtx.getAttributeSetInstanceAware().orElse(null); if (asiAware == null) { return ImmutableAttributeSet.EMPTY; } final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asiAware.getM_AttributeSetInstance_ID()); return Services.get(IAttributeSetInstanceBL.class).getImmutableAttributeSetById(asiId); } private static void updatePricingResultFromPricingConditionsResult( @NonNull final IPricingResult pricingResult, @Nullable final PricingConditionsResult pricingConditionsResult) { pricingResult.setPricingConditions(pricingConditionsResult); if (pricingConditionsResult == null) { return;
} pricingResult.setDiscount(pricingConditionsResult.getDiscount()); final BigDecimal priceStdOverride = pricingConditionsResult.getPriceStdOverride(); final BigDecimal priceListOverride = pricingConditionsResult.getPriceListOverride(); final BigDecimal priceLimitOverride = pricingConditionsResult.getPriceLimitOverride(); if (priceStdOverride != null) { pricingResult.setPriceStd(priceStdOverride); } if (priceListOverride != null) { pricingResult.setPriceList(priceListOverride); } if (priceLimitOverride != null) { pricingResult.setPriceLimit(priceLimitOverride); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\Discount.java
1
请完成以下Spring Boot application配置
server.port=8080 eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka} eureka.instance.preferIpAddress=false spring.application.name=spring-cloud-eureka-clien
t #--- spring.config.activate.on-profile=dev spring.cloud.discovery.enabled=false
repos\tutorials-master\spring-cloud-modules\spring-cloud-eureka\spring-cloud-eureka-client-profiles\src\main\resources\application.properties
2
请完成以下Java代码
protected void dispatchActivityTimeoutIfNeeded(Job timerEntity, ExecutionEntity execution, CommandContext commandContext) { String nestedActivityId = TimerEventHandler.getActivityIdFromConfiguration(timerEntity.getJobHandlerConfiguration()); ActivityImpl boundaryEventActivity = execution.getProcessDefinition().findActivity(nestedActivityId); ActivityBehavior boundaryActivityBehavior = boundaryEventActivity.getActivityBehavior(); if (boundaryActivityBehavior instanceof BoundaryEventActivityBehavior) { BoundaryEventActivityBehavior boundaryEventActivityBehavior = (BoundaryEventActivityBehavior) boundaryActivityBehavior; if (boundaryEventActivityBehavior.isInterrupting()) { dispatchExecutionTimeOut(timerEntity, execution, commandContext); } } } protected void dispatchExecutionTimeOut(Job job, ExecutionEntity execution, CommandContext commandContext) { // subprocesses for (ExecutionEntity subExecution : execution.getExecutions()) { dispatchExecutionTimeOut(job, subExecution, commandContext); } // call activities ExecutionEntity subProcessInstance = commandContext.getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId()); if (subProcessInstance != null) { dispatchExecutionTimeOut(job, subProcessInstance, commandContext); } // activity with timer boundary event ActivityImpl activity = execution.getActivity();
if (activity != null && activity.getActivityBehavior() != null) { dispatchActivityTimeOut(job, activity, execution, commandContext); } } protected void dispatchActivityTimeOut(Job job, ActivityImpl activity, ExecutionEntity execution, CommandContext commandContext) { commandContext.getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createActivityCancelledEvent(activity.getId(), (String) activity.getProperties().get("name"), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), (String) activity.getProperties().get("type"), activity.getActivityBehavior().getClass().getCanonicalName(), job), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerExecuteNestedActivityJobHandler.java
1
请完成以下Java代码
public class ScannableCodeFormatsCollection { public static ScannableCodeFormatsCollection EMPTY = new ScannableCodeFormatsCollection(ImmutableList.of()); @NonNull ImmutableList<ScannableCodeFormat> formats; private ScannableCodeFormatsCollection(@NonNull final ImmutableList<ScannableCodeFormat> formats) { this.formats = formats; } public static Collector<ScannableCodeFormat, ?, ScannableCodeFormatsCollection> collect() { return GuavaCollectors.collectUsingListAccumulator(ScannableCodeFormatsCollection::ofList); } public static ScannableCodeFormatsCollection ofList(@Nullable final List<ScannableCodeFormat> formats) { return formats != null && !formats.isEmpty() ? new ScannableCodeFormatsCollection(ImmutableList.copyOf(formats)) : EMPTY; } public ExplainedOptional<ParsedScannedCode> parse(@NonNull final ScannedCode scannedCode) { if (formats.isEmpty()) { return ExplainedOptional.emptyBecause("No formats configured"); } final TranslatableStringBuilder notMatchingExplanation = TranslatableStrings.builder(); for (final ScannableCodeFormat format : formats)
{ final ExplainedOptional<ParsedScannedCode> result = format.parse(scannedCode); if (result.isPresent()) { return result; } if (!notMatchingExplanation.isEmpty()) { notMatchingExplanation.append(" | "); } notMatchingExplanation.append(format.getName()).append(" ").append(result.getExplanation()); } return ExplainedOptional.emptyBecause(notMatchingExplanation.build()); } public boolean isEmpty() {return formats.isEmpty();} public ImmutableList<ScannableCodeFormat> toList() {return formats;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\ScannableCodeFormatsCollection.java
1
请完成以下Java代码
public Window[] getWindows() { Window[] a = new Window[windows.size()]; return windows.toArray(a); } /** * @return Number of windows managed by this window manager */ public int getWindowCount() { return windows.size(); } /** * Find window by ID * * @param AD_Window_ID * @return AWindow reference, null if not found */ public AWindow find(final AdWindowId adWindowId) { for (Window w : windows) { if (w instanceof AWindow) { AWindow a = (AWindow)w; if (AdWindowId.equals(a.getAdWindowId(), adWindowId)) { return a; } } } return null; } public FormFrame findForm(int AD_FORM_ID) { for (Window w : windows) { if (w instanceof FormFrame) { FormFrame ff = (FormFrame)w; if (ff.getAD_Form_ID() == AD_FORM_ID) { return ff; } } } return null; } } class WindowEventListener implements ComponentListener, WindowListener { WindowManager windowManager; protected WindowEventListener(WindowManager windowManager) { this.windowManager = windowManager; } @Override public void componentHidden(ComponentEvent e) { Component c = e.getComponent(); if (c instanceof Window) { c.removeComponentListener(this); ((Window)c).removeWindowListener(this); windowManager.remove((Window)c); }
} @Override public void componentMoved(ComponentEvent e) { } @Override public void componentResized(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { Window w = e.getWindow(); if (w instanceof Window) { w.removeComponentListener(this); w.removeWindowListener(this); windowManager.remove(w); } } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowManager.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override 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 ShowInMenu. @param ShowInMenu ShowInMenu */
@Override public void setShowInMenu (boolean ShowInMenu) { set_Value (COLUMNNAME_ShowInMenu, Boolean.valueOf(ShowInMenu)); } /** Get ShowInMenu. @return ShowInMenu */ @Override public boolean isShowInMenu () { Object oo = get_Value(COLUMNNAME_ShowInMenu); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow.java
1
请完成以下Spring Boot application配置
server: port: 7070 # 避免和本地的 Apollo Portal 端口冲突 app: id: demo-application # 使用的 Apollo 的项目(应用)编号 apollo: meta: http://127.0.0.1:8080 # Apollo Meta Server 地址 bootstrap: enabled: true # 是否开启 Apollo 配置预加载功能。默认为 false。 eagerLoad: enab
le: true # 是否开启 Apollo 支持日志级别的加载时机。默认为 false。 namespaces: application # 使用的 Apollo 的命名空间,默认为 application。
repos\SpringBoot-Labs-master\lab-45\lab-45-apollo-demo\src\main\resources\application.yaml
2
请完成以下Java代码
public Flux<DataBuffer> getBody() { return Mono.fromSupplier(() -> { if (exchange.getAttribute(CACHED_REQUEST_BODY_ATTR) == null) { // probably == downstream closed or no body return null; } if (dataBuffer instanceof NettyDataBuffer) { NettyDataBuffer pdb = (NettyDataBuffer) dataBuffer; return pdb.factory().wrap(pdb.getNativeBuffer().retainedSlice()); } else if (dataBuffer instanceof DefaultDataBuffer) { DefaultDataBuffer ddf = (DefaultDataBuffer) dataBuffer; return ddf.factory().wrap(Unpooled.wrappedBuffer(ddf.getNativeBuffer()).nioBuffer()); } else { throw new IllegalArgumentException( "Unable to handle DataBuffer of type " + dataBuffer.getClass()); } }).flux(); } }; if (cacheDecoratedRequest) { exchange.getAttributes().put(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR, decorator); } return decorator; } /** * One place to handle forwarding using DispatcherHandler. Allows for common code to
* be reused. * @param handler The DispatcherHandler. * @param exchange The ServerWebExchange. * @return value from handler. */ public static Mono<Void> handle(DispatcherHandler handler, ServerWebExchange exchange) { // remove attributes that may disrupt the forwarded request exchange.getAttributes().remove(GATEWAY_PREDICATE_PATH_CONTAINER_ATTR); // CORS check is applied to the original request, but should not be applied to // internally forwarded requests. // See https://github.com/spring-cloud/spring-cloud-gateway/issues/3350. exchange = exchange.mutate().request(request -> request.headers(headers -> headers.setOrigin(null))).build(); return handler.handle(exchange); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ServerWebExchangeUtils.java
1
请完成以下Java代码
public GenericIdentification20 getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link GenericIdentification20 } * */ public void setTp(GenericIdentification20 value) { this.tp = value; } /** * Gets the value of the nm property. * * @return * possible object is * {@link String }
* */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\SecuritiesAccount13.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable ConfigDataResource getParent() { return this.contributor.getResource(); } @Override public ConfigurableBootstrapContext getBootstrapContext() { return this.contributors.getBootstrapContext(); } } private class InactiveSourceChecker implements BindHandler { private final @Nullable ConfigDataActivationContext activationContext; InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) { this.activationContext = activationContext; } @Override public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) { for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) { if (!contributor.isActive(this.activationContext)) { InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name);
} } return result; } } /** * Binder options that can be used with * {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}. */ enum BinderOption { /** * Throw an exception if an inactive contributor contains a bound value. */ FAIL_ON_BIND_TO_INACTIVE_SOURCE } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java
2
请完成以下Java代码
public boolean isVirtual() { return isVirtualRepoId(repoId); } public static boolean isVirtualRepoId(final int repoId) { return repoId == VIRTUAL.repoId; } public boolean isRealPackingInstructions() { return isRealPackingInstructionsRepoId(repoId); } public static boolean isRealPackingInstructionsRepoId(final int repoId) { return repoId > 0 && !isTemplateRepoId(repoId) && !isVirtualRepoId(repoId); }
public HuPackingInstructionsId getKnownPackingInstructionsIdOrNull() { if (isVirtual()) { return HuPackingInstructionsId.VIRTUAL; } if (isTemplate()) { return HuPackingInstructionsId.TEMPLATE; } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsVersionId.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getSeqNo() { return seqNo; } /** * Sets the value of the seqNo property. * * @param value * allowed object is * {@link BigInteger } * */ public void setSeqNo(BigInteger value) { this.seqNo = value; } /** * Gets the value of the gtinPackingMaterial property. * * @return * possible object is * {@link String } * */ public String getGTINPackingMaterial() { return gtinPackingMaterial; } /** * Sets the value of the gtinPackingMaterial property. * * @param value * allowed object is * {@link String } * */ public void setGTINPackingMaterial(String value) { this.gtinPackingMaterial = value; } /** * Gets the value of the ipasscc18 property. * * @return * possible object is * {@link String } * */ public String getIPASSCC18() { return ipasscc18; } /** * Sets the value of the ipasscc18 property. * * @param value * allowed object is * {@link String } * */ public void setIPASSCC18(String value) { this.ipasscc18 = value; } /** * Gets the value of the mhuPackagingCodeText property. * * @return * possible object is * {@link String }
* */ public String getMHUPackagingCodeText() { return mhuPackagingCodeText; } /** * Sets the value of the mhuPackagingCodeText property. * * @param value * allowed object is * {@link String } * */ public void setMHUPackagingCodeText(String value) { this.mhuPackagingCodeText = value; } /** * Gets the value of the ediExpDesadvPackItem property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ediExpDesadvPackItem property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEDIExpDesadvPackItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EDIExpDesadvPackItemType } * * */ public List<EDIExpDesadvPackItemType> getEDIExpDesadvPackItem() { if (ediExpDesadvPackItem == null) { ediExpDesadvPackItem = new ArrayList<EDIExpDesadvPackItemType>(); } return this.ediExpDesadvPackItem; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvPackType.java
2
请完成以下Java代码
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } /** * Allows control over the destination a remembered user is sent to when they are * successfully authenticated. By default, the filter will just allow the current * request to proceed, but if an {@code AuthenticationSuccessHandler} is set, it will * be invoked and the {@code doFilter()} method will return immediately, thus allowing * the application to redirect the user to a specific URL, regardless of whatthe * original request was for. * @param successHandler the strategy to invoke immediately before returning from * {@code doFilter()}. */ public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) { Assert.notNull(successHandler, "successHandler cannot be null"); this.successHandler = successHandler; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the * {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; }
/** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * The session handling strategy which will be invoked immediately after an * authentication request is successfully processed by the * <tt>AuthenticationManager</tt>. Used, for example, to handle changing of the * session identifier to prevent session fixation attacks. * @param sessionStrategy the implementation to use. If not set a null implementation * is used. * @since 6.4 */ public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) { Assert.notNull(sessionStrategy, "sessionStrategy cannot be null"); this.sessionStrategy = sessionStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilter.java
1
请完成以下Java代码
public Object invoke(ELContext context, Object[] paramValues) throws ELException { return node.invoke(bindings, context, type, types, paramValues); } /** * @return <code>true</code> if this is a literal text expression */ @Override public boolean isLiteralText() { return node.isLiteralText(); } /** * @return <code>true</code> if this is a method invocation expression */ @Override public boolean isParametersProvided() { return node.isMethodInvocation(); } /** * Answer <code>true</code> if this is a deferred expression (starting with <code>#{</code>) */ public boolean isDeferred() { return deferred; } /** * Expressions are compared using the concept of a <em>structural id</em>: * variable and function names are anonymized such that two expressions with * same tree structure will also have the same structural id and vice versa. * Two method expressions are equal if * <ol> * <li>their builders are equal</li> * <li>their structural id's are equal</li> * <li>their bindings are equal</li> * <li>their expected types match</li> * <li>their parameter types are equal</li> * </ol> */ @Override public boolean equals(Object obj) { if (obj != null && obj.getClass() == getClass()) { TreeMethodExpression other = (TreeMethodExpression) obj;
if (!builder.equals(other.builder)) { return false; } if (type != other.type) { return false; } if (!Arrays.equals(types, other.types)) { return false; } return (getStructuralId().equals(other.getStructuralId()) && bindings.equals(other.bindings)); } return false; } @Override public int hashCode() { return getStructuralId().hashCode(); } @Override public String toString() { return "TreeMethodExpression(" + expr + ")"; } /** * Print the parse tree. * @param writer */ public void dump(PrintWriter writer) { NodePrinter.dump(writer, node); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); try { node = builder.build(expr).getRoot(); } catch (ELException e) { throw new IOException(e.getMessage()); } } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\TreeMethodExpression.java
1
请在Spring Boot框架中完成以下Java代码
private Evaluatee createEvaluationContext(final ReportContext reportContext) { final Map<String, Object> reportContextAsMap = createContextAsMap(reportContext); final Evaluatee2 reportContextAsEvaluatee = Evaluatees.ofMap(reportContextAsMap); final Evaluatee ctxEvaluatee = Evaluatees.ofCtx(reportContext.getCtx(), Env.WINDOW_MAIN, false); // onlyWindow=false return Evaluatees.compose(reportContextAsEvaluatee, ctxEvaluatee); } private Map<String, Object> createContextAsMap(final ReportContext reportContext) { final Collection<ProcessInfoParameter> processInfoParams = reportContext.getProcessInfoParameters(); if (processInfoParams.isEmpty()) { return ImmutableMap.of(); } final TreeMap<String, Object> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); map.put("AD_Process_ID", reportContext.getAD_Process_ID()); map.put("AD_PInstance_ID", PInstanceId.toRepoId(reportContext.getPinstanceId())); map.put("AD_Table_ID", reportContext.getAD_Table_ID());
map.put("Record_ID", reportContext.getRecord_ID()); map.put("AD_Language", reportContext.getAD_Language()); map.put("OutputType", reportContext.getOutputType()); for (final ProcessInfoParameter param : processInfoParams) { final String parameterName = param.getParameterName(); map.put(parameterName, param.getParameter()); map.put(parameterName + "_Info", param.getInfo()); map.put(parameterName + "_From", param.getParameter()); map.put(parameterName + "_From_Info", param.getInfo()); map.put(parameterName + "_To", param.getParameter_To()); map.put(parameterName + "_To_Info", param.getInfo_To()); } return Collections.unmodifiableMap(map); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\XlsReportEngine.java
2
请完成以下Java代码
public void setPOSPaymentProcessor (final @Nullable java.lang.String POSPaymentProcessor) { set_Value (COLUMNNAME_POSPaymentProcessor, POSPaymentProcessor); } @Override public java.lang.String getPOSPaymentProcessor() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessor); } @Override public void setPrinterName (final @Nullable java.lang.String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } @Override public java.lang.String getPrinterName() { return get_ValueAsString(COLUMNNAME_PrinterName); }
@Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POS.java
1
请完成以下Java代码
public void setFrequencyType (String FrequencyType) { set_Value (COLUMNNAME_FrequencyType, FrequencyType); } /** Get Frequency Type. @return Frequency of event */ public String getFrequencyType () { return (String)get_Value(COLUMNNAME_FrequencyType); } /** Set Days to keep Log. @param KeepLogDays Number of days to keep the log entries */ public void setKeepLogDays (int KeepLogDays) { set_Value (COLUMNNAME_KeepLogDays, Integer.valueOf(KeepLogDays)); } /** Get Days to keep Log. @return Number of days to keep the log entries */ public int getKeepLogDays () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set 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; } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessor.java
1
请完成以下Java代码
public String getName() { return "Undeploying process archvie "+processArchvieName; } public void performOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); final Map<String, DeployedProcessArchive> processArchiveDeploymentMap = deployedProcessApplication.getProcessArchiveDeploymentMap(); final DeployedProcessArchive deployedProcessArchive = processArchiveDeploymentMap.get(processArchive.getName()); final ProcessEngine processEngine = serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, processEngineName); // unregrister with the process engine. processEngine.getManagementService().unregisterProcessApplication(deployedProcessArchive.getAllDeploymentIds(), true);
// delete the deployment if not disabled if (PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_DELETE_UPON_UNDEPLOY, false)) { if (processEngine != null) { // always cascade & skip custom listeners deleteDeployment(deployedProcessArchive.getPrimaryDeploymentId(), processEngine.getRepositoryService()); } } } protected void deleteDeployment(String deploymentId, RepositoryService repositoryService) { repositoryService.deleteDeployment(deploymentId, true, true); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\UndeployProcessArchiveStep.java
1
请在Spring Boot框架中完成以下Java代码
public void setSessionValidationInterval(Integer sessionValidationInterval) { this.sessionValidationInterval = sessionValidationInterval; } public String getFilesUrlPrefix() { return filesUrlPrefix; } public void setFilesUrlPrefix(String filesUrlPrefix) { this.filesUrlPrefix = filesUrlPrefix; } public String getFilesPath() { return filesPath; } public void setFilesPath(String filesPath) { this.filesPath = filesPath; } public Integer getHeartbeatTimeout() { return heartbeatTimeout; } public void setHeartbeatTimeout(Integer heartbeatTimeout) { this.heartbeatTimeout = heartbeatTimeout; }
public String getPicsPath() { return picsPath; } public void setPicsPath(String picsPath) { this.picsPath = picsPath; } public String getPosapiUrlPrefix() { return posapiUrlPrefix; } public void setPosapiUrlPrefix(String posapiUrlPrefix) { this.posapiUrlPrefix = posapiUrlPrefix; } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\properties\MyProperties.java
2
请完成以下Java代码
public void calloutOnElementIdChanged(final I_AD_Tab tab) { updateTabFromElement(tab); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_AD_Tab.COLUMNNAME_AD_Element_ID) public void onBeforeTabSave_WhenElementIdChanged(final I_AD_Tab tab) { updateTabFromElement(tab); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_AD_Tab.COLUMNNAME_AD_Element_ID) public void onAfterTabSave_WhenElementIdChanged(final I_AD_Tab tab) { updateTranslationsForElement(tab); recreateElementLinkForTab(tab); } private void updateTabFromElement(final I_AD_Tab tab) { final IADElementDAO adElementDAO = Services.get(IADElementDAO.class); final I_AD_Element tabElement = adElementDAO.getById(tab.getAD_Element_ID()); if (tabElement == null) { // nothing to do. It was not yet set return; } tab.setName(tabElement.getName()); tab.setDescription(tabElement.getDescription()); tab.setHelp(tabElement.getHelp()); tab.setCommitWarning(tabElement.getCommitWarning()); tab.setEntityType(tab.getAD_Window().getEntityType()); } private void recreateElementLinkForTab(final I_AD_Tab tab) { final AdTabId adTabId = AdTabId.ofRepoIdOrNull(tab.getAD_Tab_ID()); if (adTabId != null) { final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.createADElementLinkForTabId(adTabId); }
} private void updateTranslationsForElement(final I_AD_Tab tab) { if (!IElementTranslationBL.DYNATTR_AD_Tab_UpdateTranslations.getValue(tab, true)) { // do not copy translations from element to tab return; } final AdElementId tabElementId = AdElementId.ofRepoIdOrNull(tab.getAD_Element_ID()); if (tabElementId == null) { // nothing to do. It was not yet set return; } Services.get(IElementTranslationBL.class).updateTabTranslationsFromElement(tabElementId); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void onBeforeTabDelete(final I_AD_Tab tab) { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final AdTabId adTabId = AdTabId.ofRepoId(tab.getAD_Tab_ID()); adWindowDAO.deleteFieldsByTabId(adTabId); adWindowDAO.deleteUISectionsByTabId(adTabId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\tab\model\interceptor\AD_Tab.java
1
请完成以下Java代码
public int getM_PropertiesConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); }
/** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PropertiesConfig.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } public void batchAuthorsAndBooks() { List<Author> authors = new ArrayList<>(); for (int i = 0; i < 10; i++) { Author author = new Author(); author.setName("Name_" + i); author.setGenre("Genre_" + i); author.setAge((int) ((Math.random() + 0.1) * 100)); for (int j = 0; j < 5; j++) { Book book = new Book(); book.setTitle("Title: " + j); book.setIsbn("Isbn: " + j); author.addBook(book); } authors.add(author); } authorRepository.saveAll(authors); } // explicitly delete all records from each table @Transactional public void deleteAuthorsAndBooksViaDeleteAllInBatch() { authorRepository.deleteAllInBatch(); bookRepository.deleteAllInBatch(); } // explicitly delete all records from each table @Transactional public void deleteAuthorsAndBooksViaDeleteInBatch() { List<Author> authors = authorRepository.fetchAuthorsAndBooks(60); authorRepository.deleteInBatch(authors);
authors.forEach(a -> bookRepository.deleteInBatch(a.getBooks())); } // good if you need to delete in a classical batch approach // deletes are cascaded by CascadeType.REMOVE and batched as well // the DELETE statements are not sorted at all and this causes more batches than needed for this job @Transactional public void deleteAuthorsAndBooksViaDeleteAll() { List<Author> authors = authorRepository.fetchAuthorsAndBooks(60); authorRepository.deleteAll(authors); // for deleting all Authors use deleteAll() } // good if you need to delete in a classical batch approach // (uses orphanRemoval = true, and optimize the number of batches) @Transactional public void deleteAuthorsAndBooksViaDelete() { List<Author> authors = authorRepository.fetchAuthorsAndBooks(60); authors.forEach(Author::removeBooks); authorRepository.flush(); authors.forEach(authorRepository::delete); // or, authorRepository.deleteAll(authors); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteOrphanRemoval\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } @Override public Boolean getDisplay() { return display; } public void setDisplay(Boolean display) { this.display = display; } @Override public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @Override
public boolean isAnalytics() { return analytics; } public void setAnalytics(boolean analytics) { this.analytics = analytics; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VariableDefinitionImpl that = (VariableDefinitionImpl) o; return ( required == that.required && Objects.equals(display, that.display) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(type, that.type) && Objects.equals(displayName, that.displayName) && Objects.equals(analytics, that.analytics) ); } @Override public int hashCode() { return Objects.hash(id, name, description, type, required, display, displayName, analytics); } @Override public String toString() { return ( "VariableDefinitionImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type='" + type + '\'' + ", required=" + required + ", display=" + display + ", displayName='" + displayName + '\'' + ", analytics='" + analytics + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\VariableDefinitionImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class GroupCategoryId implements RepoIdAware { int repoId; @JsonCreator public static GroupCategoryId ofRepoId(final int repoId) { return new GroupCategoryId(repoId); } @Nullable public static GroupCategoryId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new GroupCategoryId(repoId) : null; } public static Optional<GroupCategoryId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final GroupCategoryId id) { return id != null ? id.getRepoId() : -1;
} private GroupCategoryId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_CompensationGroup_Schema_Category_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupCategoryId.java
2
请完成以下Java代码
public boolean isRegistered () { Object oo = get_Value(COLUMNNAME_IsRegistered); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Type AD_Reference_ID=53245 */ public static final int TYPE_AD_Reference_ID=53245; /** Concept = C */ public static final String TYPE_Concept = "C"; /** Rule Engine = E */ public static final String TYPE_RuleEngine = "E"; /** Information = I */ public static final String TYPE_Information = "I"; /** Reference = R */ public static final String TYPE_Reference = "R"; /** Set Type. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); }
/** 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 Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept.java
1
请完成以下Java代码
public String getUserName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_User_Name); } public String getRoleName() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Role_Name); } String getAdLanguage() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Language); } Language getLanguage() { return Env.getLanguage(getCtx()); } /** * @return previous language */ String verifyLanguageAndSet(final Language lang) {
final Properties ctx = getCtx(); final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language); // // Check the language (and update it if needed) final Language validLang = Env.verifyLanguageFallbackToBase(lang); // // Actual update final String adLanguageNew = validLang.getAD_Language(); Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew); this.locale = validLang.getLocale(); UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang); return adLanguageOld; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\InternalUserSessionData.java
1
请完成以下Java代码
public static void givenStack_whenUsingForEach_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); List<Integer> result = new ArrayList<>(); for (Integer value : stack) { System.out.print(value + " "); } } public static void givenStack_whenUsingDirectForEach_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); stack.forEach(element -> System.out.println(element)); } public static void givenStack_whenUsingStreamReverse_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(20); stack.push(10); stack.push(30); Collections.reverse(stack); stack.forEach(System.out::println); } public static void givenStack_whenUsingIterator_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10);
stack.push(20); stack.push(30); Iterator<Integer> iterator = stack.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } } public static void givenStack_whenUsingListIteratorReverseOrder_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); ListIterator<Integer> iterator = stack.listIterator(stack.size()); while (iterator.hasPrevious()) { System.out.print(iterator.previous() + " "); } } public static void givenStack_whenUsingDeque_thenPrintStack() { Deque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); stack.forEach(e -> System.out.print(e + " ")); } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\PrintStack.java
1
请完成以下Java代码
private void insertRow(int currentRow) { } // inserRow /** * Get Print Data including additional Lines * * @param row * row * @param col * col * @return non null array of print objects (may be empty) */ private Object[] getPrintItems(int row, int col) { ArrayList<ArrayList<Object>> columns = null; if (m_printRows.size() > row) { columns = m_printRows.get(row); }
if (columns == null) { return new Object[] {}; } ArrayList<Object> coordinate = null; if (columns.size() > col) { coordinate = columns.get(col); } if (coordinate == null) { return new Object[] {}; } // return coordinate.toArray(); } // getPrintItems }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\TableElement.java
1
请完成以下Java代码
public int getAD_Client_ID() { return m_AD_Client_ID; } @Override public void initialize(ModelValidationEngine engine, MClient client) { if (client != null) { m_AD_Client_ID = client.getAD_Client_ID(); } engine.addModelChange(I_AD_Tab.Table_Name, this); engine.addModelChange(I_AD_Ref_Table.Table_Name, this); } @Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { // // Log Migration Scripts, if we log in with SysAdm role and the ID server is configured final RoleId roleId = RoleId.ofRepoId(AD_Role_ID); MigrationScriptFileLoggerHolder.setEnabled(roleId.isSystem() && MSequence.isExternalIDSystemEnabled()); return null; } @Override public String modelChange(PO po, int type) throws Exception { if (I_AD_Tab.Table_Name.equals(po.get_TableName()) && type == TYPE_AFTER_CHANGE && po.is_ValueChanged(I_AD_Tab.COLUMNNAME_AD_Table_ID)) { I_AD_Tab tab = InterfaceWrapperHelper.create(po, I_AD_Tab.class); updateTabFieldColumns(po.getCtx(), tab, po.get_TrxName()); } if (I_AD_Ref_Table.Table_Name.equals(po.get_TableName()) && (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE)) { I_AD_Ref_Table refTable = InterfaceWrapperHelper.create(po, I_AD_Ref_Table.class); validate(refTable); } // return null; }
private void validate(I_AD_Ref_Table refTable) { String whereClause = refTable.getWhereClause(); if (!Check.isEmpty(whereClause, true) && whereClause.indexOf("@") >= 0) { log.warn("Using context variables in table reference where clause is not adviced"); } } private void updateTabFieldColumns(Properties ctx, I_AD_Tab tab, String trxName) { final String tableName = Services.get(IADTableDAO.class).retrieveTableName(tab.getAD_Table_ID()); final List<I_AD_Field> fields = new Query(ctx, I_AD_Field.Table_Name, I_AD_Field.COLUMNNAME_AD_Tab_ID + "=?", trxName) .setParameters(tab.getAD_Tab_ID()) .setOrderBy(I_AD_Field.COLUMNNAME_SeqNo) .list(I_AD_Field.class); for (I_AD_Field field : fields) { I_AD_Column columnOld = field.getAD_Column(); int columnId = MColumn.getColumn_ID(tableName, columnOld.getColumnName()); if (columnId > 0) { field.setAD_Column_ID(columnId); InterfaceWrapperHelper.save(field); log.info("Updated AD_Column_ID for field " + field.getName()); } else { log.info("Deleting field " + field.getName()); InterfaceWrapperHelper.getPO(field).deleteEx(true); // TODO: use POWrapper.delete } } } @Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\model\validator\ApplicationDictionary.java
1
请完成以下Java代码
private DraftPPOrderBOMLineQuantities addToNullable( @Nullable final DraftPPOrderBOMLineQuantities line, @NonNull final DraftPPOrderBOMLineQuantities lineToAdd) { return line != null ? line.add(lineToAdd, uomConversionBL) : lineToAdd; } public boolean isReceipt(@NonNull final I_PP_Order_Qty ppOrderQty) { return ppOrderQty.getPP_Order_BOMLine_ID() <= 0; } @Override public void updateDraftReceiptCandidate(@NonNull UpdateDraftReceiptCandidateRequest request) { final PPOrderId pickingOrderId = request.getPickingOrderId(); final HuId huId = request.getHuID(); final Quantity qtyToUpdate = request.getQtyReceived(); huPPOrderQtyDAO.retrieveOrderQtyForHu(pickingOrderId, huId) .filter(candidate -> !candidate.isProcessed() && isReceipt(candidate)) .ifPresent(candidate -> { I_M_HU hu = candidate.getM_HU(); candidate.setQty(qtyToUpdate.toBigDecimal()); huPPOrderQtyDAO.save(candidate); }); } @Override public Set<HuId> getFinishedGoodsReceivedHUIds(@NonNull final PPOrderId ppOrderId) {
final HashSet<HuId> receivedHUIds = new HashSet<>(); huPPOrderQtyDAO.retrieveOrderQtyForFinishedGoodsReceive(ppOrderId) .stream() .filter(I_PP_Order_Qty::isProcessed) .forEach(processedCandidate -> { final HuId huId = HuId.ofRepoId(processedCandidate.getM_HU_ID()); receivedHUIds.add(huId); final I_M_HU parentHU = handlingUnitsBL.getTopLevelParent(huId); receivedHUIds.add(HuId.ofRepoId(parentHU.getM_HU_ID())); }); return receivedHUIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPOrderQtyBL.java
1
请完成以下Java代码
public static final class AuthenticatorAttestationResponseBuilder { @SuppressWarnings("NullAway.Init") private Bytes attestationObject; private @Nullable List<AuthenticatorTransport> transports; @SuppressWarnings("NullAway.Init") private Bytes clientDataJSON; private AuthenticatorAttestationResponseBuilder() { } /** * Sets the {@link #getAttestationObject()} property. * @param attestationObject the attestation object. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder attestationObject(Bytes attestationObject) { this.attestationObject = attestationObject; return this; } /** * Sets the {@link #getTransports()} property. * @param transports the transports * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder transports(AuthenticatorTransport... transports) { return transports(Arrays.asList(transports)); } /** * Sets the {@link #getTransports()} property. * @param transports the transports * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder transports(List<AuthenticatorTransport> transports) { this.transports = transports; return this; } /** * Sets the {@link #getClientDataJSON()} property.
* @param clientDataJSON the client data JSON. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder clientDataJSON(Bytes clientDataJSON) { this.clientDataJSON = clientDataJSON; return this; } /** * Builds a {@link AuthenticatorAssertionResponse}. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponse build() { return new AuthenticatorAttestationResponse(this.clientDataJSON, this.attestationObject, this.transports); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorAttestationResponse.java
1
请在Spring Boot框架中完成以下Java代码
public void initDataManagers() { if (eventSubscriptionDataManager == null) { eventSubscriptionDataManager = new MybatisEventSubscriptionDataManager(this); } } public void initEntityManagers() { if (eventSubscriptionEntityManager == null) { eventSubscriptionEntityManager = new EventSubscriptionEntityManagerImpl(this, eventSubscriptionDataManager); } } // getters and setters // ////////////////////////////////////////////////////// public EventSubscriptionServiceConfiguration getIdentityLinkServiceConfiguration() { return this; } public EventSubscriptionService getEventSubscriptionService() { return eventSubscriptionService; } public EventSubscriptionServiceConfiguration setEventSubscriptionService(EventSubscriptionService eventSubscriptionService) { this.eventSubscriptionService = eventSubscriptionService; return this; } public EventSubscriptionDataManager getEventSubscriptionDataManager() { return eventSubscriptionDataManager; } public EventSubscriptionServiceConfiguration setEventSubscriptionDataManager(EventSubscriptionDataManager eventSubscriptionDataManager) { this.eventSubscriptionDataManager = eventSubscriptionDataManager; return this; } public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return eventSubscriptionEntityManager; } public EventSubscriptionServiceConfiguration setEventSubscriptionEntityManager(EventSubscriptionEntityManager eventSubscriptionEntityManager) { this.eventSubscriptionEntityManager = eventSubscriptionEntityManager; return this; }
@Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public EventSubscriptionServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public Duration getEventSubscriptionLockTime() { return eventSubscriptionLockTime; } public EventSubscriptionServiceConfiguration setEventSubscriptionLockTime(Duration eventSubscriptionLockTime) { this.eventSubscriptionLockTime = eventSubscriptionLockTime; return this; } public String getLockOwner() { return lockOwner; } public EventSubscriptionServiceConfiguration setLockOwner(String lockOwner) { this.lockOwner = lockOwner; return this; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\EventSubscriptionServiceConfiguration.java
2
请完成以下Java代码
private static LocalDate retrieveLocalDate(final ResultSet rs) throws SQLException { return TimeUtil.asLocalDate(rs.getTimestamp(1)); } private static LocalTime retrieveLocalTime(final ResultSet rs) throws SQLException { return TimeUtil.asLocalTime(rs.getTimestamp(1)); } private static final Logger logger = LogManager.getLogger(SqlDefaultValueExpression.class); private final IStringExpression stringExpression; private final Class<V> valueClass; private final V noResultValue; private final ValueLoader<V> valueRetriever; @FunctionalInterface private interface ValueLoader<V> { V get(final ResultSet rs) throws SQLException; } private SqlDefaultValueExpression( @NonNull final IStringExpression stringExpression, final Class<V> valueType, final ValueLoader<V> valueRetriever) { this.stringExpression = stringExpression; this.valueClass = valueType; this.noResultValue = null; // IStringExpression.EMPTY_RESULT this.valueRetriever = valueRetriever; } @Override public String toString() { return stringExpression.toString(); } @Override public Class<V> getValueClass() { return valueClass; } @Override public boolean isNoResult(final Object result) { return result == null || result == noResultValue; } @Override public boolean isNullExpression() { return false; } @Override public String getExpressionString() { return stringExpression.getExpressionString(); } @Override public String getFormatedExpressionString() { return stringExpression.getFormatedExpressionString(); } @Override public Set<String> getParameterNames() { return stringExpression.getParameterNames(); }
@Override public Set<CtxName> getParameters() { return stringExpression.getParameters(); } @Override public V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { final String sql = stringExpression.evaluate(ctx, onVariableNotFound); if (Check.isEmpty(sql, true)) { logger.warn("Expression " + stringExpression + " was evaluated to empty string. Returning no result: {}", noResultValue); return noResultValue; } PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); if (rs.next()) { final V value = valueRetriever.get(rs); return value; } else { if (onVariableNotFound == OnVariableNotFound.Fail) { throw ExpressionEvaluationException.newWithPlainMessage("Got no result for " + this) .setParameter("SQL", sql) .appendParametersToMessage(); } logger.warn("Got no result for {} (SQL: {})", this, sql); return noResultValue; } } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDefaultValueExpression.java
1
请在Spring Boot框架中完成以下Java代码
public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } /** Static resource locations including themes*/ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/", "/resources/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new PathResourceResolver()); } /** BEGIN theme configuration */ @Bean public ResourceBundleThemeSource themeSource() { ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); themeSource.setDefaultEncoding("UTF-8"); themeSource.setBasenamePrefix("themes."); return themeSource; } @Bean public CookieThemeResolver themeResolver() { CookieThemeResolver resolver = new CookieThemeResolver(); resolver.setDefaultThemeName("default");
resolver.setCookieName("example-theme-cookie"); return resolver; } @Bean public ThemeChangeInterceptor themeChangeInterceptor() { ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor(); interceptor.setParamName("theme"); return interceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(themeChangeInterceptor()); } @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() { return factory -> factory.setRegisterDefaultServlet(true); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\web\config\WebConfig.java
2
请完成以下Java代码
public int size() { return cache.size(); } protected ProcessDefinitionInfoCacheObject retrieveProcessDefinitionInfoCacheObject( String processDefinitionId, CommandContext commandContext ) { ProcessDefinitionInfoEntityManager infoEntityManager = commandContext.getProcessDefinitionInfoEntityManager(); ObjectMapper objectMapper = commandContext.getProcessEngineConfiguration().getObjectMapper(); ProcessDefinitionInfoCacheObject cacheObject = null; if (cache.containsKey(processDefinitionId)) { cacheObject = cache.get(processDefinitionId); } else { cacheObject = new ProcessDefinitionInfoCacheObject(); cacheObject.setRevision(0); cacheObject.setInfoNode(objectMapper.createObjectNode()); } ProcessDefinitionInfoEntity infoEntity = infoEntityManager.findProcessDefinitionInfoByProcessDefinitionId( processDefinitionId
); if (infoEntity != null && infoEntity.getRevision() != cacheObject.getRevision()) { cacheObject.setRevision(infoEntity.getRevision()); if (infoEntity.getInfoJsonId() != null) { byte[] infoBytes = infoEntityManager.findInfoJsonById(infoEntity.getInfoJsonId()); try { ObjectNode infoNode = (ObjectNode) objectMapper.readTree(infoBytes); cacheObject.setInfoNode(infoNode); } catch (Exception e) { throw new ActivitiException( "Error reading json info node for process definition " + processDefinitionId, e ); } } } else if (infoEntity == null) { cacheObject.setRevision(0); cacheObject.setInfoNode(objectMapper.createObjectNode()); } return cacheObject; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\ProcessDefinitionInfoCache.java
1
请完成以下Java代码
public List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext) { final List<IPair<IAllocationRequest, IAllocationResult>> result = new ArrayList<>(); final Iterator<IAllocationSource> sourceIterator = sources.iterator(); while (sourceIterator.hasNext()) { final IAllocationSource source = sourceIterator.next(); final List<IPair<IAllocationRequest, IAllocationResult>> sourceResult = source.unloadAll(huContext); result.addAll(sourceResult); } return result; } @Override public void loadComplete(final IHUContext huContext) { for (final IAllocationDestination destionation : destinations)
{ destionation.loadComplete(huContext); } } @Override public void unloadComplete(final IHUContext huContext) { for (final IAllocationSource source : sources) { source.unloadComplete(huContext); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\GenericListAllocationSourceDestination.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue private int id; private String name; private String title; public Employee() { } public Employee(String name, String title) { this.name = name; this.title = title; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getId() { return id; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\boot\domain\Employee.java
2
请完成以下Java代码
public int discoverServers(String msg) throws IOException { initializeSocketForBroadcasting(); copyMessageOnBuffer(msg); // When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value. broadcastPacket(address); return receivePackets(); } List<InetAddress> listAllBroadcastAddresses() throws SocketException { List<InetAddress> broadcastList = new ArrayList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } broadcastList.addAll(networkInterface.getInterfaceAddresses() .stream() .filter(address -> address.getBroadcast() != null) .map(address -> address.getBroadcast()) .collect(Collectors.toList())); } return broadcastList; } private void initializeSocketForBroadcasting() throws SocketException { socket = new DatagramSocket();
socket.setBroadcast(true); } private void copyMessageOnBuffer(String msg) { buf = msg.getBytes(); } private void broadcastPacket(InetAddress address) throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); } private int receivePackets() throws IOException { int serversDiscovered = 0; while (serversDiscovered != expectedServerCount) { receivePacket(); serversDiscovered++; } return serversDiscovered; } private void receivePacket() throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); } public void close() { socket.close(); } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\udp\broadcast\BroadcastingClient.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricDetailRestServiceImpl implements HistoricDetailRestService { protected ObjectMapper objectMapper; protected ProcessEngine processEngine; public HistoricDetailRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { this.objectMapper = objectMapper; this.processEngine = processEngine; } @Override public HistoricDetailResource historicDetail(String detailId) { return new HistoricDetailResourceImpl(detailId, processEngine); } @Override public List<HistoricDetailDto> getHistoricDetails(UriInfo uriInfo, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { HistoricDetailQueryDto queryDto = new HistoricDetailQueryDto(objectMapper, uriInfo.getQueryParameters()); HistoricDetailQuery query = queryDto.toQuery(processEngine); return executeHistoricDetailQuery(query, firstResult, maxResults, deserializeObjectValues); } @Override public List<HistoricDetailDto> queryHistoricDetails(HistoricDetailQueryDto queryDto, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { HistoricDetailQuery query = queryDto.toQuery(processEngine); return executeHistoricDetailQuery(query, firstResult, maxResults, deserializeObjectValues); } @Override
public CountResultDto getHistoricDetailsCount(UriInfo uriInfo) { HistoricDetailQueryDto queryDto = new HistoricDetailQueryDto(objectMapper, uriInfo.getQueryParameters()); HistoricDetailQuery query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } private List<HistoricDetailDto> executeHistoricDetailQuery(HistoricDetailQuery query, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { query.disableBinaryFetching(); if (!deserializeObjectValues) { query.disableCustomObjectDeserialization(); } List<HistoricDetail> queryResult = QueryUtil.list(query, firstResult, maxResults); List<HistoricDetailDto> result = new ArrayList<HistoricDetailDto>(); for (HistoricDetail historicDetail : queryResult) { HistoricDetailDto dto = HistoricDetailDto.fromHistoricDetail(historicDetail); result.add(dto); } return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricDetailRestServiceImpl.java
2
请完成以下Java代码
public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public List<PropertyChange> getPropertyChanges() { return propertyChanges; } public void setPropertyChanges(List<PropertyChange> propertyChanges) { this.propertyChanges = propertyChanges; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getRootProcessInstanceId() { return rootProcessInstanceId; }
public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getExternalTaskId() { return externalTaskId; } public void setExternalTaskId(String externalTaskId) { this.externalTaskId = externalTaskId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java
1
请完成以下Java代码
public void invalidateView(final ViewId packingHUsViewId) { getPackingHUsViewIfExists(packingHUsViewId) .ifPresent(packingHUsView -> packingHUsView.invalidateAll()); } private Optional<HUEditorView> getPackingHUsViewIfExists(final ViewId packingHUsViewId) { final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView(packingHUsViewId); return pickingSlotsClearingView.getPackingHUsViewIfExists(packingHUsViewId); } private HUEditorView getOrCreatePackingHUsView(final ViewId packingHUsViewId) { final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView(packingHUsViewId); return pickingSlotsClearingView.computePackingHUsViewIfAbsent( packingHUsViewId, this::createPackingHUsView); } private HUEditorView createPackingHUsView(@NonNull final PackingHUsViewKey key) { return createPackingHUsView(key, null); } private HUEditorView createPackingHUsView( @NonNull final PackingHUsViewKey key, @Nullable final JSONFilterViewRequest additionalFilters) { final IHUQueryBuilder huQuery = createHUQuery(key); final ViewId packingHUsViewId = key.getPackingHUsViewId(); final ViewId pickingSlotsClearingViewId = key.getPickingSlotsClearingViewId(); final CreateViewRequest request = CreateViewRequest.builder(packingHUsViewId, JSONViewDataType.includedView) .setParentViewId(pickingSlotsClearingViewId) .setFiltersFromJSON(additionalFilters != null ? additionalFilters.getFilters() : ImmutableList.of()) .addStickyFilters(HUIdsFilterHelper.createFilter(huQuery)) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(WEBUI_PackingHUsView_AddHUsToShipperTransportation.class))
.addAdditionalRelatedProcessDescriptor(createProcessDescriptor(WEBUI_PackingHUsView_AddHUsToShipperTransportationShipAndInvoice.class)) .setParameter(WEBUI_M_HU_Transform.PARAM_CheckExistingHUsInsideView, true) .build(); return huEditorViewFactory.createView(request); } private RelatedProcessDescriptor createProcessDescriptor(final Class<? extends JavaProcess> processClass) { return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClass(processClass)) .anyTable().anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } private IHUQueryBuilder createHUQuery(final PackingHUsViewKey key) { final IHUQueryBuilder huQuery = Services.get(IHandlingUnitsDAO.class) .createHUQueryBuilder() .setIncludeAfterPickingLocator(true) .setExcludeHUsOnPickingSlot(true) .onlyNotLocked() // not already locked (NOTE: those which were enqueued to Transportation Order are locked) ; if (key.getBpartnerId() > 0) { huQuery.addOnlyInBPartnerId(BPartnerId.ofRepoId(key.getBpartnerId())); } if (key.getBpartnerLocationId() > 0) { huQuery.addOnlyWithBPartnerLocationId(key.getBpartnerLocationId()); } return huQuery; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PackingHUsViewFactory.java
1
请完成以下Java代码
private void exportInvoice(@NonNull final InvoiceToExport invoiceToExport) { final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); final List<InvoiceExportClient> exportClients = invoiceExportServiceRegistry.createExportClients(invoiceToExport); if (exportClients.isEmpty()) { loggable.addLog("InvoiceExportService - Found no InvoiceExportClient implementors for invoiceId={}; invoiceToExport={}", invoiceToExport.getId(), invoiceToExport); return; // nothing more to do } final List<AttachmentEntryCreateRequest> attachmentEntryCreateRequests = new ArrayList<>(); for (final InvoiceExportClient exportClient : exportClients) { final List<InvoiceExportResult> exportResults = exportClient.export(invoiceToExport); for (final InvoiceExportResult exportResult : exportResults) { attachmentEntryCreateRequests.add(createAttachmentRequest(exportResult)); } } for (final AttachmentEntryCreateRequest attachmentEntryCreateRequest : attachmentEntryCreateRequests) { attachmentEntryService.createNewAttachment( TableRecordReference.of(I_C_Invoice.Table_Name, invoiceToExport.getId()), attachmentEntryCreateRequest); loggable.addLog("InvoiceExportService - Attached export data to invoiceId={}; attachment={}", invoiceToExport.getId(), attachmentEntryCreateRequest); } } private AttachmentEntryCreateRequest createAttachmentRequest(@NonNull final InvoiceExportResult exportResult) { final byte[] byteArrayData; try
{ byteArrayData = ByteStreams.toByteArray(exportResult.getData()); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } final AttachmentTags attachmentTag = AttachmentTags.builder() .tag(AttachmentTags.TAGNAME_IS_DOCUMENT, StringUtils.ofBoolean(true)) // other than the "input" xml with was more or less just a template, this is a document .tag(AttachmentTags.TAGNAME_BPARTNER_RECIPIENT_ID, Integer.toString(exportResult.getRecipientId().getRepoId())) .tag(InvoiceExportClientFactory.ATTACHMENT_TAGNAME_EXPORT_PROVIDER, exportResult.getInvoiceExportProviderId()) .build(); final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest .builderFromByteArray( exportResult.getFileName(), byteArrayData) .tags(attachmentTag) .build(); return attachmentEntryCreateRequest; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\InvoiceExportService.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_C_Invoice getC_Invoice_From() { return get_ValueAsPO(COLUMNNAME_C_Invoice_From_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice_From(final org.compiere.model.I_C_Invoice C_Invoice_From) { set_ValueFromPO(COLUMNNAME_C_Invoice_From_ID, org.compiere.model.I_C_Invoice.class, C_Invoice_From); } @Override public void setC_Invoice_From_ID (final int C_Invoice_From_ID) { if (C_Invoice_From_ID < 1) set_Value (COLUMNNAME_C_Invoice_From_ID, null); else set_Value (COLUMNNAME_C_Invoice_From_ID, C_Invoice_From_ID); } @Override public int getC_Invoice_From_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_From_ID); } @Override public void setC_Invoice_Relation_ID (final int C_Invoice_Relation_ID) { if (C_Invoice_Relation_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Relation_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Relation_ID, C_Invoice_Relation_ID); } @Override public int getC_Invoice_Relation_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Relation_ID); } /**
* C_Invoice_Relation_Type AD_Reference_ID=541475 * Reference name: C_Invoice_Relation_Types */ public static final int C_INVOICE_RELATION_TYPE_AD_Reference_ID=541475; /** PurchaseToSales = POtoSO */ public static final String C_INVOICE_RELATION_TYPE_PurchaseToSales = "POtoSO"; @Override public void setC_Invoice_Relation_Type (final java.lang.String C_Invoice_Relation_Type) { set_Value (COLUMNNAME_C_Invoice_Relation_Type, C_Invoice_Relation_Type); } @Override public java.lang.String getC_Invoice_Relation_Type() { return get_ValueAsString(COLUMNNAME_C_Invoice_Relation_Type); } @Override public org.compiere.model.I_C_Invoice getC_Invoice_To() { return get_ValueAsPO(COLUMNNAME_C_Invoice_To_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice_To(final org.compiere.model.I_C_Invoice C_Invoice_To) { set_ValueFromPO(COLUMNNAME_C_Invoice_To_ID, org.compiere.model.I_C_Invoice.class, C_Invoice_To); } @Override public void setC_Invoice_To_ID (final int C_Invoice_To_ID) { if (C_Invoice_To_ID < 1) set_Value (COLUMNNAME_C_Invoice_To_ID, null); else set_Value (COLUMNNAME_C_Invoice_To_ID, C_Invoice_To_ID); } @Override public int getC_Invoice_To_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_To_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Relation.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { if (e.getSource() == butCall) { callContact(); } else if (e.getSource() == butRefresh) { refreshAll(true); m_updater.start(); } else if (e.getSource() == fShowFromAllBundles) { // fBundles.setEnabled(!fShowFromAllBundles.isSelected()); fBundles.setReadWrite(!fShowFromAllBundles.isSelected()); query(); } else if (e.getSource() == fShowOnlyDue) { query(); } else if (e.getSource() == fShowOnlyOpen) { query(); } } // @Override @Override public void windowStateChanged(WindowEvent e) { // The Customize Window was closed if (e.getID() == WindowEvent.WINDOW_CLOSED && e.getSource() == m_requestFrame && m_model != null // sometimes we get NPE ) { final I_RV_R_Group_Prospect contact = m_model.getRV_R_Group_Prospect(false); m_model.unlockContact(contact); m_frame.setEnabled(true); AEnv.showWindow(m_frame); m_requestFrame = null; refreshAll(true); m_updater.start(); }
} // @Override @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() == m_model.getContactsGridTab() && evt.getPropertyName().equals(GridTab.PROPERTY)) { updateFieldsStatus(); m_model.queryDetails(); vtableAutoSizeAll(); } } public static Image getImage(String fileNameInImageDir) { URL url = CallCenterForm.class.getResource("images/" + fileNameInImageDir); if (url == null) { log.error("Not found: " + fileNameInImageDir); return null; } Toolkit tk = Toolkit.getDefaultToolkit(); return tk.getImage(url); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CallCenterForm.java
1
请完成以下Java代码
public final class VersionReference { private final VersionProperty property; private final String value; private VersionReference(VersionProperty property, String value) { this.property = property; this.value = value; } public static VersionReference ofProperty(VersionProperty property) { return new VersionReference(property, null); } public static VersionReference ofProperty(String internalProperty) { return ofProperty(VersionProperty.of(internalProperty)); } public static VersionReference ofValue(String value) { return new VersionReference(null, value); } /** * Specify if this reference defines a property. * @return {@code true} if this version is backed by a property */ public boolean isProperty() { return this.property != null; } /** * Return the {@link VersionProperty} or {@code null} if this reference is not a * property. * @return the version property or {@code null} */ public VersionProperty getProperty() { return this.property;
} /** * Return the version or {@code null} if this reference is backed by a property. * @return the version or {@code null} */ public String getValue() { return this.value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VersionReference that = (VersionReference) o; return Objects.equals(this.property, that.property) && Objects.equals(this.value, that.value); } @Override public int hashCode() { return Objects.hash(this.property, this.value); } @Override public String toString() { return (this.property != null) ? "${" + this.property.toStandardFormat() + "}" : this.value; } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionReference.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityPostProcessorProperties getPostProcessor() { return this.securityPostProcessorProperties; } public String getPropertiesFile() { return this.propertiesFile; } public void setPropertiesFile(String propertiesFile) { this.propertiesFile = propertiesFile; } public ApacheShiroProperties getShiro() { return this.apacheShiroProperties; } public SslProperties getSsl() { return this.ssl; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public static class ApacheShiroProperties { private String iniResourcePath; public String getIniResourcePath() { return this.iniResourcePath; } public void setIniResourcePath(String iniResourcePath) { this.iniResourcePath = iniResourcePath; } } public static class SecurityLogProperties { private static final String DEFAULT_SECURITY_LOG_LEVEL = "config"; private String file; private String level = DEFAULT_SECURITY_LOG_LEVEL;
public String getFile() { return this.file; } public void setFile(String file) { this.file = file; } public String getLevel() { return this.level; } public void setLevel(String level) { this.level = level; } } public static class SecurityManagerProperties { private String className; public String getClassName() { return this.className; } public void setClassName(String className) { this.className = className; } } public static class SecurityPostProcessorProperties { private String className; public String getClassName() { return this.className; } public void setClassName(String className) { this.className = className; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SecurityProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class GatewayNoLoadBalancerClientAutoConfiguration { @Bean @ConditionalOnMissingBean(ReactiveLoadBalancerClientFilter.class) public NoLoadBalancerClientFilter noLoadBalancerClientFilter(GatewayLoadBalancerProperties properties) { return new NoLoadBalancerClientFilter(properties.isUse404()); } protected static class NoLoadBalancerClientFilter implements GlobalFilter, Ordered { private final boolean use404; public NoLoadBalancerClientFilter(boolean use404) { this.use404 = use404; } @Override public int getOrder() { return LOAD_BALANCER_CLIENT_FILTER_ORDER; }
@Override @SuppressWarnings("Duplicates") public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR); String schemePrefix = exchange.getAttribute(GATEWAY_SCHEME_PREFIX_ATTR); if (url == null || (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) { return chain.filter(exchange); } throw NotFoundException.create(use404, "Unable to find instance for " + url.getHost()); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayNoLoadBalancerClientAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class Chapter24Application { public static void main(String[] args) { SpringApplication.run(Chapter24Application.class, args); } @Api(tags = {"1-教师管理","3-教学管理"}) @RestController @RequestMapping(value = "/teacher") static class TeacherController { @ApiOperation(value = "xxx") @GetMapping("/xxx") public String xxx() { return "xxx"; } } @Api(tags = {"2-学生管理"}) @RestController @RequestMapping(value = "/student") static class StudentController {
@ApiOperation(value = "获取学生清单", tags = "3-教学管理") @GetMapping("/list") public String bbb() { return "bbb"; } @ApiOperation("获取教某个学生的老师清单") @GetMapping("/his-teachers") public String ccc() { return "ccc"; } @ApiOperation("创建一个学生") @PostMapping("/aaa") public String aaa() { return "aaa"; } } }
repos\SpringBoot-Learning-master\2.x\chapter2-4\src\main\java\com\didispace\chapter24\Chapter24Application.java
2
请完成以下Java代码
public class C_Invoice_RemoveRelation extends JavaProcess implements IProcessPrecondition { private final IQueryBL queryBL = Services.get(IQueryBL.class); @Param(parameterName = I_C_Invoice_Relation.COLUMNNAME_C_Invoice_From_ID, mandatory = true) private int poInvoiceRepoId; @Param(parameterName = I_C_Invoice_Relation.COLUMNNAME_C_Invoice_Relation_Type, mandatory = true) private String relationToRemove; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final boolean invoiceRelationsFound = queryBL.createQueryBuilder(I_C_Invoice_Relation.class) .addInSubQueryFilter(I_C_Invoice_Relation.COLUMN_C_Invoice_To_ID, I_C_Invoice.COLUMN_C_Invoice_ID, queryBL.createQueryBuilder(I_C_Invoice.class) .filter(context.getQueryFilter(I_C_Invoice.class)) .create())
.create().anyMatch(); if (!invoiceRelationsFound) { return ProcessPreconditionsResolution.rejectWithInternalReason("No invoice relations found."); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { removeRelations(); return MSG_OK; } private void removeRelations() { queryBL.createQueryBuilder(I_C_Invoice_Relation.class) .addEqualsFilter(I_C_Invoice_Relation.COLUMNNAME_C_Invoice_Relation_Type, relationToRemove) .addEqualsFilter(I_C_Invoice_Relation.COLUMNNAME_C_Invoice_From_ID, poInvoiceRepoId) .addEqualsFilter(I_C_Invoice_Relation.COLUMNNAME_C_Invoice_To_ID, getRecord_ID()) .create() .delete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_RemoveRelation.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysq
l.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
repos\SpringBoot-Learning-master\1.x\Chapter3-2-2\src\main\resources\application.properties
2
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("name", name); persistentState.put("description", description); return persistentState; } public int getRevisionNext() { return revision+1; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentId() {
return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public ByteArrayEntity getContent() { return content; } public void setContent(ByteArrayEntity content) { this.content = content; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", description=" + description + ", type=" + type + ", taskId=" + taskId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", url=" + url + ", contentId=" + contentId + ", content=" + content + ", tenantId=" + tenantId + ", createTime=" + createTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentEntity.java
1
请完成以下Java代码
private ModelColumn<I_M_HU_Attribute, Object> getHUAttributeValueColumn() { return huAttributeValueColumn; } private Set<Object> getValues() { return _values; } private Set<Object> getValuesAndSubstitutes() { if (_valuesAndSubstitutes != null) { return _valuesAndSubstitutes; } final ModelColumn<I_M_HU_Attribute, Object> valueColumn = getHUAttributeValueColumn(); final boolean isStringValueColumn = I_M_HU_Attribute.COLUMNNAME_Value.equals(valueColumn.getColumnName()); final Set<Object> valuesAndSubstitutes = new HashSet<>(); //
// Iterate current values for (final Object value : getValues()) { // Append current value to result valuesAndSubstitutes.add(value); // Search and append it's substitutes too, if found if (isStringValueColumn && value instanceof String) { final String valueStr = value.toString(); final I_M_Attribute attribute = getM_Attribute(); final Set<String> valueSubstitutes = attributeDAO.retrieveAttributeValueSubstitutes(attribute, valueStr); valuesAndSubstitutes.addAll(valueSubstitutes); } } _valuesAndSubstitutes = valuesAndSubstitutes; return _valuesAndSubstitutes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAttributeQueryFilterVO.java
1
请完成以下Java代码
public class CmsMemberReport implements Serializable { private Long id; @ApiModelProperty(value = "举报类型:0->商品评价;1->话题内容;2->用户评论") private Integer reportType; @ApiModelProperty(value = "举报人") private String reportMemberName; private Date createTime; private String reportObject; @ApiModelProperty(value = "举报状态:0->未处理;1->已处理") private Integer reportStatus; @ApiModelProperty(value = "处理结果:0->无效;1->有效;2->恶意") private Integer handleStatus; private String note; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getReportType() { return reportType; } public void setReportType(Integer reportType) { this.reportType = reportType; } public String getReportMemberName() { return reportMemberName; } public void setReportMemberName(String reportMemberName) { this.reportMemberName = reportMemberName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getReportObject() { return reportObject; } public void setReportObject(String reportObject) {
this.reportObject = reportObject; } public Integer getReportStatus() { return reportStatus; } public void setReportStatus(Integer reportStatus) { this.reportStatus = reportStatus; } public Integer getHandleStatus() { return handleStatus; } public void setHandleStatus(Integer handleStatus) { this.handleStatus = handleStatus; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", reportType=").append(reportType); sb.append(", reportMemberName=").append(reportMemberName); sb.append(", createTime=").append(createTime); sb.append(", reportObject=").append(reportObject); sb.append(", reportStatus=").append(reportStatus); sb.append(", handleStatus=").append(handleStatus); sb.append(", note=").append(note); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsMemberReport.java
1
请在Spring Boot框架中完成以下Java代码
ProblemDetail onResourceNotFound(HttpServletRequest request, BaseException baseException) { ResponseStatus resp = getResponseStatus(baseException); return handleError(request, baseException, resp.code(), resp.reason()); } static ResponseStatus getResponseStatus(BaseException ex) { return ex.getClass().getAnnotationsByType(ResponseStatus.class)[0]; } ProblemDetail handleError(HttpServletRequest request, Throwable error, HttpStatus status, String reason) { String requestURI = request.getRequestURI(); StringBuffer requestURL = request.getRequestURL(); if (requestURL != null) { requestURI = requestURL.toString(); } String method = request.getMethod(); String queryString = StringUtils.hasText(request.getQueryString()) ? "?" + request.getQueryString() : ""; log.error("Failed to process {}: {}{}", method, requestURI, queryString, error); ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(error)); return createProblemDetail(status, reason, error); } ProblemDetail createProblemDetail(HttpStatus status, String reason, Throwable error) { var pd = ProblemDetail.forStatus(status); pd.setTitle(status.getReasonPhrase()); pd.setDetail(error.toString()); pd.setProperty("reason", reason);
pd.setProperty("series", status.series()); pd.setProperty("rootCause", ExceptionUtils.getRootCause(error).toString()); pd.setProperty("trace", getTraceParent()); return pd; } String getTraceParent() { Span span = tracer.currentSpan(); if (span == null) { return ""; } return "%s-%s".formatted(span.context().traceId(), span.context().spanId()); } }
repos\spring-boot-web-application-sample-master\common\src\main\java\gt\common\config\CommonExceptionHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class DruidConfig { /** * 带有广告的common.js全路径,druid-1.1.14 */ private static final String FILE_PATH = "support/http/resources/js/common.js"; /** * 原始脚本,触发构建广告的语句 */ private static final String ORIGIN_JS = "this.buildFooter();"; /** * 替换后的脚本 */ private static final String NEW_JS = "//this.buildFooter();"; /** * 去除Druid监控页面的广告 * * @param properties DruidStatProperties属性集合 * @return {@link FilterRegistrationBean} */ @Bean @ConditionalOnWebApplication @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true") public FilterRegistrationBean<RemoveAdFilter> removeDruidAdFilter( DruidStatProperties properties) throws IOException { // 获取web监控页面的参数 DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); // 提取common.js的配置路径 String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); // 获取common.js String text = Utils.readFromResource(FILE_PATH); // 屏蔽 this.buildFooter(); 不构建广告
final String newJs = text.replace(ORIGIN_JS, NEW_JS); FilterRegistrationBean<RemoveAdFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(new RemoveAdFilter(newJs)); registration.addUrlPatterns(commonJsPattern); return registration; } /** * 删除druid的广告过滤器 * * @author BBF */ private class RemoveAdFilter implements Filter { private final String newJs; public RemoveAdFilter(String newJs) { this.newJs = newJs; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); // 重置缓冲区,响应头不会被重置 response.resetBuffer(); response.getWriter().write(newJs); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\DruidConfig.java
2
请在Spring Boot框架中完成以下Java代码
public abstract class PurchaseCandidateCreatedOrUpdatedHandler<T extends PurchaseCandidateEvent> implements MaterialEventHandler<T> { private final CandidateChangeService candidateChangeHandler; private final CandidateRepositoryRetrieval candidateRepositoryRetrieval; public PurchaseCandidateCreatedOrUpdatedHandler( @NonNull final CandidateChangeService candidateChangeHandler, @NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval) { this.candidateChangeHandler = candidateChangeHandler; this.candidateRepositoryRetrieval = candidateRepositoryRetrieval; } protected final void handlePurchaseCandidateEvent(@NonNull final PurchaseCandidateEvent event) { final MaterialDescriptor materialDescriptor = event.getPurchaseMaterialDescriptor(); final CandidatesQuery query = createCandidatesQuery(event); final Candidate existingCandidteOrNull = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query); final CandidateBuilder candidateBuilder; final PurchaseDetailBuilder purchaseDetailBuilder; if (existingCandidteOrNull != null) { candidateBuilder = existingCandidteOrNull.toBuilder(); purchaseDetailBuilder = PurchaseDetail .cast(existingCandidteOrNull.getBusinessCaseDetail()) .toBuilder(); } else { candidateBuilder = createInitialBuilder() .clientAndOrgId(event.getClientAndOrgId()); purchaseDetailBuilder = PurchaseDetail.builder(); }
final PurchaseDetail purchaseDetail = purchaseDetailBuilder .qty(materialDescriptor.getQuantity()) .vendorRepoId(event.getVendorId()) .purchaseCandidateRepoId(event.getPurchaseCandidateRepoId()) .advised(Flag.FALSE_DONT_UPDATE) .build(); candidateBuilder .materialDescriptor(materialDescriptor) .minMaxDescriptor(event.getMinMaxDescriptor()) .businessCaseDetail(purchaseDetail); final Candidate supplyCandidate = updateBuilderFromEvent(candidateBuilder, event).build(); candidateChangeHandler.onCandidateNewOrChange(supplyCandidate); } protected abstract CandidateBuilder updateBuilderFromEvent(CandidateBuilder candidateBuilder, PurchaseCandidateEvent event); protected abstract CandidatesQuery createCandidatesQuery(@NonNull final PurchaseCandidateEvent event); protected final CandidateBuilder createInitialBuilder() { return Candidate.builder() .type(CandidateType.SUPPLY) .businessCase(CandidateBusinessCase.PURCHASE) ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateCreatedOrUpdatedHandler.java
2
请完成以下Java代码
public static Object defaultInstantiateDelegate(String className, List<FieldDeclaration> fieldDeclarations) { return defaultInstantiateDelegate(className, fieldDeclarations, null); } public static void applyFieldDeclaration(List<FieldDeclaration> fieldDeclarations, Object target) { applyFieldDeclaration(fieldDeclarations, target, true); } public static void applyFieldDeclaration(List<FieldDeclaration> fieldDeclarations, Object target, boolean throwExceptionOnMissingField) { if (fieldDeclarations != null) { for (FieldDeclaration declaration : fieldDeclarations) { applyFieldDeclaration(declaration, target, throwExceptionOnMissingField); } } }
public static void applyFieldDeclaration(FieldDeclaration declaration, Object target) { applyFieldDeclaration(declaration, target, true); } public static void applyFieldDeclaration(FieldDeclaration declaration, Object target, boolean throwExceptionOnMissingField) { ReflectUtil.invokeSetterOrField(target, declaration.getName(), declaration.getValue(), throwExceptionOnMissingField); } /** * returns the class name this {@link AbstractClassDelegate} is configured to. Comes in handy if you want to check which delegates you already have e.g. in a list of listeners */ public String getClassName() { return className; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\helper\AbstractClassDelegate.java
1
请完成以下Java代码
public Builder formatted(String formatted) { this.formatted = formatted; return this; } /** * Sets the full street address, which may include house number, street name, P.O. * Box, etc. * @param streetAddress the full street address * @return the {@link Builder} */ public Builder streetAddress(String streetAddress) { this.streetAddress = streetAddress; return this; } /** * Sets the city or locality. * @param locality the city or locality * @return the {@link Builder} */ public Builder locality(String locality) { this.locality = locality; return this; } /** * Sets the state, province, prefecture, or region. * @param region the state, province, prefecture, or region * @return the {@link Builder} */ public Builder region(String region) { this.region = region; return this; } /** * Sets the zip code or postal code. * @param postalCode the zip code or postal code * @return the {@link Builder} */ public Builder postalCode(String postalCode) { this.postalCode = postalCode; return this;
} /** * Sets the country. * @param country the country * @return the {@link Builder} */ public Builder country(String country) { this.country = country; return this; } /** * Builds a new {@link DefaultAddressStandardClaim}. * @return a {@link AddressStandardClaim} */ public AddressStandardClaim build() { DefaultAddressStandardClaim address = new DefaultAddressStandardClaim(); address.formatted = this.formatted; address.streetAddress = this.streetAddress; address.locality = this.locality; address.region = this.region; address.postalCode = this.postalCode; address.country = this.country; return address; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\DefaultAddressStandardClaim.java
1
请完成以下Java代码
public BPartnerBankAccountImportHelper setProcess(final BPartnerImportProcess process) { this.process = process; return this; } @Nullable public I_C_BP_BankAccount importRecord(final I_I_BPartner importRecord) { final BPartnerId bpartnerId = BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()); I_C_BP_BankAccount bankAccount = BankAccountId.optionalOfRepoId(importRecord.getC_BP_BankAccount_ID()) .map(bankAccountId -> InterfaceWrapperHelper.load(bankAccountId, I_C_BP_BankAccount.class)) .orElse(null); if (bankAccount != null) { bankAccount.setIBAN(importRecord.getIBAN()); ModelValidationEngine.get().fireImportValidate(process, importRecord, bankAccount, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(bankAccount); } else if (!Check.isEmpty(importRecord.getSwiftCode(), true) && !Check.isEmpty(importRecord.getIBAN(), true)) { bankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class); bankAccount.setC_BPartner_ID(bpartnerId.getRepoId()); bankAccount.setIBAN(importRecord.getIBAN());
bankAccount.setA_Name(importRecord.getSwiftCode()); bankAccount.setC_Currency_ID(currencyBL.getBaseCurrency(process.getCtx()).getId().getRepoId()); final BankId bankId = bankRepository.getBankIdBySwiftCode(importRecord.getSwiftCode()).orElse(null); if (bankId != null) { bankAccount.setC_Bank_ID(bankId.getRepoId()); } ModelValidationEngine.get().fireImportValidate(process, importRecord, bankAccount, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(bankAccount); importRecord.setC_BP_BankAccount_ID(bankAccount.getC_BP_BankAccount_ID()); } return bankAccount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerBankAccountImportHelper.java
1
请完成以下Java代码
public boolean load(String path) { trie = new BinTrie<Byte>(); if (loadDat(path + Predefine.TRIE_EXT)) return true; String line = null; try { BufferedReader bw = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path))); while ((line = bw.readLine()) != null) { trie.put(line, null); } bw.close(); } catch (Exception e) { logger.warning("加载" + path + "失败," + e); } if (!trie.save(path + Predefine.TRIE_EXT)) logger.warning("缓存" + path + Predefine.TRIE_EXT + "失败"); return true; }
boolean loadDat(String path) { return trie.load(path); } public Set<String> keySet() { Set<String> keySet = new LinkedHashSet<String>(); for (Map.Entry<String, Byte> entry : trie.entrySet()) { keySet.add(entry.getKey()); } return keySet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonStringDictionary.java
1
请完成以下Java代码
public int getI_BPartner_GlobalID_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_BPartner_GlobalID_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Import-Fehlermeldung. @param I_ErrorMsg Meldungen, die durch den Importprozess generiert wurden */ @Override public void setI_ErrorMsg (java.lang.String I_ErrorMsg) { set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg); } /** Get Import-Fehlermeldung. @return Meldungen, die durch den Importprozess generiert wurden */ @Override public java.lang.String getI_ErrorMsg () { return (java.lang.String)get_Value(COLUMNNAME_I_ErrorMsg); } /** Set Importiert. @param I_IsImported Ist dieser Import verarbeitet worden? */ @Override public void setI_IsImported (boolean I_IsImported) { set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported)); } /** Get Importiert. @return Ist dieser Import verarbeitet worden? */ @Override public boolean isI_IsImported () { Object oo = get_Value(COLUMNNAME_I_IsImported); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override 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 */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override 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 URL3. @param URL3 Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public void setURL3 (java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } /** Get URL3. @return Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public java.lang.String getURL3 () { return (java.lang.String)get_Value(COLUMNNAME_URL3); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner_GlobalID.java
1
请完成以下Java代码
public void setStatusLine(final String text, final boolean error) { mt_error = error; mt_text = text; if (mt_error) { statusLine.setForeground(AdempierePLAF.getTextColor_Issue()); } else { statusLine.setForeground(AdempierePLAF.getTextColor_OK()); } if (mt_text == null || mt_text.length() == 0) { statusLine.setText(""); } else { statusLine.setText(" " + mt_text); } // Thread.yield(); } // setStatusLine /** * Get Status Line text * * @return StatusLine text */ public String getStatusLine() { return statusLine.getText().trim(); } // setStatusLine /** * Set ToolTip of StatusLine * * @param tip tip */ public void setStatusToolTip(final String tip) { statusLine.setToolTipText(tip); } // setStatusToolTip /** * Set Status DB Info * * @param text text * @param dse data status event */ @Override public void setStatusDB(final String text, final DataStatusEvent dse) { // log.info( "StatusBar.setStatusDB - " + text + " - " + created + "/" + createdBy); if (text == null || text.length() == 0) { statusDB.setText(""); statusDB.setVisible(false); } else { final StringBuilder sb = new StringBuilder(" "); sb.append(text).append(" "); statusDB.setText(sb.toString()); if (!statusDB.isVisible()) { statusDB.setVisible(true); } }
// Save // m_text = text; m_dse = dse; } // setStatusDB /** * Set Status DB Info * * @param text text */ @Override public void setStatusDB(final String text) { setStatusDB(text, null); } // setStatusDB /** * Set Status DB Info * * @param no no */ public void setStatusDB(final int no) { setStatusDB(String.valueOf(no), null); } // setStatusDB /** * Set Info Line * * @param text text */ @Override public void setInfo(final String text) { infoLine.setVisible(true); infoLine.setText(text); } // setInfo /** * Show {@link RecordInfo} dialog */ private void showRecordInfo() { if (m_dse == null) { return; } final int adTableId = m_dse.getAdTableId(); final ComposedRecordId recordId = m_dse.getRecordId(); if (adTableId <= 0 || recordId == null) { return; } if (!Env.getUserRolePermissions().isShowPreference()) { return; } // final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId); AEnv.showCenterScreen(info); } public void removeBorders() { statusLine.setBorder(BorderFactory.createEmptyBorder()); statusDB.setBorder(BorderFactory.createEmptyBorder()); infoLine.setBorder(BorderFactory.createEmptyBorder()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java
1
请完成以下Spring Boot application配置
spring: # datasource 数据源配置内容,对应 DataSourceProperties 配置属性类 datasource: url: jdbc:mysql://127.0.0.1:3306/lab-20-liquibase?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root # 数据库账号 password: # 数据库密码 # Liquibase 配置内容,对应 LiquibaseProperties 配置项 liquibase: enabled: true # 开启 Liquibase 功能。默认为 true 。 change-log: classpath:/db/changelog/db.changelog-ma
ster.yaml # Liquibase 配置文件地址 url: jdbc:mysql://127.0.0.1:3306/lab-20-liquibase?useSSL=false&useUnicode=true&characterEncoding=UTF-8 # 数据库地址 user: root # 数据库账号 password: # 数据库密码
repos\SpringBoot-Labs-master\lab-20\lab-20-database-version-control-liquibase\src\main\resources\application.yaml
2
请完成以下Java代码
default Document retrieveDocumentById(final DocumentEntityDescriptor entityDescriptor, final DocumentId recordId, final IDocumentChangesCollector changesCollector) { return retrieveDocument(DocumentQuery.ofRecordId(entityDescriptor, recordId).setChangesCollector(changesCollector).build(), changesCollector); } /** * Retrieves parent's {@link DocumentId} for a child document identified by given query. * * @return parent's {@link DocumentId}; never returns null */ DocumentId retrieveParentDocumentId(DocumentEntityDescriptor parentEntityDescriptor, DocumentQuery childDocumentQuery); /** * @return newly created document (not saved); never returns null */ Document createNewDocument(DocumentEntityDescriptor entityDescriptor, @Nullable final Document parentDocument, final IDocumentChangesCollector changesCollector); void refresh(@NonNull Document document); SaveResult save(@NonNull Document document); void delete(@NonNull Document document);
String retrieveVersion(DocumentEntityDescriptor entityDescriptor, int documentIdAsInt); int retrieveLastLineNo(DocumentQuery query); /** * Can be called to verify that this repository belongs with the given {@code entityDescriptor} */ default void assertThisRepository(@NonNull final DocumentEntityDescriptor entityDescriptor) { final DocumentsRepository documentsRepository = entityDescriptor.getDataBinding().getDocumentsRepository(); if (documentsRepository != this) { // shall not happen throw new IllegalArgumentException("Entity descriptor's repository is invalid: " + entityDescriptor + "\n Expected: " + this + "\n But it was: " + documentsRepository); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentsRepository.java
1
请完成以下Java代码
public final class HUTopLevel implements Comparable<HUTopLevel> { private final I_M_HU topLevelHU; private final I_M_HU luHU; private final I_M_HU tuHU; private final I_M_HU vhu; // pre-built: private final ArrayKey hashKey; private final HuId topLevelHUId; private final HuId luHUId; @Getter private final HuId tuHUId; private final HuId vhuId; public HUTopLevel( @NonNull final I_M_HU topLevelHU, final I_M_HU luHU, final I_M_HU tuHU, final I_M_HU vhu) { this.topLevelHU = topLevelHU; this.luHU = luHU; this.tuHU = tuHU; this.vhu = vhu; topLevelHUId = extractHuId(topLevelHU); luHUId = extractHuId(luHU); tuHUId = extractHuId(tuHU); vhuId = extractHuId(vhu); hashKey = Util.mkKey(topLevelHUId, luHUId, tuHUId, vhuId); } private static final HuId extractHuId(final I_M_HU hu) { return hu != null ? HuId.ofRepoIdOrNull(hu.getM_HU_ID()) : null; }
@Override public int compareTo(final HUTopLevel other) { if (this == other) { return 0; } if (other == null) { return +1; // nulls last } return hashKey.compareTo(other.hashKey); } /** * @return top level HU; never return <code>null</code> */ public I_M_HU getM_HU_TopLevel() { return topLevelHU; } public I_M_HU getM_LU_HU() { return luHU; } public I_M_HU getM_TU_HU() { return tuHU; } public I_M_HU getVHU() { return vhu; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUTopLevel.java
1
请在Spring Boot框架中完成以下Java代码
public boolean doCatch(Throwable e) { // log the error, return true to rollback the transaction but don't throw it forward log.error(e.getLocalizedMessage() + ", mview=" + mview + ", sourcePO=" + sourcePO + ", trxName=" + trxName, e); ok[0] = false; return true; } @Override public void doFinally() { } }); return ok[0]; } @Override public boolean isSourceChanged(MViewMetadata mdata, PO sourcePO, int changeType) { final String sourceTableName = sourcePO.get_TableName(); final Set<String> sourceColumns = mdata.getSourceColumns(sourceTableName); if (sourceColumns == null || sourceColumns.isEmpty())
return false; if (changeType == ModelValidator.TYPE_AFTER_NEW || changeType == ModelValidator.TYPE_AFTER_DELETE) { return true; } for (String sourceColumn : sourceColumns) { if (sourcePO.is_ValueChanged(sourceColumn)) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableMViewBL.java
2
请完成以下Java代码
public String getName() { return name; } } private float duration; private Medium medium; private Level level; private List<Course> prerequisite; public Course(String title, Author author) { super(title, author); } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public Medium getMedium() { return medium; } public void setMedium(Medium medium) { this.medium = medium; }
public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } public List<Course> getPrerequisite() { return prerequisite; } public void setPrerequisite(List<Course> prerequisite) { this.prerequisite = prerequisite; } }
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\domain\Course.java
1
请完成以下Java代码
private boolean isMissingObjectTypeMetadata(@Nullable JsonNode node) { return isObjectNode(node) && !node.has(AT_TYPE_METADATA_PROPERTY_NAME); } private boolean isMissingObjectTypeMetadata(@Nullable PdxInstance pdxInstance) { return pdxInstance != null && !pdxInstance.hasField(AT_TYPE_METADATA_PROPERTY_NAME); } /** * Null-safe method to determine if the given {@link JsonNode} represents a valid {@link String JSON} object. * * @param node {@link JsonNode} to evaluate. * @return a boolean valued indicating whether the given {@link JsonNode} is a valid {@link ObjectNode}. * @see com.fasterxml.jackson.databind.node.ObjectNode * @see com.fasterxml.jackson.databind.JsonNode
*/ boolean isObjectNode(@Nullable JsonNode node) { return node != null && (node.isObject() || node instanceof ObjectNode); } /** * Null-safe method to determine whether the given {@link String JSON} is valid. * * @param json {@link String} containing JSON to evaluate. * @return a boolean value indicating whether the given {@link String JSON} is valid. */ boolean isValidJson(@Nullable String json) { return StringUtils.hasText(json); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JSONFormatterPdxToJsonConverter.java
1
请完成以下Java代码
public void addTransaction(final IHUTransactionCandidate trx) { transactions.add(trx); } @Override public void addTransactions(final List<IHUTransactionCandidate> trxs) { trxs.forEach(trx -> addTransaction(trx)); } @Override public List<IHUTransactionCandidate> getTransactions() { return transactionsRO; } @Override public void addAttributeTransaction(final IHUTransactionAttribute attributeTrx) { attributeTransactions.add(attributeTrx); } @Override public void addAttributeTransactions(final List<IHUTransactionAttribute> attributeTrxs) { attributeTransactions.addAll(attributeTrxs); }
@Override public List<IHUTransactionAttribute> getAttributeTransactions() { return attributeTransactionsRO; } @Override public void aggregateTransactions() { final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); final List<IHUTransactionCandidate> aggregateTransactions = huTrxBL.aggregateTransactions(transactions); transactions.clear(); transactions.addAll(aggregateTransactions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\MutableAllocationResult.java
1
请完成以下Java代码
public static ByteArrayEntity createAndInsert(String name, byte[] bytes) { ByteArrayEntity byteArrayEntity = new ByteArrayEntity(name, bytes); Context .getCommandContext() .getDbSqlSession() .insert(byteArrayEntity); return byteArrayEntity; } public static ByteArrayEntity createAndInsert(byte[] bytes) { return createAndInsert(null, bytes); } public byte[] getBytes() { return bytes; } @Override public Object getPersistentState() { return new PersistentState(name, bytes); } @Override public int getRevisionNext() { return revision + 1; } // getters and setters ////////////////////////////////////////////////////// @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; }
@Override public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]"; } // Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } @Override public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return Objects.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class VerifyController { private final VerifyService verificationCodeService; private final EmailService emailService; @PostMapping(value = "/resetEmail") @ApiOperation("重置邮箱,发送验证码") public ResponseEntity<Object> resetEmail(@RequestParam String email){ EmailVo emailVo = verificationCodeService.sendEmail(email, CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey()); emailService.send(emailVo,emailService.find()); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping(value = "/email/resetPass") @ApiOperation("重置密码,发送验证码") public ResponseEntity<Object> resetPass(@RequestParam String email){ EmailVo emailVo = verificationCodeService.sendEmail(email, CodeEnum.EMAIL_RESET_PWD_CODE.getKey()); emailService.send(emailVo,emailService.find()); return new ResponseEntity<>(HttpStatus.OK);
} @GetMapping(value = "/validated") @ApiOperation("验证码验证") public ResponseEntity<Object> validated(@RequestParam String email, @RequestParam String code, @RequestParam Integer codeBi){ CodeBiEnum biEnum = CodeBiEnum.find(codeBi); switch (Objects.requireNonNull(biEnum)){ case ONE: verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + email ,code); break; case TWO: verificationCodeService.validated(CodeEnum.EMAIL_RESET_PWD_CODE.getKey() + email ,code); break; default: break; } return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\VerifyController.java
2
请完成以下Java代码
public class Account { private final TxnLong lastUpdate; private final TxnInteger balance; Account(final int balance) { this.lastUpdate = StmUtils.newTxnLong(System.currentTimeMillis()); this.balance = StmUtils.newTxnInteger(balance); } Integer getBalance() { return balance.atomicGet(); } void adjustBy(final int amount) { adjustBy(amount, System.currentTimeMillis()); } private void adjustBy(final int amount, final long date) { StmUtils.atomic(() -> { balance.increment(amount);
lastUpdate.set(date); if (balance.get() < 0) { throw new IllegalArgumentException("Not enough money"); } }); } void transferTo(final Account other, final int amount) { StmUtils.atomic(() -> { final long date = System.currentTimeMillis(); adjustBy(-amount, date); other.adjustBy(amount, date); }); } @Override public String toString() { return StmUtils.atomic((TxnCallable<String>) txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); } }
repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\stm\Account.java
1
请完成以下Java代码
public void onBeforeSave(BeforeSaveEvent<Object> event) { LOGGER.info("onBeforeSave: {}, {}", event.getSource(), event.getStatement()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterSave(org.springframework.data.cassandra.core.mapping.event.AfterSaveEvent) */ @Override public void onAfterSave(AfterSaveEvent<Object> event) { LOGGER.info("onAfterSave: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onBeforeDelete(org.springframework.data.cassandra.core.mapping.event.BeforeDeleteEvent) */ @Override public void onBeforeDelete(BeforeDeleteEvent<Object> event) { LOGGER.info("onBeforeDelete: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterDelete(org.springframework.data.cassandra.core.mapping.event.AfterDeleteEvent) */ @Override public void onAfterDelete(AfterDeleteEvent<Object> event) { LOGGER.info("onAfterDelete: {}", event.getSource());
} /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterLoad(org.springframework.data.cassandra.core.mapping.event.AfterLoadEvent) */ @Override public void onAfterLoad(AfterLoadEvent<Object> event) { LOGGER.info("onAfterLoad: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterConvert(org.springframework.data.cassandra.core.mapping.event.AfterConvertEvent) */ @Override public void onAfterConvert(AfterConvertEvent<Object> event) { LOGGER.info("onAfterConvert: {}", event.getSource()); } }
repos\spring-data-examples-main\cassandra\example\src\main\java\example\springdata\cassandra\events\LoggingEventListener.java
1
请完成以下Java代码
public static boolean updateCCM_Bundle_Status(int R_Group_ID, String trxName) { final boolean isActive = "Y".equals(DB.getSQLValueStringEx(trxName, "SELECT IsActive FROM R_Group WHERE R_Group_ID=?", R_Group_ID)); // final String sql = "SELECT" +" b.IsActive" +", b."+R_Group_CCM_Bundle_Status +", COALESCE(rs.IsClosed, 'N') AS IsClosed" +", COUNT(*) AS cnt" +" FROM R_Group b" +" INNER JOIN "+MRGroupProspect.Table_Name+" c ON (c.R_Group_ID=b.R_Group_ID)" +" LEFT OUTER JOIN R_Request rq ON (rq.R_Request_ID=c.R_Request_ID)" +" LEFT OUTER JOIN R_Status rs ON (rs.R_Status_ID=rq.R_Status_ID)" +" WHERE b.R_Group_ID=?" +" GROUP BY " +" b.IsActive" +", b."+R_Group_CCM_Bundle_Status +", COALESCE(rs.IsClosed, 'N')" ; int countAll = 0; int countClosed = 0; String oldStatus = null; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trxName); DB.setParameters(pstmt, new Object[]{R_Group_ID}); rs = pstmt.executeQuery(); while(rs.next()) { oldStatus = rs.getString(2); final boolean isClosed = "Y".equals(rs.getString(3)); final int no = rs.getInt(4); if (isClosed) countClosed += no; countAll += no; } } catch (SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } // final String newStatus; // Closed = field "active" is unchecked if (!isActive) { newStatus = CCM_Bundle_Status_Closed; } // New = no contacts added yet else if (countAll == 0) { newStatus = CCM_Bundle_Status_New; } // In Progress = contacts added and there are still open requests else if (countAll > 0 && countAll != countClosed) { newStatus = CCM_Bundle_Status_InProgress; } // Done(Completed) = all requests are closed else if (countAll > 0 && countAll == countClosed) { newStatus = CCM_Bundle_Status_Done;
} else { // should not happen throw new AdempiereException("Unhandled status. Please contact your System Administrator" +" (CountAll="+countAll+", CountClosed="+countClosed+", R_Status_ID="+R_Group_ID+")"); } // If status not found, try it directly // Case: the bundle has no contacts if (oldStatus == null) { oldStatus = DB.getSQLValueStringEx(trxName, "SELECT "+R_Group_CCM_Bundle_Status +" FROM R_Group WHERE R_Group_ID=?", R_Group_ID); } boolean updated = false; if (oldStatus == null || newStatus.compareTo(oldStatus) != 0) { int no = DB.executeUpdateAndThrowExceptionOnFail( "UPDATE R_Group SET "+R_Group_CCM_Bundle_Status+"=? WHERE R_Group_ID=?", new Object[]{newStatus, R_Group_ID}, trxName); if (no != 1) throw new AdempiereException("Cannot update bundle "+R_Group_ID); updated = true; } return updated; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\model\BundleUtil.java
1
请完成以下Java代码
protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(createdAfter, createdBefore) || CompareUtil.areNotInAscendingOrder(closedAfter, closedBefore) || CompareUtil.elementIsNotContainedInList(caseInstanceId, caseInstanceIds) || CompareUtil.elementIsContainedInList(caseDefinitionKey, caseKeyNotIn); } public String getBusinessKey() { return businessKey; } public String getBusinessKeyLike() { return businessKeyLike; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionIdLike() { return caseDefinitionKey + ":%:%"; } public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseDefinitionNameLike() { return caseDefinitionNameLike; } public String getCaseInstanceId() { return caseInstanceId; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public String getStartedBy() { return createdBy; } public String getSuperCaseInstanceId() {
return superCaseInstanceId; } public void setSuperCaseInstanceId(String superCaseInstanceId) { this.superCaseInstanceId = superCaseInstanceId; } public List<String> getCaseKeyNotIn() { return caseKeyNotIn; } public Date getCreatedAfter() { return createdAfter; } public Date getCreatedBefore() { return createdBefore; } public Date getClosedAfter() { return closedAfter; } public Date getClosedBefore() { return closedBefore; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java
1
请完成以下Java代码
public int getTaskCount() { return taskCount; } public void setTaskCount(int taskCount) { this.taskCount = taskCount; } public int getJobCount() { return jobCount; } public void setJobCount(int jobCount) { this.jobCount = jobCount; } public int getTimerJobCount() { return timerJobCount; } public void setTimerJobCount(int timerJobCount) { this.timerJobCount = timerJobCount; } public int getSuspendedJobCount() { return suspendedJobCount; } public void setSuspendedJobCount(int suspendedJobCount) { this.suspendedJobCount = suspendedJobCount; } public int getDeadLetterJobCount() { return deadLetterJobCount; } public void setDeadLetterJobCount(int deadLetterJobCount) { this.deadLetterJobCount = deadLetterJobCount; } public int getVariableCount() { return variableCount; } public void setVariableCount(int variableCount) { this.variableCount = variableCount; } public int getIdentityLinkCount() { return identityLinkCount; } public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount; } @Override public void setAppVersion(Integer appVersion) { this.appVersion = appVersion;
} @Override public Integer getAppVersion() { return appVersion; } //toString ///////////////////////////////////////////////////////////////// public String toString() { if (isProcessInstanceType()) { return "ProcessInstance[" + getId() + "]"; } else { StringBuilder strb = new StringBuilder(); if (isScope) { strb.append("Scoped execution[ id '" + getId() + "' ]"); } else if (isMultiInstanceRoot) { strb.append("Multi instance root execution[ id '" + getId() + "' ]"); } else { strb.append("Execution[ id '" + getId() + "' ]"); } if (activityId != null) { strb.append(" - activity '" + activityId); } if (parentId != null) { strb.append(" - parent '" + parentId + "'"); } return strb.toString(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setHeaders(Map _headers) { this.headers.putAll(_headers); } public int getReadTimeout() { return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public boolean isIgnoreContentIfUnsuccess() { return ignoreContentIfUnsuccess; } public void setIgnoreContentIfUnsuccess(boolean ignoreContentIfUnsuccess) { this.ignoreContentIfUnsuccess = ignoreContentIfUnsuccess; } public String getPostData() { return postData; } public void setPostData(String postData) { this.postData = postData; } public ClientKeyStore getClientKeyStore() {
return clientKeyStore; } public void setClientKeyStore(ClientKeyStore clientKeyStore) { this.clientKeyStore = clientKeyStore; } public com.roncoo.pay.trade.utils.httpclient.TrustKeyStore getTrustKeyStore() { return TrustKeyStore; } public void setTrustKeyStore(com.roncoo.pay.trade.utils.httpclient.TrustKeyStore trustKeyStore) { TrustKeyStore = trustKeyStore; } public boolean isHostnameVerify() { return hostnameVerify; } public void setHostnameVerify(boolean hostnameVerify) { this.hostnameVerify = hostnameVerify; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpParam.java
2
请完成以下Java代码
public ClientRegistrationRepository clientRegistrationRepository() { List<ClientRegistration> registrations = clients.stream() .map(c -> getRegistration(c)) .filter(registration -> registration != null) .collect(Collectors.toList()); return new InMemoryClientRegistrationRepository(registrations); } private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration."; @Autowired private Environment env; private ClientRegistration getRegistration(String client) { String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id"); if (clientId == null) { return null; }
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret"); if (client.equals("google")) { return CommonOAuth2Provider.GOOGLE.getBuilder(client) .clientId(clientId) .clientSecret(clientSecret) .build(); } if (client.equals("facebook")) { return CommonOAuth2Provider.FACEBOOK.getBuilder(client) .clientId(clientId) .clientSecret(clientSecret) .build(); } return null; } }
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\CustomRequestSecurityConfig.java
1
请完成以下Java代码
public String getLocationHeaderName() { return locationHeaderName; } public RewriteLocationResponseHeaderConfig setLocationHeaderName(String locationHeaderName) { this.locationHeaderName = locationHeaderName; return this; } public @Nullable String getHostValue() { return hostValue; } public RewriteLocationResponseHeaderConfig setHostValue(String hostValue) { this.hostValue = hostValue; return this; } public String getProtocolsRegex() { return protocolsRegex;
} public RewriteLocationResponseHeaderConfig setProtocolsRegex(String protocolsRegex) { this.protocolsRegex = protocolsRegex; this.hostPortPattern = compileHostPortPattern(protocolsRegex); this.hostPortVersionPattern = compileHostPortVersionPattern(protocolsRegex); return this; } public Pattern getHostPortPattern() { return hostPortPattern; } public Pattern getHostPortVersionPattern() { return hostPortVersionPattern; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RewriteLocationResponseHeaderFilterFunctions.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> add(@RequestBody SysTableWhiteList sysTableWhiteList) { if (sysTableWhiteListService.add(sysTableWhiteList)) { return Result.OK("添加成功!"); } else { return Result.error("添加失败!"); } } /** * 编辑 * * @param sysTableWhiteList * @return */ @AutoLog(value = "系统表白名单-编辑") @Operation(summary = "系统表白名单-编辑") //@RequiresRoles("admin") @RequiresPermissions("system:tableWhite:edit") @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST}) public Result<?> edit(@RequestBody SysTableWhiteList sysTableWhiteList) { if (sysTableWhiteListService.edit(sysTableWhiteList)) { return Result.OK("编辑成功!"); } else { return Result.error("编辑失败!"); } } /** * 通过id删除 * * @param id * @return */ @AutoLog(value = "系统表白名单-通过id删除") @Operation(summary = "系统表白名单-通过id删除") // @RequiresRoles("admin") @RequiresPermissions("system:tableWhite:delete") @DeleteMapping(value = "/delete") public Result<?> delete(@RequestParam(name = "id") String id) { if (sysTableWhiteListService.deleteByIds(id)) { return Result.OK("删除成功!"); } else {
return Result.error("删除失败!"); } } /** * 批量删除 * * @param ids * @return */ @AutoLog(value = "系统表白名单-批量删除") @Operation(summary = "系统表白名单-批量删除") // @RequiresRoles("admin") @RequiresPermissions("system:tableWhite:deleteBatch") @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) { if (sysTableWhiteListService.deleteByIds(ids)) { return Result.OK("批量删除成功!"); } else { return Result.error("批量删除失败!"); } } /** * 通过id查询 * * @param id * @return */ @AutoLog(value = "系统表白名单-通过id查询") @Operation(summary = "系统表白名单-通过id查询") // @RequiresRoles("admin") @RequiresPermissions("system:tableWhite:queryById") @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { SysTableWhiteList sysTableWhiteList = sysTableWhiteListService.getById(id); return Result.OK(sysTableWhiteList); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysTableWhiteListController.java
2
请完成以下Java代码
public String name() { return attributeNode.getLocalName(); } public String namespace() { return attributeNode.getNamespaceURI(); } public String prefix() { return attributeNode.getPrefix(); } public boolean hasPrefix(String prefix) { String attributePrefix = attributeNode.getPrefix(); if(attributePrefix == null) { return prefix == null; } else { return attributePrefix.equals(prefix); } } public boolean hasNamespace(String namespace) { String attributeNamespace = attributeNode.getNamespaceURI(); if (attributeNamespace == null) { return namespace == null; } else { return attributeNamespace.equals(namespace); } } public String value() { return attributeNode.getValue(); } public SpinXmlAttribute value(String value) { if (value == null) { throw LOG.unableToSetAttributeValueToNull(namespace(), name()); } attributeNode.setValue(value); return this; } public SpinXmlElement remove() { Element ownerElement = attributeNode.getOwnerElement(); ownerElement.removeAttributeNode(attributeNode); return dataFormat.createElementWrapper(ownerElement); }
public String toString() { return value(); } public void writeToWriter(Writer writer) { try { writer.write(toString()); } catch (IOException e) { throw LOG.unableToWriteAttribute(this, e); } } public <C> C mapTo(Class<C> javaClass) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(this, javaClass); } public <C> C mapTo(String javaClass) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(this, javaClass); } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlAttribute.java
1