instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | Factory propagationFactory(BaggagePropagation.FactoryBuilder factoryBuilder) {
return factoryBuilder.build();
}
@Bean
@ConditionalOnMissingBean
CorrelationScopeDecorator.Builder mdcCorrelationScopeDecoratorBuilder(
ObjectProvider<CorrelationScopeCustomizer> correlationScopeCustomizers) {
CorrelationScopeDecorator.Builder builder = MDCScopeDecorator.newBuilder();
correlationScopeCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return builder;
}
@Bean
@Order(0)
@ConditionalOnBooleanProperty(name = "management.tracing.baggage.correlation.enabled", matchIfMissing = true)
CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() {
return (builder) -> {
Correlation correlationProperties = this.tracingProperties.getBaggage().getCorrelation();
for (String field : correlationProperties.getFields()) {
BaggageField baggageField = BaggageField.create(field);
SingleCorrelationField correlationField = SingleCorrelationField.newBuilder(baggageField)
.flushOnUpdate()
.build();
builder.add(correlationField);
}
};
}
@Bean
@ConditionalOnMissingBean(CorrelationScopeDecorator.class)
ScopeDecorator correlationScopeDecorator(CorrelationScopeDecorator.Builder builder) {
return builder.build();
}
} | /**
* Propagates neither traces nor baggage.
*/
@Configuration(proxyBeanMethods = false)
static class NoPropagation {
@Bean
@ConditionalOnMissingBean(Factory.class)
CompositePropagationFactory noopPropagationFactory() {
return CompositePropagationFactory.noop();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-brave\src\main\java\org\springframework\boot\micrometer\tracing\brave\autoconfigure\BravePropagationConfigurations.java | 2 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getSqlDate() {
return sqlDate;
}
public void setSqlDate(Date sqlDate) {
this.sqlDate = sqlDate;
}
public Time getSqlTime() {
return sqlTime;
}
public void setSqlTime(Time sqlTime) {
this.sqlTime = sqlTime;
}
public Timestamp getSqlTimestamp() {
return sqlTimestamp;
}
public void setSqlTimestamp(Timestamp sqlTimestamp) {
this.sqlTimestamp = sqlTimestamp;
}
public java.util.Date getUtilDate() {
return utilDate;
}
public void setUtilDate(java.util.Date utilDate) {
this.utilDate = utilDate;
}
public java.util.Date getUtilTime() {
return utilTime;
}
public void setUtilTime(java.util.Date utilTime) {
this.utilTime = utilTime;
}
public java.util.Date getUtilTimestamp() {
return utilTimestamp;
}
public void setUtilTimestamp(java.util.Date utilTimestamp) {
this.utilTimestamp = utilTimestamp;
}
public Calendar getCalendarDate() {
return calendarDate;
}
public void setCalendarDate(Calendar calendarDate) {
this.calendarDate = calendarDate;
}
public Calendar getCalendarTimestamp() {
return calendarTimestamp;
}
public void setCalendarTimestamp(Calendar calendarTimestamp) { | this.calendarTimestamp = calendarTimestamp;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
public LocalTime getLocalTime() {
return localTimeField;
}
public void setLocalTime(LocalTime localTime) {
this.localTimeField = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\pojo\TemporalValues.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ChannelSecSecurityConfig {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user1 = User.withUsername("user1")
.password("user1Pass")
.roles("USER")
.build();
UserDetails user2 = User.withUsername("user2")
.password("user2Pass")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user1, user2);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.requestMatchers("/anonymous*")
.anonymous()
.requestMatchers("/login*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.requiresChannel()
.requestMatchers("/login*", "/perform_login")
.requiresSecure()
.anyRequest()
.requiresInsecure()
.and()
.sessionManagement() | .sessionFixation()
.none()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)
.failureUrl("/login.html?error=true")
.and()
.logout()
.logoutUrl("/perform_logout")
.deleteCookies("JSESSIONID")
.logoutSuccessHandler(logoutSuccessHandler());
return http.build();
}
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new CustomLogoutSuccessHandler();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\spring\ChannelSecSecurityConfig.java | 2 |
请完成以下Java代码 | public class Order {
/**
* 订单ID
*/
private String id;
/**
* 商品ID
*/
private String productId;
/**
* 商品名称
*/
private String productName;
/**
* 购买数量
*/
private Integer quantity;
/**
* 单价
*/
private BigDecimal unitPrice;
/**
* 总金额 | */
private BigDecimal totalAmount;
/**
* 订单状态: pending-待支付, paid-已支付, cancelled-已取消
*/
private String status;
/**
* 创建时间
*/
private Date createTime;
/**
* 用户信息(可选)
*/
private String userId;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\shop\entity\Order.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
public boolean isShowInOverview() {
return showInOverview;
}
public void setShowInOverview(boolean showInOverview) {
this.showInOverview = showInOverview;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-planitem-instances/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4")
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) { | this.caseDefinitionUrl = caseDefinitionUrl;
}
public String getDerivedCaseDefinitionUrl() {
return derivedCaseDefinitionUrl;
}
public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) {
this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl;
}
public String getStageInstanceUrl() {
return stageInstanceUrl;
}
public void setStageInstanceUrl(String stageInstanceUrl) {
this.stageInstanceUrl = stageInstanceUrl;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | public java.math.BigDecimal getQtyPromised_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
/** Set Old Zusagbar (TU).
@param QtyPromised_TU_Old Old Zusagbar (TU) */
@Override
public void setQtyPromised_TU_Old (java.math.BigDecimal QtyPromised_TU_Old)
{
set_Value (COLUMNNAME_QtyPromised_TU_Old, QtyPromised_TU_Old); | }
/** Get Old Zusagbar (TU).
@return Old Zusagbar (TU) */
@Override
public java.math.BigDecimal getQtyPromised_TU_Old ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_Old);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_QtyReport_Event.java | 1 |
请在Spring Boot框架中完成以下Java代码 | boolean isOnlyAdditional() {
return this.onlyAdditional;
}
Set<WebServiceMessageSender> getMessageSenders() {
return this.messageSenders;
}
WebServiceMessageSenders set(Collection<? extends WebServiceMessageSender> messageSenders) {
return new WebServiceMessageSenders(false, new LinkedHashSet<>(messageSenders));
}
WebServiceMessageSenders add(Collection<? extends WebServiceMessageSender> messageSenders) {
return new WebServiceMessageSenders(this.onlyAdditional, append(this.messageSenders, messageSenders));
}
}
/**
* {@link WebServiceTemplateCustomizer} to set
* {@link WebServiceTemplate#setCheckConnectionForFault(boolean)
* checkConnectionForFault}.
*/
private static final class CheckConnectionFaultCustomizer implements WebServiceTemplateCustomizer {
private final boolean checkConnectionFault;
private CheckConnectionFaultCustomizer(boolean checkConnectionFault) {
this.checkConnectionFault = checkConnectionFault;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setCheckConnectionForFault(this.checkConnectionFault);
}
}
/**
* {@link WebServiceTemplateCustomizer} to set
* {@link WebServiceTemplate#setCheckConnectionForError(boolean) | * checkConnectionForError}.
*/
private static final class CheckConnectionForErrorCustomizer implements WebServiceTemplateCustomizer {
private final boolean checkConnectionForError;
private CheckConnectionForErrorCustomizer(boolean checkConnectionForError) {
this.checkConnectionForError = checkConnectionForError;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setCheckConnectionForError(this.checkConnectionForError);
}
}
/**
* {@link WebServiceTemplateCustomizer} to set
* {@link WebServiceTemplate#setFaultMessageResolver(FaultMessageResolver)
* faultMessageResolver}.
*/
private static final class FaultMessageResolverCustomizer implements WebServiceTemplateCustomizer {
private final FaultMessageResolver faultMessageResolver;
private FaultMessageResolverCustomizer(FaultMessageResolver faultMessageResolver) {
this.faultMessageResolver = faultMessageResolver;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setFaultMessageResolver(this.faultMessageResolver);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\client\WebServiceTemplateBuilder.java | 2 |
请完成以下Java代码 | public AsyncContinuationConfiguration newConfiguration(String canonicalString) {
String[] configParts = tokenizeJobConfiguration(canonicalString);
AsyncContinuationConfiguration configuration = new AsyncContinuationConfiguration();
configuration.setAtomicOperation(configParts[0]);
configuration.setTransitionId(configParts[1]);
return configuration;
}
/**
* @return an array of length two with the following contents:
* <ul><li>First element: pvm atomic operation name
* <li>Second element: transition id (may be null)
*/
protected String[] tokenizeJobConfiguration(String jobConfiguration) {
String[] configuration = new String[2];
if (jobConfiguration != null ) {
String[] configParts = jobConfiguration.split("\\$");
if (configuration.length > 2) {
throw new ProcessEngineException("Illegal async continuation job handler configuration: '" + jobConfiguration + "': exprecting one part or two parts seperated by '$'.");
}
configuration[0] = configParts[0];
if (configParts.length == 2) {
configuration[1] = configParts[1];
}
}
return configuration;
}
public static class AsyncContinuationConfiguration implements JobHandlerConfiguration {
protected String atomicOperation;
protected String transitionId; | public String getAtomicOperation() {
return atomicOperation;
}
public void setAtomicOperation(String atomicOperation) {
this.atomicOperation = atomicOperation;
}
public String getTransitionId() {
return transitionId;
}
public void setTransitionId(String transitionId) {
this.transitionId = transitionId;
}
@Override
public String toCanonicalString() {
String configuration = atomicOperation;
if(transitionId != null) {
// store id of selected transition in case this is async after.
// id is not serialized with the execution -> we need to remember it as
// job handler configuration.
configuration += "$" + transitionId;
}
return configuration;
}
}
public void onDelete(AsyncContinuationConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\AsyncContinuationJobHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String home() {
return format("Near Caching Example");
}
@GetMapping("/ping")
public String ping() {
return format("PONG");
}
@GetMapping("/yellow-pages/{name}")
public String find(@PathVariable("name") String name) {
long t0 = System.currentTimeMillis();
Person person = this.yellowPages.find(name);
return format(String.format("{ person: %s, cacheMiss: %s, latency: %d ms }",
person, this.yellowPages.isCacheMiss(), (System.currentTimeMillis() - t0)));
}
@GetMapping("/yellow-pages/{name}/update")
public String update(@PathVariable("name") String name, | @RequestParam(name = "email", required = false) String email,
@RequestParam(name = "phoneNumber", required = false) String phoneNumber) {
Person person = this.yellowPages.save(this.yellowPages.find(name), email, phoneNumber);
return format(String.format("{ person: %s }", person));
}
@GetMapping("/yellow-pages/{name}/evict")
public String evict(@PathVariable("name") String name) {
this.yellowPages.evict(name);
return format(String.format("Evicted %s", name));
}
private String format(String value) {
return String.format(HTML, value);
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\client\controller\YellowPagesController.java | 2 |
请完成以下Java代码 | public class X_M_Nutrition_Fact extends org.compiere.model.PO implements I_M_Nutrition_Fact, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 192120900L;
/** Standard Constructor */
public X_M_Nutrition_Fact (Properties ctx, int M_Nutrition_Fact_ID, String trxName)
{
super (ctx, M_Nutrition_Fact_ID, trxName);
/** if (M_Nutrition_Fact_ID == 0)
{
setM_Nutrition_Fact_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_M_Nutrition_Fact (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;
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Nutrition Fact.
@param M_Nutrition_Fact_ID Nutrition Fact */
@Override
public void setM_Nutrition_Fact_ID (int M_Nutrition_Fact_ID)
{
if (M_Nutrition_Fact_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, Integer.valueOf(M_Nutrition_Fact_ID));
}
/** Get Nutrition Fact.
@return Nutrition Fact */ | @Override
public int getM_Nutrition_Fact_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Nutrition_Fact_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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Nutrition_Fact.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private <E extends HasImage> void updateImages(Iterable<? extends EntityId> entitiesIds, String type,
Function<E, Boolean> updater, Dao<E> dao) {
int totalCount = 0;
int updatedCount = 0;
var counts = updateImages(entitiesIds, type, updater, dao, totalCount, updatedCount);
totalCount = counts[0];
updatedCount = counts[1];
log.info("Updated {} {}s out of {}", updatedCount, type, totalCount);
}
private <E extends HasImage> void updateImages(String type, BiFunction<TenantId, PageLink, PageData<? extends EntityId>> entityIdsByTenantId,
Function<E, Boolean> updater, Dao<E> dao) {
int tenantCount = 0;
int totalCount = 0;
int updatedCount = 0;
var tenantIds = new PageDataIterable<>(tenantDao::findTenantsIds, 128);
for (var tenantId : tenantIds) {
tenantCount++;
var entitiesIds = new PageDataIterable<>(link -> entityIdsByTenantId.apply(tenantId, link), 128);
var counts = updateImages(entitiesIds, type, updater, dao, totalCount, updatedCount);
totalCount = counts[0];
updatedCount = counts[1];
if (tenantCount % 100 == 0) {
log.info("Update {}s images: processed {} tenants so far", type, tenantCount);
}
}
log.info("Updated {} {}s out of {}", updatedCount, type, totalCount);
}
private <E extends HasImage> int[] updateImages(Iterable<? extends EntityId> entitiesIds, String type,
Function<E, Boolean> updater, Dao<E> dao, int totalCount, int updatedCount) {
for (EntityId id : entitiesIds) {
totalCount++; | E entity;
try {
entity = dao.findById(TenantId.SYS_TENANT_ID, id.getId());
} catch (Exception e) {
log.error("Failed to update {} images: error fetching entity by id [{}]: {}", type, id.getId(), StringUtils.abbreviate(e.toString(), 1000));
continue;
}
try {
boolean updated = updater.apply(entity);
if (updated) {
dao.save(entity.getTenantId(), entity);
log.debug("[{}][{}] Updated {} images", entity.getTenantId(), entity.getName(), type);
updatedCount++;
}
} catch (Exception e) {
log.error("[{}][{}] Failed to update {} images", entity.getTenantId(), entity.getName(), type, e);
}
if (totalCount % 100 == 0) {
log.info("Processed {} {}s so far", totalCount, type);
}
}
return new int[]{totalCount, updatedCount};
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\update\ResourcesUpdater.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public FormType getType() {
return type;
}
public void setType(AbstractFormFieldType type) {
this.type = type;
}
public boolean isReadable() {
return isReadable;
}
public void setReadable(boolean isReadable) {
this.isReadable = isReadable;
}
public boolean isRequired() {
return isRequired;
} | public void setRequired(boolean isRequired) {
this.isRequired = isRequired;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public Expression getVariableExpression() {
return variableExpression;
}
public void setVariableExpression(Expression variableExpression) {
this.variableExpression = variableExpression;
}
public Expression getDefaultExpression() {
return defaultExpression;
}
public void setDefaultExpression(Expression defaultExpression) {
this.defaultExpression = defaultExpression;
}
public boolean isWritable() {
return isWritable;
}
public void setWritable(boolean isWritable) {
this.isWritable = isWritable;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\FormPropertyHandler.java | 1 |
请完成以下Java代码 | public void registerShutdownTask(ShutdownContext shutdownContext,
RuntimeValue<ProcessEngine> processEngine) {
// cleanup on application shutdown
shutdownContext.addShutdownTask(() -> {
ProcessEngine engine = processEngine.getValue();
// shutdown the JobExecutor
ProcessEngineConfigurationImpl configuration
= (ProcessEngineConfigurationImpl) engine.getProcessEngineConfiguration();
JobExecutor executor = configuration.getJobExecutor();
executor.shutdown();
// deregister the Process Engine from the runtime container delegate
RuntimeContainerDelegate runtimeContainerDelegate = RuntimeContainerDelegate.INSTANCE.get();
runtimeContainerDelegate.unregisterProcessEngine(engine);
});
}
protected void configureJobExecutor(ProcessEngineConfigurationImpl configuration,
CamundaEngineConfig config) {
int maxPoolSize = config.jobExecutor().threadPool().maxPoolSize();
int queueSize = config.jobExecutor().threadPool().queueSize();
// create a non-bean ManagedExecutor instance. This instance
// uses it's own Executor/thread pool. | ManagedExecutor managedExecutor = SmallRyeManagedExecutor.builder()
.maxQueued(queueSize)
.maxAsync(maxPoolSize)
.withNewExecutorService()
.build();
ManagedJobExecutor quarkusJobExecutor = new ManagedJobExecutor(managedExecutor);
// apply job executor configuration properties
PropertyHelper
.applyProperties(quarkusJobExecutor, config.jobExecutor().genericConfig(), PropertyHelper.KEBAB_CASE);
configuration.setJobExecutor(quarkusJobExecutor);
}
/**
* Retrieves a bean of the given class from the bean container.
*
* @param beanClass the class of the desired bean to fetch from the container
* @param beanContainer the bean container
* @param <T> the type of the bean to fetch
* @return the bean
*/
protected <T> T getBeanFromContainer(Class<T> beanClass, BeanContainer beanContainer) {
try (BeanContainer.Instance<T> beanManager = beanContainer.beanInstanceFactory(beanClass).create()) {
return beanManager.get();
}
}
} | repos\camunda-bpm-platform-master\quarkus-extension\engine\runtime\src\main\java\org\camunda\bpm\quarkus\engine\extension\impl\CamundaEngineRecorder.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("day", day)
.add("qtyPlanned", qtyPlanned)
.add("qtyPlannedAllocated", qtyPlannedAllocated)
.toString();
}
public Date getDay()
{
return day;
}
public void addQtyPlanned(final BigDecimal qtyPlannedToAdd)
{
if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0)
{
return;
} | qtyPlanned = qtyPlanned.add(qtyPlannedToAdd);
}
public BigDecimal allocateQtyPlanned()
{
final BigDecimal qtyPlannedToAllocate = qtyPlanned.subtract(qtyPlannedAllocated);
qtyPlannedAllocated = qtyPlanned;
return qtyPlannedToAllocate;
}
public boolean isFullyAllocated()
{
return qtyPlannedAllocated.compareTo(qtyPlanned) == 0;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\PMMContractBuilder.java | 1 |
请完成以下Java代码 | public static Map<String, EventRegistryEngine> getEventRegistryEngines() {
return eventRegistryEngines;
}
/**
* closes all event registry engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, EventRegistryEngine> engines = new HashMap<>(eventRegistryEngines);
eventRegistryEngines = new HashMap<>();
for (String eventRegistryEngineName : engines.keySet()) {
EventRegistryEngine eventRegistryEngine = engines.get(eventRegistryEngineName);
try {
eventRegistryEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (eventRegistryEngineName == null ? "the default event registry engine" :
"event registry engine " + eventRegistryEngineName), e);
}
}
eventRegistryEngineInfosByName.clear(); | eventRegistryEngineInfosByResourceUrl.clear();
eventRegistryEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
EventRegistryEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventRegistryEngines.java | 1 |
请完成以下Java代码 | public @Nullable Boolean getDenyEmptyKey() {
return denyEmptyKey;
}
public Config setDenyEmptyKey(Boolean denyEmptyKey) {
this.denyEmptyKey = denyEmptyKey;
return this;
}
public @Nullable String getEmptyKeyStatus() {
return emptyKeyStatus;
}
public Config setEmptyKeyStatus(String emptyKeyStatus) {
this.emptyKeyStatus = emptyKeyStatus;
return this; | }
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
@Override
public @Nullable String getRouteId() {
return this.routeId;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestRateLimiterGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public Optional<BPartnerId> retrieveOrgBPartnerId(final OrgId orgId)
{
final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class);
final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(orgId.getRepoId());
return orgBPartner != null ? BPartnerId.optionalOfRepoId(orgBPartner.getC_BPartner_ID()) : Optional.empty();
}
public BPartnerLocationId retrieveOrgBPartnerLocationId(@NonNull final OrgId orgId)
{
final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class);
return bpartnerOrgBL.retrieveOrgBPLocationId(orgId);
}
/**
* @param productPlanningData may be {@code null} as of gh #1635
* @param networkLine may also be {@code null} as of gh #1635
*/
public int calculateDurationDays(
@Nullable final ProductPlanning productPlanningData,
@Nullable final DistributionNetworkLine networkLine)
{
//
// Leadtime
final int leadtimeDays;
if (productPlanningData != null)
{
leadtimeDays = productPlanningData.getLeadTimeDays();
Check.assume(leadtimeDays >= 0, "leadtimeDays >= 0");
}
else
{
leadtimeDays = 0;
}
//
// Transfer time
final int transferTimeFromNetworkLine;
if (networkLine != null)
{
transferTimeFromNetworkLine = (int)networkLine.getTransferDuration().toDays(); | }
else
{
transferTimeFromNetworkLine = 0;
}
final int transferTime;
if (transferTimeFromNetworkLine > 0)
{
transferTime = transferTimeFromNetworkLine;
}
else if (productPlanningData != null)
{
transferTime = productPlanningData.getTransferTimeDays();
Check.assume(transferTime >= 0, "transferTime >= 0");
}
else
{
transferTime = 0;
}
return leadtimeDays + transferTime;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ddorder\DDOrderUtil.java | 1 |
请完成以下Java代码 | private ImmutableAttributeSet getAttributes(final IPricingContext pricingCtx)
{
final IAttributeSetInstanceAware asiAware = pricingCtx.getAttributeSetInstanceAware().orElse(null);
if (asiAware == null)
{
return ImmutableAttributeSet.EMPTY;
}
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asiAware.getM_AttributeSetInstance_ID());
return Services.get(IAttributeSetInstanceBL.class).getImmutableAttributeSetById(asiId);
}
private static void updatePricingResultFromPricingConditionsResult(
@NonNull final IPricingResult pricingResult,
@Nullable final PricingConditionsResult pricingConditionsResult)
{
pricingResult.setPricingConditions(pricingConditionsResult);
if (pricingConditionsResult == null)
{
return;
}
pricingResult.setDiscount(pricingConditionsResult.getDiscount()); | final BigDecimal priceStdOverride = pricingConditionsResult.getPriceStdOverride();
final BigDecimal priceListOverride = pricingConditionsResult.getPriceListOverride();
final BigDecimal priceLimitOverride = pricingConditionsResult.getPriceLimitOverride();
if (priceStdOverride != null)
{
pricingResult.setPriceStd(priceStdOverride);
}
if (priceListOverride != null)
{
pricingResult.setPriceList(priceListOverride);
}
if (priceLimitOverride != null)
{
pricingResult.setPriceLimit(priceLimitOverride);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\Discount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getDeploymentId() {
return deploymentId;
}
public Date getDeployedAfter() {
return deployedAfter;
}
public Date getDeployedAt() {
return deployedAt;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
} | public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public Integer getVersion() {
return version;
}
public String getVersionTag() {
return versionTag;
}
public String getVersionTagLike() {
return versionTagLike;
}
public boolean isLatest() {
return latest;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionQueryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Customer addCustomer(CustomerDto dto) {
Customer myCustomer = new Customer();
mapper.updateCustomerFromDto(dto, myCustomer);
repo.save(myCustomer);
return myCustomer;
}
public Customer updateCustomer(CustomerDto dto) {
Customer myCustomer = repo.findById(dto.getId());
mapper.updateCustomerFromDto(dto, myCustomer);
repo.save(myCustomer);
return myCustomer;
}
public CustomerStructured addCustomerStructured(String name) {
CustomerStructured myCustomer = new CustomerStructured();
myCustomer.name = name;
repo2.save(myCustomer);
return myCustomer;
} | public void addCustomerPhone(long customerId, String phone) {
ContactPhone myPhone = new ContactPhone();
myPhone.phone = phone;
myPhone.customerId = customerId;
repo3.save(myPhone);
}
public CustomerStructured updateCustomerStructured(long id, String name) {
CustomerStructured myCustomer = repo2.findById(id);
myCustomer.name = name;
repo2.save(myCustomer);
return myCustomer;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\partialupdate\service\CustomerService.java | 2 |
请完成以下Java代码 | public class MElement extends X_C_Element
{
/**
*
*/
private static final long serialVersionUID = 7656092284157893366L;
/**
* Standard Constructor
*
* @param ctx context
* @param C_Element_ID id
* @param trxName transaction
*/
public MElement(Properties ctx, int C_Element_ID, String trxName)
{
super(ctx, C_Element_ID, trxName);
if (C_Element_ID == 0)
{
// setName (null);
// setAD_Tree_ID (0);
// setElementType (null); // A
setIsBalancing(false);
setIsNaturalAccount(false);
}
} // MElement
/**
* Load Constructor
*
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MElement(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MElement
/**
* Full Constructor
*
* @param client client
* @param Name name
* @param ElementType type
* @param AD_Tree_ID tree
*/
public MElement(MClient client, String Name, String ElementType, int AD_Tree_ID)
{
this(client.getCtx(), 0, client.get_TrxName());
setClientOrg(client);
setName(Name);
setElementType(ElementType); // A
setAD_Tree_ID(AD_Tree_ID);
setIsNaturalAccount(ELEMENTTYPE_Account.equals(ElementType));
} // MElement
@Override
protected boolean beforeSave(final boolean newRecord)
{
final String elementType = getElementType();
// Natural Account
if (ELEMENTTYPE_UserDefined.equals(elementType) && isNaturalAccount()) | {
setIsNaturalAccount(false);
}
// Tree validation
int adTreeId = getAD_Tree_ID();
if (adTreeId <= 0)
{
throw new FillMandatoryException("AD_Tree_ID");
}
final I_AD_Tree tree = InterfaceWrapperHelper.load(adTreeId, I_AD_Tree.class);
final String treeType = tree.getTreeType();
if (ELEMENTTYPE_UserDefined.equals(elementType))
{
if (X_AD_Tree.TREETYPE_User1.equals(treeType) || X_AD_Tree.TREETYPE_User2.equals(treeType))
{
;
}
else
{
throw new AdempiereException("@TreeType@ <> @ElementType@ (U)");
}
}
else
{
if (!X_AD_Tree.TREETYPE_ElementValue.equals(treeType))
{
throw new AdempiereException("@TreeType@ <> @ElementType@ (A)");
}
}
return true;
}
} // MElement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MElement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected final Object getInstance() {
return this.instance;
}
@Override
public String toString() {
return this.instance.toString();
}
protected Class<?> findClass(String name) {
return findClass(getInstance().getClass().getClassLoader(), name);
}
protected Method findMethod(String name, Class<?>... parameterTypes) {
return findMethod(this.type, name, parameterTypes);
}
protected static Class<?> findClass(ClassLoader classLoader, String name) {
try {
return Class.forName(name, false, classLoader); | }
catch (ClassNotFoundException ex) {
throw new IllegalStateException(ex);
}
}
protected static Method findMethod(Class<?> type, String name, Class<?>... parameterTypes) {
try {
return type.getMethod(name, parameterTypes);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\ReflectionWrapper.java | 2 |
请完成以下Java代码 | public int getM_PackagingContainer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingContainer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName () | {
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Breite.
@param Width Breite */
public void setWidth (BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
/** Get Breite.
@return Breite */
public BigDecimal getWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Width);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_PackagingContainer.java | 1 |
请完成以下Java代码 | public void setB_BidComment_ID (int B_BidComment_ID)
{
if (B_BidComment_ID < 1)
set_ValueNoCheck (COLUMNNAME_B_BidComment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_B_BidComment_ID, Integer.valueOf(B_BidComment_ID));
}
/** Get Bid Comment.
@return Make a comment to a Bid Topic
*/
public int getB_BidComment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_B_BidComment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_B_Topic getB_Topic() throws RuntimeException
{
return (I_B_Topic)MTable.get(getCtx(), I_B_Topic.Table_Name)
.getPO(getB_Topic_ID(), get_TrxName()); }
/** Set Topic.
@param B_Topic_ID
Auction Topic
*/
public void setB_Topic_ID (int B_Topic_ID)
{
if (B_Topic_ID < 1)
set_Value (COLUMNNAME_B_Topic_ID, null);
else
set_Value (COLUMNNAME_B_Topic_ID, Integer.valueOf(B_Topic_ID));
} | /** Get Topic.
@return Auction Topic
*/
public int getB_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_B_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_BidComment.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() { | return date;
}
public void setDate(String date) {
this.date = date;
}
public UserDto getUser() {
return user;
}
public void setUser(UserDto user) {
this.user = user;
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\dto\PostDto.java | 1 |
请完成以下Java代码 | public void setCalX (int CalX)
{
set_Value (COLUMNNAME_CalX, Integer.valueOf(CalX));
}
@Override
public int getCalX()
{
return get_ValueAsInt(COLUMNNAME_CalX);
}
@Override
public void setCalY (int CalY)
{
set_Value (COLUMNNAME_CalY, Integer.valueOf(CalY));
}
@Override
public int getCalY()
{
return get_ValueAsInt(COLUMNNAME_CalY);
}
@Override
public de.metas.printing.model.I_C_Print_Package getC_Print_Package()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class);
}
@Override
public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package)
{
set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_Value (COLUMNNAME_C_Print_Package_ID, null);
else
set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setC_Print_PackageInfo_ID (int C_Print_PackageInfo_ID)
{
if (C_Print_PackageInfo_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_PackageInfo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_PackageInfo_ID, Integer.valueOf(C_Print_PackageInfo_ID));
}
@Override
public int getC_Print_PackageInfo_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_PackageInfo_ID);
}
@Override
public void setName (java.lang.String Name)
{
throw new IllegalArgumentException ("Name is virtual column"); }
@Override
public java.lang.String getName() | {
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public void setPageFrom (int PageFrom)
{
set_Value (COLUMNNAME_PageFrom, Integer.valueOf(PageFrom));
}
@Override
public int getPageFrom()
{
return get_ValueAsInt(COLUMNNAME_PageFrom);
}
@Override
public void setPageTo (int PageTo)
{
set_Value (COLUMNNAME_PageTo, Integer.valueOf(PageTo));
}
@Override
public int getPageTo()
{
return get_ValueAsInt(COLUMNNAME_PageTo);
}
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
throw new IllegalArgumentException ("PrintServiceName is virtual column"); }
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setTrayNumber (int TrayNumber)
{
throw new IllegalArgumentException ("TrayNumber is virtual column"); }
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_PackageInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DimensionsType getPackagingDimensions() {
return packagingDimensions;
}
/**
* Sets the value of the packagingDimensions property.
*
* @param value
* allowed object is
* {@link DimensionsType }
*
*/
public void setPackagingDimensions(DimensionsType value) {
this.packagingDimensions = value;
}
/**
* Gets the value of the stackingFactor property.
*
* @return
* possible object is | * {@link BigInteger }
*
*/
public BigInteger getStackingFactor() {
return stackingFactor;
}
/**
* Sets the value of the stackingFactor property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setStackingFactor(BigInteger value) {
this.stackingFactor = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ConsignmentItemInformationExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RedirectionSecurityConfig {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user1 = User.withUsername("user1")
.password("user1Pass")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user1);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers("/login*") | .permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler());
// .successHandler(new RefererAuthenticationSuccessHandler())
return http.build();
}
@Bean
public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
return new HandlerMappingIntrospector();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\spring\RedirectionSecurityConfig.java | 2 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
result = (prime * result) + ((organization == null) ? 0 : organization.hashCode());
result = (prime * result) + ((password == null) ? 0 : password.hashCode());
result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode());
result = (prime * result) + ((username == null) ? 0 : username.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;
}
final User other = (User) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (organization == null) {
if (other.organization != null) {
return false;
}
} else if (!organization.equals(other.organization)) {
return false;
}
if (password == null) {
if (other.password != null) {
return false; | }
} else if (!password.equals(other.password)) {
return false;
}
if (privileges == null) {
if (other.privileges != null) {
return false;
}
} else if (!privileges.equals(other.privileges)) {
return false;
}
if (username == null) {
if (other.username != null) {
return false;
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Object> getMemoryInfo() throws RedisConnectException {
Map<String, Object> map = null;
Properties info = redisConnectionFactory.getConnection().info();
for (Map.Entry<Object, Object> entry : info.entrySet()) {
String key = oConvertUtils.getString(entry.getKey());
if ("used_memory".equals(key)) {
map = new HashMap(5);
map.put("used_memory", entry.getValue());
map.put("create_time", System.currentTimeMillis());
}
}
log.debug("--getMemoryInfo--: " + map.toString());
return map;
}
/**
* 查询redis信息for报表
* @param type 1redis key数量 2 占用内存 3redis信息
* @return
* @throws RedisConnectException
*/
@Override
public Map<String, JSONArray> getMapForReport(String type) throws RedisConnectException {
Map<String,JSONArray> mapJson=new HashMap(5);
JSONArray json = new JSONArray();
if(REDIS_MESSAGE.equals(type)){
List<RedisInfo> redisInfo = getRedisInfo();
for(RedisInfo info:redisInfo){
Map<String, Object> map= Maps.newHashMap();
BeanMap beanMap = BeanMap.create(info);
for (Object key : beanMap.keySet()) {
map.put(key+"", beanMap.get(key));
}
json.add(map);
}
mapJson.put("data",json);
return mapJson;
}
int length = 5;
for(int i = 0; i < length; i++){
JSONObject jo = new JSONObject();
Map<String, Object> map;
if("1".equals(type)){
map= getKeysSize();
jo.put("value",map.get("dbSize"));
}else{
map = getMemoryInfo();
Integer usedMemory = Integer.valueOf(map.get("used_memory").toString());
jo.put("value",usedMemory/1000);
}
String createTime = DateUtil.formatTime(DateUtil.date((Long) map.get("create_time")-(4-i)*1000));
jo.put("name",createTime); | json.add(jo);
}
mapJson.put("data",json);
return mapJson;
}
/**
* 获取历史性能指标
* @return
* @author chenrui
* @date 2024/5/14 14:57
*/
@Override
public Map<String, List<Map<String, Object>>> getMetricsHistory() {
return REDIS_METRICS;
}
/**
* 记录近一小时redis监控数据 <br/>
* 60s一次,,记录存储keysize和内存
* @throws RedisConnectException
* @author chenrui
* @date 2024/5/14 14:09
*/
@Scheduled(fixedRate = 60000)
public void recordCustomMetric() throws RedisConnectException {
List<Map<String, Object>> list= new ArrayList<>();
if(REDIS_METRICS.containsKey("dbSize")){
list = REDIS_METRICS.get("dbSize");
}else{
REDIS_METRICS.put("dbSize",list);
}
if(list.size()>60){
list.remove(0);
}
list.add(getKeysSize());
list= new ArrayList<>();
if(REDIS_METRICS.containsKey("memory")){
list = REDIS_METRICS.get("memory");
}else{
REDIS_METRICS.put("memory",list);
}
if(list.size()>60){
list.remove(0);
}
list.add(getMemoryInfo());
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\service\impl\RedisServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Lecturer {
@Id
private Long id;
private String name;
private Integer facultyId;
public Lecturer() {
}
public Lecturer(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getFacultyId() {
return facultyId;
}
public void setFacultyId(Integer facultyId) {
this.facultyId = facultyId;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-3\src\main\java\com\baeldung\hibernate\union\model\Lecturer.java | 2 |
请完成以下Java代码 | public void customize(HelpDocument document) {
this.description.getRequestedDependencies().forEach((id, dependency) -> {
Dependency dependencyMetadata = this.metadata.getDependencies().get(id);
if (dependencyMetadata != null) {
handleDependency(document, dependencyMetadata);
}
});
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
private void handleDependency(HelpDocument document, Dependency dependency) {
GettingStartedSection gettingStartedSection = document.gettingStarted();
MultiValueMap<GuideType, Link> indexedLinks = indexLinks(dependency);
registerLinks(indexedLinks.get(GuideType.REFERENCE), defaultLinkDescription(dependency),
gettingStartedSection::referenceDocs);
registerLinks(indexedLinks.get(GuideType.GUIDE), defaultLinkDescription(dependency),
gettingStartedSection::guides);
registerLinks(indexedLinks.get(GuideType.OTHER), (links) -> null, gettingStartedSection::additionalLinks);
}
private void registerLinks(List<Link> links, Function<List<Link>, String> defaultDescription,
Supplier<BulletedSection<GettingStartedSection.Link>> section) {
if (ObjectUtils.isEmpty(links)) {
return;
}
links.forEach((link) -> {
if (link.getHref() != null) {
String description = (link.getDescription() != null) ? link.getDescription()
: defaultDescription.apply(links);
if (description != null) {
String url = link.getHref().replace("{bootVersion}", this.platformVersion);
section.get().addItem(new GettingStartedSection.Link(url, description));
}
}
});
}
private Function<List<Link>, String> defaultLinkDescription(Dependency dependency) { | return (links) -> (links.size() == 1) ? dependency.getName() : null;
}
private MultiValueMap<GuideType, Link> indexLinks(Dependency dependency) {
MultiValueMap<GuideType, Link> links = new LinkedMultiValueMap<>();
dependency.getLinks().forEach((link) -> {
if ("reference".equals(link.getRel())) {
links.add(GuideType.REFERENCE, link);
}
else if ("guide".equals(link.getRel())) {
links.add(GuideType.GUIDE, link);
}
else {
links.add(GuideType.OTHER, link);
}
});
return links;
}
private enum GuideType {
REFERENCE, GUIDE, OTHER
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\RequestedDependenciesHelpDocumentCustomizer.java | 1 |
请完成以下Java代码 | public List<InputClause> getInputs() {
return inputs;
}
public void addInput(InputClause input) {
this.inputs.add(input);
}
public List<OutputClause> getOutputs() {
return outputs;
}
public void addOutput(OutputClause output) {
this.outputs.add(output);
}
public List<DecisionRule> getRules() {
return rules;
}
public void addRule(DecisionRule rule) {
this.rules.add(rule);
}
public HitPolicy getHitPolicy() {
return hitPolicy;
}
public void setHitPolicy(HitPolicy hitPolicy) {
this.hitPolicy = hitPolicy;
}
public BuiltinAggregator getAggregation() { | return aggregation;
}
public void setAggregation(BuiltinAggregator aggregation) {
this.aggregation = aggregation;
}
public DecisionTableOrientation getPreferredOrientation() {
return preferredOrientation;
}
public void setPreferredOrientation(DecisionTableOrientation preferredOrientation) {
this.preferredOrientation = preferredOrientation;
}
public String getOutputLabel() {
return outputLabel;
}
public void setOutputLabel(String outputLabel) {
this.outputLabel = outputLabel;
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionTable.java | 1 |
请完成以下Java代码 | protected void configureJobExecutor(ProcessEngineConfigurationImpl configuration,
CamundaEngineConfig config) {
int maxPoolSize = config.jobExecutor().threadPool().maxPoolSize();
int queueSize = config.jobExecutor().threadPool().queueSize();
// create a non-bean ManagedExecutor instance. This instance
// uses it's own Executor/thread pool.
ManagedExecutor managedExecutor = SmallRyeManagedExecutor.builder()
.maxQueued(queueSize)
.maxAsync(maxPoolSize)
.withNewExecutorService()
.build();
ManagedJobExecutor quarkusJobExecutor = new ManagedJobExecutor(managedExecutor);
// apply job executor configuration properties
PropertyHelper
.applyProperties(quarkusJobExecutor, config.jobExecutor().genericConfig(), PropertyHelper.KEBAB_CASE); | configuration.setJobExecutor(quarkusJobExecutor);
}
/**
* Retrieves a bean of the given class from the bean container.
*
* @param beanClass the class of the desired bean to fetch from the container
* @param beanContainer the bean container
* @param <T> the type of the bean to fetch
* @return the bean
*/
protected <T> T getBeanFromContainer(Class<T> beanClass, BeanContainer beanContainer) {
try (BeanContainer.Instance<T> beanManager = beanContainer.beanInstanceFactory(beanClass).create()) {
return beanManager.get();
}
}
} | repos\camunda-bpm-platform-master\quarkus-extension\engine\runtime\src\main\java\org\camunda\bpm\quarkus\engine\extension\impl\CamundaEngineRecorder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void method01() {
// 查询订单
OrderDO order = orderDao.selectById(1);
System.out.println(order);
// 查询用户
UserDO user = userDao.selectById(1);
System.out.println(user);
}
@Transactional // 报错,找不到事务管理器
public void method02() {
// 查询订单
OrderDO order = orderDao.selectById(1);
System.out.println(order);
// 查询用户
UserDO user = userDao.selectById(1);
System.out.println(user);
}
public void method03() {
// 查询订单
self().method031();
// 查询用户
self().method032();
}
@Transactional(transactionManager = DBConstants.TX_MANAGER_ORDERS)
public void method031() {
OrderDO order = orderDao.selectById(1);
System.out.println(order);
} | @Transactional(transactionManager = DBConstants.TX_MANAGER_USERS)
public void method032() {
UserDO user = userDao.selectById(1);
System.out.println(user);
}
@Transactional(transactionManager = DBConstants.TX_MANAGER_ORDERS)
public void method05() {
// 查询订单
OrderDO order = orderDao.selectById(1);
System.out.println(order);
// 查询用户
self().method052();
}
@Transactional(transactionManager = DBConstants.TX_MANAGER_USERS,
propagation = Propagation.REQUIRES_NEW)
public void method052() {
UserDO user = userDao.selectById(1);
System.out.println(user);
}
} | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-jdbctemplate\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\service\OrderService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AdTreeId implements RepoIdAware
{
@Nullable
public static AdTreeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
@JsonCreator
public static AdTreeId ofRepoId(final int repoId)
{
if (repoId == DEFAULT_MENU_TREE_ID.repoId)
{
return DEFAULT_MENU_TREE_ID;
}
else
{
return new AdTreeId(repoId);
}
}
public static int toRepoId(@Nullable final AdTreeId id)
{
return id != null ? id.getRepoId() : -1;
}
public static final AdTreeId DEFAULT_MENU_TREE_ID = new AdTreeId(10); | int repoId;
private AdTreeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Tree_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final AdTreeId id1, @Nullable final AdTreeId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\AdTreeId.java | 2 |
请完成以下Java代码 | public void setPickupTimeTo (final java.sql.Timestamp PickupTimeTo)
{
set_Value (COLUMNNAME_PickupTimeTo, PickupTimeTo);
}
@Override
public java.sql.Timestamp getPickupTimeTo()
{
return get_ValueAsTimestamp(COLUMNNAME_PickupTimeTo);
}
/**
* ShipperGateway AD_Reference_ID=540808
* Reference name: ShipperGateway
*/
public static final int SHIPPERGATEWAY_AD_Reference_ID=540808;
/** GO = go */
public static final String SHIPPERGATEWAY_GO = "go";
/** Der Kurier = derKurier */
public static final String SHIPPERGATEWAY_DerKurier = "derKurier";
/** DHL = dhl */
public static final String SHIPPERGATEWAY_DHL = "dhl";
/** DPD = dpd */
public static final String SHIPPERGATEWAY_DPD = "dpd";
/** nShift = nshift */
public static final String SHIPPERGATEWAY_NShift = "nshift";
@Override
public void setShipperGateway (final @Nullable java.lang.String ShipperGateway)
{
set_Value (COLUMNNAME_ShipperGateway, ShipperGateway);
}
@Override
public java.lang.String getShipperGateway()
{
return get_ValueAsString(COLUMNNAME_ShipperGateway);
}
@Override | public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper.java | 1 |
请完成以下Java代码 | private static String extractDefaultValue(final ArrayList<String> modifiers)
{
final String defaultValue;
if (!modifiers.isEmpty() && !isModifier(modifiers.get(modifiers.size() - 1)))
{
defaultValue = modifiers.remove(modifiers.size() - 1);
}
else
{
defaultValue = VALUE_NULL;
}
return defaultValue;
}
/**
* Parse a given name, surrounded by {@value #NAME_Marker}
*/
@Nullable
public static CtxName parseWithMarkers(@Nullable final String contextWithMarkers)
{
if (contextWithMarkers == null)
{
return null;
}
String contextWithoutMarkers = contextWithMarkers.trim();
if (contextWithoutMarkers.startsWith(NAME_Marker))
{
contextWithoutMarkers = contextWithoutMarkers.substring(1);
}
if (contextWithoutMarkers.endsWith(NAME_Marker))
{
contextWithoutMarkers = contextWithoutMarkers.substring(0, contextWithoutMarkers.length() - 1);
}
return parse(contextWithoutMarkers);
}
/**
* @param expression expression with context variables (e.g. sql where clause)
* @return true if expression contains given name
*/
@VisibleForTesting
static boolean containsName(@Nullable final String name, @Nullable final String expression)
{
// FIXME: replace it with StringExpression
if (name == null || name.isEmpty()) | {
return false;
}
if (expression == null || expression.isEmpty())
{
return false;
}
final int idx = expression.indexOf(NAME_Marker + name);
if (idx < 0)
{
return false;
}
final int idx2 = expression.indexOf(NAME_Marker, idx + 1);
if (idx2 < 0)
{
return false;
}
final String nameStr = expression.substring(idx + 1, idx2);
return name.equals(parse(nameStr).getName());
}
/**
* @return true if given string is a registered modifier
*/
private static boolean isModifier(final String modifier)
{
if (Check.isEmpty(modifier))
{
return false;
}
return MODIFIERS.contains(modifier);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\CtxNames.java | 1 |
请完成以下Java代码 | public long getCleanableCaseInstanceCount() {
return cleanableCaseInstanceCount;
}
public void setCleanableCaseInstanceCount(long cleanableCaseInstanceCount) {
this.cleanableCaseInstanceCount = cleanableCaseInstanceCount;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public static List<CleanableHistoricCaseInstanceReportResultDto> convert(List<CleanableHistoricCaseInstanceReportResult> reportResult) {
List<CleanableHistoricCaseInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricCaseInstanceReportResultDto>();
for (CleanableHistoricCaseInstanceReportResult current : reportResult) {
CleanableHistoricCaseInstanceReportResultDto dto = new CleanableHistoricCaseInstanceReportResultDto();
dto.setCaseDefinitionId(current.getCaseDefinitionId());
dto.setCaseDefinitionKey(current.getCaseDefinitionKey());
dto.setCaseDefinitionName(current.getCaseDefinitionName());
dto.setCaseDefinitionVersion(current.getCaseDefinitionVersion());
dto.setHistoryTimeToLive(current.getHistoryTimeToLive());
dto.setFinishedCaseInstanceCount(current.getFinishedCaseInstanceCount());
dto.setCleanableCaseInstanceCount(current.getCleanableCaseInstanceCount());
dto.setTenantId(current.getTenantId());
dtos.add(dto);
}
return dtos;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricCaseInstanceReportResultDto.java | 1 |
请完成以下Java代码 | public void updateUser(String username, User body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); | final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = {
"application/xml", "application/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\api\UserApi.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setRate(BigDecimal value) {
this.rate = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the discountAmt property.
*
* @return
* possible object is | * {@link BigDecimal }
*
*/
public BigDecimal getDiscountAmt() {
return discountAmt;
}
/**
* Sets the value of the discountAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDiscountAmt(BigDecimal value) {
this.discountAmt = value;
}
/**
* Gets the value of the discountBaseAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getDiscountBaseAmt() {
return discountBaseAmt;
}
/**
* Sets the value of the discountBaseAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDiscountBaseAmt(BigDecimal value) {
this.discountBaseAmt = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop140VType.java | 2 |
请完成以下Java代码 | public void setChangeCount(Integer changeCount) {
this.changeCount = changeCount;
}
public String getOperateMan() {
return operateMan;
}
public void setOperateMan(String operateMan) {
this.operateMan = operateMan;
}
public String getOperateNote() {
return operateNote;
}
public void setOperateNote(String operateNote) {
this.operateNote = operateNote;
}
public Integer getSourceType() {
return sourceType;
}
public void setSourceType(Integer sourceType) { | this.sourceType = sourceType;
}
@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(", memberId=").append(memberId);
sb.append(", createTime=").append(createTime);
sb.append(", changeType=").append(changeType);
sb.append(", changeCount=").append(changeCount);
sb.append(", operateMan=").append(operateMan);
sb.append(", operateNote=").append(operateNote);
sb.append(", sourceType=").append(sourceType);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsGrowthChangeHistory.java | 1 |
请完成以下Java代码 | public IdmEngineConfiguration setSessionFactories(Map<Class<?>, SessionFactory> sessionFactories) {
this.sessionFactories = sessionFactories;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) {
this.databaseSchemaUpdate = databaseSchemaUpdate;
return this;
}
@Override
public IdmEngineConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
}
@Override
public IdmEngineConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
@Override
public IdmEngineConfiguration setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners; | return this;
}
@Override
public IdmEngineConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
@Override
public IdmEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the addressqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getADDRESSQUAL() {
return addressqual;
}
/**
* Sets the value of the addressqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setADDRESSQUAL(String value) {
this.addressqual = value;
}
/**
* Gets the value of the referencequal property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEQUAL() {
return referencequal;
}
/**
* Sets the value of the referencequal property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEQUAL(String value) {
this.referencequal = value;
}
/**
* Gets the value of the reference property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCE() {
return reference;
}
/** | * Sets the value of the reference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCE(String value) {
this.reference = value;
}
/**
* Gets the value of the referencedate1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE1() {
return referencedate1;
}
/**
* Sets the value of the referencedate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE1(String value) {
this.referencedate1 = value;
}
/**
* Gets the value of the referencedate2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE2() {
return referencedate2;
}
/**
* Sets the value of the referencedate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE2(String value) {
this.referencedate2 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HRFAD1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | void setJmsProperties(@Nullable JmsProperties jmsProperties) {
this.jmsProperties = jmsProperties;
}
/**
* Set the {@link ObservationRegistry} to use.
* @param observationRegistry the {@link ObservationRegistry}
*/
void setObservationRegistry(@Nullable ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
/**
* Configure the specified jms listener container factory. The factory can be further
* tuned and default settings can be overridden.
* @param factory the {@link DefaultJmsListenerContainerFactory} instance to configure
* @param connectionFactory the {@link ConnectionFactory} to use
*/
public void configure(DefaultJmsListenerContainerFactory factory, ConnectionFactory connectionFactory) {
Assert.notNull(factory, "'factory' must not be null");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
Assert.state(this.jmsProperties != null, "'jmsProperties' must not be null");
JmsProperties.Listener listenerProperties = this.jmsProperties.getListener();
Session sessionProperties = listenerProperties.getSession();
factory.setConnectionFactory(connectionFactory);
PropertyMapper map = PropertyMapper.get(); | map.from(this.jmsProperties::isPubSubDomain).to(factory::setPubSubDomain);
map.from(this.jmsProperties::isSubscriptionDurable).to(factory::setSubscriptionDurable);
map.from(this.jmsProperties::getClientId).to(factory::setClientId);
map.from(this.transactionManager).to(factory::setTransactionManager);
map.from(this.destinationResolver).to(factory::setDestinationResolver);
map.from(this.messageConverter).to(factory::setMessageConverter);
map.from(this.exceptionListener).to(factory::setExceptionListener);
map.from(sessionProperties.getAcknowledgeMode()::getMode).to(factory::setSessionAcknowledgeMode);
if (this.transactionManager == null && sessionProperties.getTransacted() == null) {
factory.setSessionTransacted(true);
}
map.from(this.observationRegistry).to(factory::setObservationRegistry);
map.from(sessionProperties::getTransacted).to(factory::setSessionTransacted);
map.from(listenerProperties::isAutoStartup).to(factory::setAutoStartup);
map.from(listenerProperties::formatConcurrency).to(factory::setConcurrency);
map.from(listenerProperties::getReceiveTimeout).as(Duration::toMillis).to(factory::setReceiveTimeout);
map.from(listenerProperties::getMaxMessagesPerTask).to(factory::setMaxMessagesPerTask);
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\DefaultJmsListenerContainerFactoryConfigurer.java | 2 |
请完成以下Java代码 | public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
public void migrateState() {
eventSubscription.setActivity((ActivityImpl) targetScope);
currentScope = targetScope;
}
@Override
public void migrateDependentEntities() {
}
@Override
public void addMigratingDependentInstance(MigratingInstance migratingInstance) {
}
@Override
public ExecutionEntity resolveRepresentativeExecution() {
return null;
}
@Override
public void attachState(MigratingScopeInstance targetActivityInstance) {
setParent(targetActivityInstance);
ExecutionEntity representativeExecution = targetActivityInstance.resolveRepresentativeExecution();
eventSubscription.setExecution(representativeExecution); | }
@Override
public void setParent(MigratingScopeInstance parentInstance) {
if (this.parentInstance != null) {
this.parentInstance.removeChild(this);
}
this.parentInstance = parentInstance;
if (parentInstance != null) {
parentInstance.addChild(this);
}
}
public void remove() {
eventSubscription.delete();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingCompensationEventSubscriptionInstance.java | 1 |
请完成以下Java代码 | public abstract class AbstractAlarmCommentEntity<T extends AlarmComment> extends BaseSqlEntity<T> {
@Column(name = ALARM_COMMENT_ALARM_ID, columnDefinition = "uuid")
private UUID alarmId;
@Column(name = ModelConstants.ALARM_COMMENT_USER_ID)
private UUID userId;
@Column(name = ALARM_COMMENT_TYPE)
private AlarmCommentType type;
@Convert(converter = JsonConverter.class)
@Column(name = ALARM_COMMENT_COMMENT)
private JsonNode comment;
public AbstractAlarmCommentEntity() {
super();
}
public AbstractAlarmCommentEntity(AlarmComment alarmComment) {
if (alarmComment.getId() != null) {
this.setUuid(alarmComment.getUuidId());
}
this.setCreatedTime(alarmComment.getCreatedTime());
this.alarmId = alarmComment.getAlarmId().getId();
if (alarmComment.getUserId() != null) {
this.userId = alarmComment.getUserId().getId();
}
if (alarmComment.getType() != null) {
this.type = alarmComment.getType();
}
this.setComment(alarmComment.getComment());
}
public AbstractAlarmCommentEntity(AlarmCommentEntity alarmCommentEntity) {
this.setId(alarmCommentEntity.getId());
this.setCreatedTime(alarmCommentEntity.getCreatedTime());
this.userId = alarmCommentEntity.getUserId(); | this.alarmId = alarmCommentEntity.getAlarmId();
this.type = alarmCommentEntity.getType();
this.comment = alarmCommentEntity.getComment();
}
protected AlarmComment toAlarmComment() {
AlarmComment alarmComment = new AlarmComment(new AlarmCommentId(id));
alarmComment.setCreatedTime(createdTime);
alarmComment.setAlarmId(new AlarmId(alarmId));
if (userId != null) {
alarmComment.setUserId(new UserId(userId));
}
alarmComment.setType(type);
alarmComment.setComment(comment);
return alarmComment;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AbstractAlarmCommentEntity.java | 1 |
请完成以下Java代码 | public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Long salaryValue = SalaryCurrencyConvertor.convert(value.getAmount(),
value.getCurrency(), localCurrency);
st.setString(index, value.getCurrency() + " " + salaryValue);
}
}
@Override
public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
Salary newSal = new Salary();
newSal.setAmount(value.getAmount());
newSal.setCurrency(value.getCurrency());
return newSal;
}
@Override
public boolean isMutable() {
return true; | }
@Override
public Serializable disassemble(Salary value) {
return deepCopy(value);
}
@Override
public Salary assemble(Serializable cached, Object owner) {
return deepCopy((Salary) cached);
}
@Override
public Salary replace(Salary detached, Salary managed, Object owner) {
return detached;
}
@Override
public void setParameterValues(Properties parameters) {
this.localCurrency = parameters.getProperty("currency");
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\SalaryType.java | 1 |
请完成以下Java代码 | public void setSwiftCode (java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
/** Get Swift code.
@return Swift Code or BIC
*/
@Override
public java.lang.String getSwiftCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_SwiftCode);
}
@Override
public void setIsGroupLine (final boolean IsGroupLine)
{
set_Value (COLUMNNAME_IsGroupLine, IsGroupLine);
} | @Override
public boolean isGroupLine()
{
return get_ValueAsBoolean(COLUMNNAME_IsGroupLine);
}
@Override
public void setNumberOfReferences (final int NumberOfReferences)
{
set_Value (COLUMNNAME_NumberOfReferences, NumberOfReferences);
}
@Override
public int getNumberOfReferences()
{
return get_ValueAsInt(COLUMNNAME_NumberOfReferences);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line.java | 1 |
请完成以下Java代码 | public void setDocumentLinesNumber (int DocumentLinesNumber)
{
set_Value (COLUMNNAME_DocumentLinesNumber, Integer.valueOf(DocumentLinesNumber));
}
/** Get DocumentLinesNumber.
@return DocumentLinesNumber */
@Override
public int getDocumentLinesNumber ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DocumentLinesNumber);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Abgabemeldung Konfiguration.
@param M_Shipment_Declaration_Config_ID Abgabemeldung Konfiguration */
@Override
public void setM_Shipment_Declaration_Config_ID (int M_Shipment_Declaration_Config_ID)
{
if (M_Shipment_Declaration_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, Integer.valueOf(M_Shipment_Declaration_Config_ID));
}
/** Get Abgabemeldung Konfiguration. | @return Abgabemeldung Konfiguration */
@Override
public int getM_Shipment_Declaration_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration_Config.java | 1 |
请完成以下Java代码 | public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setM_Forecast_ID (final int M_Forecast_ID)
{
if (M_Forecast_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, M_Forecast_ID);
}
@Override
public int getM_Forecast_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Forecast_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
} | @Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Forecast.java | 1 |
请完成以下Java代码 | public void assignToTourInstance(final I_M_DeliveryDay deliveryDay, final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
Check.assume(tourInstance.getM_Tour_Instance_ID() > 0, "tourInstance shall be saved: {}", tourInstance);
deliveryDay.setM_Tour_Instance(tourInstance);
// NOTE: please don't save it because it could be that is not the only change or we are in a before/after save model interceptor
}
private final void unassignFromTourInstance(final I_M_DeliveryDay deliveryDay)
{
deliveryDay.setM_Tour_Instance(null);
// NOTE: please don't save it because it could be that is not the only change or we are in a before/after save model interceptor
}
/**
* Checks if we need to have a tour instance assignment for our given delivery day
*
* @param deliveryDay
* @return true if an assignment is required
*/
private final boolean isTourInstanceAssignmentRequired(final I_M_DeliveryDay deliveryDay)
{
// Tour assignment (change) is not allowed if our delivery day is already processed
if (deliveryDay.isProcessed())
{
return false;
}
//
// If Delivery Day has documents allocated to it, we really need to assign it to a tour
final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class);
final boolean tourInstanceAssignmentRequired = deliveryDayDAO.hasAllocations(deliveryDay);
return tourInstanceAssignmentRequired;
}
private ITourInstanceQueryParams createTourInstanceQueryParams(final I_M_DeliveryDay deliveryDay) | {
final ITourInstanceQueryParams tourInstanceMatchingParams = new PlainTourInstanceQueryParams();
tourInstanceMatchingParams.setM_Tour(deliveryDay.getM_Tour());
tourInstanceMatchingParams.setDeliveryDate(deliveryDay.getDeliveryDate());
return tourInstanceMatchingParams;
}
@Override
public void process(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
tourInstance.setProcessed(true);
InterfaceWrapperHelper.save(tourInstance);
}
@Override
public void unprocess(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
tourInstance.setProcessed(false);
InterfaceWrapperHelper.save(tourInstance);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourInstanceBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Foo> findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder,
final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(pageable);
if (pageable.getPageNumber() > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response,
pageable.getPageNumber(), resultPage.getTotalPages(), pageable.getPageSize()));
return resultPage.getContent();
}
// write
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo;
} | @PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findById(resource.getId()));
service.update(resource);
}
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public void handleException(final Exception ex) {
final String error = "Application specific error handling";
logger.error(error, ex);
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\controller\FooController.java | 2 |
请完成以下Java代码 | public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Override | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Book)) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaFullJoins\src\main\java\com\bookstore\entity\Book.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PageResult<OnlineUserDto> getAll(String username, Pageable pageable){
List<OnlineUserDto> onlineUserDtos = getAll(username);
return PageUtil.toPage(
PageUtil.paging(pageable.getPageNumber(),pageable.getPageSize(), onlineUserDtos),
onlineUserDtos.size()
);
}
/**
* 查询全部数据,不分页
* @param username /
* @return /
*/
public List<OnlineUserDto> getAll(String username){
String loginKey = properties.getOnlineKey() +
(StringUtils.isBlank(username) ? "" : "*" + username);
List<String> keys = redisUtils.scan(loginKey + "*");
Collections.reverse(keys);
List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
for (String key : keys) {
onlineUserDtos.add(redisUtils.get(key, OnlineUserDto.class));
}
onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUserDtos;
}
/**
* 退出登录
* @param token /
*/
public void logout(String token) {
String loginKey = tokenProvider.loginKey(token);
redisUtils.del(loginKey);
}
/**
* 导出
* @param all /
* @param response /
* @throws IOException /
*/
public void download(List<OnlineUserDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (OnlineUserDto user : all) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("用户名", user.getUserName()); | map.put("部门", user.getDept());
map.put("登录IP", user.getIp());
map.put("登录地点", user.getAddress());
map.put("浏览器", user.getBrowser());
map.put("登录日期", user.getLoginTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
/**
* 查询用户
* @param key /
* @return /
*/
public OnlineUserDto getOne(String key) {
return redisUtils.get(key, OnlineUserDto.class);
}
/**
* 根据用户名强退用户
* @param username /
*/
public void kickOutForUsername(String username) {
String loginKey = properties.getOnlineKey() + username + "*";
redisUtils.scanDel(loginKey);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\service\OnlineUserService.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!I_C_OLCand.Table_Name.equals(context.getTableName()))
{
return ProcessPreconditionsResolution.reject();
}
if(context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final I_C_OLCand olCand = context.getSelectedModel(I_C_OLCand.class);
if(olCand.isError())
{
return ProcessPreconditionsResolution.reject("line has errors");
} | final IInputDataSourceDAO inputDataSourceDAO = Services.get(IInputDataSourceDAO.class);
final I_AD_InputDataSource dest = inputDataSourceDAO.retrieveInputDataSource(Env.getCtx(), Contracts_Constants.DATA_DESTINATION_INTERNAL_NAME, false, get_TrxName());
if (dest == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no input data source found");
}
if (dest.getAD_InputDataSource_ID() != olCand.getAD_DataDestination_ID())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("input data source not matching");
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Create_From_OLCand.java | 1 |
请完成以下Java代码 | public void updateAvatar(LoginUser loginUser) { }
@Override
public void sendAppChatSocket(String userId) {
}
@Override
public String getRoleCodeById(String id) {
return null;
}
@Override
public List<DictModel> queryRoleDictByCode(String roleCodes) {
return null;
}
@Override
public List<JSONObject> queryUserBySuperQuery(String superQuery, String matchType) {
return null;
}
@Override
public JSONObject queryUserById(String id) {
return null;
}
@Override
public List<JSONObject> queryDeptBySuperQuery(String superQuery, String matchType) {
return null;
}
@Override
public List<JSONObject> queryRoleBySuperQuery(String superQuery, String matchType) {
return null;
}
@Override
public List<String> selectUserIdByTenantId(String tenantId) {
return null;
}
@Override
public List<String> queryUserIdsByDeptIds(List<String> deptIds) {
return null;
}
@Override
public List<String> queryUserIdsByDeptPostIds(List<String> deptPostIds) {
return List.of();
}
@Override
public List<String> queryUserAccountsByDeptIds(List<String> deptIds) {
return null;
}
@Override
public List<String> queryUserIdsByRoleds(List<String> roleCodes) {
return null;
}
@Override
public List<String> queryUsernameByIds(List<String> userIds) { | return List.of();
}
@Override
public List<String> queryUsernameByDepartPositIds(List<String> positionIds) {
return null;
}
@Override
public List<String> queryUserIdsByPositionIds(List<String> positionIds) {
return null;
}
@Override
public List<String> getUserAccountsByDepCode(String orgCode) {
return null;
}
@Override
public boolean dictTableWhiteListCheckBySql(String selectSql) {
return false;
}
@Override
public boolean dictTableWhiteListCheckByDict(String tableOrDictCode, String... fields) {
return false;
}
@Override
public void announcementAutoRelease(String dataId, String currentUserName) {
}
@Override
public SysDepartModel queryCompByOrgCode(String orgCode) {
return null;
}
@Override
public SysDepartModel queryCompByOrgCodeAndLevel(String orgCode, Integer level) {
return null;
}
@Override
public Object runAiragFlow(AiragFlowDTO airagFlowDTO) {
return null;
}
@Override
public void uniPushMsgToUser(PushMessageDTO pushMessageDTO) {
}
@Override
public String getDepartPathNameByOrgCode(String orgCode, String depId) {
return "";
}
@Override
public List<String> queryUserIdsByCascadeDeptIds(List<String> deptIds) {
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\system\api\fallback\SysBaseAPIFallback.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
} | public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\persistence\multiple\model\user\User.java | 1 |
请完成以下Java代码 | public Decision getCurrentDecision() {
return currentDecision;
}
public void setCurrentDecision(Decision currentDecision) {
this.currentDecision = currentDecision;
}
public void addDiDiagram(DmnDiDiagram diDiagram) {
diDiagrams.add(diDiagram);
setCurrentDiDiagram(diDiagram);
}
public void addDiShape(DmnDiShape diShape) {
diShapes.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>());
diShapes.get(getCurrentDiDiagram().getId()).add(diShape);
setCurrentDiShape(diShape);
}
public void addDiEdge(DmnDiEdge diEdge) {
diEdges.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>());
diEdges.get(getCurrentDiDiagram().getId()).add(diEdge);
setCurrentDiEdge(diEdge);
}
public DmnDiDiagram getCurrentDiDiagram() {
return currentDiDiagram;
}
public void setCurrentDiDiagram(DmnDiDiagram currentDiDiagram) {
this.currentDiDiagram = currentDiDiagram;
}
public DmnDiShape getCurrentDiShape() {
return currentDiShape;
}
public void setCurrentDiShape(DmnDiShape currentDiShape) { | this.currentDiShape = currentDiShape;
}
public DiEdge getCurrentDiEdge() {
return currentDiEdge;
}
public void setCurrentDiEdge(DiEdge currentDiEdge) {
this.currentDiEdge = currentDiEdge;
}
public List<DmnDiDiagram> getDiDiagrams() {
return diDiagrams;
}
public List<DmnDiShape> getDiShapes(String diagramId) {
return diShapes.get(diagramId);
}
public List<DmnDiEdge> getDiEdges(String diagramId) {
return diEdges.get(diagramId);
}
} | repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\ConversionHelper.java | 1 |
请完成以下Java代码 | public Mono<Void> saveSessionInformation(ReactiveSessionInformation information) {
return Mono.empty();
}
@Override
public Mono<ReactiveSessionInformation> getSessionInformation(String sessionId) {
return this.sessionRepository.findById(sessionId).map(SpringSessionBackedReactiveSessionInformation::new);
}
@Override
public Mono<ReactiveSessionInformation> removeSessionInformation(String sessionId) {
return Mono.empty();
}
@Override
public Mono<ReactiveSessionInformation> updateLastAccessTime(String sessionId) {
return Mono.empty();
}
private static Authentication getAuthenticationToken(Object principal) {
return new AbstractAuthenticationToken(AuthorityUtils.NO_AUTHORITIES) {
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return principal;
}
};
}
class SpringSessionBackedReactiveSessionInformation extends ReactiveSessionInformation {
SpringSessionBackedReactiveSessionInformation(S session) {
super(resolvePrincipalName(session), session.getId(), session.getLastAccessedTime()); | }
private static String resolvePrincipalName(Session session) {
String principalName = session
.getAttribute(ReactiveFindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
}
SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext != null && securityContext.getAuthentication() != null) {
return securityContext.getAuthentication().getName();
}
return "";
}
@Override
public Mono<Void> invalidate() {
return super.invalidate()
.then(Mono.defer(() -> SpringSessionBackedReactiveSessionRegistry.this.sessionRepository
.deleteById(getSessionId())));
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedReactiveSessionRegistry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void pay(AliPayParam aliPayParam, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=" + alipayConfig.getCharset());
response.getWriter().write(alipayService.pay(aliPayParam));
response.getWriter().flush();
response.getWriter().close();
}
@ApiOperation("支付宝手机网站支付")
@RequestMapping(value = "/webPay", method = RequestMethod.GET)
public void webPay(AliPayParam aliPayParam, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=" + alipayConfig.getCharset());
response.getWriter().write(alipayService.webPay(aliPayParam));
response.getWriter().flush();
response.getWriter().close();
}
@ApiOperation(value = "支付宝异步回调",notes = "必须为POST请求,执行成功返回success,执行失败返回failure")
@RequestMapping(value = "/notify", method = RequestMethod.POST) | public String notify(HttpServletRequest request){
Map<String, String> params = new HashMap<>();
Map<String, String[]> requestParams = request.getParameterMap();
for (String name : requestParams.keySet()) {
params.put(name, request.getParameter(name));
}
return alipayService.notify(params);
}
@ApiOperation(value = "支付宝统一收单线下交易查询",notes = "订单支付成功返回交易状态:TRADE_SUCCESS")
@RequestMapping(value = "/query", method = RequestMethod.GET)
@ResponseBody
public CommonResult<String> query(String outTradeNo, String tradeNo){
return CommonResult.success(alipayService.query(outTradeNo,tradeNo));
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\AlipayController.java | 2 |
请完成以下Java代码 | protected String convertDelete(String sqlStatement) {
int index = sqlStatement.toUpperCase().indexOf("DELETE ");
if (index < 7) {
return "DELETE FROM " + sqlStatement.substring(index + 7);
}
return sqlStatement;
} // convertDelete
/**
* Is character a valid sql operator
* @param c
* @return boolean
*/
protected boolean isOperator(char c)
{
if ('=' == c)
return true;
else if ('<' == c)
return true;
else if ('>' == c)
return true;
else if ('|' == c)
return true;
else if ('(' == c)
return true;
else if (')' == c)
return true;
else if ('+' == c)
return true;
else if ('-' == c)
return true;
else if ('*' == c)
return true;
else if ('/' == c)
return true;
else if ('!' == c)
return true; | else if (',' == c)
return true;
else if ('?' == c)
return true;
else if ('#' == c)
return true;
else if ('@' == c)
return true;
else if ('~' == c)
return true;
else if ('&' == c)
return true;
else if ('^' == c)
return true;
else if ('!' == c)
return true;
else
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\Convert_SQL92.java | 1 |
请完成以下Java代码 | public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MSV3 Base URL.
@param MSV3_BaseUrl
Beispiel: https://msv3-server:443/msv3/v2.0
*/
@Override
public void setMSV3_BaseUrl (java.lang.String MSV3_BaseUrl)
{
set_Value (COLUMNNAME_MSV3_BaseUrl, MSV3_BaseUrl);
}
/** Get MSV3 Base URL.
@return Beispiel: https://msv3-server:443/msv3/v2.0
*/
@Override
public java.lang.String getMSV3_BaseUrl ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_BaseUrl);
}
/** Set MSV3_Vendor_Config.
@param MSV3_Vendor_Config_ID MSV3_Vendor_Config */
@Override
public void setMSV3_Vendor_Config_ID (int MSV3_Vendor_Config_ID)
{
if (MSV3_Vendor_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_Vendor_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_Vendor_Config_ID, Integer.valueOf(MSV3_Vendor_Config_ID));
}
/** Get MSV3_Vendor_Config.
@return MSV3_Vendor_Config */
@Override
public int getMSV3_Vendor_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Vendor_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kennwort.
@param Password Kennwort */
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Kennwort.
@return Kennwort */
@Override
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Nutzerkennung.
@param UserID Nutzerkennung */
@Override
public void setUserID (java.lang.String UserID)
{ | set_Value (COLUMNNAME_UserID, UserID);
}
/** Get Nutzerkennung.
@return Nutzerkennung */
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
/**
* Version AD_Reference_ID=540904
* Reference name: MSV3_Version
*/
public static final int VERSION_AD_Reference_ID=540904;
/** 1 = 1 */
public static final String VERSION_1 = "1";
/** 2 = 2 */
public static final String VERSION_2 = "2";
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.lang.String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Vendor_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected ConcurrentMessageListenerContainer<K, V> createContainerInstance(KafkaListenerEndpoint endpoint) {
TopicPartitionOffset[] topicPartitions = endpoint.getTopicPartitionsToAssign();
if (topicPartitions != null && topicPartitions.length > 0) {
ContainerProperties properties = new ContainerProperties(topicPartitions);
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
else {
Collection<String> topics = endpoint.getTopics();
Assert.state(topics != null, "'topics' must not be null");
if (!topics.isEmpty()) { // NOSONAR
ContainerProperties properties = new ContainerProperties(topics.toArray(new String[0]));
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
else {
ContainerProperties properties = new ContainerProperties(endpoint.getTopicPattern()); // NOSONAR
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
}
} | @Override
protected void initializeContainer(ConcurrentMessageListenerContainer<K, V> instance,
KafkaListenerEndpoint endpoint) {
super.initializeContainer(instance, endpoint);
Integer conc = endpoint.getConcurrency();
if (conc != null) {
instance.setConcurrency(conc);
}
else if (this.concurrency != null) {
instance.setConcurrency(this.concurrency);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\ConcurrentKafkaListenerContainerFactory.java | 2 |
请完成以下Java代码 | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((username == null) ? 0 : username.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;
Course other = (Course) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (username == null) {
return other.username == null;
} else return username.equals(other.username);
}
} | repos\spring-boot-examples-master\spring-boot-react-examples\spring-boot-react-crud-full-stack-with-maven\backend-spring-boot-react-crud-full-stack-with-maven\src\main\java\com\in28minutes\fullstack\springboot\maven\crud\springbootcrudfullstackwithmaven\course\Course.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
@Override
public String toString() {
return "RpMicroSubmitRecord{" +
"businessCode='" + businessCode + '\'' +
", subMchId='" + subMchId + '\'' +
", idCardCopy='" + idCardCopy + '\'' +
", idCardNational='" + idCardNational + '\'' +
", idCardName='" + idCardName + '\'' + | ", idCardNumber='" + idCardNumber + '\'' +
", idCardValidTime='" + idCardValidTime + '\'' +
", accountBank='" + accountBank + '\'' +
", bankAddressCode='" + bankAddressCode + '\'' +
", accountNumber='" + accountNumber + '\'' +
", storeName='" + storeName + '\'' +
", storeAddressCode='" + storeAddressCode + '\'' +
", storeStreet='" + storeStreet + '\'' +
", storeEntrancePic='" + storeEntrancePic + '\'' +
", indoorPic='" + indoorPic + '\'' +
", merchantShortname='" + merchantShortname + '\'' +
", servicePhone='" + servicePhone + '\'' +
", productDesc='" + productDesc + '\'' +
", rate='" + rate + '\'' +
", contactPhone='" + contactPhone + '\'' +
", idCardValidTimeBegin='" + idCardValidTimeBegin + '\'' +
", idCardValidTimeEnd='" + idCardValidTimeEnd + '\'' +
'}';
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpMicroSubmitRecord.java | 2 |
请完成以下Java代码 | public String getParentId() {
return parentId;
}
/**
* The business key for the process instance this execution is associated
* with.
*/
public String getProcessBusinessKey() {
return processBusinessKey;
}
/**
* The process definition key for the process instance this execution is
* associated with.
*/
public String getProcessDefinitionId() {
return processDefinitionId;
}
/** Reference to the overall process instance */
public String getProcessInstanceId() {
return processInstanceId;
}
/** | * Return the id of the tenant this execution belongs to. Can be
* <code>null</code> if the execution belongs to no single tenant.
*/
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventName=" + eventName
+ ", businessKey=" + businessKey
+ ", activityInstanceId=" + activityInstanceId
+ ", currentActivityId=" + currentActivityId
+ ", currentActivityName=" + currentActivityName
+ ", currentTransitionId=" + currentTransitionId
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", parentId=" + parentId
+ ", processBusinessKey=" + processBusinessKey
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\ExecutionEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean isParentAlreadyInHierarchy(@NonNull final I_S_Issue record)
{
final IssueId currentIssueID = IssueId.ofRepoIdOrNull(record.getS_Issue_ID());
if (currentIssueID == null)
{
return false; //means it's a new record so it doesn't have any children
}
final IssueId parentIssueID = IssueId.ofRepoIdOrNull(record.getS_Parent_Issue_ID());
if (parentIssueID != null)
{
final IssueHierarchy issueHierarchy = issueRepository.buildUpStreamIssueHierarchy(parentIssueID);
return issueHierarchy.hasNodeForId(currentIssueID);
}
return false;
}
private boolean parentAlreadyHasAnEffortIssueAssigned(@NonNull final I_S_Issue record)
{
if (record.isEffortIssue())
{
final I_S_Issue parentIssue = record.getS_Parent_Issue();
if (parentIssue != null && !parentIssue.isEffortIssue()) | {
return issueRepository.getDirectlyLinkedSubIssues(IssueId.ofRepoId(parentIssue.getS_Issue_ID()))
.stream()
.anyMatch(IssueEntity::isEffortIssue);
}
}
return false;
}
private boolean isBudgetChildForParentEffort(@NonNull final I_S_Issue record)
{
return !record.isEffortIssue()
&& record.getS_Parent_Issue() != null
&& record.getS_Parent_Issue().isEffortIssue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\interceptor\S_Issue.java | 2 |
请完成以下Java代码 | public java.lang.String getCommodityCode()
{
return get_ValueAsString(COLUMNNAME_CommodityCode);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setInternalName (final @Nullable java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* ProductType AD_Reference_ID=270
* Reference name: M_Product_ProductType
*/
public static final int PRODUCTTYPE_AD_Reference_ID=270;
/** Item = I */
public static final String PRODUCTTYPE_Item = "I";
/** Service = S */
public static final String PRODUCTTYPE_Service = "S";
/** Resource = R */
public static final String PRODUCTTYPE_Resource = "R";
/** ExpenseType = E */
public static final String PRODUCTTYPE_ExpenseType = "E";
/** Online = O */
public static final String PRODUCTTYPE_Online = "O";
/** FreightCost = F */
public static final String PRODUCTTYPE_FreightCost = "F";
@Override | public void setProductType (final @Nullable java.lang.String ProductType)
{
set_Value (COLUMNNAME_ProductType, ProductType);
}
@Override
public java.lang.String getProductType()
{
return get_ValueAsString(COLUMNNAME_ProductType);
}
/**
* VATType AD_Reference_ID=540842
* Reference name: VATType
*/
public static final int VATTYPE_AD_Reference_ID=540842;
/** RegularVAT = N */
public static final String VATTYPE_RegularVAT = "N";
/** ReducedVAT = R */
public static final String VATTYPE_ReducedVAT = "R";
/** TaxExempt = E */
public static final String VATTYPE_TaxExempt = "E";
@Override
public void setVATType (final @Nullable java.lang.String VATType)
{
set_Value (COLUMNNAME_VATType, VATType);
}
@Override
public java.lang.String getVATType()
{
return get_ValueAsString(COLUMNNAME_VATType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxCategory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ZipCode extends PanacheEntityBase {
@Id
private String zip;
private String type;
private String city;
private String state;
private String county;
private String timezone;
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} | public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
} | repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\quarkus-project\src\main\java\com\baeldung\quarkus_project\ZipCode.java | 2 |
请完成以下Java代码 | public void handleChildTermination(CmmnActivityExecution execution, CmmnActivityExecution child) {
fireForceUpdate(execution);
if (execution.isActive()) {
checkAndCompleteCaseExecution(execution);
} else if (execution.isTerminating() && isAbleToTerminate(execution)) {
String id = execution.getId();
CaseExecutionState currentState = execution.getCurrentState();
if (TERMINATING_ON_TERMINATION.equals(currentState)) {
execution.performTerminate();
} else if (TERMINATING_ON_EXIT.equals(currentState)) {
execution.performExit();
} else if (TERMINATING_ON_PARENT_TERMINATION.equals(currentState)) {
throw LOG.illegalStateTransitionException("parentTerminate", id, getTypeName());
} else {
throw LOG.terminateCaseException(id, currentState);
}
}
} | protected void checkAndCompleteCaseExecution(CmmnActivityExecution execution) {
if (canComplete(execution)) {
execution.complete();
}
}
protected void fireForceUpdate(CmmnActivityExecution execution) {
if (execution instanceof CaseExecutionEntity) {
CaseExecutionEntity entity = (CaseExecutionEntity) execution;
entity.forceUpdate();
}
}
protected String getTypeName() {
return "stage";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\StageActivityBehavior.java | 1 |
请完成以下Java代码 | public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
@Override
public void setCaseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
}
@Override
public String getCaseDefinitionName() {
return caseDefinitionName;
}
@Override
public void setCaseDefinitionName(String caseDefinitionName) {
this.caseDefinitionName = caseDefinitionName;
}
@Override
public Integer getCaseDefinitionVersion() {
return caseDefinitionVersion;
}
@Override
public void setCaseDefinitionVersion(Integer caseDefinitionVersion) {
this.caseDefinitionVersion = caseDefinitionVersion;
} | @Override
public String getCaseDefinitionDeploymentId() {
return caseDefinitionDeploymentId;
}
@Override
public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) {
this.caseDefinitionDeploymentId = caseDefinitionDeploymentId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricCaseInstance[id=").append(id)
.append(", caseDefinitionId=").append(caseDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityImpl.java | 1 |
请完成以下Java代码 | 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<ItemDefinition> getItemDefinitions() {
return itemDefinitionCollection.get(this);
}
public Collection<DrgElement> getDrgElements() {
return drgElementCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
public Collection<ElementCollection> getElementCollections() {
return elementCollectionCollection.get(this);
}
public Collection<BusinessContextElement> getBusinessContextElements() {
return businessContextElementCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, DMN_ELEMENT_DEFINITIONS)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() {
public Definitions newInstance(ModelTypeInstanceContext instanceContext) {
return new DefinitionsImpl(instanceContext);
}
}); | expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
namespaceAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAMESPACE)
.required()
.build();
exporterAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER)
.build();
exporterVersionAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER_VERSION)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importCollection = sequenceBuilder.elementCollection(Import.class)
.build();
itemDefinitionCollection = sequenceBuilder.elementCollection(ItemDefinition.class)
.build();
drgElementCollection = sequenceBuilder.elementCollection(DrgElement.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
elementCollectionCollection = sequenceBuilder.elementCollection(ElementCollection.class)
.build();
businessContextElementCollection = sequenceBuilder.elementCollection(BusinessContextElement.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DefinitionsImpl.java | 1 |
请完成以下Java代码 | public SslStoreBundle getStores() {
return (stores != null) ? stores : SslStoreBundle.NONE;
}
@Override
public SslBundleKey getKey() {
return (key != null) ? key : SslBundleKey.NONE;
}
@Override
public SslOptions getOptions() {
return (options != null) ? options : SslOptions.NONE;
}
@Override
public String getProtocol() {
return (!StringUtils.hasText(protocol)) ? DEFAULT_PROTOCOL : protocol;
}
@Override
public SslManagerBundle getManagers() {
return managersToUse;
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("key", getKey());
creator.append("options", getOptions());
creator.append("protocol", getProtocol());
creator.append("stores", getStores());
return creator.toString();
}
};
}
/**
* Factory method to create a new {@link SslBundle} which uses the system defaults.
* @return a new {@link SslBundle} instance
* @since 3.5.0
*/
static SslBundle systemDefault() {
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory | .getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(null, null);
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
SSLContext sslContext = SSLContext.getDefault();
return of(null, null, null, null, new SslManagerBundle() {
@Override
public KeyManagerFactory getKeyManagerFactory() {
return keyManagerFactory;
}
@Override
public TrustManagerFactory getTrustManagerFactory() {
return trustManagerFactory;
}
@Override
public SSLContext createSslContext(String protocol) {
return sslContext;
}
});
}
catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException ex) {
throw new IllegalStateException("Could not initialize system default SslBundle: " + ex.getMessage(), ex);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\SslBundle.java | 1 |
请完成以下Java代码 | public DocumentValidStatus getValidStatus()
{
return validStatus;
}
/* package */void setValidStatus(final DocumentValidStatus validStatus)
{
this.validStatus = validStatus;
logger.trace("collect {} validStatus: {}", fieldName, validStatus);
}
/* package */ void mergeFrom(final DocumentFieldChange fromEvent)
{
if (fromEvent.valueSet)
{
valueSet = true;
value = fromEvent.value;
valueReason = fromEvent.valueReason;
}
//
if (fromEvent.readonly != null)
{
readonly = fromEvent.readonly;
readonlyReason = fromEvent.readonlyReason;
}
//
if (fromEvent.mandatory != null)
{
mandatory = fromEvent.mandatory;
mandatoryReason = fromEvent.mandatoryReason;
}
//
if (fromEvent.displayed != null)
{
displayed = fromEvent.displayed;
displayedReason = fromEvent.displayedReason;
}
//
if (fromEvent.lookupValuesStale != null)
{
lookupValuesStale = fromEvent.lookupValuesStale;
lookupValuesStaleReason = fromEvent.lookupValuesStaleReason;
}
if (fromEvent.validStatus != null)
{
validStatus = fromEvent.validStatus;
}
if(fromEvent.fieldWarning != null)
{
fieldWarning = fromEvent.fieldWarning;
} | putDebugProperties(fromEvent.debugProperties);
}
/* package */ void mergeFrom(final IDocumentFieldChangedEvent fromEvent)
{
if (fromEvent.isValueSet())
{
valueSet = true;
value = fromEvent.getValue();
valueReason = null; // N/A
}
}
public void putDebugProperty(final String name, final Object value)
{
if (debugProperties == null)
{
debugProperties = new LinkedHashMap<>();
}
debugProperties.put(name, value);
}
public void putDebugProperties(final Map<String, Object> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
if (this.debugProperties == null)
{
this.debugProperties = new LinkedHashMap<>();
}
this.debugProperties.putAll(debugProperties);
}
public Map<String, Object> getDebugProperties()
{
return debugProperties == null ? ImmutableMap.of() : debugProperties;
}
public void setFieldWarning(@NonNull final DocumentFieldWarning fieldWarning)
{
this.fieldWarning = fieldWarning;
}
public DocumentFieldWarning getFieldWarning()
{
return fieldWarning;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldChange.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return this.scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override | public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
if (userId != null) {
sb.append(", userId=").append(userId);
}
if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\HistoricIdentityLinkEntityImpl.java | 2 |
请完成以下Java代码 | public class ZKManagerImpl implements ZKManager {
private static ZooKeeper zkeeper;
private static ZKConnection zkConnection;
public ZKManagerImpl() {
initialize();
}
/** * Initialize connection */
private void initialize() {
try {
zkConnection = new ZKConnection();
zkeeper = zkConnection.connect("localhost");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void closeConnection() {
try {
zkConnection.close();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public void create(String path, byte[] data) throws KeeperException, InterruptedException {
zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); | }
public Object getZNodeData(String path, boolean watchFlag) {
try {
byte[] b = null;
b = zkeeper.getData(path, null, null);
String data = new String(b, "UTF-8");
System.out.println(data);
return data;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public void update(String path, byte[] data) throws KeeperException, InterruptedException {
int version = zkeeper.exists(path, true)
.getVersion();
zkeeper.setData(path, data, version);
}
} | repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\zookeeper\manager\ZKManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public <S extends T> S save(S entity) {
doSave(entity);
entityManager.flush();
return entity;
}
/**
* @param entity
*/
private <S extends T> void doSave(S entity) {
var entityInformation = getEntityInformation(entity);
if (entityInformation.isNew(entity)) {
entityManager.persist(entity);
} else {
entityManager.merge(entity);
}
}
/*
* (non-Javadoc) | * @see example.springdata.jpa.compositions.FlushOnSaveRepository#saveAll(java.lang.Iterable)
*/
@Transactional
@Override
public <S extends T> Iterable<S> saveAll(Iterable<S> entities) {
entities.forEach(this::doSave);
entityManager.flush();
return entities;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <S extends T> EntityInformation<Object, S> getEntityInformation(S entity) {
var userClass = ClassUtils.getUserClass(entity.getClass());
if (entity instanceof AbstractPersistable<?>) {
return new JpaPersistableEntityInformation(userClass, entityManager.getMetamodel(),entityManager.getEntityManagerFactory().getPersistenceUnitUtil() );
}
return new JpaMetamodelEntityInformation(userClass, entityManager.getMetamodel(), entityManager.getEntityManagerFactory().getPersistenceUnitUtil());
}
} | repos\spring-data-examples-main\jpa\example\src\main\java\example\springdata\jpa\compositions\FlushOnSaveRepositoryImpl.java | 2 |
请完成以下Java代码 | public void fireMaterialEvent_voidedPPOrder(
@NonNull final I_PP_Order ppOrderRecord)
{
createAndEnqueuePPOrderDeletedEvent(ppOrderRecord);
}
@DocValidate(timings = {
ModelValidator.TIMING_AFTER_COMPLETE,
// Note: close is currently handled in MPPOrder.closeIt()
// for the other timings, we shall first figure out what we actually want
//ModelValidator.TIMING_AFTER_REACTIVATE,
//ModelValidator.TIMING_AFTER_UNCLOSE,
//ModelValidator.TIMING_AFTER_VOID
})
public void postMaterialEvent_ppOrderDocStatusChange(@NonNull final I_PP_Order ppOrderRecord)
{
final PPOrderChangedEvent changeEvent = PPOrderChangedEventFactory
.newWithPPOrderBeforeChange(ppOrderConverter, ppOrderRecord)
.inspectPPOrderAfterChange();
materialEventService.enqueueEventAfterNextCommit(changeEvent);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_PP_Order.COLUMNNAME_QtyDelivered)
public void postMaterialEvent_qtyDelivered(@NonNull final I_PP_Order ppOrderRecord)
{
final PPOrderChangedEvent changeEvent = PPOrderChangedEventFactory
.newWithPPOrderBeforeChange(ppOrderConverter, ppOrderRecord)
.inspectPPOrderAfterChange();
materialEventService.enqueueEventAfterNextCommit(changeEvent);
}
private void postPPOrderCreatedEvent(@NonNull final I_PP_Order ppOrderRecord, @NonNull final ModelChangeType type)
{
final boolean newPPOrder = type.isNew() || ModelChangeUtil.isJustActivated(ppOrderRecord);
if (!newPPOrder)
{
return; | }
if (isPPOrderCreatedFromCandidate(ppOrderRecord))
{
// dev-note: see org.eevolution.productioncandidate.service.produce.PPOrderProducerFromCandidate#postPPOrderCreatedEvent(I_PP_Order)
return;
}
ppOrderService.postPPOrderCreatedEvent(ppOrderRecord);
}
private boolean isPPOrderCreatedFromCandidate(@NonNull final I_PP_Order ppOrderRecord)
{
final ImmutableList<I_PP_OrderCandidate_PP_Order> orderAllocations = ppOrderDAO.getPPOrderAllocations(PPOrderId.ofRepoId(ppOrderRecord.getPP_Order_ID()));
return !orderAllocations.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Order_PostMaterialEvent.java | 1 |
请完成以下Java代码 | public StockQtyAndUOMQty computeInvoicableQtyPicked(@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn)
{
final Quantity pickedInUOM;
switch (invoicableQtyBasedOn)
{
case CatchWeight:
pickedInUOM = coalesce(getCatchWeightInIcUOM(), getQtyPickedInUOM());
break;
case NominalWeight:
pickedInUOM = getQtyPickedInUOM();
break;
default:
throw new AdempiereException("Unexpected InvoicableQtyBasedOn=" + invoicableQtyBasedOn);
}
return StockQtyAndUOMQty.builder()
.productId(productId) | .stockQty(qtyPicked)
.uomQty(pickedInUOM).build();
}
@Nullable
private Quantity getCatchWeightInIcUOM()
{
if (qtyCatch == null)
{
return null;
}
return Quantitys.of(qtyCatch, UOMConversionContext.of(productId), qtyPickedInUOM.getUomId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\PickedData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login")
.permitAll()
.requestMatchers("/customError")
.permitAll()
.requestMatchers("/access-denied")
.permitAll()
.requestMatchers("/secured")
.hasRole("ADMIN")
.anyRequest()
.authenticated())
.formLogin(form -> form.failureHandler(authenticationFailureHandler())
.successHandler(authenticationSuccessHandler()))
.exceptionHandling(ex -> ex.accessDeniedHandler(accessDeniedHandler()))
.logout(Customizer.withDefaults());
return http.build();
}
@Bean | public AuthenticationFailureHandler authenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new CustomAuthenticationSuccessHandler();
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\exceptionhandler\security\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ResourceGroupId implements RepoIdAware
{
@JsonCreator
public static ResourceGroupId ofRepoId(final int repoId)
{
return new ResourceGroupId(repoId);
}
@Nullable
public static ResourceGroupId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ResourceGroupId(repoId) : null;
}
public static Optional<ResourceGroupId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final ResourceGroupId ResourceGroupId)
{
return ResourceGroupId != null ? ResourceGroupId.getRepoId() : -1;
} | public static boolean equals(@Nullable final ResourceGroupId o1, @Nullable final ResourceGroupId o2)
{
return Objects.equals(o1, o2);
}
int repoId;
private ResourceGroupId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "S_Resource_Group_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\ResourceGroupId.java | 2 |
请完成以下Java代码 | public class CellValueAndNotFormulaHelper {
public Object getCellValueByFetchingLastCachedValue(String fileLocation, String cellLocation) throws IOException {
Object cellValue = new Object();
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
CellAddress cellAddress = new CellAddress(cellLocation);
Row row = sheet.getRow(cellAddress.getRow());
Cell cell = row.getCell(cellAddress.getColumn());
if (cell.getCellType() == CellType.FORMULA) {
switch (cell.getCachedFormulaResultType()) {
case BOOLEAN:
cellValue = cell.getBooleanCellValue();
break;
case NUMERIC:
cellValue = cell.getNumericCellValue();
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
default:
cellValue = null;
}
}
workbook.close();
return cellValue;
}
public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException {
Object cellValue = new Object(); | FileInputStream inputStream = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
CellAddress cellAddress = new CellAddress(cellLocation);
Row row = sheet.getRow(cellAddress.getRow());
Cell cell = row.getCell(cellAddress.getColumn());
if (cell.getCellType() == CellType.FORMULA) {
switch (evaluator.evaluateFormulaCell(cell)) {
case BOOLEAN:
cellValue = cell.getBooleanCellValue();
break;
case NUMERIC:
cellValue = cell.getNumericCellValue();
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
default:
cellValue = null;
}
}
workbook.close();
return cellValue;
}
} | repos\tutorials-master\apache-poi-4\src\main\java\com\baeldung\poi\excel\read\cellvalueandnotformula\CellValueAndNotFormulaHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InfoUpdater {
private static final Logger log = LoggerFactory.getLogger(InfoUpdater.class);
private static final ParameterizedTypeReference<Map<String, Object>> RESPONSE_TYPE = new ParameterizedTypeReference<>() {
};
private final InstanceRepository repository;
private final InstanceWebClient instanceWebClient;
private final ApiMediaTypeHandler apiMediaTypeHandler;
public InfoUpdater(InstanceRepository repository, InstanceWebClient instanceWebClient,
ApiMediaTypeHandler apiMediaTypeHandler) {
this.repository = repository;
this.instanceWebClient = instanceWebClient;
this.apiMediaTypeHandler = apiMediaTypeHandler;
}
public Mono<Void> updateInfo(InstanceId id) {
return this.repository.computeIfPresent(id, (key, instance) -> this.doUpdateInfo(instance)).then();
}
protected Mono<Instance> doUpdateInfo(Instance instance) {
if (instance.getStatusInfo().isOffline() || instance.getStatusInfo().isUnknown()) {
return Mono.empty();
}
if (!instance.getEndpoints().isPresent(Endpoint.INFO)) {
return Mono.empty();
}
log.debug("Update info for {}", instance);
return this.instanceWebClient.instance(instance)
.get()
.uri(Endpoint.INFO)
.exchangeToMono((response) -> convertInfo(instance, response))
.log(log.getName(), Level.FINEST)
.onErrorResume((ex) -> Mono.just(convertInfo(instance, ex)))
.map(instance::withInfo);
} | protected Mono<Info> convertInfo(Instance instance, ClientResponse response) {
if (response.statusCode().is2xxSuccessful() && response.headers()
.contentType()
.filter((mt) -> mt.isCompatibleWith(MediaType.APPLICATION_JSON)
|| this.apiMediaTypeHandler.isApiMediaType(mt))
.isPresent()) {
return response.bodyToMono(RESPONSE_TYPE).map(Info::from).defaultIfEmpty(Info.empty());
}
log.info("Couldn't retrieve info for {}: {}", instance, response.statusCode());
return response.releaseBody().then(Mono.just(Info.empty()));
}
protected Info convertInfo(Instance instance, Throwable ex) {
log.warn("Couldn't retrieve info for {}", instance, ex);
return Info.empty();
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\InfoUpdater.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* jwt 令牌转换
*
* @return jwt
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
return converter;
}
/**
* 非对称密钥加密,获取 public key。
* 自动选择加载方式。
*
* @return public key
*/
private String getPubKey() {
// 如果本地没有密钥,就从授权服务器中获取
return StringUtils.isEmpty(resourceServerProperties.getJwt().getKeyValue()) ? getKeyFromAuthorizationServer() : resourceServerProperties.getJwt().getKeyValue();
}
/**
* 本地没有公钥的时候,从服务器上获取
* 需要进行 Basic 认证
*
* @return public key
*/
private String getKeyFromAuthorizationServer() {
ObjectMapper objectMapper = new ObjectMapper();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders); | String pubKey = new RestTemplate().getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
try {
JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
log.info("Get Key From Authorization Server.");
return body.getStr("value");
} catch (IOException e) {
log.error("Get public key error: {}", e.getMessage());
}
return null;
}
/**
* 客户端信息
*
* @return basic
*/
private String encodeClient() {
return "Basic " + Base64.getEncoder().encodeToString((resourceServerProperties.getClientId() + ":" + resourceServerProperties.getClientSecret()).getBytes());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-resource-server\src\main\java\com\xkcoding\oauth\config\OauthResourceTokenConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FinishedGoodsReceive
{
@NonNull ImmutableMap<FinishedGoodsReceiveLineId, FinishedGoodsReceiveLine> linesById;
@NonNull WFActivityStatus status;
@Builder(toBuilder = true)
private FinishedGoodsReceive(@NonNull final ImmutableMap<FinishedGoodsReceiveLineId, FinishedGoodsReceiveLine> linesById)
{
this.linesById = linesById;
this.status = WFActivityStatus.computeStatusFromLines(linesById.values(), FinishedGoodsReceiveLine::getStatus);
}
public Stream<FinishedGoodsReceiveLine> streamLines() {return linesById.values().stream();}
public FinishedGoodsReceiveLine getLineById(final FinishedGoodsReceiveLineId lineId)
{
final FinishedGoodsReceiveLine line = getLineByIdOrNull(lineId);
if (line == null)
{
throw new AdempiereException("Line " + lineId + " was not found in " + this);
}
return line;
} | @Nullable
public FinishedGoodsReceiveLine getLineByIdOrNull(final FinishedGoodsReceiveLineId lineId)
{
return linesById.get(lineId);
}
public FinishedGoodsReceive withChangedReceiveLine(final FinishedGoodsReceiveLineId id, final UnaryOperator<FinishedGoodsReceiveLine> mapper)
{
return withLinesById(CollectionUtils.mapValue(this.linesById, id, mapper));
}
private FinishedGoodsReceive withLinesById(final ImmutableMap<FinishedGoodsReceiveLineId, FinishedGoodsReceiveLine> linesById)
{
return Objects.equals(this.linesById, linesById) ? this : toBuilder().linesById(linesById).build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\FinishedGoodsReceive.java | 2 |
请完成以下Java代码 | public boolean isSpringProfileActive(@NonNull final String profileName)
{
final ApplicationContext springApplicationContext = throwExceptionIfNull(getApplicationContext());
final String[] activeProfiles = springApplicationContext.getEnvironment().getActiveProfiles();
return Arrays
.stream(activeProfiles)
.anyMatch(env -> env.equalsIgnoreCase(profileName));
}
public static void assertUnitTestMode() {Adempiere.assertUnitTestMode();}
public static <T> void registerJUnitBean(@NonNull final T beanImpl)
{
instance.junitRegisteredBeans.registerJUnitBean(beanImpl);
}
public static <BT, T extends BT> void registerJUnitBean(@NonNull final Class<BT> beanType, @NonNull final T beanImpl)
{
instance.junitRegisteredBeans.registerJUnitBean(beanType, beanImpl);
}
public static <BT, T extends BT> void registerJUnitBeans(@NonNull final Class<BT> beanType, @NonNull final List<T> beansToAdd)
{
instance.junitRegisteredBeans.registerJUnitBeans(beanType, beansToAdd);
}
public static <T> Lazy<T> lazyBean(@NonNull final Class<T> requiredType)
{
return new Lazy<>(requiredType, null);
}
public static <T> Lazy<T> lazyBean(@NonNull final Class<T> requiredType, @Nullable final T initialBean)
{
return new Lazy<>(requiredType, initialBean);
}
public Optional<String> getProperty(@NonNull final String name)
{
if (applicationContext != null)
{
final String springContextValue = StringUtils.trimBlankToNull(applicationContext.getEnvironment().getProperty(name));
if (springContextValue != null)
{
logger.debug("Returning the spring context's value {}={} instead of looking up the AD_SysConfig record", name, springContextValue);
return Optional.of(springContextValue);
}
}
else
{
// If there is no Spring context then go an check JVM System Properties.
// Usually we will get here when we will run some tools based on metasfresh framework.
final Properties systemProperties = System.getProperties();
final String systemPropertyValue = StringUtils.trimBlankToNull(systemProperties.getProperty(name));
if (systemPropertyValue != null)
{
logger.debug("Returning the JVM system property's value {}={} instead of looking up the AD_SysConfig record", name, systemPropertyValue);
return Optional.of(systemPropertyValue);
}
// If there is no JVM System Property then go and check environment variables
return StringUtils.trimBlankToOptional(System.getenv(name));
}
return Optional.empty(); | }
//
//
//
@ToString
public static final class Lazy<T>
{
private final Class<T> requiredType;
private T bean;
private Lazy(@NonNull final Class<T> requiredType, @Nullable final T initialBean)
{
this.requiredType = requiredType;
this.bean = initialBean;
}
@NonNull
public T get()
{
T bean = this.bean;
if (bean == null)
{
bean = this.bean = instance.getBean(requiredType);
}
return bean;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\SpringContextHolder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getParentLineNumber() {
return parentLineNumber;
}
/**
* Sets the value of the parentLineNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParentLineNumber(String value) {
this.parentLineNumber = value;
}
/**
* Gets the value of the assortmentUnit property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isAssortmentUnit() {
return assortmentUnit;
}
/**
* Sets the value of the assortmentUnit property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setAssortmentUnit(Boolean value) {
this.assortmentUnit = value;
}
/**
* Gets the value of the returnableContainer property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isReturnableContainer() {
return returnableContainer;
} | /**
* Sets the value of the returnableContainer property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setReturnableContainer(Boolean value) {
this.returnableContainer = value;
}
/**
* Gets the value of the quantityInHigherLevelAssortmentUnit property.
*
* @return
* possible object is
* {@link UnitType }
*
*/
public UnitType getQuantityInHigherLevelAssortmentUnit() {
return quantityInHigherLevelAssortmentUnit;
}
/**
* Sets the value of the quantityInHigherLevelAssortmentUnit property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setQuantityInHigherLevelAssortmentUnit(UnitType value) {
this.quantityInHigherLevelAssortmentUnit = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DESADVListLineItemExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String get(final Object key)
{
return getMap().get(key);
}
@Override
public String put(final String key, final String value)
{
throw new UnsupportedOperationException();
}
@Override
public String remove(final Object key)
{
throw new UnsupportedOperationException();
}
@Override
public void putAll(final Map<? extends String, ? extends String> m)
{
throw new UnsupportedOperationException();
} | @Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public Set<String> keySet()
{
return getMap().keySet();
}
@Override
public Collection<String> values()
{
return getMap().values();
}
@Override
public Set<java.util.Map.Entry<String, String>> entrySet()
{
return getMap().entrySet();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\ResourceBundleMapWrapper.java | 2 |
请完成以下Java代码 | public Integer getChangeType() {
return changeType;
}
public void setChangeType(Integer changeType) {
this.changeType = changeType;
}
public Integer getChangeCount() {
return changeCount;
}
public void setChangeCount(Integer changeCount) {
this.changeCount = changeCount;
}
public String getOperateMan() {
return operateMan;
}
public void setOperateMan(String operateMan) {
this.operateMan = operateMan;
}
public String getOperateNote() {
return operateNote;
}
public void setOperateNote(String operateNote) {
this.operateNote = operateNote;
}
public Integer getSourceType() {
return sourceType;
} | public void setSourceType(Integer sourceType) {
this.sourceType = sourceType;
}
@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(", memberId=").append(memberId);
sb.append(", createTime=").append(createTime);
sb.append(", changeType=").append(changeType);
sb.append(", changeCount=").append(changeCount);
sb.append(", operateMan=").append(operateMan);
sb.append(", operateNote=").append(operateNote);
sb.append(", sourceType=").append(sourceType);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsGrowthChangeHistory.java | 1 |
请完成以下Java代码 | public BigDecimal getFaceAmt() {
return faceAmt;
}
/**
* Sets the value of the faceAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setFaceAmt(BigDecimal value) {
this.faceAmt = value;
}
/**
* Gets the value of the amtsdVal property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/ | public BigDecimal getAmtsdVal() {
return amtsdVal;
}
/**
* Sets the value of the amtsdVal property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmtsdVal(BigDecimal value) {
this.amtsdVal = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\FinancialInstrumentQuantityChoice.java | 1 |
请完成以下Java代码 | public <R> R forProcessInstanceReadonly(final DocumentId pinstanceId, final Function<IProcessInstanceController, R> processor)
{
final ViewActionInstance actionInstance = getActionInstance(pinstanceId);
return processor.apply(actionInstance);
}
@Override
public <R> R forProcessInstanceWritable(final DocumentId pinstanceId, final IDocumentChangesCollector changesCollector, final Function<IProcessInstanceController, R> processor)
{
final ViewActionInstance actionInstance = getActionInstance(pinstanceId);
// Make sure the process was not already executed.
// If it was executed we are not allowed to change it.
actionInstance.assertNotExecuted();
return processor.apply(actionInstance);
}
@Override
public void cacheReset()
{
viewActionInstancesByViewId.reset();
}
@ToString
private static final class ViewActionInstancesList
{
private final String viewId;
private final AtomicInteger nextIdSupplier = new AtomicInteger(1);
private final ConcurrentHashMap<DocumentId, ViewActionInstance> instances = new ConcurrentHashMap<>();
public ViewActionInstancesList(@NonNull final String viewId)
{
this.viewId = viewId;
} | public ViewActionInstance getByInstanceId(final DocumentId pinstanceId)
{
final ViewActionInstance actionInstance = instances.get(pinstanceId);
if (actionInstance == null)
{
throw new EntityNotFoundException("No view action instance found for " + pinstanceId);
}
return actionInstance;
}
private DocumentId nextPInstanceId()
{
final int nextId = nextIdSupplier.incrementAndGet();
return DocumentId.ofString(viewId + "_" + nextId);
}
public static String extractViewId(@NonNull final DocumentId pinstanceId)
{
final String pinstanceIdStr = pinstanceId.toJson();
final int idx = pinstanceIdStr.indexOf("_");
return pinstanceIdStr.substring(0, idx);
}
public void add(final ViewActionInstance viewActionInstance)
{
instances.put(viewActionInstance.getInstanceId(), viewActionInstance);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewProcessInstancesRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InOutLinesWithMissingInvoiceCandidate
{
private final List<IQueryFilter<I_M_InOutLine>> additionalFilters = new ArrayList<>();
/**
* Add additional filters to allow other modules restricting the set of order lines for which the system automatically creates invoice candidates.
*/
public void addAdditionalFilter(IQueryFilter<I_M_InOutLine> filter)
{
additionalFilters.add(filter);
}
/**
* Get all {@link I_M_InOutLine}s which are not linked to an {@link I_C_OrderLine} and there is no invoice candidate already generated for them.
*
* NOTE: this method will be used to identify those inout lines for which {@link M_InOutLine_Handler} will generate invoice candidates.
*/
public Iterator<I_M_InOutLine> retrieveLinesThatNeedAnInvoiceCandidate(@NonNull final QueryLimit limit)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final ICompositeQueryFilter<I_M_InOutLine> filters = queryBL.createCompositeQueryFilter(I_M_InOutLine.class);
filters.addEqualsFilter(I_M_InOutLine.COLUMNNAME_C_OrderLine_ID, null);
filters.addEqualsFilter(I_M_InOutLine.COLUMNNAME_Processed, true); // also processing e.g. closed InOuts
filters.addEqualsFilter(de.metas.invoicecandidate.model.I_M_InOutLine.COLUMNNAME_IsInvoiceCandidate, false); // which don't have invoice candidates already generated
filters.addOnlyActiveRecordsFilter();
//
// Filter M_InOut
{
final IQueryBuilder<I_M_InOut> inoutQueryBuilder = queryBL.createQueryBuilder(I_M_InOut.class);
// if the inout was reversed, and there is no IC yet, don't bother creating one
inoutQueryBuilder.addNotEqualsFilter(I_M_InOut.COLUMNNAME_DocStatus, IDocument.STATUS_Reversed); | // Exclude some DocTypes
{
final IQuery<I_C_DocType> validDocTypesQuery = queryBL.createQueryBuilder(I_C_DocType.class)
// Don't create InvoiceCandidates for DocSubType Saldokorrektur (FRESH-454)
.addNotEqualsFilter(I_C_DocType.COLUMNNAME_DocSubType, I_C_DocType.DOCSUBTYPE_InOutAmountCorrection)
//
.create();
inoutQueryBuilder.addInSubQueryFilter(I_M_InOut.COLUMNNAME_C_DocType_ID, I_C_DocType.COLUMNNAME_C_DocType_ID, validDocTypesQuery);
}
filters.addInSubQueryFilter(I_M_InOutLine.COLUMNNAME_M_InOut_ID, I_M_InOut.COLUMNNAME_M_InOut_ID, inoutQueryBuilder.create());
}
filters.addFilters(additionalFilters);
final IQueryBuilder<I_M_InOutLine> queryBuilder = queryBL.createQueryBuilder(I_M_InOutLine.class)
.filter(filters)
.filterByClientId();
queryBuilder.orderBy()
.addColumn(I_M_InOutLine.COLUMNNAME_M_InOutLine_ID);
queryBuilder.setLimit(limit);
return queryBuilder.create()
.iterate(I_M_InOutLine.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\InOutLinesWithMissingInvoiceCandidate.java | 2 |
请完成以下Java代码 | private Optional<DeliveryViaRule> getDeliveryViaRuleOrNull(@NonNull final I_C_BPartner bpartnerRecord, @NonNull final SOTrx soTrx)
{
if (soTrx.isSales())
{
return Optional.ofNullable(DeliveryViaRule.ofNullableCode(bpartnerRecord.getDeliveryViaRule()));
}
else if (soTrx.isPurchase())
{
return Optional.ofNullable(DeliveryViaRule.ofNullableCode(bpartnerRecord.getPO_DeliveryViaRule()));
}
return Optional.empty(); // shall not happen
}
private Optional<ShipperId> getShipperId(@NonNull final I_C_BPartner bpartnerRecord)
{
final int shipperId = bpartnerRecord.getM_Shipper_ID();
return Optional.ofNullable(ShipperId.ofRepoIdOrNull(shipperId)); | }
private PaymentRule getPaymentRule(@NonNull final BPartnerEffective bpartnerRecord, @NonNull final SOTrx soTrx)
{
// note that we fall back to a default because while the column is mandatory in the DB, it might be null in unit tests
final PaymentRule paymentRule = bpartnerRecord.getPaymentRule(soTrx);
if (soTrx.isSales() && paymentRule.isCashOrCheck()) // No Cash/Check/Transfer:
{
// for SO_Trx
return PaymentRule.OnCredit; // Payment Term
}
if (soTrx.isPurchase() && paymentRule.isCash()) // No Cash for PO_Trx
{
return PaymentRule.OnCredit; // Payment Term
}
return paymentRule;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\BPartnerOrderParamsRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AcquireJobsWithGlobalAcquireLockCmd implements Command<List<? extends JobInfoEntity>> {
protected AsyncExecutor asyncExecutor;
protected int remainingCapacity;
protected JobInfoEntityManager<? extends JobInfoEntity> jobEntityManager;
public AcquireJobsWithGlobalAcquireLockCmd(AsyncExecutor asyncExecutor, int remainingCapacity, JobInfoEntityManager<? extends JobInfoEntity> jobEntityManager) {
this.asyncExecutor = asyncExecutor;
this.remainingCapacity = remainingCapacity;
this.jobEntityManager = jobEntityManager;
}
@Override
public List<? extends JobInfoEntity> execute(CommandContext commandContext) {
int maxResults = Math.min(remainingCapacity, asyncExecutor.getMaxAsyncJobsDuePerAcquisition());
List<String> enabledCategories = asyncExecutor.getJobServiceConfiguration().getEnabledJobCategories(); | // When running with the global acquire lock, optimistic locking exceptions can't happen during acquire,
// as at most one node will be acquiring at any given time.
GregorianCalendar jobExpirationTime = calculateLockExpirationTime(asyncExecutor.getAsyncJobLockTimeInMillis(), asyncExecutor.getJobServiceConfiguration());
return jobEntityManager
.findJobsToExecuteAndLockInBulk(enabledCategories, new Page(0, maxResults), asyncExecutor.getLockOwner(), jobExpirationTime.getTime());
}
protected GregorianCalendar calculateLockExpirationTime(int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime());
gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
return gregorianCalendar;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\AcquireJobsWithGlobalAcquireLockCmd.java | 2 |
请完成以下Java代码 | public static String getFileExtension(final String filename)
{
final int idx = filename.lastIndexOf(".");
if (idx > 0)
{
return filename.substring(idx + 1);
}
return null;
}
public static void close(final Closeable closeable)
{
if (closeable == null)
{
return;
} | try
{
closeable.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
public static String toString(final InputStream in)
{
return new String(toByteArray(in), StandardCharsets.UTF_8);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\util\Util.java | 1 |
请完成以下Java代码 | public void setM_AttributeSet(final org.compiere.model.I_M_AttributeSet M_AttributeSet)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet);
}
@Override
public void setM_AttributeSet_ID (final int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID);
}
@Override
public int getM_AttributeSet_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID);
}
@Override
public void setM_AttributeSet_IncludedTab_ID (final int M_AttributeSet_IncludedTab_ID)
{
if (M_AttributeSet_IncludedTab_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, M_AttributeSet_IncludedTab_ID);
} | @Override
public int getM_AttributeSet_IncludedTab_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_IncludedTab_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSet_IncludedTab.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("excludeVariableName", excludeVariableName)
.add("parent", parent)
.toString();
}
@Nullable
@Override
public <T> T get_ValueAsObject(final String variableName)
{
if (excludeVariableName.equals(variableName))
{
return null;
}
return parent.get_ValueAsObject(variableName);
}
@Nullable
@Override
public String get_ValueAsString(final String variableName)
{
if (excludeVariableName.equals(variableName))
{
return null;
}
return parent.get_ValueAsString(variableName);
}
@Override
public Optional<Object> get_ValueIfExists(final @NonNull String variableName, final @NonNull Class<?> targetType)
{
if (excludeVariableName.equals(variableName))
{
return Optional.empty();
}
return parent.get_ValueIfExists(variableName, targetType);
}
}
@ToString
private static class RangeAwareParamsAsEvaluatee implements Evaluatee2
{
private final IRangeAwareParams params;
private RangeAwareParamsAsEvaluatee(@NonNull final IRangeAwareParams params)
{
this.params = params;
}
@Override
public boolean has_Variable(final String variableName)
{
return params.hasParameter(variableName); | }
@SuppressWarnings("unchecked")
@Override
public <T> T get_ValueAsObject(final String variableName)
{
return (T)params.getParameterAsObject(variableName);
}
@Override
public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue)
{
final BigDecimal value = params.getParameterAsBigDecimal(variableName);
return value != null ? value : defaultValue;
}
@Override
public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED)
{
return params.getParameterAsBool(variableName);
}
@Override
public Date get_ValueAsDate(final String variableName, final Date defaultValue)
{
final Timestamp value = params.getParameterAsTimestamp(variableName);
return value != null ? value : defaultValue;
}
@Override
public Integer get_ValueAsInt(final String variableName, final Integer defaultValue)
{
final int defaultValueInt = defaultValue != null ? defaultValue : 0;
return params.getParameterAsInt(variableName, defaultValueInt);
}
@Override
public String get_ValueAsString(final String variableName)
{
return params.getParameterAsString(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
return get_ValueAsString(variableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java | 1 |
请完成以下Java代码 | public static PositionLevelEnum getByLevel(int level) {
for (PositionLevelEnum position : values()) {
if (position.getLevel() == level) {
return position;
}
}
return null;
}
/**
* 根据职级名称判断是否为职员层级
* @param name 职级名称
* @return true-职员层级,false-非职员层级
*/
public static boolean isStaffLevel(String name) {
PositionLevelEnum position = getByName(name);
return position != null && position.getType() == PositionType.STAFF;
}
/**
* 根据职级名称判断是否为领导层级
* @param name 职级名称
* @return true-领导层级,false-非领导层级
*/
public static boolean isLeaderLevel(String name) {
PositionLevelEnum position = getByName(name);
return position != null && position.getType() == PositionType.LEADER;
}
/**
* 比较两个职级的等级高低
* @param name1 职级名称1
* @param name2 职级名称2
* @return 正数表示name1等级更高,负数表示name2等级更高,0表示等级相同
*/
public static int compareLevel(String name1, String name2) {
PositionLevelEnum pos1 = getByName(name1);
PositionLevelEnum pos2 = getByName(name2);
if (pos1 == null || pos2 == null) {
return 0;
}
// 等级数字越小代表职级越高
return pos2.getLevel() - pos1.getLevel();
}
/**
* 判断是否为更高等级
* @param currentName 当前职级名称
* @param targetName 目标职级名称
* @return true-目标职级更高,false-目标职级不高于当前职级
*/
public static boolean isHigherLevel(String currentName, String targetName) {
return compareLevel(targetName, currentName) > 0;
}
/**
* 获取所有职员层级名称
* @return 职员层级名称列表
*/
public static List<String> getStaffLevelNames() {
return Arrays.asList(MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName());
} | /**
* 获取所有领导层级名称
* @return 领导层级名称列表
*/
public static List<String> getLeaderLevelNames() {
return Arrays.asList(CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName());
}
/**
* 获取所有职级名称(按等级排序)
* @return 所有职级名称列表
*/
public static List<String> getAllPositionNames() {
return Arrays.asList(
CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName(),
MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName()
);
}
/**
* 获取指定等级范围的职级
* @param minLevel 最小等级
* @param maxLevel 最大等级
* @return 职级名称列表
*/
public static List<String> getPositionsByLevelRange(int minLevel, int maxLevel) {
return Arrays.stream(values())
.filter(p -> p.getLevel() >= minLevel && p.getLevel() <= maxLevel)
.map(PositionLevelEnum::getName)
.collect(java.util.stream.Collectors.toList());
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\PositionLevelEnum.java | 1 |
请完成以下Java代码 | protected boolean setExecutionContext(BaseDelegateExecution execution) {
if (execution instanceof ExecutionEntity) {
Context.setExecutionContext((ExecutionEntity) execution);
return true;
}
else if (execution instanceof CaseExecutionEntity) {
Context.setExecutionContext((CaseExecutionEntity) execution);
return true;
}
return false;
}
protected boolean isCurrentContextExecution(BaseDelegateExecution execution) {
CoreExecutionContext<?> coreExecutionContext = Context.getCoreExecutionContext();
return coreExecutionContext != null && coreExecutionContext.getExecution() == execution;
}
protected ProcessApplicationReference getProcessApplicationForInvocation(final DelegateInvocation invocation) { | BaseDelegateExecution contextExecution = invocation.getContextExecution();
ResourceDefinitionEntity contextResource = invocation.getContextResource();
if (contextExecution != null) {
return ProcessApplicationContextUtil.getTargetProcessApplication((CoreExecution) contextExecution);
}
else if (contextResource != null) {
return ProcessApplicationContextUtil.getTargetProcessApplication(contextResource);
}
else {
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\delegate\DefaultDelegateInterceptor.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.