instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class DemoController {
@Autowired
private UserServiceFeignClient userServiceFeignClient;
@GetMapping("/test01")
public UserResponse test01() {
return userServiceFeignClient.get(1);
// System.out.println("编号:" + user.getId());
// System.out.println("昵称:" + user.getName());
// System.out.println("性别:" + user.getGender());
}
@GetMapping("/test02A")
public List<UserResponse> test02A() {
return userServiceFeignClient.list("你猜", 1); | }
@GetMapping("/test02B")
public List<UserResponse> test02B() {
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("name", "昵称");
return userServiceFeignClient.list(queryMap);
}
@GetMapping("/test03")
public Integer test03() {
return userServiceFeignClient.add(new UserAddRequest()
.setName("昵称").setGender(1));
}
} | repos\SpringBoot-Labs-master\lab-58\lab-58-feign-demo\src\main\java\cn\iocoder\springboot\lab58\feigndemo\controller\DemoController.java | 2 |
请完成以下Java代码 | public void setHasExpenseLoading(Boolean value) {
this.hasExpenseLoading = value;
}
/**
* Gets the value of the doCostAssessment property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isDoCostAssessment() {
if (doCostAssessment == null) {
return false;
} else { | return doCostAssessment;
}
}
/**
* Sets the value of the doCostAssessment property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setDoCostAssessment(Boolean value) {
this.doCostAssessment = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraStationaryType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | final class GlobalMethodSecuritySelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
Class<EnableGlobalMethodSecurity> annoType = EnableGlobalMethodSecurity.class;
Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(annoType.getName(),
false);
AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationAttributes);
Assert.notNull(attributes, () -> String.format("@%s is not present on importing class '%s' as expected",
annoType.getSimpleName(), importingClassMetadata.getClassName()));
// TODO would be nice if could use BeanClassLoaderAware (does not work)
Class<?> importingClass = ClassUtils.resolveClassName(importingClassMetadata.getClassName(),
ClassUtils.getDefaultClassLoader());
boolean skipMethodSecurityConfiguration = GlobalMethodSecurityConfiguration.class
.isAssignableFrom(importingClass);
AdviceMode mode = attributes.getEnum("mode");
boolean isProxy = AdviceMode.PROXY == mode;
String autoProxyClassName = isProxy ? AutoProxyRegistrar.class.getName()
: GlobalMethodSecurityAspectJAutoProxyRegistrar.class.getName(); | boolean jsr250Enabled = attributes.getBoolean("jsr250Enabled");
List<String> classNames = new ArrayList<>(4);
if (isProxy) {
classNames.add(MethodSecurityMetadataSourceAdvisorRegistrar.class.getName());
}
classNames.add(autoProxyClassName);
if (!skipMethodSecurityConfiguration) {
classNames.add(GlobalMethodSecurityConfiguration.class.getName());
}
if (jsr250Enabled) {
classNames.add(Jsr250MetadataSourceConfiguration.class.getName());
}
return classNames.toArray(new String[0]);
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecuritySelector.java | 2 |
请完成以下Java代码 | protected Map<Class<? extends DbEntity>, DbOperation> performProcessCleanup() {
return Context
.getCommandContext()
.getHistoricProcessInstanceManager()
.deleteHistoricProcessInstancesByRemovalTime(ClockUtil.getCurrentTime(),
configuration.getMinuteFrom(), configuration.getMinuteTo(), getBatchSize());
}
protected DbOperation performBatchCleanup() {
return Context
.getCommandContext()
.getHistoricBatchManager()
.deleteHistoricBatchesByRemovalTime(ClockUtil.getCurrentTime(),
configuration.getMinuteFrom(), configuration.getMinuteTo(), getBatchSize());
}
protected DbOperation performTaskMetricsCleanup() {
return Context
.getCommandContext()
.getMeterLogManager()
.deleteTaskMetricsByRemovalTime(ClockUtil.getCurrentTime(), getTaskMetricsTimeToLive(),
configuration.getMinuteFrom(), configuration.getMinuteTo(), getBatchSize());
}
protected Map<String, Long> reportMetrics() {
Map<String, Long> reports = new HashMap<>();
DbOperation deleteOperationProcessInstance = deleteOperations.get(HistoricProcessInstanceEntity.class);
if (deleteOperationProcessInstance != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_PROCESS_INSTANCES, (long) deleteOperationProcessInstance.getRowsAffected());
}
DbOperation deleteOperationDecisionInstance = deleteOperations.get(HistoricDecisionInstanceEntity.class);
if (deleteOperationDecisionInstance != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_DECISION_INSTANCES, (long) deleteOperationDecisionInstance.getRowsAffected());
}
DbOperation deleteOperationBatch = deleteOperations.get(HistoricBatchEntity.class);
if (deleteOperationBatch != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_BATCH_OPERATIONS, (long) deleteOperationBatch.getRowsAffected());
}
DbOperation deleteOperationTaskMetric = deleteOperations.get(TaskMeterLogEntity.class);
if (deleteOperationTaskMetric != null) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_TASK_METRICS, (long) deleteOperationTaskMetric.getRowsAffected());
}
return reports;
}
protected boolean isDmnEnabled() {
return Context
.getProcessEngineConfiguration() | .isDmnEnabled();
}
protected Integer getTaskMetricsTimeToLive() {
return Context
.getProcessEngineConfiguration()
.getParsedTaskMetricsTimeToLive();
}
protected boolean shouldRescheduleNow() {
int batchSize = getBatchSize();
for (DbOperation deleteOperation : deleteOperations.values()) {
if (deleteOperation.getRowsAffected() == batchSize) {
return true;
}
}
return false;
}
public int getBatchSize() {
return Context
.getProcessEngineConfiguration()
.getHistoryCleanupBatchSize();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupRemovalTime.java | 1 |
请完成以下Java代码 | public MonitorConfig getMonitor() {
return this.monitor;
}
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
}
public ProviderConfig getProvider() {
return this.provider;
}
public void setProvider(ProviderConfig provider) {
this.provider = provider;
}
public ConsumerConfig getConsumer() {
return this.consumer;
}
public void setConsumer(ConsumerConfig consumer) {
this.consumer = consumer;
}
public Map<String, ApplicationConfig> getApplications() {
return this.applications;
}
public void setApplications(Map<String, ApplicationConfig> applications) {
this.applications = applications;
}
public Map<String, ModuleConfig> getModules() {
return this.modules;
}
public void setModules(Map<String, ModuleConfig> modules) {
this.modules = modules;
}
public Map<String, RegistryConfig> getRegistries() {
return this.registries;
}
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return this.protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
} | public Map<String, MonitorConfig> getMonitors() {
return this.monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return this.providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return this.consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
@Override
public String toString() {
return "DubboProperties [server=" + this.server + ", application=" + this.application
+ ", module=" + this.module + ", registry=" + this.registry + ", protocol=" + this.protocol
+ ", monitor=" + this.monitor + ", provider=" + this.provider + ", consumer="
+ this.consumer + ", applications=" + this.applications + ", modules=" + this.modules
+ ", registries=" + this.registries + ", protocols=" + this.protocols + ", monitors="
+ this.monitors + ", providers=" + this.providers + ", consumers=" + this.consumers + "]";
}
} | repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboProperties.java | 1 |
请完成以下Java代码 | public String getDescription()
{
return "1.4";
} // getDescription
/**
* Get Number Servers
*
* @return no of servers
*/
public String getServerCount()
{
int noRunning = 0;
int noStopped = 0;
for (int i = 0; i < m_servers.size(); i++)
{
AdempiereServer server = m_servers.get(i);
if (server.isAlive())
noRunning++;
else
noStopped++;
}
String info = String.valueOf(m_servers.size()) | + " - Running=" + noRunning
+ " - Stopped=" + noStopped;
return info;
} // getServerCount
/**
* Get start date
*
* @return start date
*/
public Timestamp getStartTime()
{
return new Timestamp(m_start.getTime());
} // getStartTime
} // AdempiereServerMgr | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AdempiereServerMgr.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void sendRpcRequestToDevice(ToDeviceRpcRequest msg) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, msg.getTenantId(), msg.getDeviceId());
ToDeviceRpcRequestActorMsg rpcMsg = new ToDeviceRpcRequestActorMsg(serviceId, msg);
if (tpi.isMyPartition()) {
log.trace("[{}] Forwarding msg {} to device actor!", msg.getDeviceId(), msg);
if (tbCoreRpcService.isPresent()) {
tbCoreRpcService.get().forwardRpcRequestToDeviceActor(rpcMsg);
} else {
log.warn("Failed to find tbCoreRpcService for local service. Possible duplication of serviceIds.");
}
} else {
log.trace("[{}] Forwarding msg {} to queue actor!", msg.getDeviceId(), msg);
clusterService.pushMsgToCore(rpcMsg, null);
}
}
private void sendRpcResponseToTbCore(String originServiceId, FromDeviceRpcResponse response) {
if (serviceId.equals(originServiceId)) {
if (tbCoreRpcService.isPresent()) {
tbCoreRpcService.get().processRpcResponseFromRuleEngine(response);
} else {
log.warn("Failed to find tbCoreRpcService for local service. Possible duplication of serviceIds.");
}
} else { | clusterService.pushNotificationToCore(originServiceId, response, null);
}
}
private void scheduleTimeout(ToDeviceRpcRequest request, UUID requestId) {
long timeout = Math.max(0, request.getExpirationTime() - System.currentTimeMillis()) + TimeUnit.SECONDS.toMillis(1);
log.trace("[{}] processing the request: [{}]", this.hashCode(), requestId);
scheduler.schedule(() -> {
log.trace("[{}] timeout the request: [{}]", this.hashCode(), requestId);
Consumer<FromDeviceRpcResponse> consumer = toDeviceRpcRequests.remove(requestId);
if (consumer != null) {
scheduler.submit(() -> consumer.accept(new FromDeviceRpcResponse(requestId, null, RpcError.TIMEOUT)));
}
}, timeout, TimeUnit.MILLISECONDS);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\rpc\DefaultTbRuleEngineRpcService.java | 2 |
请完成以下Java代码 | public IAutoCloseable switchContext(final Properties ctx)
{
Check.assumeNotNull(ctx, "ctx not null");
// Avoid StackOverflowException caused by setting the same context
if (ctx == this)
{
return NullAutoCloseable.instance;
}
final long threadIdOnSet = Thread.currentThread().getId();
final Properties ctxOld = threadLocalContext.get();
threadLocalContext.set(ctx);
return new IAutoCloseable()
{
private boolean closed = false;
@Override
public void close()
{
// Do nothing if already closed
if (closed)
{
return;
}
// Assert we are restoring the ctx in same thread.
// Because else, we would set the context "back" in another thread which would lead to huge inconsistencies.
if (Thread.currentThread().getId() != threadIdOnSet)
{
throw new IllegalStateException("Error: setting back the context shall be done in the same thread as it was set initially");
}
threadLocalContext.set(ctxOld); | closed = true;
}
};
}
/**
* Dispose the context from current thread
*/
public void dispose()
{
final Properties ctx = threadLocalContext.get();
ctx.clear();
threadLocalContext.remove();
}
public void setListener(@NonNull final IContextProviderListener listener)
{
this.listener = listener;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\ThreadLocalServerContext.java | 1 |
请完成以下Java代码 | public class RequestUtil {
/**
* 获取请求真实IP地址
*/
public static String getRequestIp(HttpServletRequest request) {
//通过HTTP代理服务器转发时添加
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
// 从本地访问时根据网卡取本机配置的IP
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost(); | } catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inetAddress.getHostAddress();
}
}
// 通过多个代理转发的情况,第一个IP为客户端真实IP,多个IP会按照','分割
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
} | repos\mall-master\mall-common\src\main\java\com\macro\mall\common\util\RequestUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NotificationService {
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
public void createNotification(NotificationDTO notificationDTO) {
Notification notification = toEntity(notificationDTO);
LOG.info("Received notification by module dependency for product {} in date {} by {}.", notification.getProductName()
, notification.getDate(), notification.getFormat());
}
@ApplicationModuleListener
public void notificationEvent(NotificationDTO event) {
Notification notification = toEntity(event);
LOG.info("Received notification by event for product {} in date {} by {}.", notification.getProductName()
, notification.getDate(), notification.getFormat()); | }
private Notification toEntity(NotificationDTO notificationDTO) {
Notification notification = new Notification();
notification.setDate(notificationDTO.getDate());
if (notificationDTO.getFormat().equals("SMS")) {
notification.setFormat(NotificationType.SMS);
}
if (notificationDTO.getFormat().equals("EMAIL")) {
notification.setFormat(NotificationType.EMAIL);
}
notification.setProductName(notificationDTO.getProductName());
return notification;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\modulith\notification\NotificationService.java | 2 |
请完成以下Java代码 | private void updateValid(final IDocumentChangesCollector changesCollector)
{
final DocumentValidStatus validStatusOld = _validStatus;
final DocumentValidStatus validStatusNew = computeValidStatus();
_validStatus = validStatusNew;
// Collect validStatus changed event
if (!NullDocumentChangesCollector.isNull(changesCollector) && !Objects.equals(validStatusOld, validStatusNew))
{
// logger.debug("updateValid: {}: {} <- {}", getFieldName(), validNew, validOld);
changesCollector.collectValidStatus(this);
}
}
/**
* Computes field's validStatus.
* IMPORTANT: this method is not updating the status, it's only computing it.
*/
private DocumentValidStatus computeValidStatus()
{
// Consider virtual fields as valid because there is nothing we can do about them
if (isReadonlyVirtualField())
{
return DocumentValidStatus.validField(getFieldName(), isInitialValue());
}
// Check mandatory constraint
if (isMandatory() && getValue() == null)
{
return DocumentValidStatus.invalidFieldMandatoryNotFilled(getFieldName(), isInitialValue());
}
return DocumentValidStatus.validField(getFieldName(), isInitialValue());
}
@Override
public DocumentValidStatus getValidStatus()
{
return _validStatus;
}
@Override
public DocumentValidStatus updateStatusIfInitialInvalidAndGet(final IDocumentChangesCollector changesCollector)
{
if (_validStatus.isInitialInvalid())
{
updateValid(changesCollector);
}
return _validStatus;
}
@Override | public boolean hasChangesToSave()
{
if (isReadonlyVirtualField())
{
return false;
}
return !isInitialValue();
}
private boolean isInitialValue()
{
return DataTypes.equals(_value, _initialValue);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
final LookupDataSource lookupDataSource = getLookupDataSourceOrNull();
if (lookupDataSource == null)
{
return Optional.empty();
}
return lookupDataSource.getZoomIntoWindowId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentField.java | 1 |
请完成以下Java代码 | public class MigratingVariableInstance implements MigratingInstance {
protected VariableInstanceEntity variable;
protected boolean isConcurrentLocalInParentScope;
public MigratingVariableInstance(VariableInstanceEntity variable, boolean isConcurrentLocalInParentScope) {
this.variable = variable;
this.isConcurrentLocalInParentScope = isConcurrentLocalInParentScope;
}
@Override
public boolean isDetached() {
return variable.getExecutionId() == null;
}
@Override
public void detachState() {
variable.getExecution().removeVariableInternal(variable);
}
@Override
public void attachState(MigratingScopeInstance owningActivityInstance) {
ExecutionEntity representativeExecution = owningActivityInstance.resolveRepresentativeExecution();
ScopeImpl currentScope = owningActivityInstance.getCurrentScope();
ExecutionEntity newOwningExecution = representativeExecution;
if (currentScope.isScope() && isConcurrentLocalInParentScope) {
newOwningExecution = representativeExecution.getParent();
}
newOwningExecution.addVariableInternal(variable);
}
@Override
public void attachState(MigratingTransitionInstance owningActivityInstance) { | ExecutionEntity representativeExecution = owningActivityInstance.resolveRepresentativeExecution();
representativeExecution.addVariableInternal(variable);
}
@Override
public void migrateState() {
migrateHistory();
}
protected void migrateHistory() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_MIGRATE, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricVariableMigrateEvt(variable);
}
});
}
}
@Override
public void migrateDependentEntities() {
// nothing to do
}
public String getVariableName() {
return variable.getName();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingVariableInstance.java | 1 |
请完成以下Spring Boot application配置 | logging.level.root=INFO
management.endpoints.web.exposure.include=*
info.app.name=Spring Boot 2 actuator Application
management.endpoint.health.group.custom.include=diskSpace,ping
management.endpoint.health.group.custom.show-components=always
management.end | point.health.group.custom.show-details=always
management.endpoint.health.group.custom.status.http-mapping.up=207 | repos\tutorials-master\spring-reactive-modules\spring-reactive-security\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public int getAD_Workbench_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workbench_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_Workbench_ID()));
}
/** Set Sequence.
@param SeqNo | Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_DesktopWorkbench.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class RefundConfigChangeHandler
{
private RefundConfig formerRefundConfig;
@Getter
private RefundConfig currentRefundConfig;
protected RefundConfigChangeHandler(@NonNull final RefundConfig currentRefundConfig)
{
assertCorrectRefundBase(currentRefundConfig);
this.currentRefundConfig = currentRefundConfig;
this.formerRefundConfig = null;
}
public void changeCurrentRefundConfig(@NonNull final RefundConfig refundConfig)
{
assertCorrectRefundBase(refundConfig);
this.formerRefundConfig = this.currentRefundConfig;
this.currentRefundConfig = refundConfig;
}
private void assertCorrectRefundBase(final RefundConfig refundConfig)
{ | Check.errorUnless(getExpectedRefundBase().equals(refundConfig.getRefundBase()),
"The given currentRefundConfig needs to have refundBase = AMOUNT_PER_UNIT; currentRefundConfig={}",
refundConfig);
}
/**
* @return the refund config that was the current config before {@link #currentRefundConfig(RefundConfig)} was called.
*/
public RefundConfig getFormerRefundConfig()
{
return Check.assumeNotNull(formerRefundConfig, "formerRefundConfig may not be null; invoke the currentRefundConfig() method first; this={}", this);
}
/**
* @param existingAssignment an assignment that belongs to the refund config from {@link #getFormerRefundConfig()}.
* @return a new assignment that belongs to the refund config that was last set using {@link #currentRefundConfig(RefundConfig)}.
*/
public abstract AssignmentToRefundCandidate createNewAssignment(AssignmentToRefundCandidate existingAssignment);
protected abstract RefundBase getExpectedRefundBase();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\allqties\refundconfigchange\RefundConfigChangeHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TestJsonController {
@Autowired
ObjectMapper mapper;
@JsonView(User.AllUserFieldView.class)
@RequestMapping("getuser")
@ResponseBody
public User getUser() {
User user = new User();
user.setUserName("mrbird");
user.setAge(26);
user.setPassword("123456");
user.setBirthday(new Date());
return user;
}
@RequestMapping("serialization")
@ResponseBody
public String serialization() {
try {
User user = new User();
user.setUserName("mrbird");
user.setBirthday(new Date());
String str = mapper.writeValueAsString(user);
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("readjsonstring")
@ResponseBody
public String readJsonString() {
try {
String json = "{\"name\":\"mrbird\",\"age\":26}";
JsonNode node = this.mapper.readTree(json);
String name = node.get("name").asText();
int age = node.get("age").asInt();
return name + " " + age;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("readjsonasobject")
@ResponseBody
public String readJsonAsObject() {
try {
String json = "{\"userName\":\"mrbird\"}";
User user = mapper.readValue(json, User.class); | String name = user.getUserName();
return name;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("formatobjecttojsonstring")
@ResponseBody
public String formatObjectToJsonString() {
try {
User user = new User();
user.setUserName("mrbird");
user.setAge(26);
user.setPassword("123456");
user.setBirthday(new Date());
String jsonStr = mapper.writeValueAsString(user);
return jsonStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("updateuser")
@ResponseBody
public int updateUser(@RequestBody List<User> list) {
return list.size();
}
@RequestMapping("customize")
@ResponseBody
public String customize() throws JsonParseException, JsonMappingException, IOException {
String jsonStr = "[{\"userName\":\"mrbird\",\"age\":26},{\"userName\":\"scott\",\"age\":27}]";
JavaType type = mapper.getTypeFactory().constructParametricType(List.class, User.class);
List<User> list = mapper.readValue(jsonStr, type);
String msg = "";
for (User user : list) {
msg += user.getUserName();
}
return msg;
}
} | repos\SpringAll-master\18.Spring-Boot-Jackson\src\main\java\com\example\controller\TestJsonController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult createBrand(@Validated @RequestBody PmsBrandDto pmsBrand) {
CommonResult commonResult;
int count = demoService.createBrand(pmsBrand);
if (count == 1) {
commonResult = CommonResult.success(pmsBrand);
LOGGER.debug("createBrand success:{}", pmsBrand);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("createBrand failed:{}", pmsBrand);
}
return commonResult;
}
@ApiOperation(value = "更新品牌")
@RequestMapping(value = "/brand/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateBrand(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandDto pmsBrandDto) {
CommonResult commonResult;
int count = demoService.updateBrand(id, pmsBrandDto);
if (count == 1) {
commonResult = CommonResult.success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}", pmsBrandDto);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
}
return commonResult;
}
@ApiOperation(value = "删除品牌") | @RequestMapping(value = "/brand/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult deleteBrand(@PathVariable("id") Long id) {
int count = demoService.deleteBrand(id);
if (count == 1) {
LOGGER.debug("deleteBrand success :id={}", id);
return CommonResult.success(null);
} else {
LOGGER.debug("deleteBrand failed :id={}", id);
return CommonResult.failed("操作失败");
}
}
@ApiOperation(value = "分页获取品牌列表")
@RequestMapping(value = "/brand/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
List<PmsBrand> brandList = demoService.listBrand(pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(brandList));
}
@ApiOperation(value = "根据编号查询品牌信息")
@RequestMapping(value = "/brand/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {
return CommonResult.success(demoService.getBrand(id));
}
} | repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\controller\DemoController.java | 2 |
请完成以下Java代码 | private TbMsg processPublishResult(TbMsg origMsg, String messageId) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(MESSAGE_ID, messageId);
return origMsg.transform()
.metaData(metaData)
.build();
}
private TbMsg processException(TbMsg origMsg, Throwable t) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage());
return origMsg.transform()
.metaData(metaData)
.build();
}
Publisher initPubSubClient(TbContext ctx) throws IOException {
ProjectTopicName topicName = ProjectTopicName.of(config.getProjectId(), config.getTopicName());
ServiceAccountCredentials credentials =
ServiceAccountCredentials.fromStream(
new ByteArrayInputStream(config.getServiceAccountKey().getBytes())); | CredentialsProvider credProvider = FixedCredentialsProvider.create(credentials);
var retrySettings = RetrySettings.newBuilder()
.setTotalTimeout(Duration.ofSeconds(10))
.setInitialRetryDelay(Duration.ofMillis(50))
.setRetryDelayMultiplier(1.1)
.setMaxRetryDelay(Duration.ofSeconds(2))
.setInitialRpcTimeout(Duration.ofSeconds(2))
.setRpcTimeoutMultiplier(1)
.setMaxRpcTimeout(Duration.ofSeconds(10))
.build();
return Publisher.newBuilder(topicName)
.setCredentialsProvider(credProvider)
.setRetrySettings(retrySettings)
.setExecutorProvider(FixedExecutorProvider.create(ctx.getPubSubRuleNodeExecutorProvider().getExecutor()))
.build();
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\gcp\pubsub\TbPubSubNode.java | 1 |
请完成以下Java代码 | public class Sys {
/**
* 服务器名称
*/
private String computerName;
/**
* 服务器Ip
*/
private String computerIp;
/**
* 项目路径
*/
private String userDir;
/**
* 操作系统
*/
private String osName;
/**
* 系统架构
*/
private String osArch;
public String getComputerName() {
return computerName;
}
public void setComputerName(String computerName) {
this.computerName = computerName;
}
public String getComputerIp() {
return computerIp;
}
public void setComputerIp(String computerIp) {
this.computerIp = computerIp;
} | public String getUserDir() {
return userDir;
}
public void setUserDir(String userDir) {
this.userDir = userDir;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public String getOsArch() {
return osArch;
}
public void setOsArch(String osArch) {
this.osArch = osArch;
}
} | repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Sys.java | 1 |
请完成以下Java代码 | public void deleteBatch(String batchId) {
commandExecutor.execute(new DeleteBatchCmd(batchId));
}
@Override
public HistoryJobQuery createHistoryJobQuery() {
return new HistoryJobQueryImpl(commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public ExternalWorkerJobAcquireBuilder createExternalWorkerJobAcquireBuilder() {
return new ExternalWorkerJobAcquireBuilderImpl(commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String externalJobId, String workerId) {
return new ExternalWorkerJobFailureBuilderImpl(externalJobId, workerId, commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public CmmnExternalWorkerTransitionBuilder createCmmnExternalWorkerTransitionBuilder(String externalJobId, String workerId) {
return new CmmnExternalWorkerTransitionBuilderImpl(commandExecutor, externalJobId, workerId);
}
@Override
public void unacquireExternalWorkerJob(String jobId, String workerId) {
commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) { | commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration()));
}
@Override
public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) {
return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager());
}
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new FlowableIllegalArgumentException("The command is null");
}
return commandExecutor.execute(command);
}
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) {
throw new FlowableIllegalArgumentException("The config is null");
}
if (command == null) {
throw new FlowableIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public LockManager getLockManager(String lockName) {
return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnManagementServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PhoneNumberGenerator {
private static int CALIFORNIA_AREA_CODE = 707;
private static int IOWA_AREA_CODE = 319;
private static int MONTANA_AREA_CODE = 406;
private static int NEW_YORK_AREA_CODE = 914;
private static int OREGON_AREA_CODE = 503;
private static int WASHINGTON_AREA_CODE = 206;
private static int WISCONSIN_AREA_CODE = 608;
private static final List<Integer> PHONE_NUMBER_AREA_CODES = Arrays.asList(
CALIFORNIA_AREA_CODE,
IOWA_AREA_CODE,
MONTANA_AREA_CODE,
NEW_YORK_AREA_CODE,
OREGON_AREA_CODE,
WASHINGTON_AREA_CODE,
WISCONSIN_AREA_CODE
);
private static final Random index = new Random(System.currentTimeMillis()); | public static String generate(String phoneNumber) {
if (!StringUtils.hasText(phoneNumber)) {
phoneNumber = String.valueOf(PHONE_NUMBER_AREA_CODES.get(index.nextInt(PHONE_NUMBER_AREA_CODES.size())))
.concat("-")
.concat(String.valueOf(index.nextInt(9)))
.concat(String.valueOf(index.nextInt(9)))
.concat(String.valueOf(index.nextInt(9)))
.concat("-")
.concat(String.valueOf(index.nextInt(9)))
.concat(String.valueOf(index.nextInt(9)))
.concat(String.valueOf(index.nextInt(9)))
.concat(String.valueOf(index.nextInt(9)));
}
return phoneNumber;
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\client\service\support\PhoneNumberGenerator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AttributeId implements RepoIdAware
{
int repoId;
@JsonCreator
public static AttributeId ofRepoId(final int repoId)
{
return new AttributeId(repoId);
}
public static AttributeId ofRepoIdObj(@NonNull final Object repoIdObj)
{
if (repoIdObj instanceof AttributeId)
{
return (AttributeId)repoIdObj;
}
else if (repoIdObj instanceof Integer)
{
return ofRepoId((int)repoIdObj);
}
else
{
try
{
final int repoId = Integer.parseInt(repoIdObj.toString());
return ofRepoId(repoId);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting '" + repoIdObj + "' (" + repoIdObj.getClass() + ") to " + AttributeId.class, ex);
}
}
}
public static AttributeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
} | public static int toRepoId(final AttributeId attributeId)
{
return attributeId != null ? attributeId.getRepoId() : -1;
}
private AttributeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(final AttributeId id1, final AttributeId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeId.java | 2 |
请完成以下Java代码 | public void setExternalSystem_Outbound_Endpoint_ID (final int ExternalSystem_Outbound_Endpoint_ID)
{
if (ExternalSystem_Outbound_Endpoint_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, ExternalSystem_Outbound_Endpoint_ID);
}
@Override
public int getExternalSystem_Outbound_Endpoint_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Outbound_Endpoint_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 setScriptIdentifier (final String ScriptIdentifier)
{
set_Value (COLUMNNAME_ScriptIdentifier, ScriptIdentifier);
}
@Override | public String getScriptIdentifier()
{
return get_ValueAsString(COLUMNNAME_ScriptIdentifier);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setWhereClause (final String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ScriptedExportConversion.java | 1 |
请完成以下Java代码 | public ActivityBehavior getInnerActivityBehavior() {
return innerActivityBehavior;
}
/**
* ACT-1339. Calling ActivityEndListeners within an {@link AtomicOperation} so that an executionContext is present.
*
* @author Aris Tzoumas
* @author Joram Barrez
*/
private static final class CallActivityListenersOperation implements AtomicOperation {
private List<ExecutionListener> listeners;
private CallActivityListenersOperation(List<ExecutionListener> listeners) {
this.listeners = listeners;
}
@Override
public void execute(InterpretableExecution execution) { | for (ExecutionListener executionListener : listeners) {
try {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new ExecutionListenerInvocation(executionListener, execution));
} catch (Exception e) {
throw new ActivitiException("Couldn't execute listener", e);
}
}
}
@Override
public boolean isAsync(InterpretableExecution execution) {
return false;
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java | 1 |
请完成以下Java代码 | public JpaRepository<S, Long> getRepository() {
return repository;
}
public int countNumberOfRequestsWithFunction(ToIntFunction<List<S>> function) {
return function.applyAsInt(repository.findAll());
}
public Optional<S> getUserById(Long id) {
return repository.findById(id);
}
public void deleteAll() {
repository.deleteAll();
}
public List<S> saveAll(Iterable<S> entities) {
return repository.saveAll(entities);
}
public List<S> findAll() {
return repository.findAll();
}
public Optional<S> getUserByIdWithPredicate(long id, Predicate<S> predicate) { | Optional<S> user = repository.findById(id);
user.ifPresent(predicate::test);
return user;
}
public int getUserByIdWithFunction(Long id, ToIntFunction<S> function) {
Optional<S> optionalUser = repository.findById(id);
if (optionalUser.isPresent()) {
return function.applyAsInt(optionalUser.get());
} else {
return 0;
}
}
public void save(S entity) {
repository.save(entity);
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\Service.java | 1 |
请完成以下Java代码 | public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID)
{
if (M_ReceiptSchedule_ID < 1)
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID);
}
@Override
public int getM_ReceiptSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID);
}
@Override
public void setQtyAllocated (final @Nullable BigDecimal QtyAllocated)
{
set_ValueNoCheck (COLUMNNAME_QtyAllocated, QtyAllocated);
}
@Override
public BigDecimal getQtyAllocated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAllocated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyAllocatedInCatchUOM (final @Nullable BigDecimal QtyAllocatedInCatchUOM)
{
set_Value (COLUMNNAME_QtyAllocatedInCatchUOM, QtyAllocatedInCatchUOM);
}
@Override
public BigDecimal getQtyAllocatedInCatchUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAllocatedInCatchUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyWithIssues (final BigDecimal QtyWithIssues)
{
set_ValueNoCheck (COLUMNNAME_QtyWithIssues, QtyWithIssues);
} | @Override
public BigDecimal getQtyWithIssues()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyWithIssues);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyWithIssuesInCatchUOM (final @Nullable BigDecimal QtyWithIssuesInCatchUOM)
{
set_Value (COLUMNNAME_QtyWithIssuesInCatchUOM, QtyWithIssuesInCatchUOM);
}
@Override
public BigDecimal getQtyWithIssuesInCatchUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyWithIssuesInCatchUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQualityDiscountPercent (final @Nullable BigDecimal QualityDiscountPercent)
{
throw new IllegalArgumentException ("QualityDiscountPercent is virtual column"); }
@Override
public BigDecimal getQualityDiscountPercent()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QualityDiscountPercent);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQualityNote (final @Nullable java.lang.String QualityNote)
{
throw new IllegalArgumentException ("QualityNote is virtual column"); }
@Override
public java.lang.String getQualityNote()
{
return get_ValueAsString(COLUMNNAME_QualityNote);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_Alloc.java | 1 |
请完成以下Java代码 | public Object getPrincipal() {
return authentication.getPrincipal();
}
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
}
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
this.roleHierarchy = roleHierarchy;
}
public void setDefaultRolePrefix(String defaultRolePrefix) {
this.defaultRolePrefix = defaultRolePrefix;
}
private Set<String> getAuthoritySet() {
if (roles == null) {
Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
if (roleHierarchy != null) {
userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities);
}
roles = AuthorityUtils.authorityListToSet(userAuthorities);
}
return roles;
}
@Override
public boolean hasPermission(Object target, Object permission) {
return permissionEvaluator.hasPermission(authentication, target, permission);
}
@Override
public boolean hasPermission(Object targetId, String targetType, Object permission) {
return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission);
}
public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) {
this.permissionEvaluator = permissionEvaluator; | }
private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) {
return role;
}
if (role.startsWith(defaultRolePrefix)) {
return role;
}
return defaultRolePrefix + role;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
}
@Override
public Object getThis() {
return this;
}
@Override
public void setFilterObject(Object obj) {
this.filterObject = obj;
}
@Override
public void setReturnObject(Object obj) {
this.returnObject = obj;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MybatisDeadLetterJobDataManager extends AbstractDataManager<DeadLetterJobEntity> implements DeadLetterJobDataManager {
protected CachedEntityMatcher<DeadLetterJobEntity> deadLetterByExecutionIdMatcher = new DeadLetterJobsByExecutionIdMatcher();
protected SingleCachedEntityMatcher<DeadLetterJobEntity> deadLetterByCorrelationIdMatcher = new JobByCorrelationIdMatcher<>();
protected JobServiceConfiguration jobServiceConfiguration;
public MybatisDeadLetterJobDataManager(JobServiceConfiguration jobServiceConfiguration) {
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Class<? extends DeadLetterJobEntity> getManagedEntityClass() {
return DeadLetterJobEntityImpl.class;
}
@Override
public DeadLetterJobEntity create() {
return new DeadLetterJobEntityImpl();
}
@Override
public DeadLetterJobEntity findJobByCorrelationId(String correlationId) {
return getEntity("selectDeadLetterJobByCorrelationId", correlationId, deadLetterByCorrelationIdMatcher, true);
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(DeadLetterJobQueryImpl jobQuery) {
String query = "selectDeadLetterJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery);
}
@Override
public long findJobCountByQueryCriteria(DeadLetterJobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery); | }
@Override
public List<DeadLetterJobEntity> findJobsByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
// If the execution has been inserted in the same command execution as this query, there can't be any in the database
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
return getListFromCache(deadLetterByExecutionIdMatcher, executionId);
}
return getList(dbSqlSession, "selectDeadLetterJobsByExecutionId", executionId, deadLetterByExecutionIdMatcher, true);
}
@Override
@SuppressWarnings("unchecked")
public List<DeadLetterJobEntity> findJobsByProcessInstanceId(final String processInstanceId) {
return getDbSqlSession().selectList("selectDeadLetterJobsByProcessInstanceId", processInstanceId);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateDeadLetterJobTenantIdForDeployment", params);
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisDeadLetterJobDataManager.java | 2 |
请完成以下Java代码 | public void setCCM_Success (String CCM_Success)
{
set_Value (COLUMNNAME_CCM_Success, CCM_Success);
}
/** Get Is Success.
@return Is Success */
public String getCCM_Success ()
{
return (String)get_Value(COLUMNNAME_CCM_Success);
}
/** 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 Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_CCM_Bundle_Result.java | 1 |
请完成以下Java代码 | private MCash createCash()
{
MCash cash = new MCash (getCtx(), 0, get_TrxName());
cash.setName(p_Name);
cash.setDescription(p_Description);
cash.setDateAcct(p_DateAcct);
cash.setStatementDate(p_StatementDate);
cash.setC_CashBook_ID(p_C_CashBook_ID);
if (!cash.save())
{
throw new IllegalStateException("Could not create Cash");
}
return cash;
} // createCash
private MCashLine[] createCashLines(MCash cash)
{
ArrayList<MCashLine> cashLineList = new ArrayList<MCashLine>();
// From Bank (From) to CashLine
MCashLine cashLine = new MCashLine (cash);
cashLine.setAmount(p_Amount);
cashLine.setC_BP_BankAccount_ID(p_From_C_BP_BankAccount_ID);
cashLine.setC_Currency_ID(m_C_Currency_ID);
if (p_Description != null)
cashLine.setDescription(p_Description);
else
cashLine.setDescription(p_Name);
cashLine.setCashType("T"); // Transfer
if (!cashLine.save())
{
throw new IllegalStateException("Could not create Cash line (From Bank)");
}
cashLineList.add(cashLine);
// From CashLine to Bank (To)
cashLine = new MCashLine (cash);
cashLine.setAmount(p_Amount.negate());
cashLine.setC_BP_BankAccount_ID(p_To_C_BP_BankAccount_ID);
cashLine.setC_Currency_ID(m_C_Currency_ID);
if (p_Description != null)
cashLine.setDescription(p_Description);
else
cashLine.setDescription(p_Name); | cashLine.setCashType("T"); // Transfer
if (!cashLine.save())
{
throw new IllegalStateException("Could not create Cash line (To Bank)");
}
cashLineList.add(cashLine);
MCashLine cashLines[] = new MCashLine[cashLineList.size()];
cashLineList.toArray(cashLines);
return cashLines;
} // createCashLines
/**
* Generate CashJournal
*
*/
private void generateBankTransfer()
{
// Create Cash & CashLines
MCash cash = createCash();
MCashLine cashLines[]= createCashLines(cash);
StringBuffer processMsg = new StringBuffer(cash.getDocumentNo());
cash.setDocAction(p_docAction);
if (!cash.processIt(p_docAction))
{
processMsg.append(" (NOT Processed)");
log.warn("Cash Processing failed: " + cash + " - " + cash.getProcessMsg());
addLog(cash.getC_Cash_ID(), cash.getStatementDate(), null,
"Cash Processing failed: " + cash + " - "
+ cash.getProcessMsg()
+ " / please complete it manually");
}
if (!cash.save())
{
throw new IllegalStateException("Could not create Cash");
}
// Add processing information to process log
addLog(cash.getC_Cash_ID(), cash.getStatementDate(), null, processMsg.toString());
m_created++;
} // generateBankTransfer
} // ImmediateBankTransfer | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\process\ImmediateBankTransfer.java | 1 |
请完成以下Java代码 | public BigDecimal getFirstWeight() {
return firstWeight;
}
public void setFirstWeight(BigDecimal firstWeight) {
this.firstWeight = firstWeight;
}
public BigDecimal getFirstFee() {
return firstFee;
}
public void setFirstFee(BigDecimal firstFee) {
this.firstFee = firstFee;
}
public BigDecimal getContinueWeight() {
return continueWeight;
}
public void setContinueWeight(BigDecimal continueWeight) {
this.continueWeight = continueWeight;
}
public BigDecimal getContinmeFee() {
return continmeFee;
}
public void setContinmeFee(BigDecimal continmeFee) {
this.continmeFee = continmeFee;
}
public String getDest() {
return dest;
}
public void setDest(String dest) {
this.dest = dest;
}
@Override | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", chargeType=").append(chargeType);
sb.append(", firstWeight=").append(firstWeight);
sb.append(", firstFee=").append(firstFee);
sb.append(", continueWeight=").append(continueWeight);
sb.append(", continmeFee=").append(continmeFee);
sb.append(", dest=").append(dest);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsFeightTemplate.java | 1 |
请完成以下Java代码 | private void markAsDestroyed()
{
asserNotDestroyed();
destroyed = true;
}
@Override
public ParentType end()
{
markAsDestroyed();
final InSubQueryFilter<ModelType> inSubQueryFilter = inSubQueryBuilder.build();
finisher.accept(inSubQueryFilter);
return parent;
}
@Override
public IInSubQueryFilterClause<ModelType, ParentType> subQuery(final IQuery<?> subQuery)
{
asserNotDestroyed();
inSubQueryBuilder.subQuery(subQuery);
return this; | }
@Override
public IInSubQueryFilterClause<ModelType, ParentType> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier)
{
asserNotDestroyed();
inSubQueryBuilder.matchingColumnNames(columnName, subQueryColumnName, modifier);
return this;
}
@Override
public IInSubQueryFilterClause<ModelType, ParentType> matchingColumnNames(final String columnName, final String subQueryColumnName)
{
asserNotDestroyed();
inSubQueryBuilder.matchingColumnNames(columnName, subQueryColumnName);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilterClause.java | 1 |
请完成以下Java代码 | private String convert (long number)
{
/* special case */
if (number == 0)
return "CERO";
String prefix = "";
if (number < 0)
{
number = -number;
prefix = "MENOS";
}
String soFar = "";
int place = 0;
do
{
long n = number % 1000;
if (n != 0)
{
String s = convertLessThanOneThousand ((int)n);
if (s.startsWith ("UN CIENTO", 1))
{
s = s.replaceFirst ("UN CIENTO", "CIEN");
}
if (s.startsWith ("CINCO CIENTOS", 1))
{
s = s.replaceFirst ("CINCO CIENTOS", "QUINIENTOS");
}
if (s.startsWith ("SIETE CIENTOS", 1))
{
s = s.replaceFirst ("SIETE CIENTOS", "SETECIENTOS");
}
if (s.startsWith ("NUEVE CIENTOS", 1))
{
s = s.replaceFirst ("NUEVE CIENTOS", "NOVECIENTOS");
}
if (s.equals(" UNO"))
{
soFar = majorNames[place] + soFar;
}
else {
if (n > 1) {
soFar = s + majorNamesPlural[place] + soFar;
} else {
soFar = s + majorNames[place] + soFar;
}
}
}
place++;
number /= 1000;
}
while (number > 0);
return (prefix + soFar).trim ();
} // convert
/**************************************************************************
* Get Amount in Words
* @param amount numeric amount (352.80)
* @return amount in words (three*five*two 80/100)
* @throws Exception
*/
public String getAmtInWords (String amount) throws Exception
{
if (amount == null)
return amount;
Language lang = Env.getLanguage(Env.getCtx());
//
StringBuffer sb = new StringBuffer ();
int pos = 0;
if(lang.isDecimalPoint())
pos = amount.lastIndexOf ('.'); // Old
else
pos = amount.lastIndexOf (',');
int pos2 = 0;
if(lang.isDecimalPoint())
pos2 = amount.lastIndexOf (','); // Old
else
pos2 = amount.lastIndexOf ('.'); | if (pos2 > pos)
pos = pos2;
String oldamt = amount;
if(lang.isDecimalPoint())
amount = amount.replaceAll (",", ""); // Old
else
amount = amount.replaceAll( "\\.","");
int newpos = 0;
if(lang.isDecimalPoint())
newpos = amount.lastIndexOf ('.'); // Old
else
newpos = amount.lastIndexOf (',');
long pesos = Long.parseLong(amount.substring (0, newpos));
sb.append (convert (pesos));
for (int i = 0; i < oldamt.length (); i++)
{
if (pos == i) // we are done
{
String cents = oldamt.substring (i + 1);
sb.append (' ')
.append (cents)
.append ("/100");
// .append ("/100 PESOS");
break;
}
}
return sb.toString ();
} // getAmtInWords
public static void main(String[] args) throws Exception {
AmtInWords_ES aiw = new AmtInWords_ES();
// for (int i=0; i<=2147000000; i++)
// System.out.println(aiw.getAmtInWords(i+",00"));
System.out.println(aiw.getAmtInWords("9223372036854775807.99"));
}
} // AmtInWords_ES | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_ES.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object[][] getGraphData() {
final Date current = new Date();
final int colCount = statusList.size() + 1;
final int rowCount = statusMetricsByMinute.size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
int j = 1;
for (final String status : statusList) {
result[0][j] = status;
j++;
}
for (int i = 1; i < rowCount; i++) {
result[i][0] = DATE_FORMAT.format(new Date(current.getTime() - (60000L * (rowCount - i))));
}
List<Integer> minuteOfStatuses;
for (int i = 1; i < rowCount; i++) {
minuteOfStatuses = statusMetricsByMinute.get(i - 1);
for (j = 1; j <= minuteOfStatuses.size(); j++) {
result[i][j] = minuteOfStatuses.get(j - 1);
}
while (j < colCount) {
result[i][j] = 0; | j++;
}
}
return result;
}
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds:60000}")
private void exportMetrics() {
List<Integer> statusCount = new ArrayList<>();
for (final String status : statusList) {
Search search = registry.find(status);
Counter counter = search.counter();
if (counter == null) {
statusCount.add(0);
} else {
statusCount.add((int) counter.count());
registry.remove(counter);
}
}
statusMetricsByMinute.add(statusCount);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\java\com\baeldung\metrics\service\CustomActuatorMetricService.java | 2 |
请完成以下Java代码 | private boolean isMatching(final I_C_VAT_Code matching, final VATCodeMatchingRequest request)
{
logger.debug("Matching: {}", matching);
logger.debug("Request: {}", request);
// Match accounting schema
if (matching.getC_AcctSchema_ID() != request.getC_AcctSchema_ID())
{
logger.debug("=> not matching (C_AcctSchema_ID)");
return false;
}
// Match tax
if (matching.getC_Tax_ID() != request.getC_Tax_ID())
{
logger.debug("=> not matching (C_Tax_ID)");
return false;
}
// Match IsSOTrx
final String matchingIsSOTrxStr = matching.getIsSOTrx();
final Boolean matchingIsSOTrx = matchingIsSOTrxStr == null ? null : DisplayType.toBoolean(matchingIsSOTrxStr);
if (matchingIsSOTrx != null && matchingIsSOTrx != request.isSOTrx())
{
logger.debug("=> not matching (IsSOTrx)");
return false;
}
// Match Date
if (!TimeUtil.isBetween(request.getDate(), matching.getValidFrom(), matching.getValidTo()))
{
logger.debug("=> not matching (Date)");
return false;
}
logger.debug("=> matching");
return true;
} | /**
* Retries all active {@link I_C_VAT_Code}s for given C_AcctSchema_ID.
*
* @param acctSchemaId C_AcctSchema_ID
*/
@Cached(cacheName = I_C_VAT_Code.Table_Name + "#by#" + I_C_VAT_Code.COLUMNNAME_C_AcctSchema_ID)
public List<I_C_VAT_Code> retriveVATCodeMatchingsForSchema(@CacheCtx final Properties ctx, final int acctSchemaId)
{
return queryBL
.createQueryBuilder(I_C_VAT_Code.class, ctx, ITrx.TRXNAME_ThreadInherited)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_VAT_Code.COLUMN_C_AcctSchema_ID, acctSchemaId)
//
.orderBy()
.addColumn(I_C_VAT_Code.COLUMNNAME_C_Tax_ID)
.addColumn(I_C_VAT_Code.COLUMN_ValidFrom, Direction.Descending, Nulls.Last)
.addColumn(I_C_VAT_Code.COLUMN_ValidTo, Direction.Descending, Nulls.Last)
.addColumn(I_C_VAT_Code.COLUMN_IsSOTrx, Direction.Ascending, Nulls.Last)
.addColumn(I_C_VAT_Code.COLUMN_C_VAT_Code_ID)
.endOrderBy()
//
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\vatcode\impl\VATCodeDAO.java | 1 |
请完成以下Java代码 | private ITranslatableString getProductName(final ProductId productId)
{
final I_M_Product product = getProductById(productId);
final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(product);
return trls.getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName());
}
private UomId getProductUomId(final ProductId productId)
{
final I_M_Product product = getProductById(productId);
return UomId.ofRepoId(product.getC_UOM_ID());
}
private Amount extractPrice(final I_M_ProductPrice productPrice)
{ | return Amount.of(productPrice.getPriceStd(), currency.getCurrencyCode());
}
private String getUOMSymbol(final UomId uomId)
{
final I_C_UOM uom = uomDAO.getById(uomId);
return StringUtils.trimBlankToOptional(uom.getUOMSymbol()).orElseGet(uom::getName);
}
private UomIdAndSymbol toUomIdAndSymbol(final UomId uomId)
{
return UomIdAndSymbol.of(uomId, getUOMSymbol(uomId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)")
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut("within(net.alanbinu.springboot2.springboot2jpacrudexample..*)"+
" || within(net.alanbinu.springboot2.springboot2jpacrudexample.service..*)"+
" || within(net.alanbinu.springboot2.springboot2jpacrudexample.controller..*)")
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
/**
* Advice that logs when a method is entered and exited.
* | * @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot2-springaop-example\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\aspect\LoggingAspect.java | 2 |
请完成以下Java代码 | public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
@Override
public String getValidateFormFields() {
return validateFormFields;
}
@Override
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getTaskIdVariableName() {
return taskIdVariableName;
}
public void setTaskIdVariableName(String taskIdVariableName) {
this.taskIdVariableName = taskIdVariableName;
}
public String getTaskCompleterVariableName() {
return taskCompleterVariableName;
}
public void setTaskCompleterVariableName(String taskCompleterVariableName) {
this.taskCompleterVariableName = taskCompleterVariableName;
} | public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
public List<FlowableListener> getTaskListeners() {
return taskListeners;
}
public void setTaskListeners(List<FlowableListener> taskListeners) {
this.taskListeners = taskListeners;
}
@Override
public HumanTask clone() {
HumanTask clone = new HumanTask();
clone.setValues(this);
return clone;
}
public void setValues(HumanTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setValidateFormFields(otherElement.getValidateFormFields());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\HumanTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) {
this.disableHtmlEscaping = disableHtmlEscaping;
}
public @Nullable String getDateFormat() {
return this.dateFormat;
}
public void setDateFormat(@Nullable String dateFormat) {
this.dateFormat = dateFormat;
}
/**
* Enumeration of levels of strictness. Values are the same as those on
* {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize
* backwards compatibility, the Gson enum is not used directly.
*/
public enum Strictness { | /**
* Lenient compliance.
*/
LENIENT,
/**
* Strict compliance with some small deviations for legacy reasons.
*/
LEGACY_STRICT,
/**
* Strict compliance.
*/
STRICT
}
} | repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java | 2 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (!selectedRowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final DocumentId rowId = selectedRowIds.getSingleDocumentId();
final HUEditorRow huRow = getView().getById(rowId);
if (huRow.isLU())
{
if (!huRow.hasIncludedTUs())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no TUs");
}
}
else if (huRow.isTU())
{
// OK
}
else
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a LU or TU");
}
if (!huRow.isHUStatusActive())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("HUStatus is not Active");
}
return ProcessPreconditionsResolution.accept();
}
@Override
// @RunOutOfTrx // run in transaction!
protected String doIt()
{ | if (p_QtyTU <= 0)
{
throw new FillMandatoryException("QtyTU");
}
final I_M_HU topLevelHU = getRecord(I_M_HU.class);
final HUsToNewTUsRequest request = HUsToNewTUsRequest.forSourceHuAndQty(topLevelHU, p_QtyTU);
final LUTUResult.TUsList tus = HUTransformService.newInstance().husToNewTUs(request);
if (tus.getQtyTU().toInt() != p_QtyTU)
{
throw new AdempiereException(WEBUI_HU_Constants.MSG_NotEnoughTUsFound, p_QtyTU, tus.getQtyTU());
}
HUMoveToDirectWarehouseService.newInstance()
.setDocumentsCollection(documentsCollection)
.setHUView(getView())
.setMovementDate(SystemTime.asInstant()) // now
// .setDescription(description) // none
.setFailOnFirstError(true)
.setLoggable(this)
.move(tus.toHURecords().iterator());
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveTUsToDirectWarehouse.java | 1 |
请完成以下Java代码 | public void destroy() {
final List<RuntimeException> errors = new ArrayList<>();
final Iterator<ScopedBeanReference> it = this.references.values().iterator();
while (it.hasNext()) {
ScopedBeanReference val = it.next();
it.remove();
try {
val.destroy();
} catch (RuntimeException e) {
errors.add(e);
}
}
if (!errors.isEmpty()) {
RuntimeException rex = errors.remove(0);
for (RuntimeException error : errors) {
rex.addSuppressed(error);
}
throw rex;
}
}
}
/**
* Container for a single scoped bean. This class manages the bean creation
*/
private static class ScopedBeanReference {
private final ObjectFactory<?> objectFactory;
private Object bean;
private Runnable destructionCallback;
/**
* Creates a new scoped bean reference using the given object factory.
*
* @param objectFactory The object factory used to create instances of that bean.
*/
public ScopedBeanReference(ObjectFactory<?> objectFactory) {
this.objectFactory = objectFactory;
}
/**
* Gets or creates the bean managed by this instance.
*
* @return The existing or newly created bean instance.
*/
public synchronized Object getBean() {
if (this.bean == null) {
this.bean = this.objectFactory.getObject();
}
return this.bean;
}
/** | * Gets the bean managed by this instance, if it exists.
*
* @return The existing bean or null.
*/
public Object getBeanIfExists() {
return this.bean;
}
/**
* Sets the given callback used to destroy the managed bean.
*
* @param destructionCallback The destruction callback to use.
*/
public void setDestructionCallback(final Runnable destructionCallback) {
this.destructionCallback = destructionCallback;
}
/**
* Executes the destruction callback if set and clears the internal bean references.
*/
public synchronized void destroy() {
Runnable callback = this.destructionCallback;
if (callback != null) {
callback.run();
}
this.bean = null;
this.destructionCallback = null;
}
@Override
public String toString() {
return "ScopedBeanReference [objectFactory=" + this.objectFactory + ", bean=" + this.bean + "]";
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\scope\GrpcRequestScope.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CompressFilePreviewImpl implements FilePreview {
private final FileHandlerService fileHandlerService;
private final CompressFileReader compressFileReader;
private final OtherFilePreviewImpl otherFilePreview;
private static final String Rar_PASSWORD_MSG = "password";
private static final Logger logger = org.slf4j.LoggerFactory.getLogger(CompressFileReader.class);
public CompressFilePreviewImpl(FileHandlerService fileHandlerService, CompressFileReader compressFileReader, OtherFilePreviewImpl otherFilePreview) {
this.fileHandlerService = fileHandlerService;
this.compressFileReader = compressFileReader;
this.otherFilePreview = otherFilePreview;
}
@Override
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
String fileName = fileAttribute.getName();
String filePassword = fileAttribute.getFilePassword();
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache();
String fileTree = null;
// 判断文件名是否存在(redis缓存读取)
if (forceUpdatedCache || !StringUtils.hasText(fileHandlerService.getConvertedFile(fileName)) || !ConfigConstants.isCacheEnabled()) {
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
if (response.isFailure()) {
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
}
String filePath = response.getContent();
try { | fileTree = compressFileReader.unRar(filePath, filePassword, fileName, fileAttribute);
} catch (Exception e) {
if (e.getMessage().toLowerCase().contains(Rar_PASSWORD_MSG)) {
model.addAttribute("needFilePassword", true);
return EXEL_FILE_PREVIEW_PAGE;
}else {
logger.error("Error processing RAR file: " + e.getMessage(), e);
}
}
if (!ObjectUtils.isEmpty(fileTree)) {
//是否保留压缩包源文件
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
KkFileUtils.deleteFileByPath(filePath);
}
if (ConfigConstants.isCacheEnabled()) {
// 加入缓存
fileHandlerService.addConvertedFile(fileName, fileTree);
}
} else {
return otherFilePreview.notSupportedFile(model, fileAttribute, "该压缩包文件无法处理!");
}
} else {
fileTree = fileHandlerService.getConvertedFile(fileName);
}
model.addAttribute("fileName", fileName);
model.addAttribute("fileTree", fileTree);
return COMPRESS_FILE_PREVIEW_PAGE;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\impl\CompressFilePreviewImpl.java | 2 |
请完成以下Java代码 | public static String validateCreditCardVV (String creditCardVV, String creditCardType)
{
// no data
if (creditCardVV == null || creditCardVV.length() == 0
|| creditCardType == null || creditCardType.length() == 0)
return "";
int length = checkNumeric(creditCardVV).length();
// Amex = 4 digits
if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex))
{
if (length == 4)
{
try
{
Integer.parseInt (creditCardVV);
return "";
}
catch (NumberFormatException ex)
{
s_log.debug("validateCreditCardVV - " + ex);
}
}
s_log.debug("validateCreditCardVV(4) CC=" + creditCardType + ", length=" + length);
return "CreditCardVVError";
}
// Visa & MasterCard - 3 digits
if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa)
|| creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard))
{
if (length == 3)
{
try
{
Integer.parseInt (creditCardVV);
return "";
}
catch (NumberFormatException ex)
{
s_log.debug("validateCreditCardVV - " + ex);
}
}
s_log.debug("validateCreditCardVV(3) CC=" + creditCardType + ", length=" + length);
return "CreditCardVVError";
}
// Other
return "";
} // validateCreditCardVV
/**************************************************************************
* Validate Routing Number
* @param routingNo Routing No
* @return "" or Error AD_Message
*/
public static String validateRoutingNo (String routingNo)
{
int length = checkNumeric(routingNo).length();
// US - length 9
// Germany - length 8
// Japan - 7
// CH - 5
// Issue: Bank account country
if (length > 0)
return "";
return "PaymentBankRoutingNotValid";
} // validateBankRoutingNo
/**
* Validate Account No
* @param AccountNo AccountNo
* @return "" or Error AD_Message
*/
public static String validateAccountNo (String AccountNo)
{
int length = checkNumeric(AccountNo).length();
if (length > 0)
return ""; | return "PaymentBankAccountNotValid";
} // validateBankAccountNo
/**
* Validate Check No
* @param CheckNo CheckNo
* @return "" or Error AD_Message
*/
public static String validateCheckNo (String CheckNo)
{
int length = checkNumeric(CheckNo).length();
if (length > 0)
return "";
return "PaymentBankCheckNotValid";
} // validateBankCheckNo
/**
* Check Numeric
* @param data input
* @return the digits of the data - ignore the rest
*/
public static String checkNumeric (String data)
{
if (data == null || data.length() == 0)
return "";
// Remove all non Digits
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length(); i++)
{
if (Character.isDigit(data.charAt(i)))
sb.append(data.charAt(i));
}
return sb.toString();
} // checkNumeric
} // MPaymentValidate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPaymentValidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
} | public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DecisionResponse.java | 2 |
请完成以下Java代码 | public String[] getWhereClauses(List<Object> params)
{
final GeodbObject go = getGeodbObject();
final String searchText = getText();
if (go == null && !Check.isEmpty(searchText, true))
return new String[]{"1=2"};
if (go == null)
return new String[]{"1=1"};
final int radius = getRadius();
//
final String whereClause = "EXISTS (SELECT 1 FROM geodb_coordinates co WHERE "
+ " co.zip=" + locationTableAlias + ".Postal" // join to C_Location.Postal
+ " AND co.c_country_id=" + locationTableAlias + ".C_Country_ID"
+ " AND " + getSQLDistanceFormula("co", go.getLat(), go.getLon()) + " <= " + radius
+ ")";
return new String[]{whereClause};
}
private static String getSQLDistanceFormula(String tableAlias, double lat, double lon)
{
return "DEGREES("
+ " (ACOS("
+ " SIN(RADIANS(" + lat + ")) * SIN(RADIANS(" + tableAlias + ".lat)) "
+ " + COS(RADIANS(" + lat + "))*COS(RADIANS(" + tableAlias + ".lat))*COS(RADIANS(" + tableAlias + ".lon) - RADIANS(" + lon + "))"
+ ") * 60 * 1.1515 " // miles
+ " * 1.609344" // KM factor | + " )"
+ " )";
}
private GeodbObject getGeodbObject()
{
return (GeodbObject)fieldCityZipAutocompleter.getUserOject();
}
@Override
public String getText()
{
return fieldCityZipAutocompleter.getText();
}
private int getRadius()
{
if (fieldRadius == null)
return 0;
Object o = fieldRadius.getValue();
if (o instanceof Number)
return ((Number)o).intValue();
return 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoQueryCriteriaBPRadius.java | 1 |
请完成以下Java代码 | protected void prepare()
{
final IQueryFilter<I_C_Invoice> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
return;
}
final int selectionCount = queryBL
.createQueryBuilder(I_C_Invoice.class)
.filter(userSelectionFilter)
.addEqualsFilter(I_C_Invoice.COLUMNNAME_DocStatus, X_C_Invoice.DOCSTATUS_Completed)
.addOnlyActiveRecordsFilter()
.create()
.createSelection(getPinstanceId()); | if (selectionCount <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
@Override
protected String doIt() throws Exception
{
enqueuer.enqueueSelection(getProcessInfo().getPinstanceId());
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_CancelAndRecreate.java | 1 |
请完成以下Java代码 | public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
@Override
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
@Override
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
@Override
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
@Override
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_Summary.java | 1 |
请完成以下Java代码 | public HUQueryBuilder addHUIdsToAlwaysInclude(final Collection<HuId> huIdsToAlwaysInclude)
{
if (huIdsToAlwaysInclude == null || huIdsToAlwaysInclude.isEmpty())
{
return this;
}
this._huIdsToAlwaysInclude.addAll(huIdsToAlwaysInclude);
this._huIdsToExclude.removeAll(huIdsToAlwaysInclude);
return this;
}
@Override
public HUQueryBuilder addPIVersionToInclude(@NonNull final HuPackingInstructionsVersionId huPIVersionId)
{
_huPIVersionIdsToInclude.add(huPIVersionId);
return this;
}
private Set<HuPackingInstructionsVersionId> getPIVersionIdsToInclude()
{
return _huPIVersionIdsToInclude;
}
@Override
public HUQueryBuilder setExcludeAfterPickingLocator(final boolean excludeAfterPickingLocator)
{
locators.setExcludeAfterPickingLocator(excludeAfterPickingLocator);
return this;
}
@Override
public HUQueryBuilder setIncludeAfterPickingLocator(final boolean includeAfterPickingLocator)
{
locators.setIncludeAfterPickingLocator(includeAfterPickingLocator);
return this;
}
@Override
public HUQueryBuilder setExcludeHUsOnPickingSlot(final boolean excludeHUsOnPickingSlot)
{
_excludeHUsOnPickingSlot = excludeHUsOnPickingSlot; | return this;
}
@Override
public IHUQueryBuilder setExcludeReservedToOtherThan(@Nullable final HUReservationDocRef documentRef)
{
_excludeReservedToOtherThanRef = documentRef;
return this;
}
@Override
public IHUQueryBuilder setExcludeReserved()
{
_excludeReserved = true;
return this;
}
@Override
public IHUQueryBuilder setIgnoreHUsScheduledInDDOrder(final boolean ignoreHUsScheduledInDDOrder)
{
this.ignoreHUsScheduledInDDOrder = ignoreHUsScheduledInDDOrder;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder.java | 1 |
请完成以下Java代码 | public static List<String> extract(String text, int size)
{
IPhraseExtractor extractor = new MutualInformationEntropyPhraseExtractor();
return extractor.extractPhrase(text, size);
}
// public static void main(String[] args)
// {
// MutualInformationEntropyPhraseExtractor extractor = new MutualInformationEntropyPhraseExtractor();
// String text = "算法工程师\n" +
// "算法(Algorithm)是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时间内获得所要求的输出。如果一个算法有缺陷,或不适合于某个问题,执行这个算法将不会解决这个问题。不同的算法可能用不同的时间、空间或效率来完成同样的任务。一个算法的优劣可以用空间复杂度与时间复杂度来衡量。算法工程师就是利用算法处理事物的人。\n" +
// "\n" +
// "1职位简介\n" +
// "算法工程师是一个非常高端的职位;\n" +
// "专业要求:计算机、电子、通信、数学等相关专业;\n" +
// "学历要求:本科及其以上的学历,大多数是硕士学历及其以上;\n" +
// "语言要求:英语要求是熟练,基本上能阅读国外专业书刊;\n" + | // "必须掌握计算机相关知识,熟练使用仿真工具MATLAB等,必须会一门编程语言。\n" +
// "\n" +
// "2研究方向\n" +
// "视频算法工程师、图像处理算法工程师、音频算法工程师 通信基带算法工程师\n" +
// "\n" +
// "3目前国内外状况\n" +
// "目前国内从事算法研究的工程师不少,但是高级算法工程师却很少,是一个非常紧缺的专业工程师。算法工程师根据研究领域来分主要有音频/视频算法处理、图像技术方面的二维信息算法处理和通信物理层、雷达信号处理、生物医学信号处理等领域的一维信息算法处理。\n" +
// "在计算机音视频和图形图像技术等二维信息算法处理方面目前比较先进的视频处理算法:机器视觉成为此类算法研究的核心;另外还有2D转3D算法(2D-to-3D conversion),去隔行算法(de-interlacing),运动估计运动补偿算法(Motion estimation/Motion Compensation),去噪算法(Noise Reduction),缩放算法(scaling),锐化处理算法(Sharpness),超分辨率算法(Super Resolution),手势识别(gesture recognition),人脸识别(face recognition)。\n" +
// "在通信物理层等一维信息领域目前常用的算法:无线领域的RRM、RTT,传送领域的调制解调、信道均衡、信号检测、网络优化、信号分解等。\n" +
// "另外数据挖掘、互联网搜索算法也成为当今的热门方向。\n" +
// "算法工程师逐渐往人工智能方向发展。";
//// System.out.println(text);
// List<String> phraseList = extractor.extractPhrase(text, 10);
// System.out.println(phraseList);
// }
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\phrase\MutualInformationEntropyPhraseExtractor.java | 1 |
请完成以下Java代码 | protected List<String[]> convertToSequence(Sentence sentence)
{
List<String[]> charList = new LinkedList<String[]>();
for (Word w : sentence.toSimpleWordList())
{
String word = CharTable.convert(w.value);
if (word.length() == 1)
{
charList.add(new String[]{word, "S"});
}
else
{
charList.add(new String[]{word.substring(0, 1), "B"});
for (int i = 1; i < word.length() - 1; ++i)
{
charList.add(new String[]{word.substring(i, i + 1), "M"});
}
charList.add(new String[]{word.substring(word.length() - 1), "E"});
}
}
return charList;
}
@Override
protected TagSet getTagSet()
{
return tagSet;
}
/**
* 获取兼容旧的Segment接口
*
* @return
*/ | public Segment toSegment()
{
return new Segment()
{
@Override
protected List<Term> segSentence(char[] sentence)
{
List<String> wordList = segment(new String(sentence));
List<Term> termList = new LinkedList<Term>();
for (String word : wordList)
{
termList.add(new Term(word, null));
}
return termList;
}
}.enableCustomDictionary(false);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMSegmenter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getOffsetX() {
return offsetX;
}
/**
* Sets the value of the offsetX property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setOffsetX(BigDecimal value) {
this.offsetX = value;
}
/**
* Gets the value of the offsetY property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getOffsetY() {
return offsetY;
}
/**
* Sets the value of the offsetY property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setOffsetY(BigDecimal value) {
this.offsetY = value;
}
/** | * Gets the value of the connectionType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConnectionType() {
return connectionType;
}
/**
* Sets the value of the connectionType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConnectionType(String value) {
this.connectionType = value;
}
/**
* Gets the value of the barcodeCapable2D property.
*
*/
public boolean isBarcodeCapable2D() {
return barcodeCapable2D;
}
/**
* Sets the value of the barcodeCapable2D property.
*
*/
public void setBarcodeCapable2D(boolean value) {
this.barcodeCapable2D = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Printer.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_AD_UI_Element getAD_UI_Element() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_UI_Element_ID, org.compiere.model.I_AD_UI_Element.class);
}
@Override
public void setAD_UI_Element(org.compiere.model.I_AD_UI_Element AD_UI_Element)
{
set_ValueFromPO(COLUMNNAME_AD_UI_Element_ID, org.compiere.model.I_AD_UI_Element.class, AD_UI_Element);
}
/** Set UI Element.
@param AD_UI_Element_ID UI Element */
@Override
public void setAD_UI_Element_ID (int AD_UI_Element_ID)
{
if (AD_UI_Element_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UI_Element_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UI_Element_ID, Integer.valueOf(AD_UI_Element_ID));
}
/** Get UI Element.
@return UI Element */
@Override
public int getAD_UI_Element_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Element_ID);
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));
}
/** 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();
}
/** | * TooltipIconName AD_Reference_ID=540912
* Reference name: TooltipIcon
*/
public static final int TOOLTIPICONNAME_AD_Reference_ID=540912;
/** text = text */
public static final String TOOLTIPICONNAME_Text = "text";
/** Set Tooltip Icon Name.
@param TooltipIconName Tooltip Icon Name */
@Override
public void setTooltipIconName (java.lang.String TooltipIconName)
{
set_Value (COLUMNNAME_TooltipIconName, TooltipIconName);
}
/** Get Tooltip Icon Name.
@return Tooltip Icon Name */
@Override
public java.lang.String getTooltipIconName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName);
}
/**
* Type AD_Reference_ID=540910
* Reference name: Type_AD_UI_ElementField
*/
public static final int TYPE_AD_Reference_ID=540910;
/** widget = widget */
public static final String TYPE_Widget = "widget";
/** tooltip = tooltip */
public static final String TYPE_Tooltip = "tooltip";
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java | 1 |
请完成以下Java代码 | public <V> V get(Object key) {
return hasKey(key) ? (V) this.context.get(key) : null;
}
@Override
public boolean hasKey(Object key) {
Assert.notNull(key, "key cannot be null");
return this.context.containsKey(key);
}
/**
* Returns the {@link OAuth2TokenClaimsSet.Builder claims} allowing the ability to
* add, replace, or remove.
* @return the {@link OAuth2TokenClaimsSet.Builder}
*/
public OAuth2TokenClaimsSet.Builder getClaims() {
return get(OAuth2TokenClaimsSet.Builder.class);
}
/**
* Constructs a new {@link Builder} with the provided claims.
* @param claimsBuilder the claims to initialize the builder
* @return the {@link Builder}
*/
public static Builder with(OAuth2TokenClaimsSet.Builder claimsBuilder) {
return new Builder(claimsBuilder);
}
/**
* A builder for {@link OAuth2TokenClaimsContext}.
*/ | public static final class Builder extends AbstractBuilder<OAuth2TokenClaimsContext, Builder> {
private Builder(OAuth2TokenClaimsSet.Builder claimsBuilder) {
Assert.notNull(claimsBuilder, "claimsBuilder cannot be null");
put(OAuth2TokenClaimsSet.Builder.class, claimsBuilder);
}
/**
* Builds a new {@link OAuth2TokenClaimsContext}.
* @return the {@link OAuth2TokenClaimsContext}
*/
@Override
public OAuth2TokenClaimsContext build() {
return new OAuth2TokenClaimsContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimsContext.java | 1 |
请完成以下Java代码 | public void setV_BPartnerCockpit_ID (final int V_BPartnerCockpit_ID)
{
if (V_BPartnerCockpit_ID < 1)
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, null);
}
else
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, Integer.valueOf(V_BPartnerCockpit_ID));
}
}
/** Get V_BPartnerCockpit_ID.
@return V_BPartnerCockpit_ID */
@Override
public int getV_BPartnerCockpit_ID ()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_V_BPartnerCockpit_ID);
if (ii == null)
{
return 0;
}
return ii.intValue(); | }
/** Set Suchschlüssel.
@param value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setvalue (final java.lang.String value)
{
set_Value (COLUMNNAME_value, value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getvalue ()
{
return (java.lang.String)get_Value(COLUMNNAME_value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_V_BPartnerCockpit.java | 1 |
请完成以下Java代码 | public ApiRequestAuditId getIdNotNull()
{
if (this.apiRequestAuditId == null)
{
throw new AdempiereException("getIdNotNull() should be called only for already persisted ApiRequestAudit objects!")
.appendParametersToMessage()
.setParameter("ApiRequestAudit", this);
}
return apiRequestAuditId;
}
@NonNull
public Optional<HttpHeadersWrapper> getRequestHeaders(@NonNull final ObjectMapper objectMapper)
{
if (Check.isBlank(httpHeaders))
{
return Optional.empty();
}
try
{
return Optional.of(objectMapper.readValue(httpHeaders, HttpHeadersWrapper.class));
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Failed to parse httpHeaders!")
.appendParametersToMessage()
.setParameter("ApiAuditRequest", this);
}
}
@NonNull
public Optional<Object> getRequestBody(@NonNull final ObjectMapper objectMapper)
{ | if (Check.isBlank(body))
{
return Optional.empty();
}
try
{
return Optional.of(objectMapper.readValue(body, Object.class));
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Failed to parse body!")
.appendParametersToMessage()
.setParameter("ApiAuditRequest", this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\request\ApiRequestAudit.java | 1 |
请完成以下Java代码 | public String getId() {
return this.id;
}
/**
* Creates a new {@link PublicKeyCredentialRpEntityBuilder}
* @return a new {@link PublicKeyCredentialRpEntityBuilder}
*/
public static PublicKeyCredentialRpEntityBuilder builder() {
return new PublicKeyCredentialRpEntityBuilder();
}
/**
* Used to create a {@link PublicKeyCredentialRpEntity}.
*
* @author Rob Winch
* @since 6.4
*/
public static final class PublicKeyCredentialRpEntityBuilder {
private @Nullable String name;
private @Nullable String id;
private PublicKeyCredentialRpEntityBuilder() {
}
/**
* Sets the {@link #getName()} property.
* @param name the name property
* @return the {@link PublicKeyCredentialRpEntityBuilder}
*/
public PublicKeyCredentialRpEntityBuilder name(String name) {
this.name = name;
return this;
} | /**
* Sets the {@link #getId()} property.
* @param id the id
* @return the {@link PublicKeyCredentialRpEntityBuilder}
*/
public PublicKeyCredentialRpEntityBuilder id(String id) {
this.id = id;
return this;
}
/**
* Creates a new {@link PublicKeyCredentialRpEntity}.
* @return a new {@link PublicKeyCredentialRpEntity}.
*/
public PublicKeyCredentialRpEntity build() {
Assert.notNull(this.name, "name cannot be null");
Assert.notNull(this.id, "id cannot be null");
return new PublicKeyCredentialRpEntity(this.name, this.id);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialRpEntity.java | 1 |
请完成以下Java代码 | public String getExpressionLanguage() {
return expressionLanguageAttribute.getValue(this);
}
public void setExpressionLanguage(String expressionLanguage) {
expressionLanguageAttribute.setValue(this, expressionLanguage);
}
public String getTypeLanguage() {
return typeLanguageAttribute.getValue(this);
}
public void setTypeLanguage(String typeLanguage) {
typeLanguageAttribute.setValue(this, typeLanguage);
}
public String getExporter() {
return exporterAttribute.getValue(this);
}
public void setExporter(String exporter) {
exporterAttribute.setValue(this, exporter);
}
public String getExporterVersion() {
return exporterVersionAttribute.getValue(this);
}
public void setExporterVersion(String exporterVersion) {
exporterVersionAttribute.setValue(this, exporterVersion);
}
public Collection<Import> getImports() {
return importCollection.get(this);
} | public Collection<Extension> getExtensions() {
return extensionCollection.get(this);
}
public Collection<RootElement> getRootElements() {
return rootElementCollection.get(this);
}
public Collection<BpmnDiagram> getBpmDiagrams() {
return bpmnDiagramCollection.get(this);
}
public Collection<Relationship> getRelationships() {
return relationshipCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DefinitionsImpl.java | 1 |
请完成以下Java代码 | public class HUsToReceiveViewFactory extends HUEditorViewFactoryTemplate
{
public static final String WINDOW_ID_STRING = "husToReceive";
public static final WindowId WINDOW_ID = WindowId.fromJson(WINDOW_ID_STRING);
public HUsToReceiveViewFactory()
{
super(ImmutableList.of(HUsToReceiveHUEditorViewCustomizer.instance));
}
@Override
protected void customizeViewLayout(final ViewLayout.Builder viewLayoutBuilder, final JSONViewDataType viewDataType)
{
viewLayoutBuilder
.clearElements()
.addElementsFromViewRowClassAndFieldNames(HUEditorRow.class,
viewDataType,
ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HUCode).restrictToMediaType(MediaType.SCREEN).build(),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_Product),
ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HU_UnitType).restrictToMediaType(MediaType.SCREEN).build(),
ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_PackingInfo).restrictToMediaType(MediaType.SCREEN).build(),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_QtyCU),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_UOM),
ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HUStatus).restrictToMediaType(MediaType.SCREEN).build());
}
@Override
protected boolean isMaterialReceipt()
{ | return true;
}
@Override
protected void customizeHUEditorViewRepository(final SqlHUEditorViewRepository.SqlHUEditorViewRepositoryBuilder huEditorViewRepositoryBuilder)
{
huEditorViewRepositoryBuilder.customProcessApplyPredicate(this::checkIfProcessDescriptorApplies);
}
private boolean checkIfProcessDescriptorApplies(@NonNull final HUEditorRow row, @NonNull final ProcessDescriptor processDescriptor)
{
if (M_HU_Report_QRCode.class.getName().equals(processDescriptor.getProcessClassname()))
{
return checkIfLabelCanBePrinted(row);
}
return true;
}
private boolean checkIfLabelCanBePrinted(@NonNull final HUEditorRow row)
{
return X_M_HU.HUSTATUS_Active.equals(row.getHUStatus());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\receiptSchedule\HUsToReceiveViewFactory.java | 1 |
请完成以下Java代码 | public static Class<?>[] getClasses(Collection<Configurations> configurations) {
List<Configurations> collated = collate(configurations);
LinkedHashSet<Class<?>> classes = collated.stream()
.flatMap(Configurations::streamClasses)
.collect(Collectors.toCollection(LinkedHashSet::new));
return ClassUtils.toClassArray(classes);
}
/**
* Collate the given configuration by sorting and merging them.
* @param configurations the source configuration
* @return the collated configurations
* @since 3.4.0
*/
public static List<Configurations> collate(Collection<Configurations> configurations) {
LinkedList<Configurations> collated = new LinkedList<>();
for (Configurations configuration : sortConfigurations(configurations)) {
if (collated.isEmpty() || collated.getLast().getClass() != configuration.getClass()) {
collated.add(configuration);
} | else {
collated.set(collated.size() - 1, collated.getLast().merge(configuration));
}
}
return collated;
}
private static List<Configurations> sortConfigurations(Collection<Configurations> configurations) {
List<Configurations> sorted = new ArrayList<>(configurations);
sorted.sort(COMPARATOR);
return sorted;
}
private static Stream<Class<?>> streamClasses(Configurations configurations) {
return configurations.getClasses().stream();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\annotation\Configurations.java | 1 |
请完成以下Java代码 | public class SynonymHelper
{
/**
* 同一行最多支持编码这么多个单词
*/
public static final long MAX_WORDS = 999L;
/**
* 尾数的长度,表示原子词的index
*/
public static final int MAX_INDEX_LENGTH = String.valueOf(MAX_WORDS).length();
public static long convertString2Id(String idString)
{
long id;
id = (idString.charAt(0) - 'A') * 26L * 10 * 10 * 26 * 10 * 10 +
(idString.charAt(1) - 'a') * 10 * 10 * 26 * 10 * 10 +
(idString.charAt(2) - '0') * 10 * 26 * 10 * 10 +
(idString.charAt(3) - '0') * 26 * 10 * 10 +
(idString.charAt(4) - 'A') * 10 * 10 +
(idString.charAt(5) - '0') * 10 +
(idString.charAt(6) - '0') ; // 编码等号前面的
return id;
}
public static String convertId2String(long id)
{
StringBuilder sbId = new StringBuilder(7);
sbId.append((char)(id / (26 * 10 * 10 * 26 * 10 * 10) + 'A')); | sbId.append((char)(id % (26 * 10 * 10 * 26 * 10 * 10) / (10 * 10 * 26 * 10 * 10) + 'a'));
sbId.append((char)(id % (10 * 10 * 26 * 10 * 10) / (10 * 26 * 10 * 10) + '0'));
sbId.append((char)(id % (10 * 26 * 10 * 10) / (26 * 10 * 10) + '0'));
sbId.append((char)(id % (26 * 10 * 10) / (10 * 10) + 'A'));
sbId.append((char)(id % (10 * 10) / (10) + '0'));
sbId.append((char)(id % (10) / (1) + '0'));
return sbId.toString();
}
public static long convertString2IdWithIndex(String idString, long index)
{
long id = convertString2Id(idString);
id = id * MAX_WORDS + index;
return id;
}
public static long convertString2IdWithIndex(String idString, int index)
{
return convertString2IdWithIndex(idString, (long) index);
}
public static String convertId2StringWithIndex(long id)
{
String idString = convertId2String(id / MAX_WORDS);
long index = id % MAX_WORDS;
return String.format("%s%0" + MAX_INDEX_LENGTH + "d", idString, index);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\synonym\SynonymHelper.java | 1 |
请完成以下Java代码 | public int compare(GridField o1, GridField o2)
{
if (o1 == o2)
{
return 0;
}
final GridFieldVO vo1 = o1.getVO();
final GridFieldVO vo2 = o2.getVO();
final int seqNo1 = vo1.isDisplayedGrid() && vo1.getSeqNoGrid() > 0 ? vo1.getSeqNoGrid() : Integer.MAX_VALUE;
final int seqNo2 = vo2.isDisplayedGrid() && vo2.getSeqNoGrid() > 0 ? vo2.getSeqNoGrid() : Integer.MAX_VALUE;
return seqNo1 - seqNo2;
}
});
//
// From GridTab's fields
// Build map: ColumnName to GridField
// Build list: visible columnNames
final Map<String, GridField> columnName2GridField = new HashMap<String, GridField>(gridFields.length);
final List<String> visibleColumnNames = new ArrayList<String>(gridFields.length);
for (int i = 0; i < gridFields.length; i++)
{
final GridField gridField = gridFields[i];
final GridFieldVO gridFieldVO = gridField.getVO();
final String columnName = gridField.getColumnName();
columnName2GridField.put(columnName, gridField);
final boolean visible = gridFieldVO.isDisplayedGrid();
if (visible)
{
visibleColumnNames.add(columnName);
}
}
//
// From Table's column model
// Load column from GridField
final TableColumnModel tableColumnModel = table.getColumnModel();
final int tableColumnsCount = tableColumnModel.getColumnCount();
for (int i = 0; i < tableColumnsCount; i++)
{
final TableColumn column = tableColumnModel.getColumn(i);
final String columnName = getColumnName(column); | // Update
final GridField gridField = columnName2GridField.get(columnName);
loadTableColumn(column, gridField);
}
//
// Reorder table's columns based on GridField settings
int currentIdx = 0;
final int visibleFieldsCount = visibleColumnNames.size();
for (final String columnName : visibleColumnNames)
{
if (currentIdx == visibleFieldsCount - 1)
{
// no reordering for the last one (see javadoc of 'tcm.moveColumn')
continue;
}
// Search where our column is now
int fromIdx = -1;
for (int i = currentIdx; i < tableColumnsCount; i++)
{
final TableColumn column = tableColumnModel.getColumn(i);
final String fromColumnName = getColumnName(column);
if (columnName.equals(fromColumnName))
{
fromIdx = i;
break;
}
}
// Move column
if (fromIdx != currentIdx)
{
tableColumnModel.moveColumn(fromIdx, currentIdx);
}
currentIdx++;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\grid\CTableColumns2GridTabSynchronizer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.objectPostProcessor.addObjectPostProcessor(objectPostProcessor);
}
/**
* Sets the {@link SecurityBuilder} to be used. This is automatically set when using
* {@link AbstractConfiguredSecurityBuilder#with(SecurityConfigurerAdapter, Customizer)}
* @param builder the {@link SecurityBuilder} to set
*/
public void setBuilder(B builder) {
this.securityBuilder = builder;
}
/**
* An {@link ObjectPostProcessor} that delegates work to numerous
* {@link ObjectPostProcessor} implementations.
*
* @author Rob Winch
*/
private static final class CompositeObjectPostProcessor implements ObjectPostProcessor<Object> {
private List<ObjectPostProcessor<?>> postProcessors = new ArrayList<>();
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) {
for (ObjectPostProcessor opp : this.postProcessors) { | Class<?> oppClass = opp.getClass();
Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
object = opp.postProcess(object);
}
}
return object;
}
/**
* Adds an {@link ObjectPostProcessor} to use
* @param objectPostProcessor the {@link ObjectPostProcessor} to add
* @return true if the {@link ObjectPostProcessor} was added, else false
*/
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\SecurityConfigurerAdapter.java | 2 |
请完成以下Java代码 | public String getBio() {
return bio;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
public void setCharacterClass(String characterClass) {
this.characterClass = characterClass;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getCityOfOrigin() { | return cityOfOrigin;
}
public void setCityOfOrigin(String cityOfOrigin) {
this.cityOfOrigin = cityOfOrigin;
}
public String getFavoriteWeapon() {
return favoriteWeapon;
}
public void setFavoriteWeapon(String favoriteWeapon) {
this.favoriteWeapon = favoriteWeapon;
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\dto\Character.java | 1 |
请完成以下Java代码 | public static int usingTwoPointer(int num) {
char[] numChars = Integer.toString(num)
.toCharArray();
int pivotIndex = numChars.length - 2;
while (pivotIndex >= 0 && numChars[pivotIndex] >= numChars[pivotIndex + 1]) {
pivotIndex--;
}
if (pivotIndex == -1)
return -1;
int minIndex = numChars.length - 1;
while (numChars[minIndex] <= numChars[pivotIndex]) {
minIndex--;
}
swap(numChars, pivotIndex, minIndex);
reverse(numChars, pivotIndex + 1, numChars.length - 1);
return Integer.parseInt(new String(numChars));
}
private static void swap(char[] numChars, int i, int j) {
char temp = numChars[i]; | numChars[i] = numChars[j];
numChars[j] = temp;
}
private static void reverse(char[] numChars, int i, int j) {
while (i < j) {
swap(numChars, i, j);
i++;
j--;
}
}
public static void main(String[] args) {
int result = usingTwoPointer(536479);
System.out.println(result);
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\nexthighestnumbersamedigit\NextHighestNumber.java | 1 |
请完成以下Java代码 | default CompletableFuture<Output> execute(DelegatePlanItemInstance planItemInstance, AsyncTaskInvoker taskInvoker) {
Input inputData = prepareExecutionData(planItemInstance);
return taskInvoker.submit(() -> execute(inputData));
}
/**
* Method invoked before doing the execution to extract needed that from the planItemInstance
* on the main thread.
* This should be used to prepare and extract data from the planItemInstance before doing the execution in a different thread.
*
* @param planItemInstance the planItemInstance from which to extract data
* @return the data for the delegate
*/
Input prepareExecutionData(DelegatePlanItemInstance planItemInstance);
/**
* Perform the actual execution of the delegate in another thread.
* This uses {@link #prepareExecutionData(DelegatePlanItemInstance)} to get the needed data
* from the {@link DelegatePlanItemInstance} and returns the output data that can is passed to {@link #afterExecution(DelegatePlanItemInstance, Object)}.
* | * <b>IMPORTANT:</b> This is a completely new thread which does not participate in the transaction of the case.
*
* @param inputData the input data for the execution created via {@link #prepareExecutionData(DelegatePlanItemInstance)}
* @return the output data of the execution
* @see #execute(DelegatePlanItemInstance, AsyncTaskInvoker)
*/
Output execute(Input inputData);
/**
* Method invoked with the result from {@link #execute(Object)}.
* This should be used to set data on the {@link DelegatePlanItemInstance}.
* This is on the same thread as {@link #prepareExecutionData(DelegatePlanItemInstance)} and participates in the case transaction.
*
* @param planItemInstance the planItemInstance to which data can be set
* @param executionData the execution data
*/
@Override
void afterExecution(DelegatePlanItemInstance planItemInstance, Output executionData);
} | repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\delegate\FlowablePlanItemFutureJavaDelegate.java | 1 |
请完成以下Java代码 | public <T> T getProperty(final String propertyName)
{
final T defaultValue = null;
return getProperty(propertyName, defaultValue);
}
@Override
public <T> T getProperty(final String propertyName, final T defaultValue)
{
Check.assumeNotNull(propertyName, "propertyName not null");
if (properties == null)
{
return defaultValue;
}
final Object valueObj = properties.get(propertyName);
if (valueObj == null)
{
return defaultValue;
}
@SuppressWarnings("unchecked")
final T value = (T)valueObj;
return value;
}
@Override | public boolean isProperty(final String propertyName)
{
final boolean defaultValue = false;
return isProperty(propertyName, defaultValue);
}
@Override
public boolean isProperty(final String propertyName, final boolean defaultValue)
{
final Boolean value = getProperty(propertyName);
if (value == null)
{
return defaultValue;
}
return value.booleanValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\AbstractDunningContext.java | 1 |
请完成以下Java代码 | public Batch execute(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = collectProcessInstanceIds(commandContext);
ensureNotEmpty(BadUserRequestException.class, "processInstanceIds", elementConfiguration.getIds());
return new BatchBuilder(commandContext)
.type(Batch.TYPE_PROCESS_INSTANCE_DELETION)
.config(getConfiguration(elementConfiguration))
.permission(BatchPermissions.CREATE_BATCH_DELETE_RUNNING_PROCESS_INSTANCES)
.operationLogHandler(this::writeUserOperationLog)
.build();
}
protected BatchElementConfiguration collectProcessInstanceIds(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
List<String> processInstanceIds = this.getProcessInstanceIds();
if (!CollectionUtil.isEmpty(processInstanceIds)) {
ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(processInstanceIds));
elementConfiguration.addDeploymentMappings(
commandContext.runWithoutAuthorization(query::listDeploymentIdMappings), processInstanceIds);
}
ProcessInstanceQueryImpl processInstanceQuery = (ProcessInstanceQueryImpl) this.processInstanceQuery;
if (processInstanceQuery != null) {
elementConfiguration.addDeploymentMappings(processInstanceQuery.listDeploymentIdMappings());
}
HistoricProcessInstanceQueryImpl historicProcessInstanceQuery = (HistoricProcessInstanceQueryImpl) this.historicProcessInstanceQuery;
if (historicProcessInstanceQuery != null) {
elementConfiguration.addDeploymentMappings(historicProcessInstanceQuery.listDeploymentIdMappings());
} | return elementConfiguration;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
protected void writeUserOperationLog(CommandContext commandContext, int numInstances) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances));
propertyChanges.add(new PropertyChange("async", null, true));
propertyChanges.add(new PropertyChange("deleteReason", null, deleteReason));
commandContext.getOperationLogManager()
.logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE,
null,
null,
null,
propertyChanges);
}
public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) {
return new DeleteProcessInstanceBatchConfiguration(elementConfiguration.getIds(), elementConfiguration.getMappings(),
deleteReason, skipCustomListeners, skipSubprocesses, false, skipIoMappings);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\DeleteProcessInstanceBatchCmd.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Other SQL Clause.
@param OtherClause
Other SQL Clause
*/
public void setOtherClause (String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
public String getOtherClause ()
{
return (String)get_Value(COLUMNNAME_OtherClause);
}
/** Set Sql WHERE. | @param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_TemplateTable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private I_C_BankStatement getCreateCashStatement(final I_C_Payment payment)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(payment);
final String trxName = InterfaceWrapperHelper.getTrxName(payment);
final int C_BP_BankAccount_ID = payment.getC_BP_BankAccount_ID();
final LocalDate statementDate = TimeUtil.asLocalDate(payment.getDateTrx());
String whereClause = I_C_BankStatement.COLUMNNAME_C_BP_BankAccount_ID + "=?"
+ " AND TRUNC(" + I_C_BankStatement.COLUMNNAME_StatementDate + ")=?"
+ " AND " + I_C_BankStatement.COLUMNNAME_Processed + "=?";
I_C_BankStatement bs = new Query(ctx, I_C_BankStatement.Table_Name, whereClause, trxName)
.setParameters(new Object[] { C_BP_BankAccount_ID, statementDate, false })
.firstOnly(I_C_BankStatement.class);
if (bs != null)
{
return bs;
}
// Get BankAccount/CashBook | I_C_BP_BankAccount ba = InterfaceWrapperHelper.create(ctx, C_BP_BankAccount_ID, I_C_BP_BankAccount.class, trxName);
if (ba == null || ba.getC_BP_BankAccount_ID() <= 0)
{
throw new AdempiereException("@NotFound@ @C_BP_BankAccount_ID@ (ID=" + C_BP_BankAccount_ID + ")");
}
// Create Statement
return createBankStatement(ba, statementDate);
}
private I_C_BankStatement createBankStatement(final I_C_BP_BankAccount account, final LocalDate statementDate)
{
final BankStatementId bankStatementId = bankStatementDAO.createBankStatement(BankStatementCreateRequest.builder()
.orgId(OrgId.ofRepoId(account.getAD_Org_ID()))
.orgBankAccountId(BankAccountId.ofRepoId(account.getC_BP_BankAccount_ID()))
.statementDate(statementDate)
.name(statementDate.toString())
.build());
return bankStatementDAO.getById(bankStatementId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\CashStatementBL.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setDesc(String desc) {
this.desc = desc;
}
public List<MenuEntity> getMenuList() {
return menuList;
}
public void setMenuList(List<MenuEntity> menuList) {
this.menuList = menuList;
}
public List<PermissionEntity> getPermissionList() {
return permissionList;
} | public void setPermissionList(List<PermissionEntity> permissionList) {
this.permissionList = permissionList;
}
@Override
public String toString() {
return "RoleEntity{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", desc='" + desc + '\'' +
", menuList=" + menuList +
", permissionList=" + permissionList +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\RoleEntity.java | 2 |
请完成以下Java代码 | public DocumentFieldLogicExpressionResultRevaluator getLogicExpressionResultRevaluator()
{
DocumentFieldLogicExpressionResultRevaluator logicExpressionRevaluator = this.logicExpressionRevaluator;
if (logicExpressionRevaluator == null)
{
logicExpressionRevaluator = this.logicExpressionRevaluator = DocumentFieldLogicExpressionResultRevaluator.using(permissions);
}
return logicExpressionRevaluator;
}
public Set<DocumentStandardAction> getStandardActions(@NonNull final Document document)
{
final HashSet<DocumentStandardAction> standardActions = new HashSet<>(document.getStandardActions());
Boolean allowWindowEdit = null;
Boolean allowDocumentEdit = null;
for (final Iterator<DocumentStandardAction> it = standardActions.iterator(); it.hasNext(); )
{
final DocumentStandardAction action = it.next();
if (action.isDocumentWriteAccessRequired())
{
if (allowDocumentEdit == null)
{
allowDocumentEdit = DocumentPermissionsHelper.canEdit(document, permissions);
}
if (!allowDocumentEdit)
{
it.remove();
continue;
} | }
if (action.isWindowWriteAccessRequired())
{
if (allowWindowEdit == null)
{
final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();
final AdWindowId adWindowId = entityDescriptor.getDocumentType().isWindow()
? entityDescriptor.getWindowId().toAdWindowId()
: null;
allowWindowEdit = adWindowId != null && permissions.checkWindowPermission(adWindowId).hasWriteAccess();
}
if (!allowWindowEdit)
{
it.remove();
//noinspection UnnecessaryContinue
continue;
}
}
}
return ImmutableSet.copyOf(standardActions);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPermissions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QRCodeConfigurationService
{
@NonNull private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
@NonNull private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
@NonNull private final IProductBL productBL = Services.get(IProductBL.class);
@NonNull private final QRCodeConfigurationRepository repository;
public static QRCodeConfigurationService newInstanceForUnitTesting()
{
SpringContextHolder.assertUnitTestMode();
return SpringContextHolder.getBeanOrSupply(
QRCodeConfigurationService.class,
() -> new QRCodeConfigurationService(new QRCodeConfigurationRepository())
);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isOneQrCodeForAggregatedHUsEnabledFor(@NonNull final I_M_HU hu)
{
if (!handlingUnitsBL.isTransportUnitOrAggregate(hu))
{
return false;
}
return getConfigurationForHuId(hu)
.map(QRCodeConfiguration::isOneQRCodeForAggregatedTUsEnabled)
.orElse(false);
}
@NonNull
public ImmutableSet<HuId> filterSplitHUsForSharingQr(@NonNull final I_M_HU sourceHU, @NonNull final ImmutableList<I_M_HU> newHUs)
{
if (!isOneQrCodeForAggregatedHUsEnabledFor(sourceHU))
{
return ImmutableSet.of();
}
return newHUs.stream()
.flatMap(newHU -> {
if (handlingUnitsBL.isLoadingUnit(newHU))
{
return handlingUnitsDAO.retrieveIncludedHUs(newHU).stream();
}
else
{
return Stream.of(newHU);
}
})
.filter(handlingUnitsBL::isTransportUnitOrAggregate)
.map(I_M_HU::getM_HU_ID) | .map(HuId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
public boolean isAtLeastOneActiveConfig()
{
return repository.isAtLeastOneActiveConfig();
}
@NonNull
public ImmutableMap<QRCodeConfigurationId, QRCodeConfiguration> getByIds(@NonNull final ImmutableSet<QRCodeConfigurationId> qrCodeConfigurationIds)
{
return repository.getActiveByIds(qrCodeConfigurationIds);
}
@NonNull
private Optional<QRCodeConfiguration> getConfigurationForHuId(@NonNull final I_M_HU hu)
{
final ProductId productId = handlingUnitsBL.getStorageFactory().getStorage(hu).getSingleProductIdOrNull();
return Optional.ofNullable(productId)
.map(productBL::getById)
.map(I_M_Product::getQRCode_Configuration_ID)
.map(QRCodeConfigurationId::ofRepoIdOrNull)
.flatMap(repository::getActiveById);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\QRCodeConfigurationService.java | 2 |
请完成以下Java代码 | public int getRowCount()
{
return m_data.getMaxRow()+1;
} // getRowCount
/**
* Get Number of Columns
* @return no of cols
*/
public int getColCount()
{
return m_data.getMaxCol()+1;
} // getColCount
/**
* Set Horizontal Space (top, between rows, button)
* @param spaceH horizontal space (top, between rows, button)
*/
public void setSpaceH (int spaceH)
{
m_spaceH = spaceH;
} // setSpaceH
/**
* Get Horizontal Space (top, between rows, button)
* @return spaceH horizontal space (top, between rows, button)
*/
public int getSpaceH()
{ | return m_spaceH;
} // getSpaceH
/**
* Set Vertical Space (left, between columns, right)
* @param spaceV vertical space (left, between columns, right)
*/
public void setSpaceV(int spaceV)
{
m_spaceV = spaceV;
} // setSpaceV
/**
* Get Vertical Space (left, between columns, right)
* @return spaceV vertical space (left, between columns, right)
*/
public int getSpaceV()
{
return m_spaceV;
} // getSpaceV
} // ALayout | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class X_M_PropertiesConfig extends org.compiere.model.PO implements I_M_PropertiesConfig, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 1359529093L;
/** Standard Constructor */
public X_M_PropertiesConfig (Properties ctx, int M_PropertiesConfig_ID, String trxName)
{
super (ctx, M_PropertiesConfig_ID, trxName);
/** if (M_PropertiesConfig_ID == 0)
{
setM_PropertiesConfig_ID (0);
setName (null);
setValue (null);
} */
}
/** Load Constructor */
public X_M_PropertiesConfig (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder ("X_M_PropertiesConfig[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Properties Configuration.
@param M_PropertiesConfig_ID Properties Configuration */
@Override
public void setM_PropertiesConfig_ID (int M_PropertiesConfig_ID)
{
if (M_PropertiesConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_ID, Integer.valueOf(M_PropertiesConfig_ID));
}
/** Get Properties Configuration.
@return Properties Configuration */
@Override
public int getM_PropertiesConfig_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PropertiesConfig.java | 2 |
请完成以下Java代码 | protected boolean beforeSave (boolean newRecord)
{
// Reset info
if (isSummary() && getAction() != null)
setAction(null);
String action = getAction();
if (action == null)
action = "";
// Clean up references
if (getAD_Window_ID() != 0 && !action.equals(ACTION_Window))
setAD_Window_ID(0);
if (getAD_Form_ID() != 0 && !action.equals(ACTION_Form))
setAD_Form_ID(0);
if (getAD_Workflow_ID() != 0 && !action.equals(ACTION_WorkFlow))
setAD_Workflow_ID(0);
if (getAD_Workbench_ID() != 0 && !action.equals(ACTION_Workbench))
setAD_Workbench_ID(0);
if (getAD_Task_ID() != 0 && !action.equals(ACTION_Task))
setAD_Task_ID(0);
if (getAD_Process_ID() != 0
&& !(action.equals(ACTION_Process) || action.equals(ACTION_Report)))
setAD_Process_ID(0);
return true;
} // beforeSave
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord)
insert_Tree(MTree_Base.TREETYPE_Menu);
return success;
} // afterSave
/**
* After Delete
* @param success
* @return deleted
*/
protected boolean afterDelete (boolean success) | {
if (success)
delete_Tree(MTree_Base.TREETYPE_Menu);
return success;
} // afterDelete
/**
* FR [ 1966326 ]
* get Menu ID
* @param String Menu Name
* @return int retValue
*/
public static int getMenu_ID(String menuName) {
int retValue = 0;
String SQL = "SELECT AD_Menu_ID FROM AD_Menu WHERE Name = ?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(SQL, null);
pstmt.setString(1, menuName);
rs = pstmt.executeQuery();
if (rs.next())
retValue = rs.getInt(1);
}
catch (SQLException e)
{
s_log.error(SQL, e);
retValue = -1;
}
finally
{
DB.close(rs, pstmt);
}
return retValue;
}
} // MMenu | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMenu.java | 1 |
请完成以下Java代码 | protected void prepare()
{
for (ProcessInfoParameter para : getParametersAsArray())
{
if (para.getParameter() == null)
{
// skip if no parameter value
continue;
}
final String name = para.getParameterName();
if (name.equals(PARAM_DunningGrace))
{
p_DunningGrace = para.getParameterAsTimestamp();
}
}
}
@Override
protected String doIt()
{
final Iterator<I_C_Dunning_Candidate> it = retrieveSelectionIterator();
setDunningGrace(it, p_DunningGrace);
return "@Updated@";
}
private void setDunningGrace(final Iterator<I_C_Dunning_Candidate> it, final Timestamp dunningGrace)
{
while (it.hasNext())
{
final I_C_Dunning_Candidate candidate = it.next();
setDunningGrace(candidate, dunningGrace);
}
}
private void setDunningGrace(final I_C_Dunning_Candidate candidate, final Timestamp dunningGrace)
{
candidate.setDunningGrace(dunningGrace); | // We want to make sure that model validators are triggered EVEN if the old DunningGrace value equals with new DunningGrace value
markColumnChanged(candidate, I_C_Dunning_Candidate.COLUMNNAME_DunningGrace);
save(candidate);
}
private Iterator<I_C_Dunning_Candidate> retrieveSelectionIterator()
{
final StringBuilder sqlWhere = new StringBuilder();
final List<Object> params = new ArrayList<>();
if (!Check.isEmpty(getProcessInfo().getWhereClause(), true))
{
sqlWhere.append(getProcessInfo().getWhereClause())
.append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'"); // 03663 : Must make sure to take only unprocessed candidates.
}
else
{
// We have no where clause. Assume all unprocessed candidates.
sqlWhere.append(I_C_Dunning_Candidate.COLUMNNAME_IsActive + " = 'Y'")
.append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'");
}
return new Query(getCtx(), I_C_Dunning_Candidate.Table_Name, sqlWhere.toString(), get_TrxName())
.setParameters(params)
.setClient_ID()
.setOnlyActiveRecords(true)
.setRequiredAccess(Access.WRITE)
.iterate(I_C_Dunning_Candidate.class, false); // guaranteed=false
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_SetDunningGrace.java | 1 |
请完成以下Java代码 | public abstract class AbstractSecurityManager implements SecurityManager {
private static final String INVALID_AUTHENTICATED_PRINCIPAL = "Invalid authenticated principal";
private final SecurityContextPrincipalProvider securityContextPrincipalProvider;
private final PrincipalIdentityProvider principalIdentityProvider;
private final PrincipalGroupsProvider principalGroupsProvider;
private final PrincipalRolesProvider principalRolesProvider;
public AbstractSecurityManager(
SecurityContextPrincipalProvider securityContextPrincipalProvider,
PrincipalIdentityProvider principalIdentityProvider,
PrincipalGroupsProvider principalGroupsProvider,
PrincipalRolesProvider principalRolesProvider
) {
this.securityContextPrincipalProvider = securityContextPrincipalProvider;
this.principalIdentityProvider = principalIdentityProvider;
this.principalGroupsProvider = principalGroupsProvider;
this.principalRolesProvider = principalRolesProvider;
}
@Override
public String getAuthenticatedUserId() {
return securityContextPrincipalProvider
.getCurrentPrincipal()
.map(principalIdentityProvider::getUserId)
.orElseThrow(this::securityException);
} | @Override
public List<String> getAuthenticatedUserGroups() {
return securityContextPrincipalProvider
.getCurrentPrincipal()
.map(principalGroupsProvider::getGroups)
.orElseThrow(this::securityException);
}
@Override
public List<String> getAuthenticatedUserRoles() {
return securityContextPrincipalProvider
.getCurrentPrincipal()
.map(principalRolesProvider::getRoles)
.orElseThrow(this::securityException);
}
protected SecurityException securityException() {
return new SecurityException(INVALID_AUTHENTICATED_PRINCIPAL);
}
} | repos\Activiti-develop\activiti-api\activiti-api-runtime-shared\src\main\java\org\activiti\api\runtime\shared\security\AbstractSecurityManager.java | 1 |
请完成以下Java代码 | public boolean isApplicable(final Class<? extends AbstractStub<?>> stubType) {
return true;
}
@Override
public AbstractStub<?> createStub(final Class<? extends AbstractStub<?>> stubType, final Channel channel) {
try {
// Search for public static *Grpc#new*Stub(Channel)
final Class<?> declaringClass = stubType.getDeclaringClass();
if (declaringClass != null) {
for (final Method method : declaringClass.getMethods()) {
final String name = method.getName();
final int modifiers = method.getModifiers();
final Parameter[] parameters = method.getParameters();
if (name.startsWith("new") && name.endsWith("Stub")
&& Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)
&& method.getReturnType().isAssignableFrom(stubType) | && parameters.length == 1
&& Channel.class.equals(parameters[0].getType())) {
return AbstractStub.class.cast(method.invoke(null, channel));
}
}
}
// Search for a public constructor *Stub(Channel)
final Constructor<? extends AbstractStub<?>> constructor = stubType.getConstructor(Channel.class);
return constructor.newInstance(channel);
} catch (final Exception e) {
throw new BeanInstantiationException(stubType, "Failed to create gRPC client via FallbackStubFactory", e);
}
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\stubfactory\FallbackStubFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EdgeConnectionTriggerProcessor implements NotificationRuleTriggerProcessor<EdgeConnectionTrigger, EdgeConnectionNotificationRuleTriggerConfig> {
@Override
public boolean matchesFilter(EdgeConnectionTrigger trigger, EdgeConnectionNotificationRuleTriggerConfig triggerConfig) {
EdgeConnectivityEvent event = trigger.isConnected() ? EdgeConnectivityEvent.CONNECTED : EdgeConnectivityEvent.DISCONNECTED;
if (CollectionUtils.isEmpty(triggerConfig.getNotifyOn()) || !triggerConfig.getNotifyOn().contains(event)) {
return false;
}
if (CollectionUtils.isNotEmpty(triggerConfig.getEdges())) {
return triggerConfig.getEdges().contains(trigger.getEdgeId().getId());
}
return true;
}
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(EdgeConnectionTrigger trigger) { | return EdgeConnectionNotificationInfo.builder()
.eventType(trigger.isConnected() ? "connected" : "disconnected")
.tenantId(trigger.getTenantId())
.customerId(trigger.getCustomerId())
.edgeId(trigger.getEdgeId())
.edgeName(trigger.getEdgeName())
.build();
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.EDGE_CONNECTION;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\EdgeConnectionTriggerProcessor.java | 2 |
请完成以下Java代码 | public Double getX() {
return xAttribute.getValue(this);
}
public void setX(double x) {
xAttribute.setValue(this, x);
}
public Double getY() {
return yAttribute.getValue(this);
}
public void setY(double y) {
yAttribute.setValue(this, y);
}
public Double getWidth() { | return widthAttribute.getValue(this);
}
public void setWidth(double width) {
widthAttribute.setValue(this, width);
}
public Double getHeight() {
return heightAttribute.getValue(this);
}
public void setHeight(double height) {
heightAttribute.setValue(this, height);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\dc\BoundsImpl.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((courseId == null) ? 0 : courseId.hashCode());
result = prime * result + ((studentId == null) ? 0 : studentId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) | return false;
CourseRatingKey other = (CourseRatingKey) obj;
if (courseId == null) {
if (other.courseId != null)
return false;
} else if (!courseId.equals(other.courseId))
return false;
if (studentId == null) {
if (other.studentId != null)
return false;
} else if (!studentId.equals(other.studentId))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\CourseRatingKey.java | 1 |
请完成以下Java代码 | public static LocalPortForwarder localPortForwarding(SSHClient ssh) throws IOException, InterruptedException {
LocalPortForwarder locForwarder;
final Parameters params = new Parameters(ssh.getRemoteHostname(), 8081, "google.com", 80);
final ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(params.getLocalHost(), params.getLocalPort()));
locForwarder = ssh.newLocalPortForwarder(params, ss);
new Thread(() -> {
try {
locForwarder.listen();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
return locForwarder;
}
public static RemotePortForwarder remotePortForwarding(SSHClient ssh) throws IOException, InterruptedException {
RemotePortForwarder rpf;
ssh.getConnection()
.getKeepAlive()
.setKeepAliveInterval(5);
rpf = ssh.getRemotePortForwarder();
new Thread(() -> {
try {
rpf.bind(new Forward(8083), new SocketForwardingConnectListener(new InetSocketAddress("google.com", 80)));
ssh.getTransport()
.join();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
return rpf;
}
public static String KeepAlive(String hostName, String userName, String password) throws IOException, InterruptedException {
String response = "";
DefaultConfig defaultConfig = new DefaultConfig();
defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE);
final SSHClient ssh = new SSHClient(defaultConfig); | try {
ssh.addHostKeyVerifier(new PromiscuousVerifier());
ssh.connect(hostName, 22);
ssh.getConnection()
.getKeepAlive()
.setKeepAliveInterval(5);
ssh.authPassword(userName, password);
Session session = ssh.startSession();
session.allocateDefaultPTY();
new CountDownLatch(1).await();
try {
session.allocateDefaultPTY();
} finally {
session.close();
}
} finally {
ssh.disconnect();
}
response = "success";
return response;
}
} | repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\sshj\SSHJAppDemo.java | 1 |
请完成以下Java代码 | public class ImmutableFeatureMDatMap extends FeatureMap
{
MutableDoubleArrayTrieInteger dat;
public ImmutableFeatureMDatMap()
{
super();
dat = new MutableDoubleArrayTrieInteger();
}
public ImmutableFeatureMDatMap(TagSet tagSet)
{
super(tagSet);
dat = new MutableDoubleArrayTrieInteger();
}
public ImmutableFeatureMDatMap(MutableDoubleArrayTrieInteger dat, TagSet tagSet)
{
super(tagSet);
this.dat = dat;
}
public ImmutableFeatureMDatMap(Map<String, Integer> featureIdMap, TagSet tagSet)
{
super(tagSet);
dat = new MutableDoubleArrayTrieInteger(featureIdMap);
}
public ImmutableFeatureMDatMap(Set<Map.Entry<String, Integer>> featureIdSet, TagSet tagSet)
{
super(tagSet);
dat = new MutableDoubleArrayTrieInteger();
for (Map.Entry<String, Integer> entry : featureIdSet)
{
dat.put(entry.getKey(), entry.getValue());
}
}
@Override
public int idOf(String string)
{
return dat.get(string);
} | @Override
public int size()
{
return dat.size();
}
@Override
public Set<Map.Entry<String, Integer>> entrySet()
{
return dat.entrySet();
}
@Override
public void save(DataOutputStream out) throws IOException
{
tagSet.save(out);
dat.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
loadTagSet(byteArray);
return dat.load(byteArray);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\ImmutableFeatureMDatMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, List<Object>> getAttributes() {
return this.attributes;
}
@Override
public String getResponseValue() {
return this.responseValue;
}
public static final class Builder {
private final String responseValue;
private String nameId;
private List<String> sessionIndexes = List.of();
private Map<String, List<Object>> attributes = Map.of();
Builder(String responseValue) {
this.responseValue = responseValue;
} | public Builder nameId(String nameId) {
this.nameId = nameId;
return this;
}
public Builder sessionIndexes(List<String> sessionIndexes) {
this.sessionIndexes = sessionIndexes;
return this;
}
public Builder attributes(Map<String, List<Object>> attributes) {
this.attributes = attributes;
return this;
}
public Saml2ResponseAssertion build() {
return new Saml2ResponseAssertion(this.responseValue, this.nameId, this.sessionIndexes, this.attributes);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2ResponseAssertion.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setInterchangeHeader(InterchangeHeaderType value) {
this.interchangeHeader = value;
}
/**
* The ID represents the unique number of the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* This segment contains references related to the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferences() {
return references;
}
/**
* Sets the value of the references property.
*
* @param value
* allowed object is
* {@link String }
* | */
public void setReferences(String value) {
this.references = value;
}
/**
* Flag indicating whether the message is a test message or not.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTestIndicator() {
return testIndicator;
}
/**
* Sets the value of the testIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTestIndicator(Boolean value) {
this.testIndicator = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\ErpelBusinessDocumentHeaderType.java | 2 |
请完成以下Java代码 | public String getFunctionNameFQ() {return className + " - " + functionName;}
}
enum Type
{
MODEL_INTERCEPTOR("modelInterceptor"),
DOC_ACTION("docAction"),
ASYNC_WORKPACKAGE("asyncWorkPackage"),
SCHEDULER("scheduler"),
EVENTBUS_REMOTE_ENDPOINT("eventbus-remote-endpoint"),
REST_CONTROLLER("rest-controller"),
REST_CONTROLLER_WITH_WINDOW_ID("rest-controller-with-windowId"),
PO("po"), | DB("db");
Type(final String code)
{
this.code = code;
}
public boolean isAnyRestControllerType()
{
return this == Type.REST_CONTROLLER || this == Type.REST_CONTROLLER_WITH_WINDOW_ID;
}
@Getter
private final String code;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\PerformanceMonitoringService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalSystemAlbertaConfigId implements IExternalSystemChildConfigId
{
int repoId;
@JsonCreator
@NonNull
public static ExternalSystemAlbertaConfigId ofRepoId(final int repoId)
{
return new ExternalSystemAlbertaConfigId(repoId);
}
@Nullable
public static ExternalSystemAlbertaConfigId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ExternalSystemAlbertaConfigId(repoId) : null;
}
public static ExternalSystemAlbertaConfigId cast(@NonNull final IExternalSystemChildConfigId id)
{
return (ExternalSystemAlbertaConfigId)id;
}
@JsonValue
public int toJson() | {
return getRepoId();
}
private ExternalSystemAlbertaConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_Config_Alberta_ID");
}
@Override
public ExternalSystemType getType()
{
return ExternalSystemType.Alberta;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\alberta\ExternalSystemAlbertaConfigId.java | 2 |
请完成以下Java代码 | public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken {
private String idToken; | JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\UserJWTController.java | 1 |
请完成以下Java代码 | private static TableRecordReference toTableRecordRef(final CustomsInvoice customsInvoice)
{
return TableRecordReference.of(I_C_Customs_Invoice.Table_Name, customsInvoice.getId());
}
private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private final UserId getNotificationRecipientUserId(final CustomsInvoice customsInvoice)
{
//
// In case of reversal i think we shall notify the current user too
if (customsInvoice.getDocStatus().isReversedOrVoided())
{ | return customsInvoice.getLastUpdatedBy();
}
//
// Fallback: notify only the creator
else
{
return customsInvoice.getCreatedBy();
}
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\event\CustomsInvoiceUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public I_R_Status getR_Status() throws RuntimeException
{
return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name)
.getPO(getR_Status_ID(), get_TrxName()); }
/** Set Status.
@param R_Status_ID
Request Status
*/
public void setR_Status_ID (int R_Status_ID)
{
if (R_Status_ID < 1)
set_Value (COLUMNNAME_R_Status_ID, null);
else
set_Value (COLUMNNAME_R_Status_ID, Integer.valueOf(R_Status_ID));
}
/** Get Status.
@return Request Status
*/
public int getR_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request Status.
@param R_Status_Value Request Status */
public void setR_Status_Value (String R_Status_Value)
{
set_Value (COLUMNNAME_R_Status_Value, R_Status_Value);
}
/** Get Request Status.
@return Request Status */
public String getR_Status_Value ()
{
return (String)get_Value(COLUMNNAME_R_Status_Value);
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); } | /** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_RV_R_Group_Prospect.java | 1 |
请完成以下Java代码 | public void setPeriod_OpenFuture (final int Period_OpenFuture)
{
set_Value (COLUMNNAME_Period_OpenFuture, Period_OpenFuture);
}
@Override
public int getPeriod_OpenFuture()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenFuture);
}
@Override
public void setPeriod_OpenHistory (final int Period_OpenHistory)
{
set_Value (COLUMNNAME_Period_OpenHistory, Period_OpenHistory);
}
@Override
public int getPeriod_OpenHistory()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenHistory);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator); | }
/**
* TaxCorrectionType AD_Reference_ID=392
* Reference name: C_AcctSchema TaxCorrectionType
*/
public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392;
/** None = N */
public static final String TAXCORRECTIONTYPE_None = "N";
/** Write_OffOnly = W */
public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */
public static final String TAXCORRECTIONTYPE_DiscountOnly = "D";
/** Write_OffAndDiscount = B */
public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B";
@Override
public void setTaxCorrectionType (final java.lang.String TaxCorrectionType)
{
set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType);
}
@Override
public java.lang.String getTaxCorrectionType()
{
return get_ValueAsString(COLUMNNAME_TaxCorrectionType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java | 1 |
请完成以下Spring Boot application配置 | mp.jwt.verify.publickey.location=publicKey.pem
quarkus.native.resources.includes=publicKey.pem
mp.jwt.verify.issuer=my-issuer
smallrye.jwt.sign.key.location=privateKey.pem
quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:testdb_;DB_CLOSE_DELAY=-1;MODE=MYSQL;DB_CLOSE_ON_EXIT=TRUE;DATABASE_TO_LOWER=TRUE
quarkus.hibernate-orm.dialect=org.hibernate.dialect.MySQLDialect
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.hibernate-orm.log.sql=true
quarkus.hibernate-orm.sql-load-script=import.sql
quarkus.http.auth.policy.role-policy1.permissions.VIEW_ADMIN_DETAILS=VIEW_ADMIN_DETAILS
quarkus.http.auth.policy.role-policy1.permissions.VIEW_USER_DETAILS=VIEW_USER_DETAILS
quarkus.http.auth.poli | cy.role-policy1.permissions.SEND_MESSAGE=SEND_MESSAGE
quarkus.http.auth.policy.role-policy1.permissions.CREATE_USER=CREATE_USER
quarkus.http.auth.policy.role-policy1.permissions.OPERATOR=OPERATOR
quarkus.http.auth.permission.roles1.paths=/permission-based/*
quarkus.http.auth.permission.roles1.policy=role-policy1 | repos\tutorials-master\quarkus-modules\quarkus-rbac\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setDateNextRun(Timestamp dateNextWork)
{
impProcessor.setDateNextRun(dateNextWork);
}
@Override
public Timestamp getDateLastRun()
{
return impProcessor.getDateLastRun();
}
@Override
public void setDateLastRun(Timestamp dateLastRun)
{
impProcessor.setDateLastRun(dateLastRun);
}
@Override
public boolean saveOutOfTrx()
{
InterfaceWrapperHelper.save(impProcessor, ITrx.TRXNAME_None);
return true; | }
@Override
public AdempiereProcessorLog[] getLogs()
{
final List<AdempiereProcessorLog> list = Services.get(IIMPProcessorDAO.class).retrieveAdempiereProcessorLogs(impProcessor);
return list.toArray(new AdempiereProcessorLog[list.size()]);
}
@Override
public String get_TableName()
{
return I_IMP_Processor.Table_Name;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\IMPProcessorAdempiereProcessorAdapter.java | 1 |
请完成以下Java代码 | private final Class<?> getDocLineClass(final int adTableId)
{
final String tableName = tableDAO.retrieveTableName(adTableId);
return headerTableName2lineModelClass.get(tableName);
}
private final IActivityAware getDocLineActivityAwareOrNull(final I_Fact_Acct_ActivityChangeRequest request)
{
final Class<?> lineClass = getDocLineClass(request.getAD_Table_ID());
if (lineClass == null)
{
addLog("Skip {0} because it's not supported", request);
return null;
}
final int lineId = request.getLine_ID();
if (lineId <= 0)
{
addLog("Skip {0} because it does not have the Line_ID set", request);
return null;
}
final Object line = InterfaceWrapperHelper.create(getCtx(), lineId, lineClass, ITrx.TRXNAME_ThreadInherited);
final IActivityAware activityAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(line, IActivityAware.class);
if (activityAware == null)
{
// no activity on line level
addLog("Skip {0} because it does not provide an activity", line);
return null; | }
return activityAware;
}
@VisibleForTesting
static interface IActivityAware
{
String COLUMNNAME_C_Activity_ID = "C_Activity_ID";
int getC_Activity_ID();
void setC_Activity_ID(final int activityId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\Fact_Acct_ActivityChangeRequest_Process.java | 1 |
请完成以下Java代码 | public boolean isPKey()
{
return m_isPKey;
} // isPKey
/**
* Column value forces page break
* @return true if page break
*/
public boolean isPageBreak()
{
return m_isPageBreak;
} // isPageBreak
/*************************************************************************/
/**
* HashCode
* @return hash code
*/
public int hashCode()
{
if (m_value == null)
return m_columnName.hashCode();
return m_columnName.hashCode() + m_value.hashCode();
} // hashCode
/**
* Equals
* @param compare compare object
* @return true if equals
*/
public boolean equals (Object compare)
{
if (compare instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)compare;
if (pde.getColumnName().equals(m_columnName))
{
if (pde.getValue() != null && pde.getValue().equals(m_value))
return true;
if (pde.getValue() == null && m_value == null)
return true;
}
}
return false;
} // equals
/**
* String representation
* @return info | */
public String toString()
{
StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value);
if (m_isPKey)
sb.append("(PK)");
return sb.toString();
} // toString
/**
* Value Has Key
* @return true if value has a key
*/
public boolean hasKey()
{
return m_value instanceof NamePair;
} // hasKey
/**
* String representation with key info
* @return info
*/
public String toStringX()
{
if (m_value instanceof NamePair)
{
NamePair pp = (NamePair)m_value;
StringBuffer sb = new StringBuffer(m_columnName);
sb.append("(").append(pp.getID()).append(")")
.append("=").append(pp.getName());
if (m_isPKey)
sb.append("(PK)");
return sb.toString();
}
else
return toString();
} // toStringX
public String getM_formatPattern() {
return m_formatPattern;
}
public void setM_formatPattern(String pattern) {
m_formatPattern = pattern;
}
} // PrintDataElement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java | 1 |
请完成以下Java代码 | private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
}
private static List<String> convertScope(Object scope) {
if (scope == null) {
return Collections.emptyList();
}
return Arrays.asList(StringUtils.delimitedListToStringArray(scope.toString(), " "));
}
}
private static final class OAuth2TokenIntrospectionMapConverter
implements Converter<OAuth2TokenIntrospection, Map<String, Object>> {
@Override
public Map<String, Object> convert(OAuth2TokenIntrospection source) {
Map<String, Object> responseClaims = new LinkedHashMap<>(source.getClaims());
if (!CollectionUtils.isEmpty(source.getScopes())) { | responseClaims.put(OAuth2TokenIntrospectionClaimNames.SCOPE,
StringUtils.collectionToDelimitedString(source.getScopes(), " "));
}
if (source.getExpiresAt() != null) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.EXP, source.getExpiresAt().getEpochSecond());
}
if (source.getIssuedAt() != null) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.IAT, source.getIssuedAt().getEpochSecond());
}
if (source.getNotBefore() != null) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.NBF, source.getNotBefore().getEpochSecond());
}
return responseClaims;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\http\converter\OAuth2TokenIntrospectionHttpMessageConverter.java | 1 |
请完成以下Java代码 | public final C_AllocationHdr_Builder currencyId(@NonNull final CurrencyId currencyId)
{
return currencyId(currencyId.getRepoId());
}
public final C_AllocationHdr_Builder currencyId(int currencyId)
{
assertNotBuilt();
allocHdr.setC_Currency_ID(currencyId);
return this;
}
public final C_AllocationHdr_Builder manual(final boolean manual)
{
assertNotBuilt();
allocHdr.setIsManual(manual);
return this;
}
public C_AllocationHdr_Builder description(final String description)
{
assertNotBuilt();
allocHdr.setDescription(description);
return this;
}
public C_AllocationLine_Builder addLine() | {
assertNotBuilt();
final C_AllocationLine_Builder lineBuilder = new C_AllocationLine_Builder(this);
allocationLineBuilders.add(lineBuilder);
return lineBuilder;
}
public final ImmutableList<I_C_AllocationLine> getC_AllocationLines()
{
return ImmutableList.copyOf(allocationLines);
}
public C_AllocationHdr_Builder disableUpdateBPartnerTotalOpenBanace()
{
IBPartnerStatisticsUpdater.DYNATTR_DisableUpdateTotalOpenBalances.setValue(allocHdr, true);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\C_AllocationHdr_Builder.java | 1 |
请完成以下Java代码 | public void setUseLifeYears (int UseLifeYears)
{
set_ValueNoCheck (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units. | @return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Change.java | 1 |
请完成以下Java代码 | public WindowId getWindowId()
{
return WINDOW_ID;
}
@Override
public void put(final IView view)
{
views.put(view);
}
@Nullable
@Override
public BankStatementReconciliationView getByIdOrNull(final ViewId viewId)
{
return BankStatementReconciliationView.cast(views.getByIdOrNull(viewId));
}
@Override
public void closeById(final ViewId viewId, final ViewCloseAction closeAction)
{
views.closeById(viewId, closeAction);
}
@Override
public Stream<IView> streamAllViews()
{
return views.streamAllViews();
} | @Override
public void invalidateView(final ViewId viewId)
{
views.invalidateView(viewId);
}
private List<RelatedProcessDescriptor> getPaymentToReconcilateProcesses()
{
return ImmutableList.of(
createProcessDescriptor(PaymentsToReconcileView_Reconcile.class));
}
private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClass(processClass))
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementReconciliationViewFactory.java | 1 |
请完成以下Java代码 | public InvoiceCandidate2WorkpackageAggregator setAD_PInstance_Creator_ID(@NonNull final PInstanceId adPInstanceId)
{
this.pInstanceId = adPInstanceId;
return this;
}
public InvoiceCandidate2WorkpackageAggregator setAsyncBatchId(final AsyncBatchId asyncBatchId)
{
_asyncBatchId = asyncBatchId;
return this;
}
public InvoiceCandidate2WorkpackageAggregator setPriority(final IWorkpackagePrioStrategy priority)
{
workpackagePriority = priority;
return this; | }
public InvoiceCandidate2WorkpackageAggregator setInvoicingParams(@NonNull final IInvoicingParams invoicingParams)
{
this.invoicingParams = invoicingParams;
return this;
}
/**
* Gets unprocessed workpackages queue size
*/
public final int getQueueSize()
{
return getWorkPackageQueue().size();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidate2WorkpackageAggregator.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.