instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public int getC_BankStatementMatcher_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementMatcher_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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 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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutDeleteReason() {
return withoutDeleteReason;
}
public void setWithoutDeleteReason(Boolean withoutDeleteReason) {
this.withoutDeleteReason = withoutDeleteReason;
}
public String getTaskCandidateGroup() {
return taskCandidateGroup;
}
public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup;
}
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
}
public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
|
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
void checkWeight(final Set<Integer> productIds, final int windowNo)
{
if (productIds == null || productIds.isEmpty())
{
return;
}
final StringBuilder invalidProducts = new StringBuilder();
for (final Integer productId : productIds)
{
if (productId == null || productId <= 0)
{
continue;
}
final I_M_Product product = Services.get(IProductDAO.class).getById(productId);
//
// 07074: Switch off weight check for all Products which are not "Artikel" (type = item)
if (!X_M_Product.PRODUCTTYPE_Item.equals(product.getProductType()))
{
continue;
}
if (product.getWeight().signum() <= 0)
{
if (invalidProducts.length() > 0)
{
invalidProducts.append(", ");
}
invalidProducts.append(product.getName());
}
}
if (invalidProducts.length() > 0)
{
final IClientUI factory = Services.get(IClientUI.class);
factory.warn(windowNo, ZERO_WEIGHT_PRODUCT_ADDED, invalidProducts.toString());
}
}
private void selectFocus(final ICalloutField calloutField)
{
final I_C_Order order = calloutField.getModel(I_C_Order.class);
final Integer bPartnerId = order.getC_BPartner_ID();
final GridTab mTab = getGridTab(calloutField);
if (mTab == null)
{
return;
}
if (bPartnerId <= 0 && mTab.getField(COLUMNNAME_C_BPartner_ID).isDisplayed(true))
{
|
mTab.getField(COLUMNNAME_C_BPartner_ID).requestFocus();
return;
}
// received via is not so important anymore, so don't request focus on it
// final String receivedVia = order.getReceivedVia();
// if (Util.isEmpty(receivedVia)) {
// mTab.getField(RECEIVED_VIA).requestFocus();
// return;
// }
final Integer shipperId = order.getM_Shipper_ID();
if (shipperId <= 0 && mTab.getField(COLUMNNAME_M_Shipper_ID).isDisplayed(true))
{
mTab.getField(COLUMNNAME_M_Shipper_ID).requestFocus();
return;
}
//
// Ask handlers to request focus
handlers.requestFocus(mTab);
}
public static void clearFields(final ICalloutField calloutField, final boolean save)
{
clearFields(calloutField.getCalloutRecord(), save);
}
@Deprecated
public static void clearFields(final ICalloutRecord calloutRecord, final boolean save)
{
final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord);
if (gridTab == null)
{
return;
}
handlers.clearFields(gridTab);
if (save)
{
gridTab.dataSave(true);
}
}
@Deprecated
private final static GridTab getGridTab(final ICalloutField calloutField)
{
final ICalloutRecord calloutRecord = calloutField.getCalloutRecord();
return GridTab.fromCalloutRecordOrNull(calloutRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\OrderFastInput.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) {
this.defaultRedisSerializer = defaultRedisSerializer;
}
protected RedisSerializer<Object> getDefaultRedisSerializer() {
return this.defaultRedisSerializer;
}
@Autowired(required = false)
public void setSessionRepositoryCustomizer(
ObjectProvider<SessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) {
this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList());
}
protected List<SessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() {
return this.sessionRepositoryCustomizers;
}
|
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
protected RedisTemplate<String, Object> createRedisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
if (getDefaultRedisSerializer() != null) {
redisTemplate.setDefaultSerializer(getDefaultRedisSerializer());
}
redisTemplate.setConnectionFactory(getRedisConnectionFactory());
redisTemplate.setBeanClassLoader(this.classLoader);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\AbstractRedisHttpSessionConfiguration.java
| 2
|
请完成以下Java代码
|
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("category", this.category);
return persistentState;
}
// getters and setters
// //////////////////////////////////////////////////////
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public int getVersion() {
return version;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
|
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public String getResourceName() {
return resourceName;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String toString() {
return "EventDefinitionEntity[" + id + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDefinitionEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MaturingConfigId implements RepoIdAware
{
@JsonCreator
@NonNull
public static MaturingConfigId ofRepoId(final int repoId)
{
return new MaturingConfigId(repoId);
}
@Nullable
public static MaturingConfigId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final MaturingConfigId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
|
private MaturingConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_Maturing_Configuration_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final MaturingConfigId id1, @Nullable final MaturingConfigId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\maturing\MaturingConfigId.java
| 2
|
请完成以下Java代码
|
private void addListenerOnCoreModelElement(CoreModelElement element,
DelegateListener<?> listener, String event) {
if (skippable) {
element.addListener(event, listener);
} else {
element.addBuiltInListener(event, listener);
}
}
private void addTaskListener(TaskDefinition taskDefinition) {
if (taskListener != null) {
for (String event : TASK_EVENTS) {
if (skippable) {
taskDefinition.addTaskListener(event, taskListener);
} else {
taskDefinition.addBuiltInTaskListener(event, taskListener);
|
}
}
}
}
/**
* Retrieves task definition.
*
* @param activity the taskActivity
* @return taskDefinition for activity
*/
private TaskDefinition taskDefinition(final ActivityImpl activity) {
final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior();
return activityBehavior.getTaskDefinition();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java
| 1
|
请完成以下Java代码
|
public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) {
this.caseDefinitionIdIn = caseDefinitionIdIn;
}
@CamundaQueryParam(value = "caseDefinitionKeyIn", converter = StringArrayConverter.class)
public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) {
this.caseDefinitionKeyIn = caseDefinitionKeyIn;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class)
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@CamundaQueryParam(value = "compact", converter = BooleanConverter.class)
public void setCompact(Boolean compact) {
this.compact = compact;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected CleanableHistoricCaseInstanceReport createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createCleanableHistoricCaseInstanceReport();
}
|
@Override
protected void applyFilters(CleanableHistoricCaseInstanceReport query) {
if (caseDefinitionIdIn != null && caseDefinitionIdIn.length > 0) {
query.caseDefinitionIdIn(caseDefinitionIdIn);
}
if (caseDefinitionKeyIn != null && caseDefinitionKeyIn.length > 0) {
query.caseDefinitionKeyIn(caseDefinitionKeyIn);
}
if (Boolean.TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIdIn != null && tenantIdIn.length > 0) {
query.tenantIdIn(tenantIdIn);
}
if (Boolean.TRUE.equals(compact)) {
query.compact();
}
}
@Override
protected void applySortBy(CleanableHistoricCaseInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_FINISHED_VALUE)) {
query.orderByFinished();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricCaseInstanceReportDto.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8080
spring:
application:
name: cloud-grpc-client
grpc:
client:
cloud-grpc-server:
address: 'discovery:///cloud-grpc-server'
enableKeepAl
|
ive: true
keepAliveWithoutCalls: true
negotiationType: plaintext
|
repos\grpc-spring-master\examples\cloud-grpc-client\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class SecondBenchmark {
@Param({"10000", "100000", "1000000"})
private int length;
private int[] numbers;
private Calculator singleThreadCalc;
private Calculator multiThreadCalc;
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(SecondBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(5)
.measurementIterations(2)
.build();
Collection<RunResult> results = new Runner(opt).run();
ResultExporter.exportResult("单线程与多线程求和性能", results, "length", "微秒");
}
@Benchmark
public long singleThreadBench() {
return singleThreadCalc.sum(numbers);
}
@Benchmark
public long multiThreadBench() {
|
return multiThreadCalc.sum(numbers);
}
@Setup
public void prepare() {
numbers = IntStream.rangeClosed(1, length).toArray();
singleThreadCalc = new SinglethreadCalculator();
multiThreadCalc = new MultithreadCalculator(Runtime.getRuntime().availableProcessors());
}
@TearDown
public void shutdown() {
singleThreadCalc.shutdown();
multiThreadCalc.shutdown();
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\sum\SecondBenchmark.java
| 1
|
请完成以下Java代码
|
public static SystemRuleEntity fromSystemRule(String app, String ip, Integer port, SystemRule rule) {
SystemRuleEntity entity = new SystemRuleEntity();
entity.setApp(app);
entity.setIp(ip);
entity.setPort(port);
entity.setHighestSystemLoad(rule.getHighestSystemLoad());
entity.setHighestCpuUsage(rule.getHighestCpuUsage());
entity.setAvgRt(rule.getAvgRt());
entity.setMaxThread(rule.getMaxThread());
entity.setQps(rule.getQps());
return entity;
}
@Override
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Double getHighestSystemLoad() {
return highestSystemLoad;
}
public void setHighestSystemLoad(Double highestSystemLoad) {
this.highestSystemLoad = highestSystemLoad;
}
public Long getAvgRt() {
return avgRt;
}
public void setAvgRt(Long avgRt) {
this.avgRt = avgRt;
}
public Long getMaxThread() {
return maxThread;
|
}
public void setMaxThread(Long maxThread) {
this.maxThread = maxThread;
}
public Double getQps() {
return qps;
}
public void setQps(Double qps) {
this.qps = qps;
}
public Double getHighestCpuUsage() {
return highestCpuUsage;
}
public void setHighestCpuUsage(Double highestCpuUsage) {
this.highestCpuUsage = highestCpuUsage;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public SystemRule toRule() {
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(highestSystemLoad);
rule.setAvgRt(avgRt);
rule.setMaxThread(maxThread);
rule.setQps(qps);
rule.setHighestCpuUsage(highestCpuUsage);
return rule;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\SystemRuleEntity.java
| 1
|
请完成以下Java代码
|
public Mono<ReactiveSessionInformation> updateLastAccessTime(String sessionId) {
return Mono.empty();
}
private static Authentication getAuthenticationToken(Object principal) {
return new AbstractAuthenticationToken(AuthorityUtils.NO_AUTHORITIES) {
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return principal;
}
};
}
class SpringSessionBackedReactiveSessionInformation extends ReactiveSessionInformation {
SpringSessionBackedReactiveSessionInformation(S session) {
super(resolvePrincipalName(session), session.getId(), session.getLastAccessedTime());
}
private static String resolvePrincipalName(Session session) {
String principalName = session
.getAttribute(ReactiveFindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
|
return principalName;
}
SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext != null && securityContext.getAuthentication() != null) {
return securityContext.getAuthentication().getName();
}
return "";
}
@Override
public Mono<Void> invalidate() {
return super.invalidate()
.then(Mono.defer(() -> SpringSessionBackedReactiveSessionRegistry.this.sessionRepository
.deleteById(getSessionId())));
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedReactiveSessionRegistry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserExpense {
@JmixGeneratedValue
@Column(name = "ID", nullable = false)
@Id
private UUID id;
@JoinColumn(name = "USER_ID", nullable = false)
@NotNull
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private User user;
@JoinColumn(name = "EXPENSE_ID", nullable = false)
@NotNull
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Expense expense;
@Column(name = "AMOUNT", nullable = false)
@NotNull
private Double amount;
@PastOrPresent(message = "{msg://com.baeldung.jmix.expensetracker.entity/UserExpense.date.validation.PastOrPresent}")
@Column(name = "DATE_", nullable = false)
@NotNull
private LocalDate date;
@Column(name = "DETAILS")
private String details;
@Column(name = "VERSION", nullable = false)
@Version
private Integer version;
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
|
public Expense getExpense() {
return expense;
}
public void setExpense(Expense expense) {
this.expense = expense;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
}
|
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\UserExpense.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int compare(PmsProductLadder o1, PmsProductLadder o2) {
return o2.getCount() - o1.getCount();
}
});
for (PmsProductLadder productLadder : productLadderList) {
if (count >= productLadder.getCount()) {
return productLadder;
}
}
return null;
}
/**
* 获取购物车中指定商品的数量
*/
private int getCartItemCount(List<OmsCartItem> itemList) {
int count = 0;
for (OmsCartItem item : itemList) {
count += item.getQuantity();
}
return count;
}
/**
* 获取购物车中指定商品的总价
*/
private BigDecimal getCartItemAmount(List<OmsCartItem> itemList, List<PromotionProduct> promotionProductList) {
BigDecimal amount = new BigDecimal(0);
for (OmsCartItem item : itemList) {
//计算出商品原价
PromotionProduct promotionProduct = getPromotionProductById(item.getProductId(), promotionProductList);
PmsSkuStock skuStock = getOriginalPrice(promotionProduct,item.getProductSkuId());
amount = amount.add(skuStock.getPrice().multiply(new BigDecimal(item.getQuantity())));
|
}
return amount;
}
/**
* 获取商品的原价
*/
private PmsSkuStock getOriginalPrice(PromotionProduct promotionProduct, Long productSkuId) {
for (PmsSkuStock skuStock : promotionProduct.getSkuStockList()) {
if (productSkuId.equals(skuStock.getId())) {
return skuStock;
}
}
return null;
}
/**
* 根据商品id获取商品的促销信息
*/
private PromotionProduct getPromotionProductById(Long productId, List<PromotionProduct> promotionProductList) {
for (PromotionProduct promotionProduct : promotionProductList) {
if (productId.equals(promotionProduct.getId())) {
return promotionProduct;
}
}
return null;
}
}
|
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\OmsPromotionServiceImpl.java
| 2
|
请完成以下Java代码
|
public CamundaFormRef getCamundaFormRef() {
return camundaFormRef;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public static TaskDto fromEntity(Task task) {
TaskDto dto = new TaskDto();
dto.id = task.getId();
dto.name = task.getName();
dto.assignee = task.getAssignee();
dto.created = task.getCreateTime();
dto.lastUpdated = task.getLastUpdated();
dto.due = task.getDueDate();
dto.followUp = task.getFollowUpDate();
if (task.getDelegationState() != null) {
dto.delegationState = task.getDelegationState().toString();
}
dto.description = task.getDescription();
dto.executionId = task.getExecutionId();
dto.owner = task.getOwner();
dto.parentTaskId = task.getParentTaskId();
dto.priority = task.getPriority();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processInstanceId = task.getProcessInstanceId();
dto.taskDefinitionKey = task.getTaskDefinitionKey();
dto.caseDefinitionId = task.getCaseDefinitionId();
dto.caseExecutionId = task.getCaseExecutionId();
dto.caseInstanceId = task.getCaseInstanceId();
|
dto.suspended = task.isSuspended();
dto.tenantId = task.getTenantId();
dto.taskState = task.getTaskState();
try {
dto.formKey = task.getFormKey();
dto.camundaFormRef = task.getCamundaFormRef();
}
catch (BadUserRequestException e) {
// ignore (initializeFormKeys was not called)
}
return dto;
}
public void updateTask(Task task) {
task.setName(getName());
task.setDescription(getDescription());
task.setPriority(getPriority());
task.setAssignee(getAssignee());
task.setOwner(getOwner());
DelegationState state = null;
if (getDelegationState() != null) {
DelegationStateConverter converter = new DelegationStateConverter();
state = converter.convertQueryParameterToType(getDelegationState());
}
task.setDelegationState(state);
task.setDueDate(getDue());
task.setFollowUpDate(getFollowUp());
task.setParentTaskId(getParentTaskId());
task.setCaseInstanceId(getCaseInstanceId());
task.setTenantId(getTenantId());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskDto.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<Object> updateRoleMenu(@RequestBody Role resources){
RoleDto role = roleService.findById(resources.getId());
getLevels(role.getLevel());
roleService.updateMenu(resources,role);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除角色")
@ApiOperation("删除角色")
@DeleteMapping
@PreAuthorize("@el.check('roles:del')")
public ResponseEntity<Object> deleteRole(@RequestBody Set<Long> ids){
for (Long id : ids) {
RoleDto role = roleService.findById(id);
getLevels(role.getLevel());
}
// 验证是否被用户关联
roleService.verification(ids);
roleService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
|
}
/**
* 获取用户的角色级别
* @return /
*/
private int getLevels(Integer level){
List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
int min = Collections.min(levels);
if(level != null){
if(level < min){
throw new BadRequestException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + level);
}
}
return min;
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\RoleController.java
| 1
|
请完成以下Java代码
|
private List<Descriptor> getDescriptors(String propertyName) {
return getPropertySources().filter((source) -> source.containsProperty(propertyName))
.map((source) -> Descriptor.get(source, propertyName))
.toList();
}
private Stream<PropertySource<?>> getPropertySources() {
if (this.environment == null) {
return Stream.empty();
}
return this.environment.getPropertySources()
.stream()
.filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source));
}
private void appendDetails(StringBuilder message, MutuallyExclusiveConfigurationPropertiesException cause,
List<Descriptor> descriptors) {
descriptors.sort(Comparator.comparing((descriptor) -> descriptor.propertyName));
message.append(String.format("The following configuration properties are mutually exclusive:%n%n"));
sortedStrings(cause.getMutuallyExclusiveNames())
.forEach((name) -> message.append(String.format("\t%s%n", name)));
message.append(String.format("%n"));
message.append(
String.format("However, more than one of those properties has been configured at the same time:%n%n"));
Set<String> configuredDescriptions = sortedStrings(descriptors,
(descriptor) -> String.format("\t%s%s%n", descriptor.propertyName,
(descriptor.origin != null) ? " (originating from '" + descriptor.origin + "')" : ""));
configuredDescriptions.forEach(message::append);
}
private Set<String> sortedStrings(Collection<String> input) {
return sortedStrings(input, Function.identity());
}
private <S> Set<String> sortedStrings(Collection<S> input, Function<S, String> converter) {
|
TreeSet<String> results = new TreeSet<>();
for (S item : input) {
results.add(converter.apply(item));
}
return results;
}
private static final class Descriptor {
private final String propertyName;
private final @Nullable Origin origin;
private Descriptor(String propertyName, @Nullable Origin origin) {
this.propertyName = propertyName;
this.origin = origin;
}
static Descriptor get(PropertySource<?> source, String propertyName) {
Origin origin = OriginLookup.getOrigin(source, propertyName);
return new Descriptor(propertyName, origin);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java
| 1
|
请完成以下Java代码
|
public int getManual_Check_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Manual_Check_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kennwort.
@param Password Kennwort */
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Kennwort.
@return Kennwort */
@Override
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Grund der Anfrage.
@param RequestReason Grund der Anfrage */
@Override
public void setRequestReason (java.lang.String RequestReason)
{
set_Value (COLUMNNAME_RequestReason, RequestReason);
}
/** Get Grund der Anfrage.
@return Grund der Anfrage */
@Override
public java.lang.String getRequestReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestReason);
}
/** Set REST API URL.
@param RestApiBaseURL REST API URL */
@Override
public void setRestApiBaseURL (java.lang.String RestApiBaseURL)
{
set_Value (COLUMNNAME_RestApiBaseURL, RestApiBaseURL);
}
/** Get REST API URL.
@return REST API URL */
@Override
public java.lang.String getRestApiBaseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL);
}
/** Set Creditpass-Prüfung wiederholen .
@param RetryAfterDays Creditpass-Prüfung wiederholen */
@Override
public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays)
{
set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays);
|
}
/** Get Creditpass-Prüfung wiederholen .
@return Creditpass-Prüfung wiederholen */
@Override
public java.math.BigDecimal getRetryAfterDays ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class NotificationTemplateImportService extends BaseEntityImportService<NotificationTemplateId, NotificationTemplate, EntityExportData<NotificationTemplate>> {
private final NotificationTemplateService notificationTemplateService;
@Override
protected void setOwner(TenantId tenantId, NotificationTemplate notificationTemplate, IdProvider idProvider) {
notificationTemplate.setTenantId(tenantId);
}
@Override
protected NotificationTemplate prepare(EntitiesImportCtx ctx, NotificationTemplate notificationTemplate, NotificationTemplate oldEntity, EntityExportData<NotificationTemplate> exportData, IdProvider idProvider) {
return notificationTemplate;
}
@Override
protected NotificationTemplate saveOrUpdate(EntitiesImportCtx ctx, NotificationTemplate notificationTemplate, EntityExportData<NotificationTemplate> exportData, IdProvider idProvider, CompareResult compareResult) {
ConstraintValidator.validateFields(notificationTemplate);
return notificationTemplateService.saveNotificationTemplate(ctx.getTenantId(), notificationTemplate);
|
}
@Override
protected void onEntitySaved(User user, NotificationTemplate savedEntity, NotificationTemplate oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTemplate deepCopy(NotificationTemplate notificationTemplate) {
return new NotificationTemplate(notificationTemplate);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TEMPLATE;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\NotificationTemplateImportService.java
| 2
|
请完成以下Java代码
|
public IDunningCandidateProducerFactory getDunningCandidateProducerFactory()
{
return dunningCandidateProducerFactory;
}
@Override
public void setDunningCandidateProducerFactory(IDunningCandidateProducerFactory dunningCandidateProducerFactory)
{
Check.assume(dunningCandidateProducerFactory != null, "dunningCandidateProducerFactory is not null");
this.dunningCandidateProducerFactory = dunningCandidateProducerFactory;
}
@Override
public IDunningProducer createDunningProducer()
{
try
{
final IDunningProducer producer = dunningProducerClass.newInstance();
return producer;
}
catch (Exception e)
{
throw new DunningException("Cannot create " + IDunningProducer.class + " for " + dunningProducerClass, e);
}
}
@Override
public void setDunningProducerClass(Class<IDunningProducer> dunningProducerClass)
{
Check.assume(dunningProducerClass != null, "dunningProducerClass is not null");
this.dunningProducerClass = dunningProducerClass;
}
@Override
public IDunningCandidateSource createDunningCandidateSource()
{
try
{
final IDunningCandidateSource source = dunningCandidateSourceClass.newInstance();
return source;
}
catch (Exception e)
{
|
throw new DunningException("Cannot create " + IDunningCandidateSource.class + " for " + dunningCandidateSourceClass, e);
}
}
@Override
public void setDunningCandidateSourceClass(Class<? extends IDunningCandidateSource> dunningCandidateSourceClass)
{
Check.assume(dunningCandidateSourceClass != null, "dunningCandidateSourceClass is not null");
this.dunningCandidateSourceClass = dunningCandidateSourceClass;
}
@Override
public String toString()
{
return "DunningConfig ["
+ "dunnableSourceFactory=" + dunnableSourceFactory
+ ", dunningCandidateProducerFactory=" + dunningCandidateProducerFactory
+ ", dunningCandidateSourceClass=" + dunningCandidateSourceClass
+ ", dunningProducerClass=" + dunningProducerClass
+ "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningConfig.java
| 1
|
请完成以下Java代码
|
public void setAsyncBatch(@NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull final AsyncBatchId asyncBatchId)
{
final I_M_ShipmentSchedule shipmentSchedule = shipmentSchedulePA.getById(shipmentScheduleId);
setAsyncBatchAndSave(shipmentSchedule, asyncBatchId);
}
private void setAsyncBatchAndSave(@NonNull final I_M_ShipmentSchedule shipmentSchedule, @NonNull final AsyncBatchId asyncBatchId)
{
if (shipmentSchedule.getC_Async_Batch_ID() > 0)
{
throw new AdempiereException("Reassigning shipmentSchedule.C_Async_Batch_ID is not allowed!");
}
if (shipmentSchedule.isProcessed())
{
Loggables.withLogger(logger, Level.WARN).addLog("ShipmentScheduleBL.setAsyncBatchAndSave(): M_ShipmentScheduled already processed,"
+ " nothing to do! ShipmentScheduleId: {}", shipmentSchedule.getM_ShipmentSchedule_ID());
return;
}
shipmentSchedule.setC_Async_Batch_ID(asyncBatchId.getRepoId());
shipmentSchedulePA.save(shipmentSchedule);
}
@Override
public I_M_ShipmentSchedule getByOrderLineId(@NonNull final OrderLineId orderLineId)
{
return shipmentSchedulePA.getByOrderLineId(orderLineId);
}
@Override
public void assertSalesOrderCanBeReactivated(@NonNull final OrderId salesOrderId)
{
if (shipmentSchedulePA.existsExportedShipmentScheduleForOrder(salesOrderId))
{
throw new AdempiereException(MSG_REACTIVATION_VOID_NOT_ALLOWED_BECAUSE_ALREADY_EXPORTED);
}
if (shipmentSchedulePA.existsSheduledForPickingShipmentScheduleForOrder(salesOrderId))
{
throw new AdempiereException(MSG_REACTIVATION_VOID_NOT_ALLOWED_BECAUSE_SCHEDULED_FOR_PICKING);
}
}
@Override
|
public Quantity getQtyScheduledForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
final BigDecimal qtyScheduledForPicking = shipmentScheduleRecord.getQtyScheduledForPicking();
final I_C_UOM uom = getUomOfProduct(shipmentScheduleRecord);
return Quantity.of(qtyScheduledForPicking, uom);
}
@Override
public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
final Quantity qtyToDeliver = getQtyToDeliver(shipmentScheduleRecord);
final Quantity qtyScheduledForPicking = getQtyScheduledForPicking(shipmentScheduleRecord);
return qtyToDeliver.subtract(qtyScheduledForPicking).toZeroIfNegative();
}
@Override
public ShipmentScheduleLoadingCache<I_M_ShipmentSchedule> newLoadingCache()
{
return newLoadingCache(I_M_ShipmentSchedule.class);
}
@Override
public <T extends I_M_ShipmentSchedule> ShipmentScheduleLoadingCache<T> newLoadingCache(@NonNull Class<T> modelClass)
{
return ShipmentScheduleLoadingCache.<T>builder()
.shipmentSchedulePA(shipmentSchedulePA)
.modelClass(modelClass)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleBL.java
| 1
|
请完成以下Java代码
|
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return TYPE_NAME.equals(mediaType.getType().toLowerCase())
&& SUB_TYPE_NAME.equals(mediaType.getSubtype().toLowerCase());
}
public MultipartFormData readFrom(Class<MultipartFormData> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
final MultipartFormData multipartFormData = createMultipartFormDataInstance();
final FileUpload fileUpload = createFileUploadInstance();
String contentType = httpHeaders.getFirst("content-type");
RestMultipartRequestContext requestContext = createRequestContext(entityStream, contentType);
// parse the request (populates the multipartFormData)
parseRequest(multipartFormData, fileUpload, requestContext);
return multipartFormData;
}
protected FileUpload createFileUploadInstance() {
return new FileUpload();
}
protected MultipartFormData createMultipartFormDataInstance() {
return new MultipartFormData();
}
protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) {
try {
FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext);
while (itemIterator.hasNext()) {
FileItemStream stream = itemIterator.next();
multipartFormData.addPart(new FormPart(stream));
}
} catch (Exception e) {
throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed");
}
}
protected RestMultipartRequestContext createRequestContext(InputStream entityStream, String contentType) {
return new RestMultipartRequestContext(entityStream, contentType);
|
}
/**
* Exposes the REST request to commons fileupload
*
*/
static class RestMultipartRequestContext implements RequestContext {
protected InputStream inputStream;
protected String contentType;
public RestMultipartRequestContext(InputStream inputStream, String contentType) {
this.inputStream = inputStream;
this.contentType = contentType;
}
public String getCharacterEncoding() {
return null;
}
public String getContentType() {
return contentType;
}
public int getContentLength() {
return -1;
}
public InputStream getInputStream() throws IOException {
return inputStream;
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\mapper\MultipartPayloadProvider.java
| 1
|
请完成以下Java代码
|
public boolean isMandatory()
{
return m_mandatory;
} // isMandatory
/**
* Enable Editor
* @param rw true, if you can enter/select data
*/
@Override
public void setReadWrite (boolean rw)
{
if (super.isEditable() != rw)
super.setEditable (rw);
setBackground(false);
} // setEditable
/**
* Is it possible to edit
* @return true, if editable
*/
@Override
public boolean isReadWrite()
{
return super.isEditable();
} // isReadWrite
/**
* Set Background based on editable / mandatory / error
* @param error if true, set background to error color, otherwise mandatory/editable
*/
@Override
public void setBackground (boolean error)
{
if (error)
setBackground(AdempierePLAF.getFieldBackground_Error());
else if (!isReadWrite())
setBackground(AdempierePLAF.getFieldBackground_Inactive());
else if (m_mandatory)
setBackground(AdempierePLAF.getFieldBackground_Mandatory());
else
setBackground(AdempierePLAF.getFieldBackground_Normal());
} // setBackground
/**
* Set Background
* @param bg
*/
@Override
public void setBackground (Color bg)
{
if (bg.equals(getBackground()))
return;
super.setBackground(bg);
} // setBackground
|
/**
* Set Editor to value
* @param value value of the editor
*/
@Override
public void setValue (Object value)
{
if (value == null)
setText("");
else
setText(value.toString());
} // setValue
/**
* Return Editor value
* @return current value
*/
@Override
public Object getValue()
{
return new String(super.getPassword());
} // getValue
/**
* Return Display Value
* @return displayed String value
*/
@Override
public String getDisplay()
{
return new String(super.getPassword());
} // getDisplay
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPassword.java
| 1
|
请完成以下Java代码
|
public void setIsSharedPrinterConfig (boolean IsSharedPrinterConfig)
{
set_Value (COLUMNNAME_IsSharedPrinterConfig, Boolean.valueOf(IsSharedPrinterConfig));
}
@Override
public boolean isSharedPrinterConfig()
{
return get_ValueAsBoolean(COLUMNNAME_IsSharedPrinterConfig);
}
@Override
public org.compiere.model.I_C_Workplace getC_Workplace()
{
return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class);
}
@Override
public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace)
{
set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace);
}
@Override
|
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Config.java
| 1
|
请完成以下Java代码
|
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(String recipientName) {
|
this.recipientName = recipientName;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getTemplateEngine() {
return templateEngine;
}
public void setTemplateEngine(String templateEngine) {
this.templateEngine = templateEngine;
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\domain\MailObject.java
| 1
|
请完成以下Java代码
|
private static final class RequireClaimValidator implements OAuth2TokenValidator<Jwt> {
private final String claimName;
RequireClaimValidator(String claimName) {
this.claimName = claimName;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
if (token.getClaim(this.claimName) == null) {
return OAuth2TokenValidatorResult
.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " must have a value",
"https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure"));
}
return OAuth2TokenValidatorResult.success();
}
OAuth2TokenValidator<Jwt> isEqualTo(String value) {
return and(satisfies((jwt) -> value.equals(jwt.getClaim(this.claimName))));
}
|
OAuth2TokenValidator<Jwt> satisfies(Predicate<Jwt> predicate) {
return and((jwt) -> {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " is not valid",
"https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure");
if (predicate.test(jwt)) {
return OAuth2TokenValidatorResult.success();
}
return OAuth2TokenValidatorResult.failure(error);
});
}
OAuth2TokenValidator<Jwt> and(OAuth2TokenValidator<Jwt> that) {
return (jwt) -> {
OAuth2TokenValidatorResult result = validate(jwt);
return (result.hasErrors()) ? result : that.validate(jwt);
};
}
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtValidators.java
| 1
|
请完成以下Java代码
|
private static void handleFutureError() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> futureWithError = executorService.submit(() -> {
throw new RuntimeException("An error occurred");
});
try {
String result = futureWithError.get();
LOG.debug("Result with Future: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
|
private static void handlePromiseWritable() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
CompletableFuture<Integer> totalPromise = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
}, executorService);
totalPromise.thenAccept(value -> System.out.println("Total $" + value));
totalPromise.complete(10);
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-2\src\main\java\com\baeldung\concurrent\futurevspromise\FutureVsPromise.java
| 1
|
请完成以下Java代码
|
public void setTotalAmt (BigDecimal TotalAmt)
{
set_ValueNoCheck (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Total Amount.
@return Total Amount
*/
public BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_ValidCombination getUnEarnedRevenue_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getUnEarnedRevenue_Acct(), get_TrxName()); }
/** Set Unearned Revenue.
@param UnEarnedRevenue_Acct
|
Account for unearned revenue
*/
public void setUnEarnedRevenue_Acct (int UnEarnedRevenue_Acct)
{
set_ValueNoCheck (COLUMNNAME_UnEarnedRevenue_Acct, Integer.valueOf(UnEarnedRevenue_Acct));
}
/** Get Unearned Revenue.
@return Account for unearned revenue
*/
public int getUnEarnedRevenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnEarnedRevenue_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_RevenueRecognition_Plan.java
| 1
|
请完成以下Java代码
|
public List<Integer> getAnswer_()
{
return answer_;
}
public void setAnswer_(List<Integer> answer_)
{
this.answer_ = answer_;
}
public List<Integer> getResult_()
{
return result_;
}
public void setResult_(List<Integer> result_)
{
this.result_ = result_;
}
public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
return;
}
TaggerImpl tagger = new TaggerImpl(Mode.TEST);
InputStream stream = null;
try
{
stream = IOUtil.newInputStream(args[0]);
}
catch (IOException e)
{
System.err.printf("model not exits for %s", args[0]);
return;
}
if (stream != null && !tagger.open(stream, 2, 0, 1.0))
{
System.err.println("open error");
return;
}
System.out.println("Done reading model");
if (args.length >= 2)
{
InputStream fis = IOUtil.newInputStream(args[1]);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
|
while (true)
{
ReadStatus status = tagger.read(br);
if (ReadStatus.ERROR == status)
{
System.err.println("read error");
return;
}
else if (ReadStatus.EOF == status)
{
break;
}
if (tagger.getX_().isEmpty())
{
break;
}
if (!tagger.parse())
{
System.err.println("parse error");
return;
}
System.out.print(tagger.toString());
}
br.close();
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java
| 1
|
请完成以下Java代码
|
public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> getTbCoreNotificationsMsgProducer() {
return toTbCoreNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() {
return toUsageStats;
|
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() {
return toHousekeeper;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbTransportQueueProducerProvider.java
| 1
|
请完成以下Java代码
|
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId=" + taskId
+ ", deploymentId=" + deploymentId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", jobId=" + jobId
+ ", jobDefinitionId=" + jobDefinitionId
+ ", batchId=" + batchId
+ ", operationId=" + operationId
+ ", operationType=" + operationType
+ ", userId=" + userId
+ ", timestamp=" + timestamp
+ ", property=" + property
|
+ ", orgValue=" + orgValue
+ ", newValue=" + newValue
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", externalTaskId=" + externalTaskId
+ ", tenantId=" + tenantId
+ ", entityType=" + entityType
+ ", category=" + category
+ ", annotation=" + annotation
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
| 1
|
请完成以下Java代码
|
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 setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
@Override
public void setPercentage (final @Nullable BigDecimal Percentage)
{
set_Value (COLUMNNAME_Percentage, Percentage);
}
@Override
public BigDecimal getPercentage()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceActual (final @Nullable BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
@Override
public BigDecimal getPriceActual()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceEntered (final @Nullable BigDecimal PriceEntered)
|
{
set_Value (COLUMNNAME_PriceEntered, PriceEntered);
}
@Override
public BigDecimal getPriceEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPrice_UOM_ID (final int Price_UOM_ID)
{
if (Price_UOM_ID < 1)
set_Value (COLUMNNAME_Price_UOM_ID, null);
else
set_Value (COLUMNNAME_Price_UOM_ID, Price_UOM_ID);
}
@Override
public int getPrice_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Price_UOM_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInPriceUOM (final @Nullable BigDecimal QtyEnteredInPriceUOM)
{
set_Value (COLUMNNAME_QtyEnteredInPriceUOM, QtyEnteredInPriceUOM);
}
@Override
public BigDecimal getQtyEnteredInPriceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInPriceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Detail.java
| 1
|
请完成以下Java代码
|
public int getRelativePeriodAsInt ()
{
BigDecimal bd = getRelativePeriod();
if (bd == null)
return 0;
return bd.intValue();
} // getRelativePeriodAsInt
/**
* Get Relative Period
* @return relative period
*/
@Override
public BigDecimal getRelativePeriod()
{
if (getColumnType().equals(COLUMNTYPE_RelativePeriod)
|| getColumnType().equals(COLUMNTYPE_SegmentValue))
return super.getRelativePeriod();
return null;
} // getRelativePeriod
/**
* Get Element Type
*/
@Override
public String getElementType()
{
if (getColumnType().equals(COLUMNTYPE_SegmentValue))
{
return super.getElementType();
}
else
{
return null;
}
} // getElementType
/**
* Get Calculation Type
*/
@Override
public String getCalculationType()
{
if (getColumnType().equals(COLUMNTYPE_Calculation))
return super.getCalculationType();
return null;
} // getCalculationType
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
// Validate Type
String ct = getColumnType();
if (ct.equals(COLUMNTYPE_RelativePeriod))
{
setElementType(null);
setCalculationType(null);
|
}
else if (ct.equals(COLUMNTYPE_Calculation))
{
setElementType(null);
setRelativePeriod(null);
}
else if (ct.equals(COLUMNTYPE_SegmentValue))
{
setCalculationType(null);
}
return true;
} // beforeSave
/**************************************************************************
/**
* Copy
* @param ctx context
* @param AD_Client_ID parent
* @param AD_Org_ID parent
* @param PA_ReportColumnSet_ID parent
* @param source copy source
* @param trxName transaction
* @return Report Column
*/
public static MReportColumn copy (Properties ctx, int AD_Client_ID, int AD_Org_ID,
int PA_ReportColumnSet_ID, MReportColumn source, String trxName)
{
MReportColumn retValue = new MReportColumn (ctx, 0, trxName);
MReportColumn.copyValues(source, retValue, AD_Client_ID, AD_Org_ID);
//
retValue.setPA_ReportColumnSet_ID(PA_ReportColumnSet_ID); // parent
retValue.setOper_1_ID(0);
retValue.setOper_2_ID(0);
return retValue;
} // copy
} // MReportColumn
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportColumn.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static ConditionOutcome noMatch(ConditionMessage message) {
return new ConditionOutcome(false, message);
}
/**
* Return {@code true} if the outcome was a match.
* @return {@code true} if the outcome matches
*/
public boolean isMatch() {
return this.match;
}
/**
* Return an outcome message or {@code null}.
* @return the message or {@code null}
*/
public @Nullable String getMessage() {
return this.message.isEmpty() ? null : this.message.toString();
}
/**
* Return an outcome message.
* @return the message
*/
public ConditionMessage getConditionMessage() {
return this.message;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
|
}
if (getClass() == obj.getClass()) {
ConditionOutcome other = (ConditionOutcome) obj;
return (this.match == other.match && ObjectUtils.nullSafeEquals(this.message, other.message));
}
return super.equals(obj);
}
@Override
public int hashCode() {
return Boolean.hashCode(this.match) * 31 + ObjectUtils.nullSafeHashCode(this.message);
}
@Override
public String toString() {
return (this.message != null) ? this.message.toString() : "";
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionOutcome.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private <I extends EntityId, E extends ExportableEntity<I>, D extends EntityExportData<E>> EntityImportService<I, E, D> getImportService(EntityType entityType) {
EntityImportService<?, ?, ?> importService = importServices.get(entityType);
if (importService == null) {
throw new IllegalArgumentException("Import for entity type " + entityType + " is not supported");
}
return (EntityImportService<I, E, D>) importService;
}
@Autowired
private void setExportServices(DefaultEntityExportService<?, ?, ?> defaultExportService,
Collection<BaseEntityExportService<?, ?, ?>> exportServices) {
exportServices.stream()
.sorted(Comparator.comparing(exportService -> exportService.getSupportedEntityTypes().size(), Comparator.reverseOrder()))
.forEach(exportService -> {
exportService.getSupportedEntityTypes().forEach(entityType -> {
this.exportServices.put(entityType, exportService);
|
});
});
SUPPORTED_ENTITY_TYPES.forEach(entityType -> {
this.exportServices.putIfAbsent(entityType, defaultExportService);
});
}
@Autowired
private void setImportServices(Collection<EntityImportService<?, ?, ?>> importServices) {
importServices.forEach(entityImportService -> {
this.importServices.put(entityImportService.getEntityType(), entityImportService);
});
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\DefaultEntitiesExportImportService.java
| 2
|
请完成以下Java代码
|
public boolean whileCharacters() {
String ltrim = whileLtrim(src);
String rtrim = whileRtrim(src);
return checkStrings(ltrim, rtrim);
}
// replaceAll() and Regular Expressions
@Benchmark
public boolean replaceAllRegularExpression() {
String ltrim = src.replaceAll("^\\s+", "");
String rtrim = src.replaceAll("\\s+$", "");
return checkStrings(ltrim, rtrim);
}
public static String patternLtrim(String s) {
return LTRIM.matcher(s)
.replaceAll("");
}
public static String patternRtrim(String s) {
return RTRIM.matcher(s)
.replaceAll("");
}
// Pattern matches() with replaceAll
@Benchmark
public boolean patternMatchesLTtrimRTrim() {
|
String ltrim = patternLtrim(src);
String rtrim = patternRtrim(src);
return checkStrings(ltrim, rtrim);
}
// Guava CharMatcher trimLeadingFrom / trimTrailingFrom
@Benchmark
public boolean guavaCharMatcher() {
String ltrim = CharMatcher.whitespace().trimLeadingFrom(src);
String rtrim = CharMatcher.whitespace().trimTrailingFrom(src);
return checkStrings(ltrim, rtrim);
}
// Apache Commons StringUtils containsIgnoreCase
@Benchmark
public boolean apacheCommonsStringUtils() {
String ltrim = StringUtils.stripStart(src, null);
String rtrim = StringUtils.stripEnd(src, null);
return checkStrings(ltrim, rtrim);
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\trim\LTrimRTrim.java
| 1
|
请完成以下Java代码
|
public static final PickingSlotRowId ofSourceHU(final HuId huId)
{
final PickingSlotId pickingSlotId = null;
final int huStorageProductId = -1;
return new PickingSlotRowId(pickingSlotId, huId, huStorageProductId);
}
public static final PickingSlotRowId fromDocumentId(final DocumentId documentId)
{
final List<String> parts = DOCUMENT_ID_SPLITTER.splitToList(documentId.toJson());
return fromStringPartsList(parts);
}
public static final PickingSlotRowId fromStringPartsList(final List<String> parts)
{
final int partsCount = parts.size();
if (partsCount < 1)
{
throw new IllegalArgumentException("Invalid id: " + parts);
}
final PickingSlotId pickingSlotId = !Check.isEmpty(parts.get(0), true) ? PickingSlotId.ofRepoIdOrNull(Integer.parseInt(parts.get(0))) : null;
final HuId huId = partsCount >= 2 ? HuId.ofRepoIdOrNull(Integer.parseInt(parts.get(1))) : null;
final int huStorageProductId = partsCount >= 3 ? Integer.parseInt(parts.get(2)) : 0;
return new PickingSlotRowId(pickingSlotId, huId, huStorageProductId);
}
@Getter
private final PickingSlotId pickingSlotId;
@Getter
private final HuId huId;
@Getter
private final int huStorageProductId;
private transient DocumentId _documentId; // lazy
private static final String SEPARATOR = "-";
private static final Joiner DOCUMENT_ID_JOINER = Joiner.on(SEPARATOR).skipNulls();
private static final Splitter DOCUMENT_ID_SPLITTER = Splitter.on(SEPARATOR);
@Builder
private PickingSlotRowId(final PickingSlotId pickingSlotId, final HuId huId, final int huStorageProductId)
{
this.pickingSlotId = pickingSlotId;
this.huId = huId;
this.huStorageProductId = huStorageProductId > 0 ? huStorageProductId : 0;
}
@Override
public String toString()
{
return toDocumentId().toJson();
|
}
public DocumentId toDocumentId()
{
DocumentId id = _documentId;
if (id == null)
{
final String idStr = DOCUMENT_ID_JOINER.join(
pickingSlotId != null ? pickingSlotId.getRepoId() : 0,
huId != null ? huId.getRepoId() : null,
huStorageProductId > 0 ? huStorageProductId : null);
id = _documentId = DocumentId.ofString(idStr);
}
return id;
}
/** @return {@code true} if this row ID represents an actual picking slot and not any sort of HU that is also shown in this view. */
public boolean isPickingSlotRow()
{
return getPickingSlotId() != null && getHuId() == null;
}
/** @return {@code true} is this row ID represents an HU that is assigned to a picking slot */
public boolean isPickedHURow()
{
return getPickingSlotId() != null && getHuId() != null;
}
/** @return {@code true} if this row ID represents an HU that is a source-HU for fine-picking. */
public boolean isPickingSourceHURow()
{
return getPickingSlotId() == null && getHuId() != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRowId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InMemoryMessageRepository implements MessageRepository {
private static AtomicLong counter = new AtomicLong();
private final ConcurrentMap<Long, Message> messages = new ConcurrentHashMap<>();
@Override
public List<Message> findAll() {
List<Message> messages = new ArrayList<Message>(this.messages.values());
return messages;
}
@Override
public Message save(Message message) {
Long id = message.getId();
if (id == null) {
id = counter.incrementAndGet();
message.setId(id);
}
this.messages.put(id, message);
return message;
}
@Override
public Message update(Message message) {
this.messages.put(message.getId(), message);
return message;
}
@Override
|
public Message updateText(Message message) {
Message msg=this.messages.get(message.getId());
msg.setText(message.getText());
this.messages.put(msg.getId(), msg);
return msg;
}
@Override
public Message findMessage(Long id) {
return this.messages.get(id);
}
@Override
public void deleteMessage(Long id) {
this.messages.remove(id);
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 2-8 课: Spring Boot 构建一个 RESTful Web 服务\spring-boot-web-restful\src\main\java\com\neo\repository\InMemoryMessageRepository.java
| 2
|
请完成以下Java代码
|
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_CostElement getM_CostElement() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class);
}
@Override
public void setM_CostElement(org.compiere.model.I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement);
}
/** Set Kostenart.
@param M_CostElement_ID
Produkt-Kostenart
*/
@Override
public void setM_CostElement_ID (int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
|
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID));
}
/** Get Kostenart.
@return Produkt-Kostenart
*/
@Override
public int getM_CostElement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_CostElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String encode(String input) {
return URLEncoder.encode(input, StandardCharsets.UTF_8);
}
private char[] encode(char[] input) {
return URLEncoder.encode(new String(input), StandardCharsets.UTF_8).toCharArray();
}
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getSsl();
if (!ssl.isEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
|
return this.sslBundles.getBundle(ssl.getBundle());
}
return SslBundle.systemDefault();
}
private List<String> getOptions() {
List<String> options = new ArrayList<>();
if (StringUtils.hasText(this.properties.getReplicaSetName())) {
options.add("replicaSet=" + this.properties.getReplicaSetName());
}
if (this.properties.getUsername() != null && this.properties.getAuthenticationDatabase() != null) {
options.add("authSource=" + this.properties.getAuthenticationDatabase());
}
return options;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\PropertiesMongoConnectionDetails.java
| 2
|
请完成以下Java代码
|
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
Properties properties = (Properties) returnValue;
ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
HttpServletResponse response = servletWebRequest.getResponse();
ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(response);
// 获取请求头
HttpHeaders headers = servletServerHttpResponse.getHeaders();
MediaType contentType = headers.getContentType();
// 获取编码
Charset charset = null;
if (contentType != null) {
|
charset = contentType.getCharset();
}
charset = charset == null ? Charset.forName("UTF-8") : charset;
// 获取请求体
OutputStream body = servletServerHttpResponse.getBody();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body, charset);
properties.store(outputStreamWriter, "Serialized by PropertiesHandlerMethodReturnValueHandler#handleReturnValue");
// 告诉 Spring MVC 请求已经处理完毕
mavContainer.setRequestHandled(true);
}
}
|
repos\SpringAll-master\47.Spring-Boot-Content-Negotiation\src\main\java\com\example\demo\handler\PropertiesHandlerMethodReturnValueHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setSerialNo (final @Nullable java.lang.String SerialNo)
{
set_Value (COLUMNNAME_SerialNo, SerialNo);
}
@Override
public java.lang.String getSerialNo()
{
return get_ValueAsString(COLUMNNAME_SerialNo);
}
@Override
public void setServiceRepair_Old_Shipped_HU_ID (final int ServiceRepair_Old_Shipped_HU_ID)
{
if (ServiceRepair_Old_Shipped_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID, ServiceRepair_Old_Shipped_HU_ID);
}
@Override
|
public int getServiceRepair_Old_Shipped_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID);
}
@Override
public void setWarrantyStartDate (final @Nullable java.sql.Timestamp WarrantyStartDate)
{
set_Value (COLUMNNAME_WarrantyStartDate, WarrantyStartDate);
}
@Override
public java.sql.Timestamp getWarrantyStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_WarrantyStartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_ServiceRepair_Old_Shipped_HU.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
// 登录成功处理类
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeRequests(authorize -> {
try {
authorize
//静态文件允许访问
.requestMatchers(adminContextPath + "/assets/**").permitAll()
//登录页面允许访问
.requestMatchers(adminContextPath + "/login", "/css/**", "/js/**", "/image/*").permitAll()
//其他所有请求需要登录
.anyRequest().authenticated()
.and()
//登录页面配置,用于替换security默认页面
.formLogin(formLogin -> formLogin.loginPage(adminContextPath + "/login").successHandler(successHandler))
//登出页面配置,用于替换security默认页面
.logout(logout -> logout.logoutUrl(adminContextPath + "/logout"))
.httpBasic(Customizer.withDefaults())
|
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
"/instances",
"/actuator/**")
);
} catch (Exception e) {
e.printStackTrace();
}
}
);
return http.build();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-monitor\src\main\java\org\jeecg\monitor\config\SecuritySecureConfig.java
| 2
|
请完成以下Java代码
|
public static String getRelativeName(String fullDn, Context baseCtx) throws NamingException {
String baseDn = baseCtx.getNameInNamespace();
if (baseDn.isEmpty()) {
return fullDn;
}
LdapName base = LdapNameBuilder.newInstance(baseDn).build();
LdapName full = LdapNameBuilder.newInstance(fullDn).build();
if (base.equals(full)) {
return "";
}
Assert.isTrue(full.startsWith(base), "Full DN does not start with base DN");
for (int i = 0; i < base.size(); i++) {
full.remove(0);
}
return full.toString();
}
/**
* Gets the full dn of a name by prepending the name of the context it is relative to.
* If the name already contains the base name, it is returned unaltered.
*/
public static LdapName getFullDn(LdapName dn, Context baseCtx) throws NamingException {
LdapName baseDn = LdapNameBuilder.newInstance(baseCtx.getNameInNamespace()).build();
if (dn.startsWith(baseDn)) {
return dn;
}
baseDn.addAll(dn);
return baseDn;
}
public static String convertPasswordToString(Object passObj) {
Assert.notNull(passObj, "Password object to convert must not be null");
if (passObj instanceof byte[]) {
return Utf8.decode((byte[]) passObj);
}
if (passObj instanceof String) {
return (String) passObj;
}
throw new IllegalArgumentException("Password object was not a String or byte array.");
}
/**
* Works out the root DN for an LDAP URL.
* <p>
* For example, the URL <tt>ldap://monkeymachine:11389/dc=springframework,dc=org</tt>
* has the root DN "dc=springframework,dc=org".
* </p>
* @param url the LDAP URL
* @return the root DN
*/
|
public static String parseRootDnFromUrl(String url) {
Assert.hasLength(url, "url must have length");
String urlRootDn;
if (url.startsWith("ldap:") || url.startsWith("ldaps:")) {
URI uri = parseLdapUrl(url);
urlRootDn = uri.getRawPath();
}
else {
// Assume it's an embedded server
urlRootDn = url;
}
if (urlRootDn.startsWith("/")) {
urlRootDn = urlRootDn.substring(1);
}
return urlRootDn;
}
/**
* Parses the supplied LDAP URL.
* @param url the URL (e.g.
* <tt>ldap://monkeymachine:11389/dc=springframework,dc=org</tt>).
* @return the URI object created from the URL
* @throws IllegalArgumentException if the URL is null, empty or the URI syntax is
* invalid.
*/
private static URI parseLdapUrl(String url) {
Assert.hasLength(url, "url must have length");
try {
return new URI(url);
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException("Unable to parse url: " + url, ex);
}
}
}
|
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\LdapUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static ClientId ofRepoIdOrNull(final int repoId)
{
if (repoId == SYSTEM.repoId)
{
return SYSTEM;
}
else if (repoId == TRASH.repoId)
{
return TRASH;
}
else if (repoId == METASFRESH.repoId)
{
return METASFRESH;
}
else if (repoId <= 0)
{
return null;
}
else
{
return new ClientId(repoId);
}
}
public static final ClientId SYSTEM = new ClientId(0);
@VisibleForTesting
static final ClientId TRASH = new ClientId(99);
public static final ClientId METASFRESH = new ClientId(1000000);
int repoId;
private ClientId(final int repoId)
{
// NOTE: validation happens in ofRepoIdOrNull method
this.repoId = repoId;
}
public boolean isSystem()
{
return repoId == SYSTEM.repoId;
}
|
public boolean isTrash()
{
return repoId == TRASH.repoId;
}
public boolean isRegular()
{
return !isSystem() && !isTrash();
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final ClientId clientId)
{
return clientId != null ? clientId.getRepoId() : -1;
}
public static boolean equals(@Nullable final ClientId id1, @Nullable final ClientId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\ClientId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ConfigureFeignUrlController {
private final AlbumClient albumClient;
private final PostClient postClient;
private final TodoClient todoClient;
private final ObjectFactory<HttpMessageConverters> messageConverters;
private final ObjectProvider<HttpMessageConverterCustomizer> customizers;
public ConfigureFeignUrlController(AlbumClient albumClient,
PostClient postClient,
Decoder decoder,
Encoder encoder,
ObjectFactory<HttpMessageConverters> messageConverters, ObjectProvider<HttpMessageConverterCustomizer> customizers) {
this.albumClient = albumClient;
this.postClient = postClient;
this.messageConverters = messageConverters;
this.customizers = customizers;
this.todoClient = Feign.builder().encoder(encoder).decoder(decoder).target(Target.EmptyTarget.create(TodoClient.class));
}
@GetMapping(value = "albums/{id}")
public Album getAlbumById(@PathVariable(value = "id") Integer id) {
return albumClient.getAlbumById(id);
}
|
@GetMapping(value = "posts/{id}")
public Post getPostById(@PathVariable(value = "id") Integer id) {
return postClient.getPostById(id);
}
@GetMapping(value = "todos/{id}")
public Todo getTodoById(@PathVariable(value = "id") Integer id) {
return todoClient.getTodoById(URI.create("https://jsonplaceholder.typicode.com/todos/" + id));
}
@GetMapping(value = "/dynamicAlbums/{id}")
public Album getAlbumByIdAndDynamicUrl(@PathVariable(value = "id") Integer id) {
AlbumClient client = Feign.builder()
.requestInterceptor(new DynamicUrlInterceptor(() -> "https://jsonplaceholder.typicode.com/albums/"))
.contract(new SpringMvcContract())
.encoder(new SpringEncoder(messageConverters))
.decoder(new SpringDecoder(messageConverters, customizers))
.target(Target.EmptyTarget.create(AlbumClient.class));
return client.getAlbumByIdAndDynamicUrl(id);
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign\src\main\java\com\baeldung\cloud\openfeign\controller\ConfigureFeignUrlController.java
| 2
|
请完成以下Java代码
|
public boolean addAll(Collection<? extends Target> c) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("addAll()", "collection is immutable");
}
else {
boolean result = false;
for (Target o: c) {
result |= add(o);
}
return result;
}
}
public boolean removeAll(Collection<?> c) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("removeAll()", "collection is immutable");
}
else {
boolean result = false;
for (Object o: c) {
result |= remove(o);
}
return result;
}
|
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("clear()", "collection is immutable");
}
else {
Collection<DomElement> view = new ArrayList<DomElement>();
for (Source referenceSourceElement : referenceSourceCollection.get(referenceSourceParentElement)) {
view.add(referenceSourceElement.getDomElement());
}
performClearOperation(referenceSourceParentElement, view);
}
}
};
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ElementReferenceCollectionImpl.java
| 1
|
请完成以下Java代码
|
public class DropShipLocationAdapter
implements IDocumentDeliveryLocationAdapter, RecordBasedLocationAdapter<DropShipLocationAdapter>
{
private final I_C_OLCand delegate;
@Getter
@Setter
private String deliveryToAddress;
DropShipLocationAdapter(@NonNull final I_C_OLCand delegate)
{
this.delegate = delegate;
}
@Override
public boolean isDropShip()
{
return BPartnerLocationId.ofRepoIdOrNull(getDropShip_BPartner_ID(), getDropShip_Location_ID()) != null;
}
@Override
public int getM_Warehouse_ID()
{
return delegate.getM_Warehouse_ID();
}
@Override
public int getDropShip_BPartner_ID()
{
return delegate.getDropShip_BPartner_ID();
}
@Override
public void setDropShip_BPartner_ID(final int DropShip_BPartner_ID)
{
delegate.setDropShip_BPartner_ID(DropShip_BPartner_ID);
}
@Override
public int getDropShip_Location_ID()
{
return delegate.getDropShip_Location_ID();
}
@Override
public void setDropShip_Location_ID(final int DropShip_Location_ID)
{
delegate.setDropShip_Location_ID(DropShip_Location_ID);
}
@Override
public int getDropShip_Location_Value_ID()
{
return delegate.getDropShip_Location_Value_ID();
}
@Override
public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID)
{
delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID);
}
@Override
|
public int getDropShip_User_ID()
{
return delegate.getDropShip_User_ID();
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
delegate.setDropShip_User_ID(DropShip_User_ID);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public DropShipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new DropShipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\DropShipLocationAdapter.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty()
{
return fields.isEmpty();
}
public ImmutableList<DataEntryRecordField<?>> getFields()
{
return ImmutableList.copyOf(fields.values());
}
public Optional<ZonedDateTime> getCreatedValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getCreated);
}
public Optional<UserId> getCreatedByValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getCreatedBy);
}
public Optional<ZonedDateTime> getUpdatedValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getUpdated);
}
public Optional<UserId> getUpdatedByValue(@NonNull final DataEntryFieldId fieldId)
{
|
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getUpdatedBy);
}
public Optional<CreatedUpdatedInfo> getCreatedUpdatedInfo(@NonNull final DataEntryFieldId fieldId)
{
return getOptional(fieldId)
.map(DataEntryRecordField::getCreatedUpdatedInfo);
}
public Optional<Object> getFieldValue(@NonNull final DataEntryFieldId fieldId)
{
return getOptional(fieldId)
.map(DataEntryRecordField::getValue);
}
private Optional<DataEntryRecordField<?>> getOptional(@NonNull final DataEntryFieldId fieldId)
{
return Optional.ofNullable(fields.get(fieldId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecord.java
| 1
|
请完成以下Java代码
|
protected void configureConnectionLimits(final T builder) {
if (this.properties.getMaxConnectionIdle() != null) {
throw new IllegalStateException(
"MaxConnectionIdle is set but this implementation does not support maxConnectionIdle!");
}
if (this.properties.getMaxConnectionAge() != null) {
throw new IllegalStateException(
"MaxConnectionAge is set but this implementation does not support maxConnectionAge!");
}
if (this.properties.getMaxConnectionAgeGrace() != null) {
throw new IllegalStateException(
"MaxConnectionAgeGrace is set but this implementation does not support maxConnectionAgeGrace!");
}
}
/**
* Configures the security options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureSecurity(final T builder) {
if (this.properties.getSecurity().isEnabled()) {
throw new IllegalStateException("Security is enabled but this implementation does not support security!");
}
}
/**
* Configures limits such as max message sizes that should be used by the server.
*
|
* @param builder The server builder to configure.
*/
protected void configureLimits(final T builder) {
final DataSize maxInboundMessageSize = this.properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
final DataSize maxInboundMetadataSize = this.properties.getMaxInboundMetadataSize();
if (maxInboundMetadataSize != null) {
builder.maxInboundMetadataSize((int) maxInboundMetadataSize.toBytes());
}
}
@Override
public String getAddress() {
return this.properties.getAddress();
}
@Override
public int getPort() {
return this.properties.getPort();
}
@Override
public void addService(final GrpcServiceDefinition service) {
this.serviceList.add(service);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\serverfactory\AbstractGrpcServerFactory.java
| 1
|
请完成以下Java代码
|
public static IAutoCloseable temporaryDisableItIf(final boolean condition)
{
return condition ? temporaryDisableIt() : IAutoCloseable.NOP;
}
public static IAutoCloseable temporaryDisableIt()
{
final boolean disabledOld = disabled.getAndSet(true);
return () -> disabled.set(disabledOld);
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40;
}
@Override
|
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return !disabled.get();
}
@Override
public String generateStringValue(
final Properties ctx_IGNORED,
@NonNull final IAttributeSet attributeSet,
final I_M_Attribute attribute_IGNORED)
{
final I_M_HU hu = Services.get(IHUAttributesBL.class).getM_HU(attributeSet);
// Just don't use the M_HU_ID as serial number. It introduced FUD as multiple packs can have the same HU and each pack needs an individual SSCC.
final SSCC18 sscc18 = sscc18CodeBL.generate(OrgId.ofRepoIdOrAny(hu.getAD_Org_ID()));
return sscc18.asString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attributes\sscc18\impl\SSCC18AttributeValueGenerator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
|
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
@Bean(destroyMethod = "destroy")
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
return new RedisLockRegistry(redisConnectionFactory, "lock");
}
}
|
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\config\RedisConfig.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this).addValue(orderLine).toString();
}
@Override
public Properties getCtx()
{
return ctx;
}
@Override
public int getAD_Client_ID()
{
return orderLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return orderLine.getAD_Org_ID();
|
}
@Override
public int getM_Product_ID()
{
return orderLine.getM_Product_ID();
}
@Override
public int getM_Warehouse_ID()
{
return orderLine.getM_Warehouse_ID();
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return orderLine.getM_AttributeSetInstance();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\OrderLineReceiptScheduleProducer.java
| 1
|
请完成以下Java代码
|
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getZipCode() {
return zipCode;
}
@Override
public void update(final String quote) {
// user got updated with a new quote
|
}
@Override
public void subscribe(final Subject subject) {
subject.attach(this);
}
@Override
public void unsubscribe(final Subject subject) {
subject.detach(this);
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
}
|
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\lapsedlistener\User.java
| 1
|
请完成以下Java代码
|
public class Delivery {
private String message;
public Delivery(String message) {
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Delivery delivery = (Delivery) o;
|
return Objects.equals(message, delivery.message);
}
@Override
public int hashCode() {
return message != null ? message.hashCode() : 0;
}
public static Delivery freeDelivery() {
return new Delivery("Free delivery");
}
public static Delivery defaultDelivery() {
return new Delivery("Default delivery");
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\nullconversion\Delivery.java
| 1
|
请完成以下Java代码
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ParticipantAssociation.class, BPMN_ELEMENT_PARTICIPANT_ASSOCIATION)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ParticipantAssociation>() {
public ParticipantAssociation newInstance(ModelTypeInstanceContext instanceContext) {
return new ParticipantAssociationImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
innerParticipantRefChild = sequenceBuilder.element(InnerParticipantRef.class)
.required()
.qNameElementReference(Participant.class)
.build();
outerParticipantRefChild = sequenceBuilder.element(OuterParticipantRef.class)
.required()
.qNameElementReference(Participant.class)
.build();
typeBuilder.build();
}
public ParticipantAssociationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
|
public Participant getInnerParticipant() {
return innerParticipantRefChild.getReferenceTargetElement(this);
}
public void setInnerParticipant(Participant innerParticipant) {
innerParticipantRefChild.setReferenceTargetElement(this, innerParticipant);
}
public Participant getOuterParticipant() {
return outerParticipantRefChild.getReferenceTargetElement(this);
}
public void setOuterParticipant(Participant outerParticipant) {
outerParticipantRefChild.setReferenceTargetElement(this, outerParticipant);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ParticipantAssociationImpl.java
| 1
|
请完成以下Java代码
|
private Component createActionComponent(final ISideAction action)
{
final SideActionType type = action.getType();
if (type == SideActionType.Toggle)
{
return new CheckableSideActionComponent(action);
}
else if (type == SideActionType.ExecutableAction)
{
return new HyperlinkSideActionComponent(action);
}
else if (type == SideActionType.Label)
{
return new LabelSideActionComponent(action);
}
else
{
throw new IllegalArgumentException("Unknown action type: " + type);
}
}
protected void updateActionComponent(final Component actionComp, final ISideAction action)
{
// TODO Auto-generated method stub
}
private final boolean hasActions()
|
{
return model != null && model.getActions().getSize() > 0;
}
private final void refreshUI()
{
// Auto-hide if no actions
setVisible(hasActions());
final Container actionsPanel = getActionsPanel();
actionsPanel.revalidate();
}
@Override
public void setVisible(final boolean visible)
{
final boolean visibleOld = isVisible();
super.setVisible(visible);
firePropertyChange(PROPERTY_Visible, visibleOld, isVisible());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupPanel.java
| 1
|
请完成以下Java代码
|
public void setContentHTML (String ContentHTML)
{
set_Value (COLUMNNAME_ContentHTML, ContentHTML);
}
/** Get Content HTML.
@return Contains the content itself
*/
public String getContentHTML ()
{
return (String)get_Value(COLUMNNAME_ContentHTML);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set LinkURL.
@param LinkURL
Contains URL to a target
*/
public void setLinkURL (String LinkURL)
{
set_Value (COLUMNNAME_LinkURL, LinkURL);
}
/** Get LinkURL.
@return Contains URL to a target
*/
public String getLinkURL ()
{
return (String)get_Value(COLUMNNAME_LinkURL);
}
/** Set Publication Date.
@param PubDate
Date on which this article will / should get published
*/
public void setPubDate (Timestamp PubDate)
{
set_Value (COLUMNNAME_PubDate, PubDate);
|
}
/** Get Publication Date.
@return Date on which this article will / should get published
*/
public Timestamp getPubDate ()
{
return (Timestamp)get_Value(COLUMNNAME_PubDate);
}
/** Set Title.
@param Title
Name this entity is referred to as
*/
public void setTitle (String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Title.
@return Name this entity is referred to as
*/
public String getTitle ()
{
return (String)get_Value(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public OrderMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderMapping orderMapping = (OrderMapping) o;
return Objects.equals(this.orderId, orderMapping.orderId) &&
Objects.equals(this.salesId, orderMapping.salesId) &&
Objects.equals(this.updated, orderMapping.updated);
|
}
@Override
public int hashCode() {
return Objects.hash(orderId, salesId, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OrderMapping {\n");
sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n");
sb.append(" salesId: ").append(toIndentedString(salesId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderMapping.java
| 2
|
请完成以下Java代码
|
public Map<String, Set<String>> getCustomGroupIdentityLinks() {
return customGroupIdentityLinks;
}
public void setCustomGroupIdentityLinks(Map<String, Set<String>> customGroupIdentityLinks) {
this.customGroupIdentityLinks = customGroupIdentityLinks;
}
public List<CustomProperty> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(List<CustomProperty> customProperties) {
this.customProperties = customProperties;
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public UserTask clone() {
UserTask clone = new UserTask();
clone.setValues(this);
return clone;
}
public void setValues(UserTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setCandidateGroups(new ArrayList<String>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<String>(otherElement.getCandidateUsers()));
|
setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks);
setCustomUserIdentityLinks(otherElement.customUserIdentityLinks);
formProperties = new ArrayList<FormProperty>();
if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) {
formProperties.add(property.clone());
}
}
taskListeners = new ArrayList<ActivitiListener>();
if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) {
for (ActivitiListener listener : otherElement.getTaskListeners()) {
taskListeners.add(listener.clone());
}
}
}
@Override
public void accept(ReferenceOverrider referenceOverrider) {
referenceOverrider.override(this);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\UserTask.java
| 1
|
请完成以下Java代码
|
public class RepackNumberAttributeCallout implements IAttributeValueGeneratorAdapter, IAttributeValueCalloutAdapter
{
@Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
final String attributeKey = attribute.getValue();
if (RepackNumberUtils.ATTR_IsRepackNumberRequired.equals(attributeKey))
{
return true;
}
else if (RepackNumberUtils.ATTR_RepackNumber.equals(attributeKey))
{
return !RepackNumberUtils.isRepackNumberRequired(attributeSet);
}
else
{
return false;
}
}
|
@Override
public boolean isDisplayedUI(final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
final String attributeKey = attribute.getValue();
if (RepackNumberUtils.ATTR_IsRepackNumberRequired.equals(attributeKey))
{
return RepackNumberUtils.isRepackNumberRequired(attributeSet);
}
else if (RepackNumberUtils.ATTR_RepackNumber.equals(attributeKey))
{
return RepackNumberUtils.isRepackNumberRequired(attributeSet);
}
else
{
return false;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\attributes\RepackNumberAttributeCallout.java
| 1
|
请完成以下Java代码
|
public List<AccountingDocToRepost> retrieve(final int limit)
{
Check.assumeGreaterThanZero(limit, "limit");
return DB.retrieveRowsOutOfTrx(
"SELECT * FROM " + Table_Name + " ORDER BY SeqNo LIMIT ?",
Collections.singletonList(limit),
this::retrieveRow);
}
private AccountingDocToRepost retrieveRow(final ResultSet rs) throws SQLException
{
return AccountingDocToRepost.builder()
.seqNo(rs.getInt("SeqNo"))
.recordRef(TableRecordReference.of(
rs.getString("TableName"),
rs.getInt("Record_ID")))
.clientId(ClientId.ofRepoId(rs.getInt("AD_Client_ID")))
|
.force(StringUtils.toBoolean(rs.getString("force")))
.onErrorNotifyUserId(UserId.ofRepoIdOrNullIfSystem(rs.getInt("on_error_notify_user_id")))
.build();
}
public void delete(@NonNull final Collection<AccountingDocToRepost> docsToRepost)
{
if (docsToRepost.isEmpty()) {return;}
final ImmutableSet<Integer> seqNos = docsToRepost.stream()
.map(AccountingDocToRepost::getSeqNo)
.collect(ImmutableSet.toImmutableSet());
DB.executeUpdateAndThrowExceptionOnFail(
"DELETE FROM " + Table_Name + " WHERE " + DB.buildSqlList("SeqNo", seqNos),
null,
ITrx.TRXNAME_None);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\server\accouting_docs_to_repost_db_table\AccountingDocsToRepostDBTableRepository.java
| 1
|
请完成以下Java代码
|
public JdkClientHttpRequestFactoryBuilder withExecutor(Executor executor) {
return new JdkClientHttpRequestFactoryBuilder(getCustomizers(), this.httpClientBuilder.withExecutor(executor));
}
/**
* Return a new {@link JdkClientHttpRequestFactoryBuilder} that applies additional
* customization to the underlying {@link java.net.http.HttpClient.Builder}.
* @param httpClientCustomizer the customizer to apply
* @return a new {@link JdkClientHttpRequestFactoryBuilder} instance
*/
public JdkClientHttpRequestFactoryBuilder withHttpClientCustomizer(
Consumer<HttpClient.Builder> httpClientCustomizer) {
Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null");
return new JdkClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withCustomizer(httpClientCustomizer));
}
/**
* Return a new {@link JdkClientHttpRequestFactoryBuilder} that applies the given
* customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply
* @return a new {@link JdkClientHttpRequestFactoryBuilder}
* @since 4.0.0
*/
public JdkClientHttpRequestFactoryBuilder with(UnaryOperator<JdkClientHttpRequestFactoryBuilder> customizer) {
return customizer.apply(this);
}
@Override
|
protected JdkClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) {
HttpClient httpClient = this.httpClientBuilder.build(settings.withReadTimeout(null));
JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient);
PropertyMapper map = PropertyMapper.get();
map.from(settings::readTimeout).to(requestFactory::setReadTimeout);
return requestFactory;
}
static class Classes {
static final String HTTP_CLIENT = "java.net.http.HttpClient";
static boolean present(@Nullable ClassLoader classLoader) {
return ClassUtils.isPresent(HTTP_CLIENT, classLoader);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\JdkClientHttpRequestFactoryBuilder.java
| 1
|
请完成以下Java代码
|
void createButtons() {
for (int i = 0; i < chars.length; i++) {
JButton button = new JButton(new CharAction(chars[i]));
button.setMaximumSize(new Dimension(50, 22));
//button.setMinimumSize(new Dimension(22, 22));
button.setPreferredSize(new Dimension(30, 22));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.setBorderPainted(false);
button.setOpaque(false);
button.setMargin(new Insets(0,0,0,0));
button.setFont(new Font("serif", 0, 14));
if (i == chars.length-1) {
button.setText("nbsp");
button.setFont(new Font("Dialog",0,10));
button.setMargin(new Insets(0,0,0,0));
}
this.add(button, null);
|
}
}
class CharAction extends AbstractAction {
CharAction(String name) {
super(name);
//putValue(Action.SHORT_DESCRIPTION, name);
}
public void actionPerformed(ActionEvent e) {
String s = this.getValue(Action.NAME).toString();
editor.replaceSelection(s);
if (s.length() == 2)
editor.setCaretPosition(editor.getCaretPosition()-1);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\CharTablePanel.java
| 1
|
请完成以下Java代码
|
public class C_Order_ProductionSimulationView_Launcher extends JavaProcess implements IProcessPrecondition
{
public static final String VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR = "OrderLineDescriptor";
private final IOrderDAO orderDAO = Services.get(IOrderDAO.class);
private final ProductionSimulationService productionSimulationService = SpringContextHolder.instance.getBean(ProductionSimulationService.class);
private final PostMaterialEventService postMaterialEventService = SpringContextHolder.instance.getBean(PostMaterialEventService.class);
private final IViewsRepository viewsFactory = SpringContextHolder.instance.getBean(IViewsRepository.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.getSelectedIncludedRecords().size() != 1)
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final OrderLineId orderLineId = OrderLineId.ofRepoId(Check.singleElement(getSelectedIncludedRecordIds(I_C_OrderLine.class)));
final I_C_Order salesOrder = orderDAO.getById(OrderId.ofRepoId(getRecord_ID()));
final OrderLineDescriptor orderLineDescriptor = OrderLineDescriptor.builder()
.orderId(salesOrder.getC_Order_ID())
.orderLineId(orderLineId.getRepoId())
.orderBPartnerId(salesOrder.getC_BPartner_ID())
.docTypeId(salesOrder.getC_DocType_ID())
.build();
try
{
productionSimulationService.processSimulatedDemand(orderLineId, salesOrder, orderLineDescriptor);
final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(ProductionSimulationViewFactory.WINDOWID)
.setParameter(VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR, orderLineDescriptor)
|
.build())
.getViewId();
getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder()
.viewId(viewId.getViewId())
.target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay)
.build());
}
catch (final Exception exception)
{
log.error("Error encountered while launching ProductionSimulationModal:", exception);
postMaterialEventService.enqueueEventNow(DeactivateAllSimulatedCandidatesEvent.builder()
.eventDescriptor(EventDescriptor.ofClientAndOrg(Env.getClientAndOrgId()))
.build());
throw AdempiereException.wrapIfNeeded(exception);
}
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\process\C_Order_ProductionSimulationView_Launcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
private StringRedisTemplate stringRedisTemplate;
@Override
public void set(String key, String value, long expiresInSeconds) {
stringRedisTemplate.opsForValue().set(key, value, expiresInSeconds, TimeUnit.SECONDS);
}
@Override
public boolean exists(String key) {
return stringRedisTemplate.hasKey(key);
}
|
@Override
public void delete(String key) {
stringRedisTemplate.delete(key);
}
@Override
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public Long increment(String key, long val) {
return stringRedisTemplate.opsForValue().increment(key,val);
}
}
|
repos\springboot-demo-master\Captcha\src\main\java\com\et\captcha\service\CaptchaCacheServiceRedisImpl.java
| 2
|
请完成以下Java代码
|
public I_MSV3_Bestellung_Transaction store()
{
final MSV3PurchaseOrderRequestPersister purchaseOrderRequestPersister = MSV3PurchaseOrderRequestPersister.createNewForOrgId(orgId);
final I_MSV3_Bestellung_Transaction transactionRecord = newInstanceOutOfTrx(I_MSV3_Bestellung_Transaction.class);
transactionRecord.setAD_Org_ID(orgId.getRepoId());
final I_MSV3_Bestellung requestRecord = purchaseOrderRequestPersister.storePurchaseOrderRequest(request);
transactionRecord.setMSV3_Bestellung(requestRecord);
if (response != null)
{
final MSV3PurchaseOrderResponsePersister purchaseOrderResponsePersister = MSV3PurchaseOrderResponsePersister.createNewForOrgId(orgId);
final I_MSV3_BestellungAntwort bestellungAntwortRecord = //
purchaseOrderResponsePersister.storePurchaseOrderResponse(response);
transactionRecord.setMSV3_BestellungAntwort(bestellungAntwortRecord);
responseItemPartRepoIds = purchaseOrderResponsePersister.getResponseItemPartRepoIds();
}
if (faultInfo != null)
{
final I_MSV3_FaultInfo faultInfoRecord = Msv3FaultInfoDataPersister
.newInstanceWithOrgId(orgId)
.storeMsv3FaultInfoOrNull(faultInfo);
transactionRecord.setMSV3_FaultInfo(faultInfoRecord);
}
if (otherException != null)
{
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(otherException);
transactionRecord.setAD_Issue_ID(issueId.getRepoId());
}
|
save(transactionRecord);
return transactionRecord;
}
public RuntimeException getExceptionOrNull()
{
if (faultInfo == null && otherException == null)
{
return null;
}
return Msv3ClientException.builder()
.msv3FaultInfo(faultInfo)
.cause(otherException)
.build();
}
public MSV3OrderResponsePackageItemPartRepoId getResponseItemPartRepoId(final OrderResponsePackageItemPartId partId)
{
return responseItemPartRepoIds.getRepoId(partId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\purchaseOrder\MSV3PurchaseOrderTransaction.java
| 1
|
请完成以下Java代码
|
public class ADRefList
{
@Getter @NonNull private final ReferenceId referenceId;
@Getter @NonNull final String name;
@Getter boolean isOrderByValue;
private final ImmutableMap<String, ADRefListItem> itemsByValue;
private final ImmutableList<ADRefListItem> items; // required for toBuilder()
@Builder(toBuilder = true)
private ADRefList(
final @NonNull ReferenceId referenceId,
final @NonNull String name,
final boolean isOrderByValue,
final @NonNull List<ADRefListItem> items)
{
|
this.referenceId = referenceId;
this.name = name;
this.isOrderByValue = isOrderByValue;
this.items = ImmutableList.copyOf(items);
this.itemsByValue = Maps.uniqueIndex(items, ADRefListItem::getValue);
}
public Set<String> getValues() {return itemsByValue.keySet();}
public Collection<ADRefListItem> getItems() {return itemsByValue.values();}
public Optional<ADRefListItem> getItemByValue(@Nullable final String value) {return Optional.ofNullable(itemsByValue.get(value));}
public boolean containsValue(final String value) {return itemsByValue.get(value) != null;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ad_reference\ADRefList.java
| 1
|
请完成以下Java代码
|
private PreparedStatement getFetchStmt(Aggregation aggType, String orderBy) {
switch (orderBy) {
case ASC_ORDER:
if (fetchStmtsAsc == null) {
stmtCreationLock.lock();
try {
if (fetchStmtsAsc == null) {
fetchStmtsAsc = initFetchStmt(orderBy);
}
} finally {
stmtCreationLock.unlock();
}
}
return fetchStmtsAsc[aggType.ordinal()];
case DESC_ORDER:
if (fetchStmtsDesc == null) {
stmtCreationLock.lock();
try {
if (fetchStmtsDesc == null) {
fetchStmtsDesc = initFetchStmt(orderBy);
}
} finally {
stmtCreationLock.unlock();
}
}
return fetchStmtsDesc[aggType.ordinal()];
default:
throw new RuntimeException("Not supported" + orderBy + "order!");
}
}
|
private PreparedStatement[] initFetchStmt(String orderBy) {
PreparedStatement[] fetchStmts = new PreparedStatement[Aggregation.values().length];
for (Aggregation type : Aggregation.values()) {
if (type == Aggregation.SUM && fetchStmts[Aggregation.AVG.ordinal()] != null) {
fetchStmts[type.ordinal()] = fetchStmts[Aggregation.AVG.ordinal()];
} else if (type == Aggregation.AVG && fetchStmts[Aggregation.SUM.ordinal()] != null) {
fetchStmts[type.ordinal()] = fetchStmts[Aggregation.SUM.ordinal()];
} else {
fetchStmts[type.ordinal()] = prepare(SELECT_PREFIX +
String.join(", ", ModelConstants.getFetchColumnNames(type)) + " FROM " + ModelConstants.TS_KV_CF
+ " WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + EQUALS_PARAM
+ "AND " + ModelConstants.ENTITY_ID_COLUMN + EQUALS_PARAM
+ "AND " + ModelConstants.KEY_COLUMN + EQUALS_PARAM
+ "AND " + ModelConstants.PARTITION_COLUMN + EQUALS_PARAM
+ "AND " + ModelConstants.TS_COLUMN + " >= ? "
+ "AND " + ModelConstants.TS_COLUMN + " < ?"
+ (type == Aggregation.NONE ? " ORDER BY " + ModelConstants.TS_COLUMN + " " + orderBy + " LIMIT ?" : ""));
}
}
return fetchStmts;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\CassandraBaseTimeseriesDao.java
| 1
|
请完成以下Java代码
|
public void setMobileUI_UserProfile_DD_CaptionItem_ID (final int MobileUI_UserProfile_DD_CaptionItem_ID)
{
if (MobileUI_UserProfile_DD_CaptionItem_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_CaptionItem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_CaptionItem_ID, MobileUI_UserProfile_DD_CaptionItem_ID);
}
@Override
public int getMobileUI_UserProfile_DD_CaptionItem_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_CaptionItem_ID);
}
@Override
public void setMobileUI_UserProfile_DD_ID (final int MobileUI_UserProfile_DD_ID)
{
if (MobileUI_UserProfile_DD_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, MobileUI_UserProfile_DD_ID);
}
|
@Override
public int getMobileUI_UserProfile_DD_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_DD_CaptionItem.java
| 1
|
请完成以下Java代码
|
public PrintPackage createPackageTypeResponse(final PRTCPrintPackageType xmlPrintPackage)
{
final PRTCPrintPackageType xmlPrintPackageToUse;
if (xmlPrintPackage == null)
{
xmlPrintPackageToUse = factory.createPRTCPrintPackageType();
xmlPrintPackageToUse.getPRTCPrintPackageInfo().add(factory.createPRTCPrintPackageInfoType());
}
else
{
xmlPrintPackageToUse = xmlPrintPackage;
}
final PrintPackage printPckgPC = new PrintPackage();
printPckgPC.setTransactionId(xmlPrintPackageToUse.getTransactionID());
printPckgPC.setPageCount(toInt(xmlPrintPackageToUse.getPageCount(), 0));
printPckgPC.setFormat(xmlPrintPackageToUse.getBinaryFormat());
printPckgPC.setCopies(xmlPrintPackageToUse.getCopies() == null ? 1 : xmlPrintPackageToUse.getCopies().intValue()); // task 08958
if (xmlPrintPackageToUse.getCPrintPackageID() != null
&& xmlPrintPackageToUse.getCPrintJobInstructionsID() == null)
{
logger.log(Level.SEVERE, "Print job Instructions ID cannot be null!");
throw new IllegalArgumentException("Print job Instructions ID cannot be null!");
}
// Avoid NPE, because if printPckgAD.getCPrintPackageID() is null, it means the message is meant to be empty and it's treated elsewhere
if (xmlPrintPackageToUse.getCPrintJobInstructionsID() != null)
{
printPckgPC.setPrintJobInstructionsID(xmlPrintPackageToUse.getCPrintJobInstructionsID().toString());
}
printPckgPC.setPrintPackageInfos(mkPrintPackageInfoList(xmlPrintPackageToUse.getPRTCPrintPackageInfo()));
return printPckgPC;
|
}
private static List<PrintPackageInfo> mkPrintPackageInfoList(final List<PRTCPrintPackageInfoType> printPckgInfosAD)
{
final List<PrintPackageInfo> printPckgInfosPC = new ArrayList<PrintPackageInfo>();
for (final PRTCPrintPackageInfoType printPckgInfoAD : printPckgInfosAD)
{
final PrintPackageInfo printPckgInfoPC = new PrintPackageInfo();
printPckgInfoPC.setPrintService(printPckgInfoAD.getPrintServiceName());
printPckgInfoPC.setTray(printPckgInfoAD.getTrayName());
printPckgInfoPC.setTrayNumber(
printPckgInfoAD.getTrayNumber() == null
? -1
: printPckgInfoAD.getTrayNumber().intValue());
printPckgInfoPC.setPageFrom(toInt(printPckgInfoAD.getPageFrom(), 0));
printPckgInfoPC.setPageTo(toInt(printPckgInfoAD.getPageTo(), 0));
printPckgInfoPC.setCalX(printPckgInfoAD.getCalX() == null ? 0 : printPckgInfoAD.getCalX().intValue());
printPckgInfoPC.setCalY(printPckgInfoAD.getCalY() == null ? 0 : printPckgInfoAD.getCalY().intValue());
printPckgInfosPC.add(printPckgInfoPC);
}
return printPckgInfosPC;
}
private static int toInt(BigInteger value, int defaultValue)
{
return value == null ? defaultValue : value.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\inout\bean\PRTCPrintPackageTypeConverter.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
|
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double calculate() {
double bmi = weight / (height * height);
String formattedBmi = String.format("%.2f", bmi);
return Double.parseDouble(formattedBmi);
}
}
|
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\consoletableoutput\BodyMassIndex.java
| 1
|
请完成以下Java代码
|
public Collection<OutputCaseParameter> getOutputParameters() {
return outputParameterCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Task.class, CMMN_ELEMENT_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(PlanItemDefinition.class)
.instanceProvider(new ModelTypeInstanceProvider<Task>() {
public Task newInstance(ModelTypeInstanceContext instanceContext) {
return new TaskImpl(instanceContext);
}
});
isBlockingAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_IS_BLOCKING)
.defaultValue(true)
.build();
|
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputsCollection = sequenceBuilder.elementCollection(InputsCaseParameter.class)
.build();
outputsCollection = sequenceBuilder.elementCollection(OutputsCaseParameter.class)
.build();
inputParameterCollection = sequenceBuilder.elementCollection(InputCaseParameter.class)
.build();
outputParameterCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TaskImpl.java
| 1
|
请完成以下Java代码
|
public class DeleteIdentityLinkForCaseDefinitionCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String caseDefinitionId;
protected String userId;
protected String groupId;
public DeleteIdentityLinkForCaseDefinitionCmd(String caseDefinitionId, String userId, String groupId) {
validateParams(userId, groupId, caseDefinitionId);
this.caseDefinitionId = caseDefinitionId;
this.userId = userId;
this.groupId = groupId;
}
protected void validateParams(String userId, String groupId, String caseDefinitionId) {
if (caseDefinitionId == null) {
throw new FlowableIllegalArgumentException("caseDefinitionId is null");
}
if (userId == null && groupId == null) {
throw new FlowableIllegalArgumentException("userId and groupId cannot both be null");
}
}
|
@Override
public Void execute(CommandContext commandContext) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
CaseDefinitionEntity caseDefinition = cmmnEngineConfiguration.getCaseDefinitionEntityManager().findById(caseDefinitionId);
if (caseDefinition == null) {
throw new FlowableObjectNotFoundException("Cannot find case definition with id " + caseDefinitionId, CaseDefinition.class);
}
cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService()
.deleteScopeDefinitionIdentityLink(caseDefinition.getId(), ScopeTypes.CMMN, userId, groupId);
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\DeleteIdentityLinkForCaseDefinitionCmd.java
| 1
|
请完成以下Java代码
|
public int getExternalSystem_Config_LeichMehl_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_LeichMehl_ID);
}
@Override
public void setExternalSystemValue (final String ExternalSystemValue)
{
set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue);
}
@Override
public String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
@Override
public void setIsPluFileExportAuditEnabled (final boolean IsPluFileExportAuditEnabled)
{
set_Value (COLUMNNAME_IsPluFileExportAuditEnabled, IsPluFileExportAuditEnabled);
}
@Override
public boolean isPluFileExportAuditEnabled()
{
return get_ValueAsBoolean(COLUMNNAME_IsPluFileExportAuditEnabled);
}
/**
* PluFileDestination AD_Reference_ID=541911
* Reference name: PluFileDestination
*/
public static final int PLUFILEDESTINATION_AD_Reference_ID=541911;
/** Disk = 2DSK */
public static final String PLUFILEDESTINATION_Disk = "2DSK";
/** TCP = 1TCP */
public static final String PLUFILEDESTINATION_TCP = "1TCP";
@Override
public void setPluFileDestination (final java.lang.String PluFileDestination)
{
set_Value (COLUMNNAME_PluFileDestination, PluFileDestination);
}
@Override
public java.lang.String getPluFileDestination()
{
return get_ValueAsString(COLUMNNAME_PluFileDestination);
}
|
@Override
public void setPluFileLocalFolder (final @Nullable java.lang.String PluFileLocalFolder)
{
set_Value (COLUMNNAME_PluFileLocalFolder, PluFileLocalFolder);
}
@Override
public java.lang.String getPluFileLocalFolder()
{
return get_ValueAsString(COLUMNNAME_PluFileLocalFolder);
}
@Override
public void setProduct_BaseFolderName (final String Product_BaseFolderName)
{
set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName);
}
@Override
public String getProduct_BaseFolderName()
{
return get_ValueAsString(COLUMNNAME_Product_BaseFolderName);
}
@Override
public void setTCP_Host (final String TCP_Host)
{
set_Value (COLUMNNAME_TCP_Host, TCP_Host);
}
@Override
public String getTCP_Host()
{
return get_ValueAsString(COLUMNNAME_TCP_Host);
}
@Override
public void setTCP_PortNumber (final int TCP_PortNumber)
{
set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber);
}
@Override
public int getTCP_PortNumber()
{
return get_ValueAsInt(COLUMNNAME_TCP_PortNumber);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class C_InvoiceLine
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
private final IInvoiceLineBL invoiceLineBL = Services.get(IInvoiceLineBL.class);
private final IBPartnerProductBL partnerProductBL = Services.get(IBPartnerProductBL.class);
/**
* Set QtyInvoicedInPriceUOM, just to make sure is up2date.
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void setQtyInvoicedInPriceUOM(final I_C_InvoiceLine invoiceLine)
{
invoiceLineBL.setQtyInvoicedInPriceUOM(invoiceLine);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW })
public void updateIsReadOnly(final I_C_InvoiceLine invoiceLine)
{
invoiceBL.updateInvoiceLineIsReadOnlyFlags(InterfaceWrapperHelper.create(invoiceLine.getC_Invoice(), I_C_Invoice.class), invoiceLine);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE,
}, ifColumnsChanged = I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID)
public void setIsPackagingMaterial(final I_C_InvoiceLine invoiceLine)
{
if (invoiceLine.getC_OrderLine() == null)
{
// in case the c_orderline_id is removed, make sure the flag is on false. The user can set it on true, manually
invoiceLine.setIsPackagingMaterial(false);
return;
}
final de.metas.interfaces.I_C_OrderLine ol = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), de.metas.interfaces.I_C_OrderLine.class);
|
invoiceLine.setIsPackagingMaterial(ol.isPackagingMaterial());
}
/**
* If we have a not-yet-processed invoice line in a verification-set, then allow to delete that line.
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void deleteVerificationData(final I_C_InvoiceLine invoiceLine)
{
queryBL.createQueryBuilder(I_C_Invoice_Verification_SetLine.class)
.addEqualsFilter(I_C_Invoice_Verification_SetLine.COLUMNNAME_C_InvoiceLine_ID, invoiceLine.getC_InvoiceLine_ID())
.create()
.delete();
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_InvoiceLine.COLUMNNAME_M_Product_ID })
public void checkExcludedProducts(final I_C_InvoiceLine invoiceLine)
{
final org.compiere.model.I_C_Invoice invoice = invoiceBL.getById(InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID()));
//Product should always be set, but we can't make it mandatory in db because of existing cases
final ProductId productId = ProductId.ofRepoId(invoiceLine.getM_Product_ID());
final BPartnerId partnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final SOTrx soTrx = SOTrx.ofBooleanNotNull(invoice.isSOTrx());
partnerProductBL.assertNotExcludedFromTransaction(soTrx, productId, partnerId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\interceptor\C_InvoiceLine.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public R<List<MenuVO>> tree() {
List<MenuVO> tree = menuService.tree();
return R.data(tree);
}
/**
* 获取权限分配树形结构
*/
@GetMapping("/grant-tree")
@ApiOperationSupport(order = 10)
@Operation(summary = "权限分配树形结构", description = "权限分配树形结构")
public R<GrantTreeVO> grantTree(BladeUser user) {
GrantTreeVO vo = new GrantTreeVO();
vo.setMenu(menuService.grantTree(user));
vo.setDataScope(menuService.grantDataScopeTree(user));
return R.data(vo);
}
/**
* 获取权限分配树形结构
*/
@GetMapping("/role-tree-keys")
@ApiOperationSupport(order = 11)
@Operation(summary = "角色所分配的树", description = "角色所分配的树")
public R<CheckedTreeVO> roleTreeKeys(String roleIds) {
CheckedTreeVO vo = new CheckedTreeVO();
vo.setMenu(menuService.roleTreeKeys(roleIds));
vo.setDataScope(menuService.dataScopeTreeKeys(roleIds));
return R.data(vo);
}
/**
* 获取配置的角色权限
*/
@GetMapping("auth-routes")
@ApiOperationSupport(order = 12)
@Operation(summary = "菜单的角色权限")
public R<List<Kv>> authRoutes(BladeUser user) {
if (Func.isEmpty(user) || user.getUserId() == 0L) {
return null;
}
return R.data(menuService.authRoutes(user));
}
/**
* 顶部菜单数据
*/
@GetMapping("/top-menu")
@ApiOperationSupport(order = 13)
@Operation(summary = "顶部菜单数据", description = "顶部菜单数据")
public R<List<TopMenu>> topMenu(BladeUser user) {
if (Func.isEmpty(user)) {
return null;
}
List<TopMenu> list = topMenuService.list(Wrappers.<TopMenu>query().lambda().orderByAsc(TopMenu::getSort));
return R.data(list);
}
/**
|
* 获取顶部菜单树形结构
*/
@GetMapping("/grant-top-tree")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
@ApiOperationSupport(order = 14)
@Operation(summary = "顶部菜单树形结构", description = "顶部菜单树形结构")
public R<GrantTreeVO> grantTopTree(BladeUser user) {
GrantTreeVO vo = new GrantTreeVO();
vo.setMenu(menuService.grantTopTree(user));
return R.data(vo);
}
/**
* 获取顶部菜单树形结构
*/
@GetMapping("/top-tree-keys")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
@ApiOperationSupport(order = 15)
@Operation(summary = "顶部菜单所分配的树", description = "顶部菜单所分配的树")
public R<CheckedTreeVO> topTreeKeys(String topMenuIds) {
CheckedTreeVO vo = new CheckedTreeVO();
vo.setMenu(menuService.topTreeKeys(topMenuIds));
return R.data(vo);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\MenuController.java
| 2
|
请完成以下Java代码
|
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_UserGroup getAD_UserGroup() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class);
}
@Override
public void setAD_UserGroup(org.compiere.model.I_AD_UserGroup AD_UserGroup)
{
set_ValueFromPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class, AD_UserGroup);
}
/** Set Nutzergruppe.
@param AD_UserGroup_ID Nutzergruppe */
@Override
public void setAD_UserGroup_ID (int AD_UserGroup_ID)
{
if (AD_UserGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID));
}
/** Get Nutzergruppe.
@return Nutzergruppe */
@Override
|
public int getAD_UserGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Private_Access.java
| 1
|
请完成以下Java代码
|
default void setBPartnerId(@Nullable final BPartnerId bpartnerId)
{
setC_BPartner_ID(BPartnerId.toRepoId(bpartnerId));
}
/**
* Match only those {@link I_M_HU_PI_Item_Product}s which belong to a {@link I_M_ProductPrice} of this PLV.
*/
void setPriceListVersionId(@Nullable final PriceListVersionId priceListVersionId);
@Nullable
PriceListVersionId getPriceListVersionId();
void setDate(@Nullable ZonedDateTime date);
ZonedDateTime getDate();
boolean isAllowAnyProduct();
void setAllowAnyProduct(final boolean allowAnyProduct);
boolean isAllowInfiniteCapacity();
void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity);
String getHU_UnitType();
void setHU_UnitType(final String huUnitType);
boolean isAllowVirtualPI();
void setAllowVirtualPI(final boolean allowVirtualPI);
boolean isOneConfigurationPerPI();
/**
* If true, it will retain only one configuration (i.e. {@link I_M_HU_PI_Item_Product}) for each distinct {@link I_M_HU_PI} found.
*/
void setOneConfigurationPerPI(final boolean oneConfigurationPerPI);
boolean isAllowDifferentCapacities();
/**
* In case {@link #isOneConfigurationPerPI()}, if <code>allowDifferentCapacities</code> is true, it will retain one configuration for each distinct {@link I_M_HU_PI} <b>AND</b>
* {@link I_M_HU_PI_Item_Product#getQty()}.
* </ul>
|
*/
void setAllowDifferentCapacities(boolean allowDifferentCapacities);
// 08393
// the possibility to create the query for any partner (not just for a given one or null)
boolean isAllowAnyPartner();
void setAllowAnyPartner(final boolean allowAnyPartner);
/**
* task: https://metasfresh.atlassian.net/browse/FRESH-386
*/
// @formatter:off
void setM_Product_Packaging_ID(int packagingProductId);
int getM_Product_Packaging_ID();
// @formatter:on
// @formatter:off
void setDefaultForProduct(final boolean defaultForProduct);
boolean isDefaultForProduct();
// @formatter:on
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUPIItemProductQuery.java
| 1
|
请完成以下Java代码
|
private I_M_InventoryLine getInventoryLineRecordFor(final @NotNull InventoryLine inventoryLine)
{
final InventoryAndLineId inventoryAndLineId = InventoryAndLineId.of(inventory.getId(), inventoryLine.getIdNonNull());
final I_M_InventoryLine inventoryLineRecord = inventoryLineRecords.get(inventoryAndLineId);
if (inventoryLineRecord == null)
{
throw new AdempiereException("No inventory line found for " + inventoryAndLineId);
}
return inventoryLineRecord;
}
private IAllocationDestination createAllocationDestination(final @NonNull InventoryLine inventoryLine, final @NonNull InventoryLineHU inventoryLineHU)
{
if (inventoryLineHU.getHuId() == null)
{
if (inventoryLineHU.getHuQRCode() != null)
{
return HUProducerDestination.of(inventoryLineHU.getHuQRCode().getPackingInstructionsId())
.setHUStatus(X_M_HU.HUSTATUS_Active)
.setLocatorId(inventoryLine.getLocatorId());
}
else
{
final InventoryLinePackingInstructions packingInstructions = inventoryLine.getPackingInstructions();
if (packingInstructions.isVHU())
{
return HUProducerDestination.ofVirtualPI()
.setHUStatus(X_M_HU.HUSTATUS_Active)
.setLocatorId(inventoryLine.getLocatorId());
}
else
{
final LUTUProducerDestination lutuProducer = new LUTUProducerDestination();
lutuProducer.setHUStatus(X_M_HU.HUSTATUS_Active);
lutuProducer.setLocatorId(inventoryLine.getLocatorId());
lutuProducer.setTUPI(packingInstructions.getTuPIItemProductId(), inventoryLine.getProductId());
if (packingInstructions.getLuPIId() != null)
{
lutuProducer.setLUPI(packingInstructions.getLuPIId());
lutuProducer.setMaxLUsInfinite();
}
else
{
lutuProducer.setNoLU();
}
|
return lutuProducer;
}
}
}
else
{
final I_M_HU hu = handlingUnitsBL.getById(inventoryLineHU.getHuId());
return HUListAllocationSourceDestination.of(hu, AllocationStrategyType.UNIFORM);
}
}
private static List<I_M_HU> extractCreatedHUs(
@NonNull final IAllocationDestination huDestination)
{
if (huDestination instanceof IHUProducerAllocationDestination)
{
return ((IHUProducerAllocationDestination)huDestination).getCreatedHUs();
}
else
{
throw new HUException("No HU was created by " + huDestination);
}
}
private boolean isIgnoreOnInventoryMinusAndNoHU()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_IgnoreOnInventoryMinusAndNoHU, false);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\impl\SyncInventoryQtyToHUsCommand.java
| 1
|
请完成以下Java代码
|
public boolean isProcessed()
{
return isReconciled();
}
@Override
public DocumentPath getDocumentPath()
{
return null;
}
@Override
public Set<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
|
}
static DocumentId convertPaymentIdToDocumentId(@NonNull final PaymentId paymentId)
{
return DocumentId.of(paymentId);
}
static PaymentId convertDocumentIdToPaymentId(@NonNull final DocumentId rowId)
{
return rowId.toId(PaymentId::ofRepoId);
}
public Amount getPayAmtNegateIfOutbound()
{
return getPayAmt().negateIf(!inboundPayment);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentToReconcileRow.java
| 1
|
请完成以下Java代码
|
public static Optional<InvoiceLineId> ofRepoIdOptional(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
int repoId;
private InvoiceLineId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_InvoiceLine_ID");
}
@JsonValue
@Override
public int getRepoId()
|
{
return repoId;
}
public static int toRepoId(@Nullable final InvoiceLineId invoiceLineId)
{
return toRepoIdOr(invoiceLineId, -1);
}
public static int toRepoIdOr(@Nullable final InvoiceLineId invoiceLineId, final int defaultValue)
{
return invoiceLineId != null ? invoiceLineId.getRepoId() : defaultValue;
}
public static boolean equals(@Nullable final InvoiceLineId id1, @Nullable final InvoiceLineId id2) {return Objects.equals(id1, id2);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\invoice\InvoiceLineId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class NotificationFilterController {
private final FilteringNotifier filteringNotifier;
public NotificationFilterController(FilteringNotifier filteringNotifier) {
this.filteringNotifier = filteringNotifier;
}
@GetMapping(path = "/notifications/filters", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public Collection<NotificationFilter> getFilters() {
return filteringNotifier.getNotificationFilters().values();
}
@PostMapping(path = "/notifications/filters", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addFilter(@RequestParam(name = "instanceId", required = false) String instanceId,
@RequestParam(name = "applicationName", required = false) String name,
@RequestParam(name = "ttl", required = false) Long ttl) {
if (hasText(instanceId) || hasText(name)) {
NotificationFilter filter = createFilter(hasText(instanceId) ? InstanceId.of(instanceId) : null, name, ttl);
filteringNotifier.addFilter(filter);
return ResponseEntity.ok(filter);
}
else {
return ResponseEntity.badRequest().body("Either 'instanceId' or 'applicationName' must be set");
}
}
@DeleteMapping(path = "/notifications/filters/{id}")
public ResponseEntity<Void> deleteFilter(@PathVariable("id") String id) {
NotificationFilter deleted = filteringNotifier.removeFilter(id);
if (deleted != null) {
return ResponseEntity.ok().build();
|
}
else {
return ResponseEntity.notFound().build();
}
}
private NotificationFilter createFilter(@Nullable InstanceId id, String name, @Nullable Long ttl) {
Instant expiry = ((ttl != null) && (ttl >= 0)) ? Instant.now().plusMillis(ttl) : null;
if (id != null) {
return new InstanceIdNotificationFilter(id, expiry);
}
else {
return new ApplicationNameNotificationFilter(name, expiry);
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\filter\web\NotificationFilterController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getIndex() {
return this.index;
}
public void setIndex(String index) {
this.index = index;
}
public String getIndexDateFormat() {
return this.indexDateFormat;
}
public void setIndexDateFormat(String indexDateFormat) {
this.indexDateFormat = indexDateFormat;
}
public String getIndexDateSeparator() {
return this.indexDateSeparator;
}
public void setIndexDateSeparator(String indexDateSeparator) {
this.indexDateSeparator = indexDateSeparator;
}
public String getTimestampFieldName() {
return this.timestampFieldName;
}
public void setTimestampFieldName(String timestampFieldName) {
this.timestampFieldName = timestampFieldName;
}
public boolean isAutoCreateIndex() {
return this.autoCreateIndex;
}
public void setAutoCreateIndex(boolean autoCreateIndex) {
this.autoCreateIndex = autoCreateIndex;
}
public @Nullable String getUserName() {
return this.userName;
}
public void setUserName(@Nullable String userName) {
this.userName = userName;
}
public @Nullable String getPassword() {
return this.password;
|
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getPipeline() {
return this.pipeline;
}
public void setPipeline(@Nullable String pipeline) {
this.pipeline = pipeline;
}
public @Nullable String getApiKeyCredentials() {
return this.apiKeyCredentials;
}
public void setApiKeyCredentials(@Nullable String apiKeyCredentials) {
this.apiKeyCredentials = apiKeyCredentials;
}
public boolean isEnableSource() {
return this.enableSource;
}
public void setEnableSource(boolean enableSource) {
this.enableSource = enableSource;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Payer payer = (Payer) o;
return Objects.equals(this._id, payer._id) &&
Objects.equals(this.name, payer.name) &&
Objects.equals(this.type, payer.type) &&
Objects.equals(this.ikNumber, payer.ikNumber) &&
Objects.equals(this.timestamp, payer.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(_id, name, type, ikNumber, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Payer {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
|
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" ikNumber: ").append(toIndentedString(ikNumber)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Payer.java
| 2
|
请完成以下Java代码
|
public static APITransactionId ofString(@NonNull final String value)
{
return new APITransactionId(value);
}
public static Optional<APITransactionId> optionalOfString(@Nullable final String value)
{
return Check.isNotBlank(value) ? Optional.of(ofString(value)) : Optional.empty();
}
private final String value;
private APITransactionId(@NonNull final String value)
{
Check.assumeNotEmpty(value, "value is not empty");
|
this.value = value;
}
@Override
@Deprecated
public String toString()
{
return toJson();
}
@JsonValue
public String toJson()
{
return value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\exportaudit\APITransactionId.java
| 1
|
请完成以下Java代码
|
public void fireCamundaEngineStartEvent() {
Arc.container().beanManager()
.getEvent()
.select(CamundaEngineStartupEvent.class)
.fire(new CamundaEngineStartupEvent());
}
public void registerShutdownTask(ShutdownContext shutdownContext,
RuntimeValue<ProcessEngine> processEngine) {
// cleanup on application shutdown
shutdownContext.addShutdownTask(() -> {
ProcessEngine engine = processEngine.getValue();
// shutdown the JobExecutor
ProcessEngineConfigurationImpl configuration
= (ProcessEngineConfigurationImpl) engine.getProcessEngineConfiguration();
JobExecutor executor = configuration.getJobExecutor();
executor.shutdown();
// deregister the Process Engine from the runtime container delegate
RuntimeContainerDelegate runtimeContainerDelegate = RuntimeContainerDelegate.INSTANCE.get();
runtimeContainerDelegate.unregisterProcessEngine(engine);
});
}
protected void configureJobExecutor(ProcessEngineConfigurationImpl configuration,
CamundaEngineConfig config) {
int maxPoolSize = config.jobExecutor().threadPool().maxPoolSize();
int queueSize = config.jobExecutor().threadPool().queueSize();
|
// create a non-bean ManagedExecutor instance. This instance
// uses it's own Executor/thread pool.
ManagedExecutor managedExecutor = SmallRyeManagedExecutor.builder()
.maxQueued(queueSize)
.maxAsync(maxPoolSize)
.withNewExecutorService()
.build();
ManagedJobExecutor quarkusJobExecutor = new ManagedJobExecutor(managedExecutor);
// apply job executor configuration properties
PropertyHelper
.applyProperties(quarkusJobExecutor, config.jobExecutor().genericConfig(), PropertyHelper.KEBAB_CASE);
configuration.setJobExecutor(quarkusJobExecutor);
}
/**
* Retrieves a bean of the given class from the bean container.
*
* @param beanClass the class of the desired bean to fetch from the container
* @param beanContainer the bean container
* @param <T> the type of the bean to fetch
* @return the bean
*/
protected <T> T getBeanFromContainer(Class<T> beanClass, BeanContainer beanContainer) {
try (BeanContainer.Instance<T> beanManager = beanContainer.beanInstanceFactory(beanClass).create()) {
return beanManager.get();
}
}
}
|
repos\camunda-bpm-platform-master\quarkus-extension\engine\runtime\src\main\java\org\camunda\bpm\quarkus\engine\extension\impl\CamundaEngineRecorder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getDLM_Partition_Config_Reference_ID()
{
return DLM_Partition_Config_Reference_ID;
}
public RefBuilder setIsPartitionBoundary(final boolean partitionBoundary)
{
this.partitionBoundary = partitionBoundary;
return this;
}
public LineBuilder endRef()
{
return parentbuilder.endRef();
}
/**
* Convenience method to end the current ref builder and start a new one.
*
* @return the new reference builder, <b>not</b> this instance.
*/
public RefBuilder newRef()
{
return endRef().ref();
}
/**
* Supposed to be called only by the parent builder.
*
* @param parent
* @return
*/
/* package */ PartitionerConfigReference build(final PartitionerConfigLine parent)
{
final PartitionerConfigReference partitionerConfigReference = new PartitionerConfigReference(parent, referencingColumnName, referencedTableName, partitionBoundary);
partitionerConfigReference.setDLM_Partition_Config_Reference_ID(DLM_Partition_Config_Reference_ID);
return partitionerConfigReference;
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(referencedTableName)
.append(referencingColumnName)
.append(parentbuilder)
.toHashcode();
};
/**
* Note: it's important not to include {@link #getDLM_Partition_Config_Reference_ID()} in the result.
* Check the implementation of {@link PartitionerConfigLine.LineBuilder#endRef()} for details.
*/
@Override
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final RefBuilder other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(referencedTableName, other.referencedTableName)
.append(referencingColumnName, other.referencingColumnName)
.append(parentbuilder, other.parentbuilder)
.isEqual();
}
@Override
public String toString()
{
return "RefBuilder [referencingColumnName=" + referencingColumnName + ", referencedTableName=" + referencedTableName + ", partitionBoundary=" + partitionBoundary + ", DLM_Partition_Config_Reference_ID=" + DLM_Partition_Config_Reference_ID + "]";
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionerConfigReference.java
| 2
|
请完成以下Java代码
|
public class X_AD_DocType_BoilerPlate extends org.compiere.model.PO implements I_AD_DocType_BoilerPlate, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 2032686751L;
/** Standard Constructor */
public X_AD_DocType_BoilerPlate (final Properties ctx, final int AD_DocType_BoilerPlate_ID, @Nullable final String trxName)
{
super (ctx, AD_DocType_BoilerPlate_ID, trxName);
}
/** Load Constructor */
public X_AD_DocType_BoilerPlate (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 setAD_BoilerPlate_ID (final int AD_BoilerPlate_ID)
{
if (AD_BoilerPlate_ID < 1)
set_Value (COLUMNNAME_AD_BoilerPlate_ID, null);
else
set_Value (COLUMNNAME_AD_BoilerPlate_ID, AD_BoilerPlate_ID);
}
@Override
public int getAD_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BoilerPlate_ID);
}
@Override
public void setAD_DocType_BoilerPlate_ID (final int AD_DocType_BoilerPlate_ID)
{
if (AD_DocType_BoilerPlate_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_DocType_BoilerPlate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_DocType_BoilerPlate_ID, AD_DocType_BoilerPlate_ID);
}
@Override
public int getAD_DocType_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_DocType_BoilerPlate_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
|
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_DocType_BoilerPlate.java
| 1
|
请完成以下Java代码
|
public void rollback() {
// Just in case the rollback isn't triggered by an
// exception, we mark the current transaction rollBackOnly.
transactionManager.getTransaction(null).setRollbackOnly();
}
public void addTransactionListener(
final TransactionState transactionState,
final TransactionListener transactionListener
) {
if (transactionState.equals(TransactionState.COMMITTING)) {
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
@Override
public void beforeCommit(boolean readOnly) {
transactionListener.execute(commandContext);
}
}
);
} else if (transactionState.equals(TransactionState.COMMITTED)) {
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
transactionListener.execute(commandContext);
}
}
);
} else if (transactionState.equals(TransactionState.ROLLINGBACK)) {
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
@Override
public void beforeCompletion() {
transactionListener.execute(commandContext);
}
}
);
} else if (transactionState.equals(TransactionState.ROLLED_BACK)) {
|
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
@Override
public void afterCompletion(int status) {
if (TransactionSynchronization.STATUS_ROLLED_BACK == status) {
transactionListener.execute(commandContext);
}
}
}
);
}
}
protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered {
public void suspend() {}
public void resume() {}
public void flush() {}
public void beforeCommit(boolean readOnly) {}
public void beforeCompletion() {}
public void afterCommit() {}
public void afterCompletion(int status) {}
@Override
public int getOrder() {
return transactionSynchronizationAdapterOrder;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringTransactionContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RuntimeParametersProcessor implements Processor
{
@Override
public void process(final Exchange exchange) throws Exception
{
final ImportOrdersRouteContext context =
ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_ORDERS_CONTEXT, ImportOrdersRouteContext.class);
final Optional<Instant> nextImportStartingTimestamp = context.getNextImportStartingTimestamp();
if (nextImportStartingTimestamp.isEmpty())
{
//nothing to do
exchange.getIn().setBody(null);
return;
|
}
final JsonRuntimeParameterUpsertItem runtimeParameterUpsertItem = JsonRuntimeParameterUpsertItem.builder()
.externalSystemParentConfigId(context.getExternalSystemRequest().getExternalSystemConfigId())
.name(PARAM_UPDATED_AFTER)
.request(context.getExternalSystemRequest().getCommand())
.value(nextImportStartingTimestamp.get().toString())
.build();
final JsonESRuntimeParameterUpsertRequest request = JsonESRuntimeParameterUpsertRequest.builder()
.runtimeParameterUpsertItems(ImmutableList.of(runtimeParameterUpsertItem))
.build();
exchange.getIn().setBody(request);
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\order\processor\RuntimeParametersProcessor.java
| 2
|
请完成以下Java代码
|
public SEPACreditTransferXML exportCreditTransferXML(@NonNull final I_SEPA_Export sepaExport, @NonNull final SEPAExportContext exportContext)
{
final SEPAProtocol protocol = SEPAProtocol.ofCode(sepaExport.getSEPA_Protocol());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final SEPAMarshaler marshaler = newSEPAMarshaler(protocol, exportContext);
try
{
marshaler.marshal(sepaExport, out);
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
return SEPACreditTransferXML.builder()
.filename(FileUtil.stripIllegalCharacters(sepaExport.getDocumentNo()) + ".xml")
.contentType(MimeType.TYPE_XML)
.content(out.toByteArray())
.build();
}
|
private SEPAMarshaler newSEPAMarshaler(@NonNull final SEPAProtocol protocol, @NonNull final SEPAExportContext exportContext)
{
if (SEPAProtocol.CREDIT_TRANSFER_PAIN_001_001_03_CH_02.equals(protocol))
{
final BankRepository bankRepository = SpringContextHolder.instance.getBean(BankRepository.class);
return new SEPAVendorCreditTransferMarshaler_Pain_001_001_03_CH_02(bankRepository, exportContext, bankAccountService);
}
else if (SEPAProtocol.DIRECT_DEBIT_PAIN_008_003_02.equals(protocol))
{
return new SEPACustomerDirectDebitMarshaler_Pain_008_003_02(bankAccountService);
}
else
{
throw new AdempiereException("Unknown SEPA protocol: " + protocol);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\SEPADocumentBL.java
| 1
|
请完成以下Java代码
|
public static String toString(Object... elements) {
StringBuilder sb = new StringBuilder();
if (isEnabled()) {
buildEnabled(sb, elements);
}
else {
buildDisabled(sb, elements);
}
return sb.toString();
}
private static void buildEnabled(StringBuilder sb, Object[] elements) {
boolean writingAnsi = false;
boolean containsEncoding = false;
for (Object element : elements) {
if (element instanceof AnsiElement) {
containsEncoding = true;
if (!writingAnsi) {
sb.append(ENCODE_START);
writingAnsi = true;
}
else {
sb.append(ENCODE_JOIN);
}
}
else {
if (writingAnsi) {
sb.append(ENCODE_END);
writingAnsi = false;
}
}
sb.append(element);
}
if (containsEncoding) {
sb.append(writingAnsi ? ENCODE_JOIN : ENCODE_START);
sb.append(RESET);
sb.append(ENCODE_END);
}
}
private static void buildDisabled(StringBuilder sb, @Nullable Object[] elements) {
for (Object element : elements) {
if (!(element instanceof AnsiElement) && element != null) {
sb.append(element);
}
}
}
private static boolean isEnabled() {
if (enabled == Enabled.DETECT) {
if (ansiCapable == null) {
ansiCapable = detectIfAnsiCapable();
}
return ansiCapable;
}
return enabled == Enabled.ALWAYS;
}
|
private static boolean detectIfAnsiCapable() {
try {
if (Boolean.FALSE.equals(consoleAvailable)) {
return false;
}
if (consoleAvailable == null) {
Console console = System.console();
if (console == null) {
return false;
}
Method isTerminalMethod = ClassUtils.getMethodIfAvailable(Console.class, "isTerminal");
if (isTerminalMethod != null) {
Boolean isTerminal = (Boolean) isTerminalMethod.invoke(console);
if (Boolean.FALSE.equals(isTerminal)) {
return false;
}
}
}
return !(OPERATING_SYSTEM_NAME.contains("win"));
}
catch (Throwable ex) {
return false;
}
}
/**
* Possible values to pass to {@link AnsiOutput#setEnabled}. Determines when to output
* ANSI escape sequences for coloring application output.
*/
public enum Enabled {
/**
* Try to detect whether ANSI coloring capabilities are available. The default
* value for {@link AnsiOutput}.
*/
DETECT,
/**
* Enable ANSI-colored output.
*/
ALWAYS,
/**
* Disable ANSI-colored output.
*/
NEVER
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiOutput.java
| 1
|
请完成以下Java代码
|
public List<OptimizeHistoricIdentityLinkLogEntity> getHistoricIdentityLinkLogs(Date occurredAfter,
Date occurredAt,
int maxResults) {
return commandExecutor.execute(
new OptimizeHistoricIdentityLinkLogQueryCmd(occurredAfter, occurredAt, maxResults)
);
}
public List<HistoricProcessInstance> getCompletedHistoricProcessInstances(Date finishedAfter,
Date finishedAt,
int maxResults) {
return commandExecutor.execute(
new OptimizeCompletedHistoricProcessInstanceQueryCmd(finishedAfter, finishedAt, maxResults)
);
}
public List<HistoricProcessInstance> getRunningHistoricProcessInstances(Date startedAfter,
Date startedAt,
int maxResults) {
return commandExecutor.execute(
new OptimizeRunningHistoricProcessInstanceQueryCmd(startedAfter, startedAt, maxResults)
);
}
public List<HistoricVariableUpdate> getHistoricVariableUpdates(Date occurredAfter,
Date occurredAt,
boolean excludeObjectValues,
int maxResults) {
return commandExecutor.execute(
new OptimizeHistoricVariableUpdateQueryCmd(occurredAfter, occurredAt, excludeObjectValues, maxResults)
);
}
public List<HistoricIncidentEntity> getCompletedHistoricIncidents(Date finishedAfter,
Date finishedAt,
|
int maxResults) {
return commandExecutor.execute(
new OptimizeCompletedHistoricIncidentsQueryCmd(finishedAfter, finishedAt, maxResults)
);
}
public List<HistoricIncidentEntity> getOpenHistoricIncidents(Date createdAfter,
Date createdAt,
int maxResults) {
return commandExecutor.execute(
new OptimizeOpenHistoricIncidentsQueryCmd(createdAfter, createdAt, maxResults)
);
}
public List<HistoricDecisionInstance> getHistoricDecisionInstances(Date evaluatedAfter,
Date evaluatedAt,
int maxResults) {
return commandExecutor.execute(
new OptimizeHistoricDecisionInstanceQueryCmd(evaluatedAfter, evaluatedAt, maxResults)
);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\OptimizeService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ListenableFuture<JsonNode> executeJsonAsync(TbMsg msg) {
return executeScriptAsync(msg);
}
@Override
protected String executeToStringTransform(JsonNode result) {
if (result.isTextual()) {
return result.asText();
}
throw wrongResultType(result);
}
@Override
protected JsonNode convertResult(Object result) {
return JacksonUtil.toJsonNode(result != null ? result.toString() : null);
}
private static TbMsg unbindMsg(JsonNode msgData, TbMsg msg) {
String data = null;
Map<String, String> metadata = null;
String messageType = null;
if (msgData.has(RuleNodeScriptFactory.MSG)) {
JsonNode msgPayload = msgData.get(RuleNodeScriptFactory.MSG);
data = JacksonUtil.toString(msgPayload);
}
if (msgData.has(RuleNodeScriptFactory.METADATA)) {
JsonNode msgMetadata = msgData.get(RuleNodeScriptFactory.METADATA);
|
metadata = JacksonUtil.convertValue(msgMetadata, new TypeReference<>() {});
}
if (msgData.has(RuleNodeScriptFactory.MSG_TYPE)) {
messageType = msgData.get(RuleNodeScriptFactory.MSG_TYPE).asText();
}
String newData = data != null ? data : msg.getData();
TbMsgMetaData newMetadata = metadata != null ? new TbMsgMetaData(metadata) : msg.getMetaData().copy();
String newMessageType = StringUtils.isNotEmpty(messageType) ? messageType : msg.getType();
return msg.transform()
.type(newMessageType)
.metaData(newMetadata)
.data(newData)
.build();
}
private TbScriptException wrongResultType(JsonNode result) {
return new TbScriptException(scriptId, TbScriptException.ErrorCode.RUNTIME, null, new ClassCastException("Wrong result type: " + result.getNodeType()));
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\script\RuleNodeJsScriptEngine.java
| 2
|
请完成以下Java代码
|
public <T> EqualsBuilder appendByRef(final T value1, final T value2)
{
if (!isEqual)
{
return this;
}
if (value1 != value2)
{
isEqual = false;
}
return this;
}
public EqualsBuilder append(final Map<String, Object> map1, final Map<String, Object> map2, final boolean handleEmptyAsNull)
{
if (!isEqual)
{
return this;
}
if (handleEmptyAsNull)
{
final Object value1 = map1 == null || map1.isEmpty() ? null : map1;
final Object value2 = map2 == null || map2.isEmpty() ? null : map2;
return append(value1, value2);
}
return append(map1, map2);
}
public boolean isEqual()
{
return isEqual;
}
/**
* Checks and casts <code>other</code> to same class as <code>obj</code>.
*
* This method shall be used as first statement in an {@link Object#equals(Object)} implementation. <br/>
* <br/>
* Example:
*
* <pre>
* public boolean equals(Object obj)
* {
* if (this == obj)
* {
* return true;
* }
* final MyClass other = EqualsBuilder.getOther(this, obj);
* if (other == null)
* {
* return false;
* }
*
* return new EqualsBuilder()
* .append(prop1, other.prop1)
* .append(prop2, other.prop2)
* .append(prop3, other.prop3)
* // ....
* .isEqual();
* }
* </pre>
|
*
* @param thisObj this object
* @param obj other object
* @return <code>other</code> casted to same class as <code>obj</code> or null if <code>other</code> is null or does not have the same class
*/
public static <T> T getOther(final T thisObj, final Object obj)
{
if (thisObj == null)
{
throw new IllegalArgumentException("obj is null");
}
if (thisObj == obj)
{
@SuppressWarnings("unchecked")
final T otherCasted = (T)obj;
return otherCasted;
}
if (obj == null)
{
return null;
}
if (thisObj.getClass() != obj.getClass())
{
return null;
}
@SuppressWarnings("unchecked")
final T otherCasted = (T)obj;
return otherCasted;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\EqualsBuilder.java
| 1
|
请完成以下Java代码
|
public final class ListUtils
{
private ListUtils()
{
}
public static List<Integer> asList(final int... arr)
{
if (arr == null || arr.length == 0)
{
return Collections.emptyList();
}
final List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr)
{
list.add(i);
}
return list;
}
/**
* Creates a copy as list of given iterable.
*
* @param iterable
* @return list or null if the parameter was null
*/
public static final <T> List<T> copyAsList(final Iterable<? extends T> iterable)
{
if (iterable == null)
{
return null;
}
if (iterable instanceof Collection)
{
final Collection<? extends T> col = (Collection<? extends T>)iterable;
return new ArrayList<>(col);
}
else
{
final List<T> list = new ArrayList<>();
for (final T item : iterable)
{
list.add(item);
}
return list;
}
}
/**
* Creates a new list having all elements from given <code>list</code> in reversed order.
*
* NOTE: returning list is not guaranteed to me modifiable.
*
* @param list
* @return
*/
public static <T> List<T> copyAndReverse(final List<T> list)
{
if (list == null)
{
return null;
|
}
if (list.isEmpty())
{
return Collections.emptyList();
}
final List<T> listCopy = new ArrayList<>(list);
Collections.reverse(listCopy);
return listCopy;
}
/**
* @param list
* @param predicate
* @return a filtered copy of given list
*/
public static final <E> List<E> copyAndFilter(final List<? extends E> list, final Predicate<? super E> predicate)
{
final List<E> copy = new ArrayList<>();
for (final E element : list)
{
if (predicate.apply(element))
{
copy.add(element);
}
}
return copy;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\ListUtils.java
| 1
|
请完成以下Java代码
|
public class DefaultLazyPropertyFilter implements EncryptablePropertyFilter {
private Singleton<EncryptablePropertyFilter> singleton;
/**
* <p>Constructor for DefaultLazyPropertyFilter.</p>
*
* @param e a {@link org.springframework.core.env.ConfigurableEnvironment} object
* @param customFilterBeanName a {@link java.lang.String} object
* @param isCustom a boolean
* @param bf a {@link org.springframework.beans.factory.BeanFactory} object
*/
public DefaultLazyPropertyFilter(ConfigurableEnvironment e, String customFilterBeanName, boolean isCustom, BeanFactory bf) {
singleton = new Singleton<>(() ->
Optional.of(customFilterBeanName)
.filter(bf::containsBean)
.map(name -> (EncryptablePropertyFilter) bf.getBean(name))
.map(tap(bean -> log.info("Found Custom Filter Bean {} with name: {}", bean, customFilterBeanName)))
.orElseGet(() -> {
if (isCustom) {
throw new IllegalStateException(String.format("Property Filter custom Bean not found with name '%s'", customFilterBeanName));
}
log.info("Property Filter custom Bean not found with name '{}'. Initializing Default Property Filter", customFilterBeanName);
return createDefault(e);
}));
}
/**
* <p>Constructor for DefaultLazyPropertyFilter.</p>
*
* @param environment a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public DefaultLazyPropertyFilter(ConfigurableEnvironment environment) {
singleton = new Singleton<>(() -> createDefault(environment));
|
}
private DefaultPropertyFilter createDefault(ConfigurableEnvironment environment) {
JasyptEncryptorConfigurationProperties props = JasyptEncryptorConfigurationProperties.bindConfigProps(environment);
final JasyptEncryptorConfigurationProperties.PropertyConfigurationProperties.FilterConfigurationProperties filterConfig = props.getProperty().getFilter();
return new DefaultPropertyFilter(filterConfig.getIncludeSources(), filterConfig.getExcludeSources(),
filterConfig.getIncludeNames(), filterConfig.getExcludeNames());
}
/** {@inheritDoc} */
@Override
public boolean shouldInclude(PropertySource<?> source, String name) {
return singleton.get().shouldInclude(source, name);
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\filter\DefaultLazyPropertyFilter.java
| 1
|
请完成以下Java代码
|
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceManager() {
return getSession(HistoricActivityInstanceEntityManager.class);
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceManager() {
return getSession(HistoricVariableInstanceEntityManager.class);
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
}
protected AttachmentEntityManager getAttachmentManager() {
return getSession(AttachmentEntityManager.class);
}
|
protected HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return Context.getProcessEngineConfiguration();
}
@Override
public void close() {
}
@Override
public void flush() {
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getScopeDefinitionId() {
return job.getScopeDefinitionId();
}
@Override
public String getCorrelationId() {
return job.getCorrelationId();
}
@Override
public boolean isExclusive() {
return job.isExclusive();
}
@Override
public Date getCreateTime() {
return job.getCreateTime();
}
@Override
public String getId() {
return job.getId();
}
@Override
public int getRetries() {
return job.getRetries();
}
@Override
public String getExceptionMessage() {
return job.getExceptionMessage();
}
@Override
public String getTenantId() {
|
return job.getTenantId();
}
@Override
public String getJobHandlerType() {
return job.getJobHandlerType();
}
@Override
public String getJobHandlerConfiguration() {
return job.getJobHandlerConfiguration();
}
@Override
public String getCustomValues() {
return job.getCustomValues();
}
@Override
public String getLockOwner() {
return job.getLockOwner();
}
@Override
public Date getLockExpirationTime() {
return job.getLockExpirationTime();
}
@Override
public String toString() {
return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]")
.add("job=" + job)
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.