instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Integer getVersion() {
return version;
}
public void setVersion(final Integer version) {
this.version = version;
}
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public Boolean getActive() {
return active;
}
public void setActive(final Boolean active) {
this.active = active;
}
public void setPassword(final String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities != null ? authorities : Collections.emptyList();
}
@Override
public void setAuthorities(final Collection<? extends GrantedAuthority> authorities) { | this.authorities = authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return Boolean.TRUE.equals(active);
}
@InstanceName
@DependsOnProperties({"firstName", "lastName", "username"})
public String getDisplayName() {
return String.format("%s %s [%s]", (firstName != null ? firstName : ""),
(lastName != null ? lastName : ""), username).trim();
}
@Override
public String getTimeZoneId() {
return timeZoneId;
}
public void setTimeZoneId(final String timeZoneId) {
this.timeZoneId = timeZoneId;
}
} | repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Kursart.
@param C_ConversionType_ID
Currency Conversion Rate Type
*/
@Override
public void setC_ConversionType_ID (int C_ConversionType_ID)
{
if (C_ConversionType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, Integer.valueOf(C_ConversionType_ID));
}
/** Get Kursart.
@return Currency Conversion Rate Type
*/
@Override
public int getC_ConversionType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** 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
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType.java | 1 |
请完成以下Java代码 | public CaseInstanceStartEventSubscriptionModificationBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) {
correlationParameterValues.put(parameterName, parameterValue);
return this;
}
@Override
public CaseInstanceStartEventSubscriptionModificationBuilder addCorrelationParameterValues(Map<String, Object> parameters) {
correlationParameterValues.putAll(parameters);
return this;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public boolean hasNewCaseDefinitionId() {
return StringUtils.isNotBlank(newCaseDefinitionId);
}
public String getNewCaseDefinitionId() {
return newCaseDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public boolean hasCorrelationParameterValues() {
return correlationParameterValues.size() > 0;
}
public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues;
}
@Override | public void migrateToLatestCaseDefinition() {
checkValidInformation();
cmmnRuntimeService.migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(this);
}
@Override
public void migrateToCaseDefinition(String caseDefinitionId) {
this.newCaseDefinitionId = caseDefinitionId;
checkValidInformation();
cmmnRuntimeService.migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(this);
}
protected void checkValidInformation() {
if (StringUtils.isEmpty(caseDefinitionId)) {
throw new FlowableIllegalArgumentException("The case definition must be provided using the exact id of the version the subscription was registered for.");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionModificationBuilderImpl.java | 1 |
请完成以下Java代码 | public class SystemUtils {
private static Logger log = LoggerFactory.getLogger(SystemUtils.class);
/**
* 模拟两个用户
*
* @return List<User>
*/
private static List<User> users() {
List<User> users = new ArrayList<>();
// 模拟两个用户:
// 1. 用户名 admin,密码 123456,角色 admin(管理员),权限 "user:add","user:view"
// 1. 用户名 scott,密码 123456,角色 regist(注册用户),权限 "user:view"
users.add(new User(
"admin",
"bfc62b3f67a4c3e57df84dad8cc48a3b",
new HashSet<>(Collections.singletonList("admin")),
new HashSet<>(Arrays.asList("user:add", "user:view")))); | users.add(new User(
"scott",
"11bd73355c7bbbac151e4e4f943e59be",
new HashSet<>(Collections.singletonList("regist")),
new HashSet<>(Collections.singletonList("user:view"))));
return users;
}
/**
* 获取用户
*
* @param username 用户名
* @return 用户
*/
public static User getUser(String username) {
List<User> users = SystemUtils.users();
return users.stream().filter(user -> StringUtils.equalsIgnoreCase(username, user.getUsername())).findFirst().orElse(null);
}
} | repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\utils\SystemUtils.java | 1 |
请完成以下Java代码 | public String getImageURL ()
{
return (String)get_Value(COLUMNNAME_ImageURL);
}
/** 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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Image.java | 1 |
请完成以下Java代码 | public class RateLimiterAspect {
private final static String SEPARATOR = ":";
private final static String REDIS_LIMIT_KEY_PREFIX = "limit:";
private final StringRedisTemplate stringRedisTemplate;
private final RedisScript<Long> limitRedisScript;
@Pointcut("@annotation(com.xkcoding.ratelimit.redis.annotation.RateLimiter)")
public void rateLimit() {
}
@Around("rateLimit()")
public Object pointcut(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
// 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
if (rateLimiter != null) {
String key = rateLimiter.key();
// 默认用类名+方法名做限流的 key 前缀
if (StrUtil.isBlank(key)) {
key = method.getDeclaringClass().getName() + StrUtil.DOT + method.getName();
}
// 最终限流的 key 为 前缀 + IP地址
// TODO: 此时需要考虑局域网多用户访问的情况,因此 key 后续需要加上方法参数更加合理
key = key + SEPARATOR + IpUtil.getIpAddr();
long max = rateLimiter.max();
long timeout = rateLimiter.timeout();
TimeUnit timeUnit = rateLimiter.timeUnit();
boolean limited = shouldLimited(key, max, timeout, timeUnit); | if (limited) {
throw new RuntimeException("手速太快了,慢点儿吧~");
}
}
return point.proceed();
}
private boolean shouldLimited(String key, long max, long timeout, TimeUnit timeUnit) {
// 最终的 key 格式为:
// limit:自定义key:IP
// limit:类名.方法名:IP
key = REDIS_LIMIT_KEY_PREFIX + key;
// 统一使用单位毫秒
long ttl = timeUnit.toMillis(timeout);
// 当前时间毫秒数
long now = Instant.now().toEpochMilli();
long expired = now - ttl;
// 注意这里必须转为 String,否则会报错 java.lang.Long cannot be cast to java.lang.String
Long executeTimes = stringRedisTemplate.execute(limitRedisScript, Collections.singletonList(key), now + "", ttl + "", expired + "", max + "");
if (executeTimes != null) {
if (executeTimes == 0) {
log.error("【{}】在单位时间 {} 毫秒内已达到访问上限,当前接口上限 {}", key, ttl, max);
return true;
} else {
log.info("【{}】在单位时间 {} 毫秒内访问 {} 次", key, ttl, executeTimes);
return false;
}
}
return false;
}
} | repos\spring-boot-demo-master\demo-ratelimit-redis\src\main\java\com\xkcoding\ratelimit\redis\aspect\RateLimiterAspect.java | 1 |
请完成以下Java代码 | public Object put(String name, Object value) {
if (storeScriptVariables) {
Object oldValue = null;
if (!UNSTORED_KEYS.contains(name)) {
oldValue = variableScope.getVariable(name);
variableScope.setVariable(name, value);
return oldValue;
}
}
return defaultBindings.put(name, value);
}
public Set<Map.Entry<String, Object>> entrySet() {
return variableScope.getVariables().entrySet();
}
public Set<String> keySet() {
return variableScope.getVariables().keySet();
}
public int size() {
return variableScope.getVariables().size();
}
public Collection<Object> values() {
return variableScope.getVariables().values();
}
public void putAll(Map<? extends String, ? extends Object> toMerge) {
throw new UnsupportedOperationException();
}
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return defaultBindings.remove(key); | }
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public void addUnstoredKey(String unstoredKey) {
UNSTORED_KEYS.add(unstoredKey);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindings.java | 1 |
请完成以下Java代码 | public Integer idOf(char[] label)
{
return trie.get(label);
}
/**
* label转id
* @param label
* @return
*/
public Integer idOf(String label)
{
return trie.get(label);
}
/**
* 字母表大小
* @return
*/
public int size()
{
return trie.size();
}
public void save(DataOutputStream out) throws Exception
{
out.writeInt(idToLabelMap.length);
for (String value : idToLabelMap)
{
TextUtility.writeString(value, out); | }
}
public boolean load(ByteArray byteArray)
{
idToLabelMap = new String[byteArray.nextInt()];
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
for (int i = 0; i < idToLabelMap.length; i++)
{
idToLabelMap[i] = byteArray.nextString();
map.put(idToLabelMap[i], i);
}
return trie.build(map) == 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Alphabet.java | 1 |
请完成以下Java代码 | public void concurrentModificationFailureIgnored(DbOperation operation) {
logDebug(
"110",
"An OptimisticLockingListener attempted to ignore a failure of: {}. "
+ "Since the database aborted the transaction, ignoring the failure "
+ "is not possible and an exception is thrown instead.",
operation
);
}
// exception code 110 is already taken. See requiredCamundaAdminOrPermissionException() for details.
public static List<SQLException> findRelatedSqlExceptions(Throwable exception) {
List<SQLException> sqlExceptionList = new ArrayList<>();
Throwable cause = exception;
do {
if (cause instanceof SQLException) {
SQLException sqlEx = (SQLException) cause;
sqlExceptionList.add(sqlEx);
while (sqlEx.getNextException() != null) {
sqlExceptionList.add(sqlEx.getNextException());
sqlEx = sqlEx.getNextException();
}
}
cause = cause.getCause();
} while (cause != null);
return sqlExceptionList;
}
public static String collectExceptionMessages(Throwable cause) {
StringBuilder message = new StringBuilder(cause.getMessage());
//collect real SQL exception messages in case of batch processing
Throwable exCause = cause;
do { | if (exCause instanceof BatchExecutorException) {
final List<SQLException> relatedSqlExceptions = findRelatedSqlExceptions(exCause);
StringBuilder sb = new StringBuilder();
for (SQLException sqlException : relatedSqlExceptions) {
sb.append(sqlException).append("\n");
}
message.append("\n").append(sb);
}
exCause = exCause.getCause();
} while (exCause != null);
return message.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\EnginePersistenceLogger.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Date getLaunchDate() {
return launchDate;
}
public void setLaunchDateDate(Date launchDate) { | this.launchDate = launchDate;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
} | repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\worker\entity\WorkerNodeEntity.java | 1 |
请完成以下Java代码 | public String getPassword() {
return password;
}
/**
* 设置 密码.
*
* @param password 密码.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* 获取 md5密码盐.
*
* @return md5密码盐.
*/
public String getSalt() {
return salt;
}
/**
* 设置 md5密码盐.
*
* @param salt md5密码盐.
*/
public void setSalt(String salt) {
this.salt = salt;
}
/**
* 获取 联系电话.
*
* @return 联系电话.
*/
public String getPhone() {
return phone;
}
/**
* 设置 联系电话.
*
* @param phone 联系电话.
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* 获取 备注.
*
* @return 备注.
*/
public String getTips() {
return tips;
}
/**
* 设置 备注.
*
* @param tips 备注.
*/
public void setTips(String tips) {
this.tips = tips;
}
/**
* 获取 状态 1:正常 2:禁用.
*
* @return 状态 1:正常 2:禁用.
*/
public Integer getState() {
return state;
}
/**
* 设置 状态 1:正常 2:禁用.
*
* @param state 状态 1:正常 2:禁用.
*/
public void setState(Integer state) {
this.state = state;
} | /**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Manager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getDefinitionCacheLimit() {
return definitionCacheLimit;
}
public void setDefinitionCacheLimit(int definitionCacheLimit) {
this.definitionCacheLimit = definitionCacheLimit;
}
public boolean isEnableSafeXml() {
return enableSafeXml;
}
public void setEnableSafeXml(boolean enableSafeXml) {
this.enableSafeXml = enableSafeXml;
}
public boolean isEventRegistryStartProcessInstanceAsync() {
return eventRegistryStartProcessInstanceAsync;
}
public void setEventRegistryStartProcessInstanceAsync(boolean eventRegistryStartProcessInstanceAsync) {
this.eventRegistryStartProcessInstanceAsync = eventRegistryStartProcessInstanceAsync;
}
public boolean isEventRegistryUniqueProcessInstanceCheckWithLock() {
return eventRegistryUniqueProcessInstanceCheckWithLock;
} | public void setEventRegistryUniqueProcessInstanceCheckWithLock(boolean eventRegistryUniqueProcessInstanceCheckWithLock) {
this.eventRegistryUniqueProcessInstanceCheckWithLock = eventRegistryUniqueProcessInstanceCheckWithLock;
}
public Duration getEventRegistryUniqueProcessInstanceStartLockTime() {
return eventRegistryUniqueProcessInstanceStartLockTime;
}
public void setEventRegistryUniqueProcessInstanceStartLockTime(Duration eventRegistryUniqueProcessInstanceStartLockTime) {
this.eventRegistryUniqueProcessInstanceStartLockTime = eventRegistryUniqueProcessInstanceStartLockTime;
}
public static class AsyncHistory {
private boolean enabled;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\process\FlowableProcessProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getRefererUrl(HttpServletRequest request) {
return request.getHeader("referer");
}
/**
*
* @param request
* 请求
* @return 返回请求的数据流
* @throws IOException
*/
public String parseRequestString(HttpServletRequest request) throws IOException {
String inputLine;
String notityXml = "";
while ((inputLine = request.getReader().readLine()) != null) {
notityXml += inputLine;
}
request.getReader().close();
return notityXml; | }
/**
* 把json对象串转换成map对象
* @param jsonObjStr e.g. {'name':'get','int':1,'double',1.1,'null':null}
* @return Map
*/
public HashMap<String, String> convertToMap(JSONParam[] params) {
HashMap<String, String> map = new HashMap<String, String>();
for(JSONParam param:params){
map.put(param.getName(), param.getValue());
}
return map;
}
} | repos\roncoo-pay-master\roncoo-pay-web-merchant\src\main\java\com\roncoo\pay\controller\common\BaseController.java | 2 |
请完成以下Spring Boot application配置 | # Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09
spring.redis.database=0
# Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=localhost
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=6379
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=
spring.redis.lettuce.pool.max- | active=8
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.shutdown-timeout=100
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0 | repos\spring-boot-leaning-master\2.x_data\1-4 Spring Boot 和 Nosql 数据库的使用\spring-boot-redis\src\main\resources\application.properties | 2 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-provider
cloud:
# Sentinel 配置项,对应 SentinelProperties 配置属性类
sentinel:
enabled: true # 是否开启。默认为 true 开启
eager: true # 是否饥饿加载。默认为 false 关闭
transport:
dashboard: 127.0.0.1:7070 # Sentinel 控制台地址
filter:
url-patterns: /** # 拦截请求的地址。默认为 /*
management:
endpoints:
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
endpoin | t:
# Health 端点配置项,对应 HealthProperties 配置类
health:
enabled: true # 是否开启。默认为 true 开启。
show-details: ALWAYS # 何时显示完整的健康信息。默认为 NEVER 都不展示。可选 WHEN_AUTHORIZED 当经过授权的用户;可选 ALWAYS 总是展示。 | repos\SpringBoot-Labs-master\labx-04-spring-cloud-alibaba-sentinel\labx-04-sca-sentinel-actuator-provider\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public long getLibraryId() {
return libraryId;
}
public void setLibraryId(long libraryId) {
this.libraryId = libraryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ForeignCollection<Book> getBooks() {
return books;
}
public void setBooks(ForeignCollection<Book> books) {
this.books = books;
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ormlite\Library.java | 1 |
请完成以下Java代码 | public static final <T> String createUIKey(final Class<T> editorClass)
{
return createUIKey(editorClass.getSimpleName());
}
/**
* Creates the {@link UIDefaults} key for given <code>editorClassKey</code>.
*
* @param editorClass
* @return UI defaults key
*/
public static final String createUIKey(final String editorClassKey)
{
final String uiKey = editorClassKey + ".DialogButtonAlign";
return uiKey;
}
/** @return {@link VEditorDialogButtonAlign} value of given <code>editorClass</code> from {@link UIManager}. */
private static final <T> VEditorDialogButtonAlign getFromUIManager(final Class<T> editorClass)
{
//
// Editor property
{
final String alignUIKey = createUIKey(editorClass);
final VEditorDialogButtonAlign align = (VEditorDialogButtonAlign)UIManager.get(alignUIKey);
if (align != null)
{
return align;
} | }
//
// Default property
{
final VEditorDialogButtonAlign align = (VEditorDialogButtonAlign)UIManager.get(DEFAULT_EditorUI);
if (align != null)
{
return align;
}
}
//
// Fallback to default value
return DEFAULT_Value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\VEditorDialogButtonAlign.java | 1 |
请完成以下Java代码 | public BigDecimal getAllocatedAmt(final I_C_Payment payment)
{
final PaymentId paymentId = PaymentId.ofRepoId(payment.getC_Payment_ID());
return getAllocatedAmt(paymentId);
}
@Override
public BigDecimal getAllocatedAmt(final PaymentId paymentId)
{
final BigDecimal amt = DB.getSQLValueBDEx(ITrx.TRXNAME_ThreadInherited,
"SELECT paymentAllocatedAmt(?)",
paymentId);
return amt != null ? amt : BigDecimal.ZERO;
}
@Override
public void updateDiscountAndPayment(final I_C_Payment payment, final int c_Invoice_ID, final I_C_DocType c_DocType)
{
final String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2
+ " invoiceOpen(C_Invoice_ID, ?)," // 3 #1
+ " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3
+ "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, c_Invoice_ID);
pstmt.setTimestamp(2, payment.getDateTrx());
pstmt.setInt(3, c_Invoice_ID);
pstmt.setInt(4, c_Invoice_ID);
rs = pstmt.executeQuery();
if (rs.next())
{
final int bpartnerId = rs.getInt(1);
payment.setC_BPartner_ID(bpartnerId);
// Set Invoice Currency
final int C_Currency_ID = rs.getInt(2);
payment.setC_Currency_ID(C_Currency_ID);
//
BigDecimal InvoiceOpen = rs.getBigDecimal(3); // Set Invoice
// OPen Amount
if (InvoiceOpen == null)
{
InvoiceOpen = BigDecimal.ZERO;
}
BigDecimal DiscountAmt = rs.getBigDecimal(4); // Set Discount
// Amt
if (DiscountAmt == null)
{
DiscountAmt = BigDecimal.ZERO;
} | BigDecimal payAmt = InvoiceOpen.subtract(DiscountAmt);
if (X_C_DocType.DOCBASETYPE_APCreditMemo.equals(c_DocType.getDocBaseType())
|| X_C_DocType.DOCBASETYPE_ARCreditMemo.equals(c_DocType.getDocBaseType()))
{
if (payAmt.signum() < 0)
{
payAmt = payAmt.abs();
}
}
payment.setPayAmt(payAmt);
payment.setDiscountAmt(DiscountAmt);
}
}
catch (final SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PaymentDAO.java | 1 |
请完成以下Java代码 | public void setIsBeforeApproval (boolean IsBeforeApproval)
{
set_Value (COLUMNNAME_IsBeforeApproval, Boolean.valueOf(IsBeforeApproval));
}
/** Get Before Approval.
@return The Check is before the (manual) approval
*/
public boolean isBeforeApproval ()
{
Object oo = get_Value(COLUMNNAME_IsBeforeApproval);
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);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_BudgetControl.java | 1 |
请完成以下Java代码 | @Nullable ExpressionAttribute resolveAttribute(Method method, @Nullable Class<?> targetClass) {
PreAuthorize preAuthorize = findPreAuthorizeAnnotation(method, targetClass);
if (preAuthorize == null) {
return null;
}
Expression expression = getExpressionHandler().getExpressionParser().parseExpression(preAuthorize.value());
MethodAuthorizationDeniedHandler handler = resolveHandler(method, targetClass);
return new PreAuthorizeExpressionAttribute(expression, handler);
}
private MethodAuthorizationDeniedHandler resolveHandler(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
HandleAuthorizationDenied deniedHandler = this.handleAuthorizationDeniedScanner.scan(method, targetClassToUse);
if (deniedHandler != null) {
return this.handlerResolver.apply(deniedHandler.handlerClass());
}
return this.defaultHandler;
}
private @Nullable PreAuthorize findPreAuthorizeAnnotation(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
return this.preAuthorizeScanner.scan(method, targetClassToUse);
}
/**
* Uses the provided {@link ApplicationContext} to resolve the
* {@link MethodAuthorizationDeniedHandler} from {@link PreAuthorize}.
* @param context the {@link ApplicationContext} to use
*/
void setApplicationContext(ApplicationContext context) {
Assert.notNull(context, "context cannot be null");
this.handlerResolver = (clazz) -> resolveHandler(context, clazz);
}
void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) { | this.preAuthorizeScanner = SecurityAnnotationScanners.requireUnique(PreAuthorize.class, defaults);
}
private MethodAuthorizationDeniedHandler resolveHandler(ApplicationContext context,
Class<? extends MethodAuthorizationDeniedHandler> handlerClass) {
if (handlerClass == this.defaultHandler.getClass()) {
return this.defaultHandler;
}
String[] beanNames = context.getBeanNamesForType(handlerClass);
if (beanNames.length == 0) {
throw new IllegalStateException("Could not find a bean of type " + handlerClass.getName());
}
if (beanNames.length > 1) {
throw new IllegalStateException("Expected to find a single bean of type " + handlerClass.getName()
+ " but found " + Arrays.toString(beanNames));
}
return context.getBean(beanNames[0], handlerClass);
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreAuthorizeExpressionAttributeRegistry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityJwtConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityJwtConfiguration.class);
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Bean
public JwtDecoder jwtDecoder(SecurityMetersService metersService) {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build();
return token -> {
try {
return jwtDecoder.decode(token);
} catch (Exception e) {
if (e.getMessage().contains("Invalid signature")) {
metersService.trackTokenInvalidSignature();
} else if (e.getMessage().contains("Jwt expired at")) {
metersService.trackTokenExpired();
} else if (
e.getMessage().contains("Invalid JWT serialization") ||
e.getMessage().contains("Malformed token") ||
e.getMessage().contains("Invalid unsecured/JWS/JWE")
) {
metersService.trackTokenMalformed();
} else {
log.error("Unknown JWT error {}", e.getMessage()); | }
throw e;
}
};
}
@Bean
public JwtEncoder jwtEncoder() {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey()));
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY);
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
private SecretKey getSecretKey() {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\config\SecurityJwtConfiguration.java | 2 |
请完成以下Java代码 | public String getAmtInWords (String amount) throws Exception
{
if (amount == null)
return amount;
StringBuffer sb = new StringBuffer ();
amount = amount.replaceAll (" ", "").replaceAll("\u00A0", "");
char sep = amount.contains(",")?',':'.'; //Try to determine the separator either comma or a full stop
int pos = amount.lastIndexOf (sep);
long levs = Long.parseLong((pos >=0)?amount.substring (0, pos):amount);
sb.append (convert (levs) + " " + lev[levs ==1?0:1]);
if(pos > 0) {
String stotinki = amount.substring (pos + 1);
if(stotinki.length() > 2){
stotinki = stotinki.substring(0,2);
}
sb.append (" " + concat + " ")
.append (convert(Long.parseLong(stotinki)))
.append (" \u0441\u0442\u043E\u0442\u0438\u043D\u043A\u0438"); //stotinki"
}
return sb.toString ();
} //getAmtInWords
/**
*Test Print
*@param amt amount
*/
private void print (String amt)
{
try
{
System.out.println(amt + " = " + getAmtInWords(amt));
}
catch (Exception e)
{
e.printStackTrace(); | }
} //print
/**
*Test
*@param args ignored
*/
public static void main (String[] args)
{
AmtInWords_BG aiw = new AmtInWords_BG();
aiw.print("0.23");
aiw.print("23");
aiw.print ("0,23");
aiw.print ("1,23");
aiw.print ("12,345");
aiw.print ("123,45");
aiw.print ("1 234,56");
aiw.print ("12 345,78");
aiw.print ("123 457,89");
aiw.print ("1 234 578,90");
aiw.print("10,00");
aiw.print("50,00");
aiw.print("100,00");
aiw.print("300,00");
aiw.print("1 000,00");
aiw.print("3 000,00");
aiw.print("10 000,00");
aiw.print("1 000 000,00");
aiw.print("100 000 000,00");
aiw.print("100 000 000 000 000 0000,00");
} //main
} //AmtInWords_BG | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_BG.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SomeBean {
@JsonView(Views.Public.class)
private String field1;
@JsonView(Views.Public.class)
private String field2;
//@JsonIgnore
@JsonView(Views.Public.class)
private String field3;
public SomeBean(String field1, String field2, String field3) {
super();
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
} | public String getField1() {
return field1;
}
public String getField2() {
return field2;
}
public String getField3() {
return field3;
}
@Override
public String toString() {
return "SomeBean [field1=" + field1 + ", field2=" + field2 + ", field3=" + field3 + "]";
}
} | repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\filtering\SomeBean.java | 2 |
请完成以下Java代码 | private boolean expr_sempred(ExprContext _localctx, int predIndex) {
switch (predIndex) {
case 0:
return precpred(_ctx, 5);
case 1:
return precpred(_ctx, 4);
}
return true;
}
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\r-\4\2\t\2\4\3\t"+
"\3\4\4\t\4\3\2\6\2\n\n\2\r\2\16\2\13\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\5\3\27\n\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4 \n\4\3\4\3\4\3\4\3\4\3\4"+
"\3\4\7\4(\n\4\f\4\16\4+\13\4\3\4\2\3\6\5\2\4\6\2\4\3\2\6\7\3\2\b\t\2\60"+
"\2\t\3\2\2\2\4\26\3\2\2\2\6\37\3\2\2\2\b\n\5\4\3\2\t\b\3\2\2\2\n\13\3"+ | "\2\2\2\13\t\3\2\2\2\13\f\3\2\2\2\f\3\3\2\2\2\r\16\5\6\4\2\16\17\7\f\2"+
"\2\17\27\3\2\2\2\20\21\7\n\2\2\21\22\7\3\2\2\22\23\5\6\4\2\23\24\7\f\2"+
"\2\24\27\3\2\2\2\25\27\7\f\2\2\26\r\3\2\2\2\26\20\3\2\2\2\26\25\3\2\2"+
"\2\27\5\3\2\2\2\30\31\b\4\1\2\31 \7\13\2\2\32 \7\n\2\2\33\34\7\4\2\2\34"+
"\35\5\6\4\2\35\36\7\5\2\2\36 \3\2\2\2\37\30\3\2\2\2\37\32\3\2\2\2\37\33"+
"\3\2\2\2 )\3\2\2\2!\"\f\7\2\2\"#\t\2\2\2#(\5\6\4\b$%\f\6\2\2%&\t\3\2\2"+
"&(\5\6\4\7\'!\3\2\2\2\'$\3\2\2\2(+\3\2\2\2)\'\3\2\2\2)*\3\2\2\2*\7\3\2"+
"\2\2+)\3\2\2\2\7\13\26\37\')";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} | repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprParser.java | 1 |
请完成以下Java代码 | protected List<DbEntityOperation> sortByReferences(SortedSet<DbEntityOperation> preSorted) {
// copy the pre-sorted set and apply final sorting to list
List<DbEntityOperation> opList = new ArrayList<DbEntityOperation>(preSorted);
for (int i = 0; i < opList.size(); i++) {
DbEntityOperation currentOperation = opList.get(i);
DbEntity currentEntity = currentOperation.getEntity();
Set<String> currentReferences = currentOperation.getFlushRelevantEntityReferences();
// check whether this operation must be placed after another operation
int moveTo = i;
for(int k = i+1; k < opList.size(); k++) {
DbEntityOperation otherOperation = opList.get(k);
DbEntity otherEntity = otherOperation.getEntity();
Set<String> otherReferences = otherOperation.getFlushRelevantEntityReferences();
if(currentOperation.getOperationType() == INSERT) {
// if we reference the other entity, we need to be inserted after that entity
if(currentReferences != null && currentReferences.contains(otherEntity.getId())) {
moveTo = k;
break; // we can only reference a single entity
}
} else { // UPDATE or DELETE
// if the other entity has a reference to us, we must be placed after the other entity
if(otherReferences != null && otherReferences.contains(currentEntity.getId())) {
moveTo = k;
// cannot break, there may be another entity further to the right which also references us
}
}
} | if(moveTo > i) {
opList.remove(i);
opList.add(moveTo, currentOperation);
i--;
}
}
return opList;
}
protected void determineDependencies(List<DbOperation> flush) {
TreeSet<DbEntityOperation> defaultValue = new TreeSet<DbEntityOperation>();
for (DbOperation operation : flush) {
if (operation instanceof DbEntityOperation) {
DbEntity entity = ((DbEntityOperation) operation).getEntity();
if (entity instanceof HasDbReferences) {
Map<String, Class> dependentEntities = ((HasDbReferences) entity).getDependentEntities();
if (dependentEntities != null) {
dependentEntities.forEach((id, type) -> {
deletes.getOrDefault(type, defaultValue).forEach(o -> {
if (id.equals(o.getEntity().getId())) {
o.setDependency(operation);
}
});
});
}
}
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbOperationManager.java | 1 |
请完成以下Java代码 | public int getHR_ListType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.eevolution.model.I_HR_Payroll getHR_Payroll() throws RuntimeException
{
return (org.eevolution.model.I_HR_Payroll)MTable.get(getCtx(), org.eevolution.model.I_HR_Payroll.Table_Name)
.getPO(getHR_Payroll_ID(), get_TrxName()); }
/** Set Payroll.
@param HR_Payroll_ID Payroll */
public void setHR_Payroll_ID (int HR_Payroll_ID)
{
if (HR_Payroll_ID < 1)
set_Value (COLUMNNAME_HR_Payroll_ID, null);
else
set_Value (COLUMNNAME_HR_Payroll_ID, Integer.valueOf(HR_Payroll_ID));
}
/** Get Payroll.
@return Payroll */
public int getHR_Payroll_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Employee.
@param IsEmployee
Indicates if this Business Partner is an employee
*/
public void setIsEmployee (boolean IsEmployee)
{
set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee));
}
/** Get Employee.
@return Indicates if this Business Partner is an employee
*/
public boolean isEmployee ()
{
Object oo = get_Value(COLUMNNAME_IsEmployee);
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);
}
/** Get Record ID/ColumnName | @return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** 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 Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_List.java | 1 |
请完成以下Java代码 | private Attributes getDefaultAttributes()
{
return Attributes.ofList(
ATTRIBUTE_CODES.stream()
.map(this::getDefaultAttribute)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList())
);
}
@Nullable
private Attribute getDefaultAttribute(@NonNull AttributeCode attributeCode)
{
return Attribute.of(productService.getAttribute(attributeCode));
} | @NonNull
private InventoryLine findFirstMatchingLine(final Predicate<InventoryLine> predicate)
{
return lines.stream()
.filter(predicate)
.findFirst()
.orElseThrow(() -> new AdempiereException("No line found for the given HU QR code"));
}
private boolean isLineMatchingHU(final InventoryLine line, final I_M_HU hu)
{
return !line.isCounted()
&& LocatorId.equals(line.getLocatorId(), huCache.getLocatorId(hu))
&& huCache.getProductIds(hu).contains(line.getProductId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\job\qrcode\ResolveHUCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected final String getLoginProcessingUrl() {
return this.loginProcessingUrl;
}
/**
* Gets the URL to send users to if authentication fails
* @return the URL to send users if authentication fails (e.g. "/login?error").
*/
protected final String getFailureUrl() {
return this.failureUrl;
}
/**
* Updates the default values for authentication.
*/
protected final void updateAuthenticationDefaults() {
if (this.loginProcessingUrl == null) {
loginProcessingUrl(this.loginPage);
}
if (this.failureHandler == null) {
failureUrl(this.loginPage + "?error");
}
LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) {
logoutConfigurer.logoutSuccessUrl(this.loginPage + "?logout");
}
}
/**
* Updates the default values for access.
*/
protected final void updateAccessDefaults(B http) {
if (this.permitAll) { | PermitAllSupport.permitAll(http, this.loginPage, this.loginProcessingUrl, this.failureUrl);
}
}
/**
* Sets the loginPage and updates the {@link AuthenticationEntryPoint}.
* @param loginPage
*/
private void setLoginPage(String loginPage) {
this.loginPage = loginPage;
this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage);
}
private <C> C getBeanOrNull(B http, Class<C> clazz) {
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
return context.getBeanProvider(clazz).getIfUnique();
}
@SuppressWarnings("unchecked")
private T getSelf() {
return (T) this;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractAuthenticationFilterConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
*process BizException
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = BizException.class)
@ResponseBody
public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){
logger.error("biz exception!the reason is:{}",e.getErrorMsg());
return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
}
/**
* process NUllException
* @param req
* @param e
* @return
*/ | @ExceptionHandler(value =NullPointerException.class)
@ResponseBody
public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){
logger.error("null exception!the reason is:",e);
return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
}
/**
* unkown Exception
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public ResultBody exceptionHandler(HttpServletRequest req, Exception e){
logger.error("unkown Exception!the reason is:",e);
return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
}
} | repos\springboot-demo-master\Exception\src\main\java\com\et\exception\config\GlobalExceptionHandler.java | 2 |
请完成以下Java代码 | protected void configure(FilterRegistration.Dynamic registration) {
super.configure(registration);
EnumSet<DispatcherType> dispatcherTypes = determineDispatcherTypes();
Set<String> servletNames = new LinkedHashSet<>();
for (ServletRegistrationBean<?> servletRegistrationBean : this.servletRegistrationBeans) {
servletNames.add(servletRegistrationBean.getServletName());
}
servletNames.addAll(this.servletNames);
if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
}
else {
if (!servletNames.isEmpty()) {
registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(servletNames));
}
if (!this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(this.urlPatterns));
}
}
}
/**
* Return the {@link Filter} to be registered.
* @return the filter
*/
public abstract @Nullable T getFilter(); | /**
* Returns the filter name that will be registered.
* @return the filter name
* @since 3.2.0
*/
public String getFilterName() {
return getOrDeduceName(getFilter());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(getOrDeduceName(this));
if (this.servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(Arrays.toString(DEFAULT_URL_MAPPINGS));
}
else {
if (!this.servletNames.isEmpty()) {
builder.append(" servlets=").append(this.servletNames);
}
if (!this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(this.urlPatterns);
}
}
builder.append(" order=").append(getOrder());
return builder.toString();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\AbstractFilterRegistrationBean.java | 1 |
请完成以下Java代码 | public int getM_ProductDownload_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductDownload_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductDownload.java | 1 |
请完成以下Java代码 | public String getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTp(String value) {
this.tp = value;
}
/**
* Gets the value of the qty property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getQty() {
return qty;
}
/**
* Sets the value of the qty property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQty(String value) {
this.qty = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ProprietaryQuantity1.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class T100 implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -6000839351758419437L;
private String record;
private String partner;
private String messageNo;
private String contractValue;
public final String getRecord()
{
return record;
}
public final void setRecord(final String record)
{
this.record = record;
}
public final String getPartner()
{
return partner;
}
public final void setPartner(final String partner)
{
this.partner = partner;
}
public final String getMessageNo()
{
return messageNo;
}
public final void setMessageNo(final String messageNo)
{
this.messageNo = messageNo;
}
public final String getContractValue()
{
return contractValue;
}
public final void setContractValue(final String contractValue)
{
this.contractValue = contractValue;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (contractValue == null ? 0 : contractValue.hashCode());
result = prime * result + (messageNo == null ? 0 : messageNo.hashCode());
result = prime * result + (partner == null ? 0 : partner.hashCode());
result = prime * result + (record == null ? 0 : record.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
} | final T100 other = (T100)obj;
if (contractValue == null)
{
if (other.contractValue != null)
{
return false;
}
}
else if (!contractValue.equals(other.contractValue))
{
return false;
}
if (messageNo == null)
{
if (other.messageNo != null)
{
return false;
}
}
else if (!messageNo.equals(other.messageNo))
{
return false;
}
if (partner == null)
{
if (other.partner != null)
{
return false;
}
}
else if (!partner.equals(other.partner))
{
return false;
}
if (record == null)
{
if (other.record != null)
{
return false;
}
}
else if (!record.equals(other.record))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "T100 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", contractValue=" + contractValue + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\T100.java | 2 |
请完成以下Java代码 | public String getHttpHeadersAsString() {
return httpHeaders != null ? httpHeaders.formatAsString() : null;
}
public void setHttpHeaders(HttpHeaders httpHeaders) {
this.httpHeaders = httpHeaders;
}
public HttpHeaders getSecureHttpHeaders() {
return secureHttpHeaders;
}
public String getSecureHttpHeadersAsString() {
return secureHttpHeaders != null ? secureHttpHeaders.formatAsString(true) : null;
}
public void setSecureHttpHeaders(HttpHeaders secureHttpHeaders) {
this.secureHttpHeaders = secureHttpHeaders;
}
public String getBody() {
return body;
}
public void setBody(String body) {
if (multiValueParts != null && !multiValueParts.isEmpty()) {
throw new FlowableIllegalStateException("Cannot set both body and multi value parts");
} else if (formParameters != null && !formParameters.isEmpty()) {
throw new FlowableIllegalStateException("Cannot set both body and form parameters");
}
this.body = body;
}
public String getBodyEncoding() {
return bodyEncoding;
}
public void setBodyEncoding(String bodyEncoding) {
this.bodyEncoding = bodyEncoding;
}
public Collection<MultiValuePart> getMultiValueParts() {
return multiValueParts;
} | public void addMultiValuePart(MultiValuePart part) {
if (body != null) {
throw new FlowableIllegalStateException("Cannot set both body and multi value parts");
} else if (formParameters != null && !formParameters.isEmpty()) {
throw new FlowableIllegalStateException("Cannot set both form parameters and multi value parts");
}
if (multiValueParts == null) {
multiValueParts = new ArrayList<>();
}
multiValueParts.add(part);
}
public Map<String, List<String>> getFormParameters() {
return formParameters;
}
public void addFormParameter(String key, String value) {
if (body != null) {
throw new FlowableIllegalStateException("Cannot set both body and form parameters");
} else if (multiValueParts != null && !multiValueParts.isEmpty()) {
throw new FlowableIllegalStateException("Cannot set both multi value parts and form parameters");
}
if (formParameters == null) {
formParameters = new LinkedHashMap<>();
}
formParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public boolean isNoRedirects() {
return noRedirects;
}
public void setNoRedirects(boolean noRedirects) {
this.noRedirects = noRedirects;
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpRequest.java | 1 |
请完成以下Java代码 | public class CompositeDocumentRepostingSupplier implements IDocumentRepostingSupplier
{
// list of handlers to be used when the reposting process is called
private final CopyOnWriteArrayList<IDocumentRepostingSupplier> suppliers = new CopyOnWriteArrayList<>();
// add the handler in the list
public void addSupplier(final IDocumentRepostingSupplier supplier)
{
if (supplier == null)
{
return;
}
suppliers.addIfAbsent(supplier);
}
@Override
public List<IDocument> retrievePostedWithoutFactAcct(final Properties ctx, final Timestamp startTime) | {
final IDocumentBL docActionBL = Services.get(IDocumentBL.class);
final List<IDocument> documentsPostedWithoutFactAcct = new ArrayList<>();
// Retrieve the documents marked as posted but with no fact accounts from all the handlers
for (final IDocumentRepostingSupplier handler : suppliers)
{
final List<?> documents = handler.retrievePostedWithoutFactAcct(ctx, startTime);
for (final Object document : documents)
{
documentsPostedWithoutFactAcct.add(docActionBL.getDocument(document));
}
}
return documentsPostedWithoutFactAcct;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\spi\impl\CompositeDocumentRepostingSupplier.java | 1 |
请完成以下Java代码 | private JsonResponseBPartnerLocationAndContact toJson(
@Nullable final String orgCode,
@Nullable final BPartnerInfo bpartnerInfo,
@NonNull final MasterdataProvider masterdataProvider)
{
if (bpartnerInfo == null)
{
return null;
}
final BPartnerId bpartnerId = bpartnerInfo.getBpartnerId();
final BPartnerLocationId bpartnerLocationId = bpartnerInfo.getBpartnerLocationId();
final BPartnerContactId contactId = bpartnerInfo.getContactId();
return JsonResponseBPartnerLocationAndContact.builder()
.bpartner(masterdataProvider.getJsonBPartnerById(orgCode, bpartnerId))
.location(masterdataProvider.getJsonBPartnerLocationById(orgCode, bpartnerLocationId))
.contact(masterdataProvider.getJsonBPartnerContactById(orgCode, contactId))
.build();
}
public JsonOLCandCreateBulkResponse toJson(
@NonNull final List<OLCand> olCands,
@NonNull final MasterdataProvider masterdataProvider)
{
return JsonOLCandCreateBulkResponse.ok(olCands.stream()
.map(olCand -> toJson(olCand, masterdataProvider))
.collect(ImmutableList.toImmutableList()));
}
private JsonOLCand toJson(
@NonNull final OLCand olCand,
@NonNull final MasterdataProvider masterdataProvider)
{
final OrgId orgId = OrgId.ofRepoId(olCand.getAD_Org_ID());
final ZoneId orgTimeZone = masterdataProvider.getOrgTimeZone(orgId);
final String orgCode = orgDAO.retrieveOrgValue(orgId); | return JsonOLCand.builder()
.id(olCand.getId())
.poReference(olCand.getPOReference())
.externalLineId(olCand.getExternalLineId())
.externalHeaderId(olCand.getExternalHeaderId())
//
.org(masterdataProvider.getJsonOrganizationById(orgId))
//
.bpartner(toJson(orgCode, olCand.getBPartnerInfo(), masterdataProvider))
.billBPartner(toJson(orgCode, olCand.getBillBPartnerInfo(), masterdataProvider))
.dropShipBPartner(toJson(orgCode, olCand.getDropShipBPartnerInfo().orElse(null), masterdataProvider))
.handOverBPartner(toJson(orgCode, olCand.getHandOverBPartnerInfo().orElse(null), masterdataProvider))
//
.dateOrdered(olCand.getDateOrdered())
.datePromised(TimeUtil.asLocalDate(olCand.getDatePromised(), orgTimeZone))
.flatrateConditionsId(olCand.getFlatrateConditionsId())
//
.productId(olCand.getM_Product_ID())
.productDescription(olCand.getProductDescription())
.qty(olCand.getQty().toBigDecimal())
.uomId(olCand.getQty().getUomId().getRepoId())
.qtyItemCapacity(Quantitys.toBigDecimalOrNull(olCand.getQtyItemCapacityEff()))
.huPIItemProductId(olCand.getHUPIProductItemId())
//
.pricingSystemId(PricingSystemId.toRepoId(olCand.getPricingSystemId()))
.price(olCand.getPriceActual())
.discount(olCand.getDiscount())
//
.warehouseDestId(WarehouseId.toRepoId(olCand.getWarehouseDestId()))
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\JsonConverters.java | 1 |
请完成以下Java代码 | protected T doBind() {
Bindable<T> bindable = Bindable.of(this.configurable.getConfigClass());
T bound = bindOrCreate(bindable, this.normalizedProperties, this.configurable.shortcutFieldPrefix(),
/* this.name, */this.service.validator.get(), this.service.conversionService.get());
return bound;
}
}
public static class InstanceBuilder<T> extends AbstractBuilder<T, InstanceBuilder<T>> {
private final T instance;
public InstanceBuilder(ConfigurationService service, T instance) {
super(service);
this.instance = instance;
}
@Override
protected InstanceBuilder<T> getThis() {
return this;
}
@Override
protected void validate() {
Objects.requireNonNull(this.instance, "instance may not be null");
}
@Override
protected T doBind() {
T toBind = getTargetObject(this.instance);
Bindable<T> bindable = Bindable.ofInstance(toBind);
return bindOrCreate(bindable, this.normalizedProperties, this.name, this.service.validator.get(),
this.service.conversionService.get());
}
}
public static abstract class AbstractBuilder<T, B extends AbstractBuilder<T, B>> {
protected final ConfigurationService service;
protected BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction;
protected String name;
protected Map<String, Object> normalizedProperties;
protected Map<String, String> properties;
public AbstractBuilder(ConfigurationService service) {
this.service = service;
}
protected abstract B getThis();
public B name(String name) {
this.name = name;
return getThis();
}
public B eventFunction(BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction) {
this.eventFunction = eventFunction;
return getThis();
}
public B normalizedProperties(Map<String, Object> normalizedProperties) {
this.normalizedProperties = normalizedProperties;
return getThis();
}
public B properties(Map<String, String> properties) {
this.properties = properties;
return getThis(); | }
protected abstract void validate();
protected Map<String, Object> normalizeProperties() {
Map<String, Object> normalizedProperties = new HashMap<>();
this.properties.forEach(normalizedProperties::put);
return normalizedProperties;
}
protected abstract T doBind();
public T bind() {
validate();
Assert.hasText(this.name, "name may not be empty");
Assert.isTrue(this.properties != null || this.normalizedProperties != null,
"properties and normalizedProperties both may not be null");
if (this.normalizedProperties == null) {
this.normalizedProperties = normalizeProperties();
}
T bound = doBind();
if (this.eventFunction != null && this.service.publisher != null) {
ApplicationEvent applicationEvent = this.eventFunction.apply(bound, this.normalizedProperties);
this.service.publisher.publishEvent(applicationEvent);
}
return bound;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ConfigurationService.java | 1 |
请完成以下Java代码 | public AppClusterServerStateWrapVO setBelongToApp(Boolean belongToApp) {
this.belongToApp = belongToApp;
return this;
}
public Integer getConnectedCount() {
return connectedCount;
}
public AppClusterServerStateWrapVO setConnectedCount(Integer connectedCount) {
this.connectedCount = connectedCount;
return this;
}
public ClusterServerStateVO getState() {
return state;
} | public AppClusterServerStateWrapVO setState(ClusterServerStateVO state) {
this.state = state;
return this;
}
@Override
public String toString() {
return "AppClusterServerStateWrapVO{" +
"id='" + id + '\'' +
", ip='" + ip + '\'' +
", port='" + port + '\'' +
", belongToApp=" + belongToApp +
", state=" + state +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\AppClusterServerStateWrapVO.java | 1 |
请完成以下Java代码 | public void onBPGroupChanged(final I_C_Campaign_Price record)
{
if (record == null)
{
return;
}
final BPGroupId bpGroupId = BPGroupId.ofRepoIdOrNull(record.getC_BP_Group_ID());
if (bpGroupId == null)
{
return;
}
record.setC_BPartner_ID(-1);
}
@CalloutMethod(columnNames = I_C_Campaign_Price.COLUMNNAME_C_Country_ID, skipIfCopying = true)
public void onCountryChanged(final I_C_Campaign_Price record)
{
final CountryId countryId = CountryId.ofRepoIdOrNull(record.getC_Country_ID());
if (countryId == null)
{
return;
}
updateCurrency(record, countryId);
}
private void updateCurrency(final I_C_Campaign_Price record, final CountryId countryId)
{
countriesRepo.getCountryCurrencyId(countryId).ifPresent(currencyId -> record.setC_Currency_ID(currencyId.getRepoId()));
}
@CalloutMethod(columnNames = I_C_Campaign_Price.COLUMNNAME_M_Product_ID, skipIfCopying = true)
public void onProductChanged(final I_C_Campaign_Price record)
{
final ProductId productId = ProductId.ofRepoIdOrNull(record.getM_Product_ID());
if (productId == null)
{ | return;
}
final UomId stockUomId = productBL.getStockUOMId(productId);
record.setC_UOM_ID(stockUomId.getRepoId());
updatePricingInfo(record);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Campaign_Price.COLUMNNAME_C_BPartner_ID, I_C_Campaign_Price.COLUMNNAME_C_BP_Group_ID, I_C_Campaign_Price.COLUMNNAME_M_PricingSystem_ID })
public void beforeSave(final I_C_Campaign_Price record)
{
if (record.getC_BPartner_ID() <= 0 && record.getC_BP_Group_ID() <= 0 && record.getM_PricingSystem_ID() <= 0)
{
throw new AdempiereException(ERR_MandatoryFields);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\callout\C_Campaign_Price.java | 1 |
请完成以下Java代码 | public class ProcessInstanceMigrationBatchCmd implements Command<Batch> {
protected String processDefinitionId;
protected String processDefinitionKey;
protected int processDefinitionVersion;
protected String processDefinitionTenantId;
protected ProcessInstanceMigrationDocument processInstanceMigrationDocument;
public ProcessInstanceMigrationBatchCmd(String processDefinitionId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) {
if (processDefinitionId == null) {
throw new FlowableException("Must specify a process definition id to migrate");
}
if (processInstanceMigrationDocument == null) {
throw new FlowableException("Must specify a process migration document to migrate");
}
this.processDefinitionId = processDefinitionId;
this.processInstanceMigrationDocument = processInstanceMigrationDocument;
}
public ProcessInstanceMigrationBatchCmd(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId,
ProcessInstanceMigrationDocument processInstanceMigrationDocument) {
if (processDefinitionKey == null) {
throw new FlowableException("Must specify a process definition key to migrate"); | }
if (processInstanceMigrationDocument == null) {
throw new FlowableException("Must specify a process migration document to migrate");
}
this.processDefinitionKey = processDefinitionKey;
this.processDefinitionVersion = processDefinitionVersion;
this.processDefinitionTenantId = processDefinitionTenantId;
this.processInstanceMigrationDocument = processInstanceMigrationDocument;
}
@Override
public Batch execute(CommandContext commandContext) {
ProcessInstanceMigrationManager migrationManager = CommandContextUtil.getProcessEngineConfiguration(commandContext).getProcessInstanceMigrationManager();
if (processDefinitionId != null) {
return migrationManager.batchMigrateProcessInstancesOfProcessDefinition(processDefinitionId, processInstanceMigrationDocument, commandContext);
}
return migrationManager.batchMigrateProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion,
processDefinitionTenantId, processInstanceMigrationDocument, commandContext);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ProcessInstanceMigrationBatchCmd.java | 1 |
请完成以下Java代码 | public Predicate<ServerWebExchange> apply(Config config) {
Objects.requireNonNull(config.getDatetime1(), DATETIME1_KEY + " must not be null");
Assert.isTrue(config.getDatetime1().isBefore(config.getDatetime2()),
config.getDatetime1() + " must be before " + config.getDatetime2());
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange serverWebExchange) {
final ZonedDateTime now = ZonedDateTime.now();
return now.isAfter(config.getDatetime1()) && now.isBefore(config.getDatetime2());
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Between: %s and %s", config.getDatetime1(), config.getDatetime2());
}
};
}
public static class Config {
@NotNull
private @Nullable ZonedDateTime datetime1;
@NotNull
private @Nullable ZonedDateTime datetime2;
public @Nullable ZonedDateTime getDatetime1() {
return datetime1;
} | public Config setDatetime1(ZonedDateTime datetime1) {
this.datetime1 = datetime1;
return this;
}
public @Nullable ZonedDateTime getDatetime2() {
return datetime2;
}
public Config setDatetime2(ZonedDateTime datetime2) {
this.datetime2 = datetime2;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\BetweenRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public Timestamp getSubscribeDate ()
{
if (m_ci != null)
return m_ci.getSubscribeDate();
return null;
}
/**
* Get Opt Out Date
* @return opt-out date
*/
public Timestamp getOptOutDate ()
{
if (m_ci != null)
return m_ci.getOptOutDate(); | return null;
}
/**
* Is Subscribed
* @return true if sunscribed
*/
public boolean isSubscribed()
{
if (m_AD_User_ID <= 0 || m_ci == null)
return false;
// We have a BPartner Contact
return m_ci.isSubscribed();
} // isSubscribed
} // MInterestArea | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MInterestArea.java | 1 |
请完成以下Java代码 | public final ArrayKey buildKey()
{
return Util.mkKey(keyParts.toArray());
}
public void add(final Object keyPart)
{
keyParts.add(keyPart);
}
public void setTrxName(String trxName)
{
this.trxName = trxName;
}
public String getTrxName()
{
return trxName;
}
public void setSkipCaching()
{
this.skipCaching = true;
}
public boolean isSkipCaching()
{
return skipCaching;
} | /**
* Advices the caching engine to refresh the cached value, instead of checking the cache.
*
* NOTE: this option will have NO affect if {@link #isSkipCaching()}.
*/
public void setCacheReload()
{
this.cacheReload = true;
}
/** @return true if instead the underlying method shall be invoked and cache shall be refreshed with that value */
public boolean isCacheReload()
{
return cacheReload;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheKeyBuilder.java | 1 |
请完成以下Java代码 | public String getCode()
{
return getDocBaseType().getCode();
}
public boolean isSales()
{
return getSoTrx().isSales();
}
public boolean isPurchase()
{
return getSoTrx().isPurchase();
}
/**
* @return is Account Payable (AP), aka purchase
* @see #isPurchase()
*/
public boolean isAP() {return isPurchase();}
public boolean isCustomerInvoice()
{
return this == CustomerInvoice;
}
public boolean isCustomerCreditMemo()
{
return this == CustomerCreditMemo;
} | public boolean isVendorCreditMemo()
{
return this == VendorCreditMemo;
}
public boolean isIncomingCash()
{
return (isSales() && !isCreditMemo()) // ARI
|| (isPurchase() && isCreditMemo()) // APC
;
}
public boolean isOutgoingCash()
{
return !isIncomingCash();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceDocBaseType.java | 1 |
请完成以下Java代码 | public frame addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frame addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frame addElement(String element)
{
addElementToRegistry(element); | return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public frame removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frame.java | 1 |
请完成以下Java代码 | public Builder setHasTreeSupport(final boolean hasTreeSupport)
{
this.hasTreeSupport = hasTreeSupport;
return this;
}
public Builder setTreeCollapsible(final boolean treeCollapsible)
{
this.treeCollapsible = treeCollapsible;
return this;
}
public Builder setTreeExpandedDepth(final int treeExpandedDepth)
{
this.treeExpandedDepth = treeExpandedDepth; | return this;
}
public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails)
{
this.allowOpeningRowDetails = allowOpeningRowDetails;
return this;
}
public Builder setFocusOnFieldName(final String focusOnFieldName)
{
this.focusOnFieldName = focusOnFieldName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void save(@NonNull final CandidateQtyDetailsPersistMultiRequest saveRequest)
{
deleteByCandidateId(saveRequest.getCandidateId());
final List<I_MD_Candidate_QtyDetails> qtyDetails = saveRequest
.getDetails()
.stream()
.map(request -> create(saveRequest.getCandidateId(), saveRequest.getStockCandidateId(), request))
.collect(Collectors.toList());
saveAll(qtyDetails);
}
private void deleteByCandidateId(@NonNull final CandidateId candidateId)
{
query.createQueryBuilder(I_MD_Candidate_QtyDetails.class)
.addEqualsFilter(I_MD_Candidate_QtyDetails.COLUMNNAME_MD_Candidate_ID, candidateId) | .create()
.delete();
}
private I_MD_Candidate_QtyDetails create(final @NonNull CandidateId candidateId, @Nullable final CandidateId stockCandidateId, final CandidateQtyDetailsPersistRequest request)
{
final I_MD_Candidate_QtyDetails po = InterfaceWrapperHelper.newInstance(I_MD_Candidate_QtyDetails.class);
po.setMD_Candidate_ID(candidateId.getRepoId());
po.setStock_MD_Candidate_ID(CandidateId.toRepoId(stockCandidateId));
po.setDetail_MD_Candidate_ID(CandidateId.toRepoId(request.getDetailCandidateId()));
po.setQty(request.getQtyInStockUom());
return po;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateQtyDetailsRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | Map<String, String> fetchTokenKeys() {
try {
Map<?, ?> response = this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class);
Assert.state(response != null, "'response' must not be null");
return extractTokenKeys(response);
}
catch (HttpStatusCodeException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable");
}
}
private Map<String, String> extractTokenKeys(Map<?, ?> response) {
Map<String, String> tokenKeys = new HashMap<>();
List<?> keys = (List<?>) response.get("keys");
Assert.state(keys != null, "'keys' must not be null");
for (Object key : keys) {
Map<?, ?> tokenKey = (Map<?, ?>) key;
tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value"));
}
return tokenKeys;
}
/**
* Return the URL of the UAA.
* @return the UAA url
*/ | String getUaaUrl() {
if (this.uaaUrl == null) {
try {
Map<?, ?> response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class);
Assert.state(response != null, "'response' must not be null");
String tokenEndpoint = (String) response.get("token_endpoint");
Assert.state(tokenEndpoint != null, "'tokenEndpoint' must not be null");
this.uaaUrl = tokenEndpoint;
}
catch (HttpStatusCodeException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"Unable to fetch token keys from UAA");
}
}
return this.uaaUrl;
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\SecurityService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy { | /**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java | 2 |
请完成以下Java代码 | public void setPA_ReportCube_ID (int PA_ReportCube_ID)
{
if (PA_ReportCube_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, Integer.valueOf(PA_ReportCube_ID));
}
/** Get Report Cube.
@return Define reporting cube for pre-calculation of summary accounting data.
*/
public int getPA_ReportCube_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportCube_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportCube.java | 1 |
请完成以下Java代码 | public I_C_Order getC_Order() throws RuntimeException
{
return (I_C_Order)MTable.get(getCtx(), I_C_Order.Table_Name)
.getPO(getC_Order_ID(), get_TrxName()); }
/** Set Order.
@param C_Order_ID
Order
*/
public void setC_Order_ID (int C_Order_ID)
{
if (C_Order_ID < 1)
set_Value (COLUMNNAME_C_Order_ID, null);
else
set_Value (COLUMNNAME_C_Order_ID, Integer.valueOf(C_Order_ID));
}
/** Get Order.
@return Order
*/
public int getC_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Payment getC_Payment() throws RuntimeException
{
return (I_C_Payment)MTable.get(getCtx(), I_C_Payment.Table_Name)
.getPO(getC_Payment_ID(), get_TrxName()); }
/** Set Payment.
@param C_Payment_ID
Payment identifier
*/
public void setC_Payment_ID (int C_Payment_ID)
{
if (C_Payment_ID < 1)
set_Value (COLUMNNAME_C_Payment_ID, null);
else
set_Value (COLUMNNAME_C_Payment_ID, Integer.valueOf(C_Payment_ID)); | }
/** Get Payment.
@return Payment identifier
*/
public int getC_Payment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Not Committed Aount.
@param NonCommittedAmt
Amount not committed yet
*/
public void setNonCommittedAmt (BigDecimal NonCommittedAmt)
{
set_Value (COLUMNNAME_NonCommittedAmt, NonCommittedAmt);
}
/** Get Not Committed Aount.
@return Amount not committed yet
*/
public BigDecimal getNonCommittedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_NonCommittedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_SellerFunds.java | 1 |
请完成以下Java代码 | public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl();
}
public HistoricJobLogQueryImpl createHistoricJobLogQuery() {
return new HistoricJobLogQueryImpl();
}
public UserQueryImpl createUserQuery() {
return new DbUserQueryImpl();
}
public GroupQueryImpl createGroupQuery() {
return new DbGroupQueryImpl();
} | public void registerOptimisticLockingListener(OptimisticLockingListener optimisticLockingListener) {
if(optimisticLockingListeners == null) {
optimisticLockingListeners = new ArrayList<>();
}
optimisticLockingListeners.add(optimisticLockingListener);
}
public List<String> getTableNamesPresentInDatabase() {
return persistenceSession.getTableNamesPresent();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\DbEntityManager.java | 1 |
请完成以下Java代码 | public Collection<V> values()
{
return cache.asMap().values();
} // values
@Override
protected final void finalize() throws Throwable
{
// NOTE: to avoid memory leaks we need to programatically clear our internal state
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
logger.debug("Running finalize");
cache.invalidateAll();
}
}
public CCacheStats stats()
{ | final CacheStats guavaStats = cache.stats();
return CCacheStats.builder()
.cacheId(cacheId)
.name(cacheName)
.labels(labels)
.config(config)
.debugAcquireStacktrace(debugAcquireStacktrace)
//
.size(cache.size())
.hitCount(guavaStats.hitCount())
.missCount(guavaStats.missCount())
.build();
}
private boolean isNoCache()
{
return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java | 1 |
请完成以下Java代码 | protected void lookupProvider(Map<String, DataFormat> dataFormats, DataFormatProvider provider) {
String dataFormatName = provider.getDataFormatName();
if (!dataFormats.containsKey(dataFormatName)) {
DataFormat dataFormatInstance = provider.createInstance();
dataFormats.put(dataFormatName, dataFormatInstance);
LOG.logDataFormat(dataFormatInstance);
} else {
throw LOG.multipleProvidersForDataformat(dataFormatName);
}
}
@SuppressWarnings("rawtypes")
protected void applyConfigurators(Map<String, DataFormat> dataFormats) {
ServiceLoader<DataFormatConfigurator> configuratorLoader = ServiceLoader.load(DataFormatConfigurator.class);
for (DataFormatConfigurator configurator : configuratorLoader) {
LOG.logDataFormatConfigurator(configurator);
applyConfigurator(dataFormats, configurator);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void applyConfigurator(Map<String, DataFormat> dataFormats, DataFormatConfigurator configurator) {
for (DataFormat dataFormat : dataFormats.values()) {
if (configurator.getDataFormatClass().isAssignableFrom(dataFormat.getClass())) {
configurator.configure(dataFormat);
}
}
}
public String checkHostname() {
String hostname;
try {
hostname = getHostname();
} catch (UnknownHostException e) {
throw LOG.cannotGetHostnameException(e);
}
return hostname;
}
public String getHostname() throws UnknownHostException {
return InetAddress.getLocalHost().getHostName();
}
public String getBaseUrl() {
return urlResolver.getBaseUrl();
}
protected String getWorkerId() { | return workerId;
}
protected List<ClientRequestInterceptor> getInterceptors() {
return interceptors;
}
protected int getMaxTasks() {
return maxTasks;
}
protected Long getAsyncResponseTimeout() {
return asyncResponseTimeout;
}
protected long getLockDuration() {
return lockDuration;
}
protected boolean isAutoFetchingEnabled() {
return isAutoFetchingEnabled;
}
protected BackoffStrategy getBackoffStrategy() {
return backoffStrategy;
}
public String getDefaultSerializationFormat() {
return defaultSerializationFormat;
}
public String getDateFormat() {
return dateFormat;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public ValueMappers getValueMappers() {
return valueMappers;
}
public TypedValues getTypedValues() {
return typedValues;
}
public EngineClient getEngineClient() {
return engineClient;
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java | 1 |
请完成以下Java代码 | public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
/**
* The default {@code Function} that maps {@link OneTimeToken} to a {@code List} of
* {@link SqlParameterValue}.
*
* @author Max Batischev
* @since 6.4
*/
private static class OneTimeTokenParametersMapper implements Function<OneTimeToken, List<SqlParameterValue>> {
@Override
public List<SqlParameterValue> apply(OneTimeToken oneTimeToken) {
List<SqlParameterValue> parameters = new ArrayList<>();
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue()));
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getUsername()));
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(oneTimeToken.getExpiresAt())));
return parameters;
}
} | /**
* The default {@link RowMapper} that maps the current row in
* {@code java.sql.ResultSet} to {@link OneTimeToken}.
*
* @author Max Batischev
* @since 6.4
*/
private static class OneTimeTokenRowMapper implements RowMapper<OneTimeToken> {
@Override
public OneTimeToken mapRow(ResultSet rs, int rowNum) throws SQLException {
String tokenValue = rs.getString("token_value");
String userName = rs.getString("username");
Instant expiresAt = rs.getTimestamp("expires_at").toInstant();
return new DefaultOneTimeToken(tokenValue, userName, expiresAt);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\JdbcOneTimeTokenService.java | 1 |
请完成以下Java代码 | public List<ObjectType> getObject() {
if (object == null) {
object = new ArrayList<ObjectType>();
}
return this.object;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id; | }
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\SignatureType.java | 1 |
请完成以下Java代码 | public class StatsTimer {
@Getter
private final String name;
private final Timer timer;
private int count;
private long totalTime;
public StatsTimer(String name, Timer micrometerTimer) {
this.name = name;
this.timer = micrometerTimer;
}
public void record(long timeMs) {
record(timeMs, TimeUnit.MILLISECONDS);
}
public void record(long timing, TimeUnit timeUnit) {
count++; | totalTime += timeUnit.toMillis(timing);
timer.record(timing, timeUnit);
}
public double getAvg() {
if (count == 0) {
return 0.0;
}
return (double) totalTime / count;
}
public void reset() {
count = 0;
totalTime = 0;
}
} | repos\thingsboard-master\common\stats\src\main\java\org\thingsboard\server\common\stats\StatsTimer.java | 1 |
请完成以下Java代码 | public List<EventDeployment> findDeploymentsByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) {
return dataManager.findDeploymentsByQueryCriteria(deploymentQuery);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return dataManager.getDeploymentResourceNames(deploymentId);
}
@Override
public List<EventDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findDeploymentsByNativeQuery(parameterMap);
}
@Override
public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) { | return dataManager.findDeploymentCountByNativeQuery(parameterMap);
}
protected EventResourceEntityManager getResourceEntityManager() {
return engineConfiguration.getResourceEntityManager();
}
protected EventDefinitionEntityManager getEventDefinitionEntityManager() {
return engineConfiguration.getEventDefinitionEntityManager();
}
protected ChannelDefinitionEntityManager getChannelDefinitionEntityManager() {
return engineConfiguration.getChannelDefinitionEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDeploymentEntityManagerImpl.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
@Override | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\User.java | 1 |
请完成以下Java代码 | public BPartnerContactType deepCopy()
{
return new BPartnerContactType(this);
}
public boolean getIsDefaultContactOr(final boolean defaultValue)
{
return defaultContact.orElse(defaultValue);
}
public boolean getIsBillToDefaultOr(final boolean defaultValue)
{
return billToDefault.orElse(defaultValue);
}
public boolean getIsShipToDefaultOr(final boolean defaultValue)
{
return shipToDefault.orElse(defaultValue);
}
public boolean getIsSalesDefaultOr(final boolean defaultValue)
{
return salesDefault.orElse(defaultValue);
}
public boolean getIsSalesOr(final boolean defaultValue)
{
return sales.orElse(defaultValue);
}
public boolean getIsPurchaseDefaultOr(final boolean defaultValue)
{
return purchaseDefault.orElse(defaultValue);
}
public boolean getIsPurchaseOr(final boolean defaultValue) | {
return purchase.orElse(defaultValue);
}
public void setDefaultContact(final boolean defaultContact)
{
this.defaultContact = Optional.of(defaultContact);
}
public void setBillToDefault(final boolean billToDefault)
{
this.billToDefault = Optional.of(billToDefault);
}
public void setShipToDefault(final boolean shipToDefault)
{
this.shipToDefault = Optional.of(shipToDefault);
}
public void setPurchaseDefault(final boolean purchaseDefault)
{
this.purchaseDefault = Optional.of(purchaseDefault);
}
public void setSalesDefault(final boolean salesDefault)
{
this.salesDefault = Optional.of(salesDefault);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerContactType.java | 1 |
请完成以下Java代码 | private Map<SecurPharmProductId, SecurPharmProduct> retrieveProductDataResultByIds(@NonNull final Collection<SecurPharmProductId> productDataResultIds)
{
Check.assumeNotEmpty(productDataResultIds, "productDataResultIds is not empty");
return queryBL
.createQueryBuilder(I_M_Securpharm_Productdata_Result.class)
.addInArrayFilter(I_M_Securpharm_Productdata_Result.COLUMNNAME_M_Securpharm_Productdata_Result_ID, productDataResultIds)
.create()
.stream()
.map(record -> toProductDataResult(record))
.collect(GuavaCollectors.toImmutableMapByKey(SecurPharmProduct::getId));
}
public Collection<SecurPharmProduct> getProductsByHuIds(@NonNull final Collection<HuId> huIds)
{
if (huIds.isEmpty())
{
return ImmutableList.of();
}
final ImmutableSet<SecurPharmProductId> ids = queryBL
.createQueryBuilder(I_M_Securpharm_Productdata_Result.class)
.addInArrayFilter(I_M_Securpharm_Productdata_Result.COLUMNNAME_M_HU_ID, huIds)
.create()
.idsAsSet(SecurPharmProductId::ofRepoId);
return getProductsByIds(ids);
}
private static SecurPharmProduct toProductDataResult(@NonNull final I_M_Securpharm_Productdata_Result record)
{
final boolean error = record.isError();
return SecurPharmProduct.builder() | .error(error)
.resultCode(record.getLastResultCode())
.resultMessage(record.getLastResultMessage())
.productDetails(!error ? toProductDetails(record) : null)
.huId(HuId.ofRepoId(record.getM_HU_ID()))
.id(SecurPharmProductId.ofRepoId(record.getM_Securpharm_Productdata_Result_ID()))
.build();
}
private static ProductDetails toProductDetails(final I_M_Securpharm_Productdata_Result record)
{
return ProductDetails.builder()
.productCode(record.getProductCode())
.productCodeType(ProductCodeType.ofCode(record.getProductCodeType()))
//
.lot(record.getLotNumber())
.serialNumber(record.getSerialNumber())
//
.expirationDate(JsonExpirationDate.ofLocalDate(TimeUtil.asLocalDate(record.getExpirationDate())))
//
.activeStatus(JsonProductPackageState.ofYesNoString(record.getActiveStatus()))
.inactiveReason(record.getInactiveReason())
//
.decommissioned(record.isDecommissioned())
.decommissionedServerTransactionId(record.getDecommissionedServerTransactionId())
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\product\SecurPharmProductRepository.java | 1 |
请完成以下Java代码 | public class InvoiceLineBPartnerAware implements IBPartnerAware
{
public static final IBPartnerAwareFactory factory = new IBPartnerAwareFactory()
{
@Override
public IBPartnerAware createBPartnerAware(Object model)
{
final I_C_InvoiceLine invoiceLine = InterfaceWrapperHelper.create(model, I_C_InvoiceLine.class);
final IBPartnerAware partnerAware = new InvoiceLineBPartnerAware(invoiceLine);
return partnerAware;
}
};
private final I_C_InvoiceLine invoiceLine;
private InvoiceLineBPartnerAware(final I_C_InvoiceLine invoiceLine)
{
super();
Check.assumeNotNull(invoiceLine, "Invoice line not null");
this.invoiceLine = invoiceLine;
}
@Override
public int getAD_Client_ID()
{
return invoiceLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return invoiceLine.getAD_Org_ID();
}
@Override
public boolean isSOTrx()
{
final I_C_Invoice invoice = getInvoice();
return invoice.isSOTrx();
}
@Override
public I_C_BPartner getC_BPartner() | {
final I_C_Invoice invoice = getInvoice();
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner partner = InterfaceWrapperHelper.create(bpartnerDAO.getById(invoice.getC_BPartner_ID()), I_C_BPartner.class);
if (partner == null)
{
return null;
}
return partner;
}
private I_C_Invoice getInvoice()
{
final I_C_Invoice invoice = invoiceLine.getC_Invoice();
if (invoice == null)
{
throw new AdempiereException("Invoice not set for" + invoiceLine);
}
return invoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\InvoiceLineBPartnerAware.java | 1 |
请完成以下Java代码 | public void dispose()
{
if (m_editor != null)
{
m_editor.dispose();
m_editor = null;
}
actionListener = null;
// m_mField = null;
// m_table = null;
} // dispose
/**
* @return true if we can stop current editor
*/
private boolean canStopEditing()
{
// nothing atm
return true;
}
@Override
public boolean stopCellEditing()
{
if (!canStopEditing())
{
return false;
}
if (!super.stopCellEditing())
{
return false;
}
clearCurrentEditing();
return true;
}
@Override
public void cancelCellEditing()
{
if (!canStopEditing()) | {
return ;
}
clearCurrentEditing();
super.cancelCellEditing();
}
private void clearCurrentEditing()
{
// metas: reset editing coordinates
editingRowIndexModel = -1;
editingColumnIndexModel = -1;
editingKeyId = -100;
if (m_editor instanceof VLookup)
{
((VLookup)m_editor).setStopEditing(true);
}
}
public void setActionListener(final ActionListener listener)
{
actionListener = listener;
}
} // VCellEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCellEditor.java | 1 |
请完成以下Java代码 | public void goodAccept(String one, String two, String three) {
if (one == null || two == null || three == null) {
throw new IllegalArgumentException();
}
process(one);
process(two);
process(three);
}
public void badAccept(String one, String two, String three) {
if (one == null) {
throw new IllegalArgumentException();
} else {
process(one);
}
if (two == null) { | throw new IllegalArgumentException();
} else {
process(two);
}
if (three == null) {
throw new IllegalArgumentException();
} else {
process(three);
}
}
private void process(String one) {
}
} | repos\tutorials-master\patterns-modules\design-patterns-behavioral\src\main\java\com\baeldung\nulls\Preconditions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SimpleMachineDiscovery implements MachineDiscovery {
private final ConcurrentMap<String, AppInfo> apps = new ConcurrentHashMap<>();
@Override
public long addMachine(MachineInfo machineInfo) {
AssertUtil.notNull(machineInfo, "machineInfo cannot be null");
AppInfo appInfo = apps.computeIfAbsent(machineInfo.getApp(), o -> new AppInfo(machineInfo.getApp(), machineInfo.getAppType()));
appInfo.addMachine(machineInfo);
return 1;
}
@Override
public boolean removeMachine(String app, String ip, int port) {
AssertUtil.assertNotBlank(app, "app name cannot be blank");
AppInfo appInfo = apps.get(app);
if (appInfo != null) {
return appInfo.removeMachine(ip, port);
}
return false;
}
@Override
public List<String> getAppNames() {
return new ArrayList<>(apps.keySet());
} | @Override
public AppInfo getDetailApp(String app) {
AssertUtil.assertNotBlank(app, "app name cannot be blank");
return apps.get(app);
}
@Override
public Set<AppInfo> getBriefApps() {
return new HashSet<>(apps.values());
}
@Override
public void removeApp(String app) {
AssertUtil.assertNotBlank(app, "app name cannot be blank");
apps.remove(app);
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\SimpleMachineDiscovery.java | 2 |
请完成以下Java代码 | public void setDocumentNo (final @Nullable java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setIsProcessing (final boolean IsProcessing)
{
set_Value (COLUMNNAME_IsProcessing, IsProcessing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_IsProcessing);
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
@Override
public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
} | @Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQM_Analysis_Report_ID (final int QM_Analysis_Report_ID)
{
if (QM_Analysis_Report_ID < 1)
set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, null);
else
set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, QM_Analysis_Report_ID);
}
@Override
public int getQM_Analysis_Report_ID()
{
return get_ValueAsInt(COLUMNNAME_QM_Analysis_Report_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_QM_Analysis_Report.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.jpa.simple.model");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager(); | transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\simple\config\PersistenceConfig.java | 2 |
请完成以下Java代码 | public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value("AD_User_ID");
if (ii == null)
return -1;
return ii.intValue();
} // getAD_User_ID
/**
* Get Role
* @return AD_Role_ID or -1 if none
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value("AD_Role_ID");
if (ii == null)
return -1; | return ii.intValue();
} // getAD_Role_ID
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlertRecipient[");
sb.append(get_ID())
.append(",AD_User_ID=").append(getAD_User_ID())
.append(",AD_Role_ID=").append(getAD_Role_ID())
.append ("]");
return sb.toString ();
} // toString
} // MAlertRecipient | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertRecipient.java | 1 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getHandlerType() {
return this.handlerType;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isRetriesLeft() {
return retriesLeft;
} | public boolean isExecutable() {
return executable;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CreateProjectRequest
{
@NonNull
OrgId orgId;
@NonNull
ProjectCategory projectCategory;
@NonNull
CurrencyId currencyId;
@Nullable
BPartnerLocationId bpartnerAndLocationId;
@Nullable
BPartnerContactId contactId;
@Nullable | PriceListVersionId priceListVersionId;
@Nullable
WarehouseId warehouseId;
@Singular
@NonNull List<ProjectLine> lines;
@Value
@Builder
public static class ProjectLine
{
@NonNull ProductId productId;
@NonNull Quantity plannedQty;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\CreateProjectRequest.java | 2 |
请完成以下Java代码 | public String html() throws ParserConfigurationException, TransformerException, IOException {
Element xml = input.getDocumentElement();
Document doc = factory
.newDocumentBuilder()
.newDocument();
//Build Map
Map<String, String> map = buildMap(xml);
//Head
Element html = doc.createElement("html");
html.setAttribute("lang", "en");
Element head = buildHead(map, doc);
html.appendChild(head);
//Body
Element body = buildBody(map, doc);
html.appendChild(body);
doc.appendChild(html);
return String.format("<!DOCTYPE html>%n%s", applyTransformation(doc));
}
private String applyTransformation(Document doc) throws TransformerException, IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
try (Writer output = new StringWriter()) {
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(output));
return output.toString();
}
}
private Map<String, String> buildMap(Element xml) {
Map<String, String> map = new HashMap<>();
map.put("heading", xml
.getElementsByTagName("heading") | .item(0)
.getTextContent());
map.put("from", String.format("from: %s", xml
.getElementsByTagName("from")
.item(0)
.getTextContent()));
map.put("content", xml
.getElementsByTagName("content")
.item(0)
.getTextContent());
return map;
}
private Element buildHead(Map<String, String> map, Document doc) {
Element head = doc.createElement("head");
Element title = doc.createElement("title");
title.setTextContent(map.get("heading"));
head.appendChild(title);
return head;
}
private Element buildBody(Map<String, String> map, Document doc) {
Element body = doc.createElement("body");
Element from = doc.createElement("p");
from.setTextContent(map.get("from"));
Element success = doc.createElement("p");
success.setTextContent(map.get("content"));
body.appendChild(from);
body.appendChild(success);
return body;
}
} | repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xmlhtml\jaxp\JaxpTransformer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JimuDataReader implements IAiRagEnhanceJava {
@Override
public Map<String, Object> process(Map<String, Object> inputParams) {
// inputParams: {"bizData":"/xxxx/xxxx/xxxx/xxxx.xls"}
try {
String filePath = (String) inputParams.get("bizData");
if (filePath == null || filePath.isEmpty()) {
throw new IllegalArgumentException("File path is empty");
}
File excelFile = new File(filePath);
if (!excelFile.exists() || !excelFile.isFile()) {
throw new IllegalArgumentException("File not found: " + filePath);
}
// Since we don't know the target entity class, we'll read the Excel generically
return readExcelData(excelFile);
} catch (Exception e) {
log.error("Error processing Excel file", e);
throw new JeecgBootBizTipException("调用java增强失败", e);
}
}
/**
* Excel导入工具方法,基于ExcelImportUtil
*
* @param file Excel文件
* @return Excel读取结果,包含字段和数据
* @throws Exception 导入过程中的异常
*/
public static Map<String, Object> readExcelData(File file) throws Exception {
Map<String, Object> result = new HashMap<>();
// 设置导入参数 | ImportParams params = new ImportParams();
params.setTitleRows(0); // 没有标题
params.setHeadRows(1); // 第一行是表头
// 读取Excel数据
List<Map<String, Object>> dataList = ExcelImportUtil.importExcel(file, Map.class, params);
// 如果没有数据,返回空结果
if (dataList == null || dataList.isEmpty()) {
result.put("fields", new ArrayList<>());
result.put("datas", new ArrayList<>());
return result;
}
// 从第一行数据中获取字段名
List<String> fieldNames = new ArrayList<>(dataList.get(0).keySet());
result.put("fields", fieldNames);
result.put("datas", dataList);
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\demo\JimuDataReader.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PictureServiceImpl implements PictureService {
@Autowired
private PictureDao pictureDao;
@Override
public PageResult getPicturePage(PageUtil pageUtil) {
List<Picture> pictures = pictureDao.findPictures(pageUtil);
int total = pictureDao.getTotalPictures(pageUtil);
PageResult pageResult = new PageResult(pictures, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public Picture queryObject(Integer id) {
return pictureDao.findPictureById(id);
}
@Override
public int save(Picture picture) { | return pictureDao.insertPicture(picture);
}
@Override
public int update(Picture picture) {
return pictureDao.updPicture(picture);
}
@Override
public int delete(Integer id) {
return pictureDao.delPicture(id);
}
@Override
public int deleteBatch(Integer[] ids) {
return pictureDao.deleteBatch(ids);
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\service\impl\PictureServiceImpl.java | 2 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer("MDocTypeCounter[");
sb.append(get_ID()).append(",").append(getName())
.append(",C_DocType_ID=").append(getC_DocType_ID())
.append(",Counter=").append(getCounter_C_DocType_ID())
.append(",DocAction=").append(getDocAction())
.append("]");
return sb.toString();
} // toString
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
if (getAD_Org_ID() != 0)
{
setAD_Org_ID(0); | }
if (!newRecord
&& (is_ValueChanged("C_DocType_ID") || is_ValueChanged("Counter_C_DocType_ID")))
{
setIsValid(false);
}
// try to validate
if (!isValid())
{
validate();
}
return true;
} // beforeSave
} // MDocTypeCounter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDocTypeCounter.java | 1 |
请完成以下Java代码 | public Duration parse(String value) {
return Duration.of(Long.parseLong(value), this.chronoUnit);
}
public String print(Duration value) {
return longValue(value) + this.suffix;
}
public long longValue(Duration value) {
return this.longValue.apply(value);
}
public static Unit fromChronoUnit(@Nullable ChronoUnit chronoUnit) {
if (chronoUnit == null) {
return Unit.MILLIS;
}
for (Unit candidate : values()) {
if (candidate.chronoUnit == chronoUnit) {
return candidate;
}
} | throw new IllegalArgumentException("Unknown unit " + chronoUnit);
}
public static Unit fromSuffix(String suffix) {
for (Unit candidate : values()) {
if (candidate.suffix.equalsIgnoreCase(suffix)) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit '" + suffix + "'");
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DurationStyle.java | 1 |
请完成以下Java代码 | public class X_EDI_M_Product_Lookup_UPC_v extends org.compiere.model.PO implements I_EDI_M_Product_Lookup_UPC_v, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -955743163L;
/** Standard Constructor */
public X_EDI_M_Product_Lookup_UPC_v (final Properties ctx, final int EDI_M_Product_Lookup_UPC_v_ID, @Nullable final String trxName)
{
super (ctx, EDI_M_Product_Lookup_UPC_v_ID, trxName);
}
/** Load Constructor */
public X_EDI_M_Product_Lookup_UPC_v (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
} | /** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setGLN (final @Nullable java.lang.String GLN)
{
set_Value (COLUMNNAME_GLN, GLN);
}
@Override
public java.lang.String getGLN()
{
return get_ValueAsString(COLUMNNAME_GLN);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_M_Product_Lookup_UPC_v.java | 1 |
请完成以下Java代码 | public void setC_Withholding_ID (int C_Withholding_ID)
{
if (C_Withholding_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Withholding_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Withholding_ID, Integer.valueOf(C_Withholding_ID));
}
/** Get Withholding.
@return Withholding type defined
*/
public int getC_Withholding_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Withholding_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getWithholding_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) | .getPO(getWithholding_Acct(), get_TrxName()); }
/** Set Withholding.
@param Withholding_Acct
Account for Withholdings
*/
public void setWithholding_Acct (int Withholding_Acct)
{
set_Value (COLUMNNAME_Withholding_Acct, Integer.valueOf(Withholding_Acct));
}
/** Get Withholding.
@return Account for Withholdings
*/
public int getWithholding_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Withholding_Acct);
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_C_Withholding_Acct.java | 1 |
请完成以下Java代码 | public UserOperationLogContextEntryBuilder inContextOf(ExternalTaskEntity task, ExecutionEntity execution, ProcessDefinitionEntity definition) {
if (execution != null) {
inContextOf(execution);
} else if (definition != null) {
inContextOf(definition);
}
entry.setExternalTaskId(task.getId());
entry.setTenantId(task.getTenantId());
return this;
}
public UserOperationLogContextEntryBuilder propertyChanges(List<PropertyChange> propertyChanges) {
entry.setPropertyChanges(propertyChanges);
return this;
}
public UserOperationLogContextEntryBuilder propertyChanges(PropertyChange propertyChange) {
List<PropertyChange> propertyChanges = new ArrayList<PropertyChange>();
propertyChanges.add(propertyChange);
entry.setPropertyChanges(propertyChanges);
return this;
}
public UserOperationLogContextEntry create() {
return entry;
}
public UserOperationLogContextEntryBuilder jobId(String jobId) {
entry.setJobId(jobId);
return this;
}
public UserOperationLogContextEntryBuilder jobDefinitionId(String jobDefinitionId) {
entry.setJobDefinitionId(jobDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder processDefinitionId(String processDefinitionId) {
entry.setProcessDefinitionId(processDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder processDefinitionKey(String processDefinitionKey) {
entry.setProcessDefinitionKey(processDefinitionKey);
return this;
}
public UserOperationLogContextEntryBuilder processInstanceId(String processInstanceId) {
entry.setProcessInstanceId(processInstanceId);
return this;
}
public UserOperationLogContextEntryBuilder caseDefinitionId(String caseDefinitionId) {
entry.setCaseDefinitionId(caseDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder deploymentId(String deploymentId) {
entry.setDeploymentId(deploymentId);
return this;
} | public UserOperationLogContextEntryBuilder batchId(String batchId) {
entry.setBatchId(batchId);
return this;
}
public UserOperationLogContextEntryBuilder taskId(String taskId) {
entry.setTaskId(taskId);
return this;
}
public UserOperationLogContextEntryBuilder caseInstanceId(String caseInstanceId) {
entry.setCaseInstanceId(caseInstanceId);
return this;
}
public UserOperationLogContextEntryBuilder category(String category) {
entry.setCategory(category);
return this;
}
public UserOperationLogContextEntryBuilder annotation(String annotation) {
entry.setAnnotation(annotation);
return this;
}
public UserOperationLogContextEntryBuilder tenantId(String tenantId) {
entry.setTenantId(tenantId);
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntryBuilder.java | 1 |
请完成以下Java代码 | public class Type extends DefaultMetadataElement implements Describable {
private String description;
private String action;
private final Map<String, String> tags = new LinkedHashMap<>();
public void setAction(String action) {
String actionToUse = action;
if (!actionToUse.startsWith("/")) {
actionToUse = "/" + actionToUse;
}
this.action = actionToUse;
}
@Override
public String getDescription() {
return this.description; | }
public void setDescription(String description) {
this.description = description;
}
public String getAction() {
return this.action;
}
public Map<String, String> getTags() {
return this.tags;
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Type.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (id != other.id)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", author=" + author + "]";
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\java\com\baeldung\persistence\model\Book.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
return delegate.prepareStatement(customizeSql(sql), resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
return delegate.prepareCall(customizeSql(sql), resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
return delegate.prepareStatement(customizeSql(sql), autoGeneratedKeys);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{
return delegate.prepareStatement(customizeSql(sql), columnIndexes);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
return delegate.prepareStatement(customizeSql(sql), columnNames);
}
@Override
public Clob createClob() throws SQLException
{
return delegate.createClob();
}
@Override
public Blob createBlob() throws SQLException
{
return delegate.createBlob();
}
@Override
public NClob createNClob() throws SQLException
{
return delegate.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException
{
return delegate.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException
{
return delegate.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException
{
delegate.setClientInfo(name, value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
delegate.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException
{
return delegate.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException
{
return delegate.getClientInfo();
}
@Override | public Array createArrayOf(String typeName, Object[] elements) throws SQLException
{
return delegate.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
return delegate.createStruct(typeName, attributes);
}
@Override
public void setSchema(String schema) throws SQLException
{
delegate.setSchema(schema);
}
@Override
public String getSchema() throws SQLException
{
return delegate.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException
{
delegate.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
delegate.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException
{
return delegate.getNetworkTimeout();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperJdbcConnection.java | 2 |
请完成以下Java代码 | public String getIp() {
return this.ip;
}
public String getCountry() {
return this.country;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'")
.add("version='" + this.version + "'")
.add("ip='" + this.ip + "'")
.add("country='" + this.country + "'")
.toString();
}
}
/**
* Additional information about what part of the request is invalid.
*/
public static class ErrorStateInformation {
private boolean invalid = true;
private Boolean javaVersion;
private Boolean language;
private Boolean configurationFileFormat;
private Boolean packaging;
private Boolean type;
private InvalidDependencyInformation dependencies;
private String message;
public boolean isInvalid() {
return this.invalid;
}
public Boolean getJavaVersion() {
return this.javaVersion;
}
public void setJavaVersion(Boolean javaVersion) {
this.javaVersion = javaVersion;
}
public Boolean getLanguage() {
return this.language;
}
public void setLanguage(Boolean language) {
this.language = language;
}
public Boolean getConfigurationFileFormat() {
return this.configurationFileFormat;
}
public void setConfigurationFileFormat(Boolean configurationFileFormat) {
this.configurationFileFormat = configurationFileFormat;
}
public Boolean getPackaging() {
return this.packaging;
}
public void setPackaging(Boolean packaging) {
this.packaging = packaging;
}
public Boolean getType() {
return this.type;
}
public void setType(Boolean type) {
this.type = type;
}
public InvalidDependencyInformation getDependencies() {
return this.dependencies;
}
public void triggerInvalidDependencies(List<String> dependencies) {
this.dependencies = new InvalidDependencyInformation(dependencies);
} | public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid)
.add("javaVersion=" + this.javaVersion)
.add("language=" + this.language)
.add("configurationFileFormat=" + this.configurationFileFormat)
.add("packaging=" + this.packaging)
.add("type=" + this.type)
.add("dependencies=" + this.dependencies)
.add("message='" + this.message + "'")
.toString();
}
}
/**
* Invalid dependencies information.
*/
public static class InvalidDependencyInformation {
private boolean invalid = true;
private final List<String> values;
public InvalidDependencyInformation(List<String> values) {
this.values = values;
}
public boolean isInvalid() {
return this.invalid;
}
public List<String> getValues() {
return this.values;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString();
}
}
} | repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java | 1 |
请完成以下Java代码 | public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellte Menge.
@return Bestellte Menge
*/
@Override
public java.math.BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Bestellte Menge (TU).
@param QtyOrdered_TU
Bestellte Menge (TU)
*/ | @Override
public void setQtyOrdered_TU (java.math.BigDecimal QtyOrdered_TU)
{
set_Value (COLUMNNAME_QtyOrdered_TU, QtyOrdered_TU);
}
/** Get Bestellte Menge (TU).
@return Bestellte Menge (TU)
*/
@Override
public java.math.BigDecimal getQtyOrdered_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_TU);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_OrderLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Menu extends BaseEntity implements Serializable {
@Id
@Column(name = "menu_id")
@NotNull(groups = {Update.class})
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JSONField(serialize = false)
@ManyToMany(mappedBy = "menus")
@ApiModelProperty(value = "菜单角色")
private Set<Role> roles;
@ApiModelProperty(value = "菜单标题")
private String title;
@Column(name = "name")
@ApiModelProperty(value = "菜单组件名称")
private String componentName;
@ApiModelProperty(value = "排序")
private Integer menuSort = 999;
@ApiModelProperty(value = "组件路径")
private String component;
@ApiModelProperty(value = "路由地址")
private String path;
@ApiModelProperty(value = "菜单类型,目录、菜单、按钮")
private Integer type;
@ApiModelProperty(value = "权限标识")
private String permission;
@ApiModelProperty(value = "菜单图标")
private String icon;
@Column(columnDefinition = "bit(1) default 0")
@ApiModelProperty(value = "缓存") | private Boolean cache;
@Column(columnDefinition = "bit(1) default 0")
@ApiModelProperty(value = "是否隐藏")
private Boolean hidden;
@ApiModelProperty(value = "上级菜单")
private Long pid;
@ApiModelProperty(value = "子节点数目", hidden = true)
private Integer subCount = 0;
@ApiModelProperty(value = "外链菜单")
private Boolean iFrame;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Menu menu = (Menu) o;
return Objects.equals(id, menu.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\domain\Menu.java | 2 |
请完成以下Java代码 | public class GuavaEventBusBeanPostProcessor implements DestructionAwareBeanPostProcessor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final SpelExpressionParser expressionParser = new SpelExpressionParser();
@Override
public void postProcessBeforeDestruction(final Object bean, final String beanName) throws BeansException {
this.process(bean, EventBus::unregister, "destruction");
}
@Override
public boolean requiresDestruction(Object bean) {
return true;
}
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
this.process(bean, EventBus::register, "initialization");
return bean;
}
private void process(final Object bean, final BiConsumer<EventBus, Object> consumer, final String action) {
Object proxy = this.getTargetObject(bean);
final Subscriber annotation = AnnotationUtils.getAnnotation(proxy.getClass(), Subscriber.class);
if (annotation == null)
return;
this.logger.info("{}: processing bean of type {} during {}", this.getClass().getSimpleName(), proxy.getClass().getName(),
action); | final String annotationValue = annotation.value();
try {
final Expression expression = this.expressionParser.parseExpression(annotationValue);
final Object value = expression.getValue();
if (!(value instanceof EventBus)) {
this.logger.error("{}: expression {} did not evaluate to an instance of EventBus for bean of type {}",
this.getClass().getSimpleName(), annotationValue, proxy.getClass().getSimpleName());
return;
}
final EventBus eventBus = (EventBus)value;
consumer.accept(eventBus, proxy);
} catch (ExpressionException ex) {
this.logger.error("{}: unable to parse/evaluate expression {} for bean of type {}", this.getClass().getSimpleName(),
annotationValue, proxy.getClass().getName());
}
}
private Object getTargetObject(Object proxy) throws BeansException {
if (AopUtils.isJdkDynamicProxy(proxy)) {
try {
return ((Advised)proxy).getTargetSource().getTarget();
} catch (Exception e) {
throw new FatalBeanException("Error getting target of JDK proxy", e);
}
}
return proxy;
}
} | repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GuavaEventBusBeanPostProcessor.java | 1 |
请完成以下Java代码 | public void produce(){
try {
MessageProducer messageProducer; // 消息生产者
session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建Session
destination=session.createQueue("queue1");
messageProducer=session.createProducer(destination); // 创建消息生产者
for(int i=0;i<JMSProducerThread.SENDNUM;i++){
TextMessage message=session.createTextMessage("ActiveMQ中"+Thread.currentThread().getName()+"线程发送的数据"+":"+i);
System.out.println(Thread.currentThread().getName()+"线程"+"发送消息:"+"ActiveMQ 发布的消息"+":"+i);
messageProducer.send(message);
session.commit();
}
} catch (JMSException e) {
e.printStackTrace();
}
} | /**
* 发送消息
* @param session
* @param messageProducer
* @throws Exception
*/
public static void sendMessage(Session session,MessageProducer messageProducer)throws Exception{
for(int i=0;i<JMSProducerThread.SENDNUM;i++){
TextMessage message=session.createTextMessage("ActiveMQ 发送的消息"+i);
System.out.println("发送消息:"+"ActiveMQ 发布的消息"+i);
messageProducer.send(message);
}
}
} | repos\spring-boot-quick-master\quick-activemq\src\main\java\com\mq\client\JMSProducerThread.java | 1 |
请完成以下Java代码 | private PaymentProcessor getPaymentProcessor(final PaymentRule paymentRule)
{
return getPaymentProcessorIfExists(paymentRule)
.orElseThrow(() -> new AdempiereException("No payment processor found for payment rule: " + paymentRule));
}
private Optional<PaymentProcessor> getPaymentProcessorIfExists(final PaymentRule paymentRule)
{
return paymentProcessors.getByPaymentRule(paymentRule);
}
public void captureAmount(@NonNull final PaymentReservationCaptureRequest request)
{
final PaymentReservation reservation = getBySalesOrderIdNotVoided(request.getSalesOrderId())
.orElse(null);
if (reservation == null)
{
return;
}
// eagerly fetching the processor to fail fast
final PaymentProcessor paymentProcessor = getPaymentProcessor(reservation.getPaymentRule());
final PaymentId paymentId = createPayment(request);
final PaymentReservationCapture capture = PaymentReservationCapture.builder()
.reservationId(reservation.getId())
.status(PaymentReservationCaptureStatus.NEW)
//
.orgId(reservation.getOrgId())
.salesOrderId(reservation.getSalesOrderId())
.salesInvoiceId(request.getSalesInvoiceId())
.paymentId(paymentId)
//
.amount(request.getAmount())
// | .build();
capturesRepo.save(capture);
paymentProcessor.processCapture(reservation, capture);
reservationsRepo.save(reservation);
capture.setStatusAsCompleted();
capturesRepo.save(capture);
}
private PaymentId createPayment(@NonNull final PaymentReservationCaptureRequest request)
{
final I_C_Payment payment = Services.get(IPaymentBL.class).newInboundReceiptBuilder()
.invoiceId(request.getSalesInvoiceId())
.bpartnerId(request.getCustomerId())
.payAmt(request.getAmount().toBigDecimal())
.currencyId(request.getAmount().getCurrencyId())
.tenderType(TenderType.DirectDeposit)
.dateTrx(request.getDateTrx())
.createAndProcess();
return PaymentId.ofRepoId(payment.getC_Payment_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public OperationCustomizer operationCustomizer() {
return (operation, handlerMethod) -> {
String path = getFullPath(handlerMethod);
if (!isExcludedPath(path)) {
operation.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN));
}else{
log.info("忽略加入 X_ACCESS_TOKEN 的 PATH:" + path);
}
return operation;
};
}
private String getFullPath(HandlerMethod handlerMethod) {
StringBuilder fullPath = new StringBuilder();
// 获取类级别的路径
RequestMapping classMapping = handlerMethod.getBeanType().getAnnotation(RequestMapping.class);
if (classMapping != null && classMapping.value().length > 0) {
fullPath.append(classMapping.value()[0]);
}
// 获取方法级别的路径
RequestMapping methodMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
if (methodMapping != null && methodMapping.value().length > 0) {
String methodPath = methodMapping.value()[0];
// 确保路径正确拼接,处理斜杠
if (!fullPath.toString().endsWith("/") && !methodPath.startsWith("/")) {
fullPath.append("/");
}
fullPath.append(methodPath);
}
return fullPath.toString();
}
private boolean isExcludedPath(String path) {
// 使用缓存避免重复计算
return EXCLUDED_PATHS_CACHE.computeIfAbsent(path, p -> { | // 精确匹配
if (exactPatterns.contains(p)) {
return true;
}
// 通配符匹配
return wildcardPatterns.stream().anyMatch(p::startsWith);
});
}
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("JeecgBoot 后台服务API接口文档")
.version("3.9.0")
.contact(new Contact().name("北京国炬信息技术有限公司").url("www.jeccg.com").email("jeecgos@163.com"))
.description("后台API接口")
.termsOfService("NO terms of service")
.license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.html")))
.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN))
.components(new Components().addSecuritySchemes(CommonConstant.X_ACCESS_TOKEN,
new SecurityScheme()
.name(CommonConstant.X_ACCESS_TOKEN)
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER) // 关键:指定为 header
));
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\Swagger3Config.java | 2 |
请完成以下Java代码 | public void setTrxName (java.lang.String TrxName)
{
set_ValueNoCheck (COLUMNNAME_TrxName, TrxName);
}
/** Get Transaktion.
@return Name of the transaction
*/
@Override
public java.lang.String getTrxName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrxName);
}
/** Set Undo. | @param Undo Undo */
@Override
public void setUndo (java.lang.String Undo)
{
set_Value (COLUMNNAME_Undo, Undo);
}
/** Get Undo.
@return Undo */
@Override
public java.lang.String getUndo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Undo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog.java | 1 |
请完成以下Java代码 | class FindColumnNameCellEditor extends FindCellEditor implements TableCellRenderer
{
private static final long serialVersionUID = 508502538438329051L;
private final DefaultTableCellRenderer defaultRenderer = new DefaultTableCellRenderer();
private CComboBox<FindPanelSearchField> _editor;
public FindColumnNameCellEditor()
{
super();
}
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column)
{
final String valueToDisplay = value == null ? "" : FindPanelSearchField.castToFindPanelSearchField(value).getDisplayNameTrl();
return defaultRenderer.getTableCellRendererComponent(table, valueToDisplay, isSelected, hasFocus, row, column);
}
@Override
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int col)
{
updateEditor(table);
return super.getTableCellEditorComponent(table, value, isSelected, row, col);
}
@Override
protected CComboBox<FindPanelSearchField> getEditor()
{
if (_editor == null)
{
_editor = new CComboBox<>();
_editor.setRenderer(new ToStringListCellRenderer<FindPanelSearchField>()
{
private static final long serialVersionUID = 1L;
@Override
protected String renderToString(final FindPanelSearchField value)
{
return value == null ? "" : value.getDisplayNameTrl();
}
}); | _editor.enableAutoCompletion();
}
return _editor;
}
private void updateEditor(final JTable table)
{
final CComboBox<FindPanelSearchField> editor = getEditor();
//
// Set available search fields if not already set
if (editor.getItemCount() == 0)
{
final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel();
final Collection<FindPanelSearchField> availableSearchFields = model.getAvailableSearchFields();
if (availableSearchFields != null)
{
final List<FindPanelSearchField> availableSearchFieldsList = new ArrayList<>(availableSearchFields);
Collections.sort(availableSearchFieldsList, Comparator.comparing(FindPanelSearchField::getDisplayNameTrl));
editor.setModel(new ListComboBoxModel<FindPanelSearchField>(availableSearchFieldsList));
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindColumnNameCellEditor.java | 1 |
请完成以下Java代码 | void handleEvent(@NonNull final LocationGeocodeEventRequest request)
{
I_C_Location locationRecord = null;
try
{
locationRecord = locationsRepo.getById(request.getLocationId());
final GeoCoordinatesRequest coordinatesRequest = createGeoCoordinatesRequest(locationRecord);
final Optional<GeographicalCoordinates> xoy = geocodingService.findBestCoordinates(coordinatesRequest);
if (xoy.isPresent())
{
locationRecord.setLatitude(xoy.get().getLatitude());
locationRecord.setLongitude(xoy.get().getLongitude());
locationRecord.setGeocodingStatus(X_C_Location.GEOCODINGSTATUS_Resolved);
locationRecord.setGeocoding_Issue_ID(-1);
}
else
{
locationRecord.setLatitude(null);
locationRecord.setLongitude(null);
locationRecord.setGeocodingStatus(X_C_Location.GEOCODINGSTATUS_NotResolved);
locationRecord.setGeocoding_Issue_ID(-1);
}
}
catch (final Exception ex)
{
final AdIssueId issueId = errorManager.createIssue(ex);
if (locationRecord != null)
{
locationRecord.setGeocodingStatus(X_C_Location.GEOCODINGSTATUS_Error);
locationRecord.setGeocoding_Issue_ID(issueId.getRepoId());
}
}
finally
{
if (locationRecord != null)
{
locationsRepo.save(locationRecord);
}
}
}
private GeoCoordinatesRequest createGeoCoordinatesRequest(@NonNull final I_C_Location locationRecord) | {
final String countryCode2 = countryDAO.retrieveCountryCode2ByCountryId(CountryId.ofRepoId(locationRecord.getC_Country_ID()));
final String address = Joiner.on(" ")
.skipNulls()
.join(locationRecord.getAddress1(), locationRecord.getAddress2(), locationRecord.getAddress3(), locationRecord.getAddress4());
final String postal = locationRecord.getPostal();
final String city = locationRecord.getCity();
return GeoCoordinatesRequest.builder()
.countryCode2(countryCode2)
.address(address)
.postal(postal)
.city(city)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\asynchandler\LocationGeocodeEventHandler.java | 1 |
请完成以下Java代码 | public <T> T execute(Command<T> command) {
CommandContext context = null;
if(!alwaysOpenNew) {
// check whether we can reuse the command context
CommandContext existingCommandContext = Context.getCommandContext();
if(existingCommandContext != null && isFromSameEngine(existingCommandContext)) {
context = existingCommandContext;
}
}
// only create a new command context on the current command level (CAM-10002)
boolean isNew = ProcessEngineContextImpl.consume();
boolean isOuterCommand = (context == null);
boolean openNew = (isOuterCommand || isNew);
CommandInvocationContext commandInvocationContext = new CommandInvocationContext(command, processEngineConfiguration, isOuterCommand);
Context.setCommandInvocationContext(commandInvocationContext);
try {
if(openNew) {
LOG.debugOpeningNewCommandContext();
context = commandContextFactory.createCommandContext();
} else {
LOG.debugReusingExistingCommandContext();
}
Context.setCommandContext(context);
Context.setProcessEngineConfiguration(processEngineConfiguration);
// delegate to next interceptor in chain
return next.execute(command);
} catch (Throwable t) {
commandInvocationContext.trySetThrowable(t);
} finally {
try {
if (openNew) { | LOG.closingCommandContext();
context.close(commandInvocationContext);
} else {
commandInvocationContext.rethrow();
}
} finally {
Context.removeCommandInvocationContext();
Context.removeCommandContext();
Context.removeProcessEngineConfiguration();
// restore the new command context flag
ProcessEngineContextImpl.set(isNew);
}
}
return null;
}
protected boolean isFromSameEngine(CommandContext existingCommandContext) {
return processEngineConfiguration == existingCommandContext.getProcessEngineConfiguration();
}
public CommandContextFactory getCommandContextFactory() {
return commandContextFactory;
}
public void setCommandContextFactory(CommandContextFactory commandContextFactory) {
this.commandContextFactory = commandContextFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineContext(ProcessEngineConfigurationImpl processEngineContext) {
this.processEngineConfiguration = processEngineContext;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandContextInterceptor.java | 1 |
请完成以下Java代码 | protected ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) {
return jsExecutor.submit(() -> {
try {
evalLock.lock();
try {
if (useJsSandbox) {
sandbox.eval(jsScript);
} else {
engine.eval(jsScript);
}
} finally {
evalLock.unlock();
}
scriptInfoMap.put(scriptId, scriptInfo);
return scriptId;
} catch (ScriptException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.COMPILATION, jsScript, e);
} catch (ScriptCPUAbuseException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.TIMEOUT, jsScript, e);
} catch (Exception e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.OTHER, jsScript, e);
}
});
} | @Override
protected ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo scriptInfo, Object[] args) {
return jsExecutor.submit(() -> {
try {
if (useJsSandbox) {
return sandbox.getSandboxedInvocable().invokeFunction(scriptInfo.getFunctionName(), args);
} else {
return ((Invocable) engine).invokeFunction(scriptInfo.getFunctionName(), args);
}
} catch (ScriptException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.RUNTIME, null, e);
} catch (Exception e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.OTHER, null, e);
}
});
}
protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException {
if (useJsSandbox) {
sandbox.eval(scriptInfo.getFunctionName() + " = undefined;");
} else {
engine.eval(scriptInfo.getFunctionName() + " = undefined;");
}
}
} | repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\NashornJsInvokeService.java | 1 |
请完成以下Java代码 | public class Document {
@XmlElement(name = "BkToCstmrStmt", required = true)
protected BankToCustomerStatementV02 bkToCstmrStmt;
/**
* Gets the value of the bkToCstmrStmt property.
*
* @return
* possible object is
* {@link BankToCustomerStatementV02 }
*
*/
public BankToCustomerStatementV02 getBkToCstmrStmt() {
return bkToCstmrStmt; | }
/**
* Sets the value of the bkToCstmrStmt property.
*
* @param value
* allowed object is
* {@link BankToCustomerStatementV02 }
*
*/
public void setBkToCstmrStmt(BankToCustomerStatementV02 value) {
this.bkToCstmrStmt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\Document.java | 1 |
请完成以下Java代码 | public final class JacksonUtils {
private static final boolean JDK8_MODULE_PRESENT =
ClassUtils.isPresent("com.fasterxml.jackson.datatype.jdk8.Jdk8Module", null);
private static final boolean JAVA_TIME_MODULE_PRESENT =
ClassUtils.isPresent("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule", null);
private static final boolean JODA_MODULE_PRESENT =
ClassUtils.isPresent("com.fasterxml.jackson.datatype.joda.JodaModule", null);
private static final boolean KOTLIN_MODULE_PRESENT =
ClassUtils.isPresent("kotlin.Unit", null) &&
ClassUtils.isPresent("com.fasterxml.jackson.module.kotlin.KotlinModule", null);
/**
* Factory for {@link ObjectMapper} instances with registered well-known modules
* and disabled {@link MapperFeature#DEFAULT_VIEW_INCLUSION} and
* {@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} features.
* @return the {@link ObjectMapper} instance.
*/
public static ObjectMapper enhancedObjectMapper() {
ObjectMapper objectMapper = JsonMapper.builder()
.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build();
registerWellKnownModulesIfAvailable(objectMapper);
return objectMapper;
}
private static void registerWellKnownModulesIfAvailable(ObjectMapper objectMapper) {
objectMapper.registerModule(new JacksonMimeTypeModule());
if (JDK8_MODULE_PRESENT) {
objectMapper.registerModule(Jdk8ModuleProvider.MODULE);
}
if (JAVA_TIME_MODULE_PRESENT) {
objectMapper.registerModule(JavaTimeModuleProvider.MODULE);
}
if (JODA_MODULE_PRESENT) {
objectMapper.registerModule(JodaModuleProvider.MODULE);
}
if (KOTLIN_MODULE_PRESENT) {
objectMapper.registerModule(KotlinModuleProvider.MODULE);
}
} | private JacksonUtils() {
}
private static final class Jdk8ModuleProvider {
static final com.fasterxml.jackson.databind.Module MODULE =
new com.fasterxml.jackson.datatype.jdk8.Jdk8Module();
}
private static final class JavaTimeModuleProvider {
static final com.fasterxml.jackson.databind.Module MODULE =
new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule();
}
private static final class JodaModuleProvider {
static final com.fasterxml.jackson.databind.Module MODULE =
new com.fasterxml.jackson.datatype.joda.JodaModule();
}
private static final class KotlinModuleProvider {
static final com.fasterxml.jackson.databind.Module MODULE =
new com.fasterxml.jackson.module.kotlin.KotlinModule.Builder().build();
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\JacksonUtils.java | 1 |
请完成以下Java代码 | void save(@NonNull final POSOrder order)
{
final I_C_POS_Order orderRecord;
if (order.getLocalId() != null)
{
orderRecord = getOrderRecordById(order.getLocalId());
}
else
{
orderRecord = getOrderRecordByExternalId(order.getExternalId())
.orElseGet(() -> InterfaceWrapperHelper.newInstance(I_C_POS_Order.class));
}
updateRecord(orderRecord, order);
InterfaceWrapperHelper.save(orderRecord);
final POSOrderId posOrderId = extractPOSOrderId(orderRecord);
order.setLocalId(posOrderId);
order.setDocumentNo(orderRecord.getDocumentNo());
addToCache(orderRecord);
//
// Lines
{
final HashMap<String, I_C_POS_OrderLine> lineRecordsByExternalId = getLineRecordsByOrderId(posOrderId).stream().collect(GuavaCollectors.toHashMapByKey(I_C_POS_OrderLine::getExternalId));
final ArrayList<I_C_POS_OrderLine> lineRecordsNew = new ArrayList<>(lineRecordsByExternalId.size());
for (final POSOrderLine line : order.getLines())
{
I_C_POS_OrderLine lineRecord = lineRecordsByExternalId.remove(line.getExternalId());
if (lineRecord == null)
{
lineRecord = InterfaceWrapperHelper.newInstance(I_C_POS_OrderLine.class);
}
lineRecord.setC_POS_Order_ID(posOrderId.getRepoId());
lineRecord.setAD_Org_ID(order.getOrgId().getRepoId());
updateRecord(lineRecord, line);
InterfaceWrapperHelper.save(lineRecord);
lineRecordsNew.add(lineRecord);
}
InterfaceWrapperHelper.deleteAll(lineRecordsByExternalId.values());
putLineRecordsToCache(posOrderId, lineRecordsNew);
}
//
// Payments
{
final HashMap<POSPaymentExternalId, I_C_POS_Payment> paymentRecordsByExternalId = getPaymentRecordsByOrderId(posOrderId).stream().collect(GuavaCollectors.toHashMapByKey(POSOrdersLoaderAndSaver::extractExternalId));
final ArrayList<I_C_POS_Payment> paymentRecordsNew = new ArrayList<>(paymentRecordsByExternalId.size());
for (final POSPayment payment : order.getAllPayments())
{
I_C_POS_Payment paymentRecord = paymentRecordsByExternalId.remove(payment.getExternalId());
if (paymentRecord == null) | {
paymentRecord = InterfaceWrapperHelper.newInstance(I_C_POS_Payment.class);
}
paymentRecord.setC_POS_Order_ID(posOrderId.getRepoId());
paymentRecord.setAD_Org_ID(order.getOrgId().getRepoId());
updateRecord(paymentRecord, payment);
InterfaceWrapperHelper.save(paymentRecord);
paymentRecordsNew.add(paymentRecord);
payment.setLocalId(POSPaymentId.ofRepoId(paymentRecord.getC_POS_Payment_ID()));
}
InterfaceWrapperHelper.deleteAll(paymentRecordsByExternalId.values());
putPaymentRecordsToCache(posOrderId, paymentRecordsNew);
}
eventDispatcher.fireOrderChanged(order);
}
private static @NonNull POSPaymentExternalId extractExternalId(final I_C_POS_Payment record)
{
return POSPaymentExternalId.ofString(record.getExternalId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrdersLoaderAndSaver.java | 1 |
请完成以下Java代码 | private void trace(String msg, @Nullable Object... msgParts) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(String.format(msg, msgParts));
}
}
/**
* Supplies the default target Url that will be used if no saved request is found or
* the {@code alwaysUseDefaultTargetUrl} property is set to true. If not set, defaults
* to {@code /}.
* @return the defaultTargetUrl property
*/
protected final String getDefaultTargetUrl() {
return this.defaultTargetUrl;
}
/**
* Supplies the default target Url that will be used if no saved request is found in
* the session, or the {@code alwaysUseDefaultTargetUrl} property is set to true. If
* not set, defaults to {@code /}. It will be treated as relative to the web-app's
* context path, and should include the leading <code>/</code>. Alternatively,
* inclusion of a scheme name (such as "http://" or "https://") as the prefix will
* denote a fully-qualified URL and this is also supported.
* @param defaultTargetUrl
*/
public void setDefaultTargetUrl(String defaultTargetUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultTargetUrl),
"defaultTarget must start with '/' or with 'http(s)'");
this.defaultTargetUrl = defaultTargetUrl;
}
/**
* If <code>true</code>, will always redirect to the value of {@code defaultTargetUrl}
* (defaults to <code>false</code>).
*/
public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl) {
this.alwaysUseDefaultTargetUrl = alwaysUseDefaultTargetUrl;
}
protected boolean isAlwaysUseDefaultTargetUrl() {
return this.alwaysUseDefaultTargetUrl;
}
/**
* If this property is set, the current request will be checked for this a parameter
* with this name and the value used as the target URL if present.
* @param targetUrlParameter the name of the parameter containing the encoded target
* URL. Defaults to null.
*/
public void setTargetUrlParameter(String targetUrlParameter) {
if (targetUrlParameter != null) {
Assert.hasText(targetUrlParameter, "targetUrlParameter cannot be empty");
} | this.targetUrlParameter = targetUrlParameter;
}
protected @Nullable String getTargetUrlParameter() {
return this.targetUrlParameter;
}
/**
* Allows overriding of the behaviour when redirecting to a target URL.
* @param redirectStrategy {@link RedirectStrategy} to use
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return this.redirectStrategy;
}
/**
* If set to {@code true} the {@code Referer} header will be used (if available).
* Defaults to {@code false}.
*/
public void setUseReferer(boolean useReferer) {
this.useReferer = useReferer;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AbstractAuthenticationTargetUrlRequestHandler.java | 1 |
请完成以下Java代码 | public String getRolePrefix() {
return this.rolePrefix;
}
/**
* Allows the default role prefix of <code>ROLE_</code> to be overridden. May be set
* to an empty value, although this is usually not desirable.
* @param rolePrefix the new prefix
*/
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix());
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object
* @return always <code>true</code>
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
} | @Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if (authentication == null) {
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities();
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\RoleVoter.java | 1 |
请完成以下Java代码 | 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 Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** 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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CycleStep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Player {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private Integer score;
public Player(Integer score) {
this.score = score;
}
public Player() {
}
public long getId() {
return id;
} | public void setId(long id) {
this.id = id;
}
public Integer getScore() {
return score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
return id == player.id && Objects.equals(score, player.score);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\spring\data\persistence\findbyvsfindallby\model\Player.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.