instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void recreateADElementLinkForFieldId(@NonNull final AdFieldId adFieldId)
{
deleteExistingADElementLinkForFieldId(adFieldId);
createADElementLinkForFieldId(adFieldId);
}
@Override
public void createADElementLinkForFieldId(@NonNull final AdFieldId adFieldId)
{
// NOTE: no params because we want to log migration scripts
DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited,
MigrationScriptFileLoggerHolder.DDL_PREFIX + "select AD_Element_Link_Create_Missing_Field(" + adFieldId.getRepoId() + ")",
new Object[] {});
}
@Override
public void deleteExistingADElementLinkForFieldId(final AdFieldId adFieldId)
{
// IMPORTANT: we have to call delete directly because we don't want to have the AD_Element_Link_ID is the migration scripts
DB.executeUpdateAndThrowExceptionOnFail(
"DELETE FROM " + I_AD_Element_Link.Table_Name + " WHERE AD_Field_ID=" + adFieldId.getRepoId(),
ITrx.TRXNAME_ThreadInherited);
}
@Override
public void recreateADElementLinkForTabId(@NonNull final AdTabId adTabId)
{
deleteExistingADElementLinkForTabId(adTabId);
createADElementLinkForTabId(adTabId);
}
@Override
public void createADElementLinkForTabId(@NonNull final AdTabId adTabId)
{
// NOTE: no params because we want to log migration scripts
DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited,
MigrationScriptFileLoggerHolder.DDL_PREFIX + "select AD_Element_Link_Create_Missing_Tab(" + adTabId.getRepoId() + ")",
new Object[] {});
}
@Override
public void deleteExistingADElementLinkForTabId(final AdTabId adTabId)
{
// IMPORTANT: we have to call delete directly because we don't want to have the AD_Element_Link_ID is the migration scripts
DB.executeUpdateAndThrowExceptionOnFail(
"DELETE FROM " + I_AD_Element_Link.Table_Name + " WHERE AD_Tab_ID=" + adTabId.getRepoId(),
ITrx.TRXNAME_ThreadInherited);
}
@Override | public void recreateADElementLinkForWindowId(final AdWindowId adWindowId)
{
deleteExistingADElementLinkForWindowId(adWindowId);
createADElementLinkForWindowId(adWindowId);
}
@Override
public void createADElementLinkForWindowId(final AdWindowId adWindowId)
{
// NOTE: no params because we want to log migration scripts
DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited,
MigrationScriptFileLoggerHolder.DDL_PREFIX + "select AD_Element_Link_Create_Missing_Window(" + adWindowId.getRepoId() + ")",
new Object[] {});
}
@Override
public void deleteExistingADElementLinkForWindowId(final AdWindowId adWindowId)
{
// IMPORTANT: we have to call delete directly because we don't want to have the AD_Element_Link_ID is the migration scripts
DB.executeUpdateAndThrowExceptionOnFail(
"DELETE FROM " + I_AD_Element_Link.Table_Name + " WHERE AD_Window_ID=" + adWindowId.getRepoId(),
ITrx.TRXNAME_ThreadInherited);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\impl\ElementLinkBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RoleController extends BladeController {
private IRoleService roleService;
/**
* 详情
*/
@GetMapping("/detail")
@ApiOperationSupport(order = 1)
@Operation(summary = "详情", description = "传入role")
public R<RoleVO> detail(Role role) {
Role detail = roleService.getOne(Condition.getQueryWrapper(role));
return R.data(RoleWrapper.build().entityVO(detail));
}
/**
* 列表
*/
@GetMapping("/list")
@Parameters({
@Parameter(name = "roleName", description = "参数名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "roleAlias", description = "角色别名", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 2)
@Operation(summary = "列表", description = "传入role")
public R<List<RoleVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> role, BladeUser bladeUser) {
QueryWrapper<Role> queryWrapper = Condition.getQueryWrapper(role, Role.class);
List<Role> list = roleService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Role::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(RoleWrapper.build().listNodeVO(list));
}
/**
* 获取角色树形结构
*/
@GetMapping("/tree")
@ApiOperationSupport(order = 3)
@Operation(summary = "树形结构", description = "树形结构")
public R<List<RoleVO>> tree(String tenantId, BladeUser bladeUser) {
List<RoleVO> tree = roleService.tree(Func.toStr(tenantId, bladeUser.getTenantId()));
return R.data(tree);
}
/**
* 获取指定角色树形结构
*/
@GetMapping("/tree-by-id")
@ApiOperationSupport(order = 4)
@Operation(summary = "树形结构", description = "树形结构")
public R<List<RoleVO>> treeById(Long roleId, BladeUser bladeUser) {
Role role = roleService.getById(roleId);
List<RoleVO> tree = roleService.tree(Func.notNull(role) ? role.getTenantId() : bladeUser.getTenantId());
return R.data(tree);
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 5) | @Operation(summary = "新增或修改", description = "传入role")
public R submit(@Valid @RequestBody Role role, BladeUser user) {
CacheUtil.clear(SYS_CACHE);
if (Func.isEmpty(role.getId())) {
role.setTenantId(user.getTenantId());
}
return R.status(roleService.saveOrUpdate(role));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 6)
@Operation(summary = "删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
CacheUtil.clear(SYS_CACHE);
return R.status(roleService.removeByIds(Func.toLongList(ids)));
}
/**
* 设置菜单权限
*/
@PostMapping("/grant")
@ApiOperationSupport(order = 7)
@Operation(summary = "权限设置", description = "传入roleId集合以及menuId集合")
public R grant(@RequestBody GrantVO grantVO) {
CacheUtil.clear(SYS_CACHE);
boolean temp = roleService.grant(grantVO.getRoleIds(), grantVO.getMenuIds(), grantVO.getDataScopeIds());
return R.status(temp);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RoleController.java | 2 |
请完成以下Java代码 | public class LocationElement extends GridElement
{
/**
* Constructor
* @param ctx context
* @param C_Location_ID location
* @param font font
* @param color color
* @param isHeightOneLine
* @param label
* @param labelSuffix
*/
public LocationElement(Properties ctx, int C_Location_ID, Font font, Paint color,
boolean isHeightOneLine,
String label, String labelSuffix, String language)
{
super(isHeightOneLine ? 1 : 10, 1); // max
setGap(0,0);
MLocation ml = MLocation.get (ctx, C_Location_ID, null);
// log.debug("C_Location_ID=" + C_Location_ID);
if (ml != null)
{
int index = 0;
if (isHeightOneLine)
{
String line = (label != null ? label : "")
+ ml.toString()
+ (labelSuffix != null ? labelSuffix : "");
setData(index++, 0, line, font, color);
}
else if (ml.isAddressLinesReverse())
{
setData(index++, 0, ml.getCountry(true, language), font, color);
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(ml.getCityRegionPostal());
for (int i = 0; i < lines.length; i++)
setData(index++, 0, lines[i], font, color);
if (ml.getAddress4() != null && ml.getAddress4().length() > 0)
setData(index++, 0, ml.getAddress4(), font, color);
if (ml.getAddress3() != null && ml.getAddress3().length() > 0)
setData(index++, 0, ml.getAddress3(), font, color);
if (ml.getAddress2() != null && ml.getAddress2().length() > 0)
setData(index++, 0, ml.getAddress2(), font, color);
if (ml.getAddress1() != null && ml.getAddress1().length() > 0)
setData(index++, 0, ml.getAddress1(), font, color);
}
else
{
if (ml.getAddress1() != null && ml.getAddress1().length() > 0)
setData(index++, 0, ml.getAddress1(), font, color); | if (ml.getAddress2() != null && ml.getAddress2().length() > 0)
setData(index++, 0, ml.getAddress2(), font, color);
if (ml.getAddress3() != null && ml.getAddress3().length() > 0)
setData(index++, 0, ml.getAddress3(), font, color);
if (ml.getAddress4() != null && ml.getAddress4().length() > 0)
setData(index++, 0, ml.getAddress4(), font, color);
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(ml.getCityRegionPostal());
for (int i = 0; i < lines.length; i++)
setData(index++, 0, lines[i], font, color);
setData(index++, 0, ml.getCountry(true, language), font, color);
}
}
} // LocationElement
/**
* @deprecated since 3.3.1b
* @see #LocationElement(Properties, int, Font, Paint, boolean, String, String)
*/
public LocationElement(Properties ctx, int C_Location_ID, Font font, Paint color) {
this(ctx, C_Location_ID, font, color, false, null, null, null);
}
} // LocationElement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\LocationElement.java | 1 |
请完成以下Java代码 | public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public void setCaseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
}
public String getCaseDefinitionName() {
return caseDefinitionName;
}
public void setCaseDefinitionName(String caseDefinitionName) {
this.caseDefinitionName = caseDefinitionName;
}
public int getCaseDefinitionVersion() {
return caseDefinitionVersion;
}
public void setCaseDefinitionVersion(int caseDefinitionVersion) {
this.caseDefinitionVersion = caseDefinitionVersion;
}
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public void setHistoryTimeToLive(Integer historyTimeToLive) {
this.historyTimeToLive = historyTimeToLive;
}
public long getFinishedCaseInstanceCount() { | return finishedCaseInstanceCount;
}
public void setFinishedCaseInstanceCount(Long finishedCaseInstanceCount) {
this.finishedCaseInstanceCount = finishedCaseInstanceCount;
}
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 String toString() {
return this.getClass().getSimpleName()
+ "[caseDefinitionId = " + caseDefinitionId
+ ", caseDefinitionKey = " + caseDefinitionKey
+ ", caseDefinitionName = " + caseDefinitionName
+ ", caseDefinitionVersion = " + caseDefinitionVersion
+ ", historyTimeToLive = " + historyTimeToLive
+ ", finishedCaseInstanceCount = " + finishedCaseInstanceCount
+ ", cleanableCaseInstanceCount = " + cleanableCaseInstanceCount
+ ", tenantId = " + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricCaseInstanceReportResultEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.jpa.domain");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
} | @Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\jpa\config\PersistenceConfig.java | 2 |
请完成以下Java代码 | 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);
}
/**
* HU_UnitType AD_Reference_ID=540472
* Reference name: HU_UnitType
*/
public static final int HU_UNITTYPE_AD_Reference_ID=540472;
/** TransportUnit = TU */
public static final String HU_UNITTYPE_TransportUnit = "TU";
/** LoadLogistiqueUnit = LU */
public static final String HU_UNITTYPE_LoadLogistiqueUnit = "LU";
/** VirtualPI = V */
public static final String HU_UNITTYPE_VirtualPI = "V";
@Override
public void setHU_UnitType (final @Nullable java.lang.String HU_UnitType)
{
set_Value (COLUMNNAME_HU_UnitType, HU_UnitType);
}
@Override
public java.lang.String getHU_UnitType()
{ | return get_ValueAsString(COLUMNNAME_HU_UnitType);
}
@Override
public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID)
{
if (M_HU_PackagingCode_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID);
}
@Override
public int getM_HU_PackagingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID);
}
@Override
public void setPackagingCode (final java.lang.String PackagingCode)
{
set_Value (COLUMNNAME_PackagingCode, PackagingCode);
}
@Override
public java.lang.String getPackagingCode()
{
return get_ValueAsString(COLUMNNAME_PackagingCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackagingCode.java | 1 |
请完成以下Java代码 | public void setSize (double Width, double Height)
{
this.width = Width;
this.height = Height;
} // setSize
/**
* Set Size
* @param dim dimension
*/
public void setSize (Dimension dim)
{
this.width = dim.getWidth();
this.height = dim.getHeight();
} // setSize
/**
* Add Size below existing
* @param dWidth width to increase if below
* @param dHeight height to add
*/
public void addBelow (double dWidth, double dHeight)
{
if (this.width < dWidth)
this.width = dWidth;
this.height += dHeight;
} // addBelow
/**
* Add Size below existing
* @param dim add dimension
*/
public void addBelow (Dimension dim)
{
addBelow (dim.width, dim.height);
} // addBelow
/**
* Round to next Int value
*/
public void roundUp()
{
width = Math.ceil(width);
height = Math.ceil(height);
} // roundUp
/**
* Get Width
* @return width
*/
public double getWidth()
{
return width;
} // getWidth
/**
* Get Height
* @return height
*/
public double getHeight()
{
return height;
} // getHeight
/*************************************************************************/
/** | * Hash Code
* @return hash code
*/
public int hashCode()
{
long bits = Double.doubleToLongBits(width);
bits ^= Double.doubleToLongBits(height) * 31;
return (((int) bits) ^ ((int) (bits >> 32)));
} // hashCode
/**
* Equals
* @param obj object
* @return true if w/h is same
*/
public boolean equals (Object obj)
{
if (obj != null && obj instanceof Dimension2D)
{
Dimension2D d = (Dimension2D)obj;
if (d.getWidth() == width && d.getHeight() == height)
return true;
}
return false;
} // equals
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("Dimension2D[w=").append(width).append(",h=").append(height).append("]");
return sb.toString();
} // toString
} // Dimension2DImpl | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Dimension2DImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GLCategoryId implements RepoIdAware
{
int repoId;
@JsonCreator
public static GLCategoryId ofRepoId(final int repoId)
{
return new GLCategoryId(repoId);
}
public static GLCategoryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new GLCategoryId(repoId) : null;
}
public static int toRepoId(GLCategoryId glCategoryId) | {
return glCategoryId != null ? glCategoryId.getRepoId() : -1;
}
private GLCategoryId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "GL_Category_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\GLCategoryId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PrimaryConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
private Map<String, Object> getVendorProperties() {
return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
}
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary | @Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
// HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
// jpaVendorAdapter.setGenerateDdl(true);
return builder
.dataSource(primaryDataSource)
.packages("com.didispace.chapter38.p") //设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.properties(getVendorProperties())
.build();
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
} | repos\SpringBoot-Learning-master\2.x\chapter3-8\src\main\java\com\didispace\chapter38\PrimaryConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTenantId() {
return tenantId;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
@ApiModelProperty(value = "Array of variables (in the general variables format) to use as payload to pass along with the signal. Cannot be used in case async is set to true, this will result in an error.")
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
@JsonIgnore
public boolean isCustomTenantSet() {
return tenantId != null && !StringUtils.isEmpty(tenantId);
}
@ApiModelProperty(value = "Name of the signal") | public String getSignalName() {
return signalName;
}
public void setSignalName(String signalName) {
this.signalName = signalName;
}
public void setAsync(boolean async) {
this.async = async;
}
@ApiModelProperty(value = "If true, handling of the signal will happen asynchronously. Return code will be 202 - Accepted to indicate the request is accepted but not yet executed. If false,\n"
+ " handling the signal will be done immediately and result (200 - OK) will only return after this completed successfully. Defaults to false if omitted.")
public boolean isAsync() {
return async;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\SignalEventReceivedRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
Resource resource = new ClassPathResource("META-INF/spring.integration.properties");
if (resource.exists()) {
registerIntegrationPropertiesPropertySource(environment, resource);
}
}
protected void registerIntegrationPropertiesPropertySource(ConfigurableEnvironment environment, Resource resource) {
PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
try {
OriginTrackedMapPropertySource propertyFileSource = (OriginTrackedMapPropertySource) loader
.load("META-INF/spring.integration.properties", resource)
.get(0);
environment.getPropertySources().addLast(new IntegrationPropertiesPropertySource(propertyFileSource));
}
catch (IOException ex) {
throw new IllegalStateException("Failed to load integration properties from " + resource, ex);
}
}
private static final class IntegrationPropertiesPropertySource extends PropertySource<Map<String, Object>>
implements OriginLookup<String> {
private static final String PREFIX = "spring.integration.";
private static final Map<String, String> KEYS_MAPPING;
static {
Map<String, String> mappings = new HashMap<>();
mappings.put(PREFIX + "channel.auto-create", IntegrationProperties.CHANNELS_AUTOCREATE);
mappings.put(PREFIX + "channel.max-unicast-subscribers",
IntegrationProperties.CHANNELS_MAX_UNICAST_SUBSCRIBERS);
mappings.put(PREFIX + "channel.max-broadcast-subscribers",
IntegrationProperties.CHANNELS_MAX_BROADCAST_SUBSCRIBERS);
mappings.put(PREFIX + "error.require-subscribers", IntegrationProperties.ERROR_CHANNEL_REQUIRE_SUBSCRIBERS);
mappings.put(PREFIX + "error.ignore-failures", IntegrationProperties.ERROR_CHANNEL_IGNORE_FAILURES);
mappings.put(PREFIX + "endpoint.default-timeout", IntegrationProperties.ENDPOINTS_DEFAULT_TIMEOUT);
mappings.put(PREFIX + "endpoint.throw-exception-on-late-reply",
IntegrationProperties.THROW_EXCEPTION_ON_LATE_REPLY);
mappings.put(PREFIX + "endpoint.read-only-headers", IntegrationProperties.READ_ONLY_HEADERS); | mappings.put(PREFIX + "endpoint.no-auto-startup", IntegrationProperties.ENDPOINTS_NO_AUTO_STARTUP);
KEYS_MAPPING = Collections.unmodifiableMap(mappings);
}
private final OriginTrackedMapPropertySource delegate;
IntegrationPropertiesPropertySource(OriginTrackedMapPropertySource delegate) {
super("META-INF/spring.integration.properties", delegate.getSource());
this.delegate = delegate;
}
@Override
public @Nullable Object getProperty(String name) {
String mapped = KEYS_MAPPING.get(name);
return (mapped != null) ? this.delegate.getProperty(mapped) : null;
}
@Override
public @Nullable Origin getOrigin(String key) {
String mapped = KEYS_MAPPING.get(key);
return (mapped != null) ? this.delegate.getOrigin(mapped) : null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationPropertiesEnvironmentPostProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void configureGemFireProperties(@NonNull ConfigurableEnvironment environment,
@NonNull CacheFactoryBean cache) {
Assert.notNull(environment, "Environment must not be null");
Assert.notNull(cache, "CacheFactoryBean must not be null");
MutablePropertySources propertySources = environment.getPropertySources();
if (propertySources != null) {
Set<String> gemfirePropertyNames = propertySources.stream()
.filter(EnumerablePropertySource.class::isInstance)
.map(EnumerablePropertySource.class::cast)
.map(EnumerablePropertySource::getPropertyNames)
.map(propertyNamesArray -> ArrayUtils.nullSafeArray(propertyNamesArray, String.class))
.flatMap(Arrays::stream)
.filter(this::isGemFireDotPrefixedProperty)
.filter(this::isValidGemFireProperty)
.collect(Collectors.toSet());
Properties gemfireProperties = cache.getProperties();
gemfirePropertyNames.stream()
.filter(gemfirePropertyName -> isNotSet(gemfireProperties, gemfirePropertyName))
.filter(this::isValidGemFireProperty)
.forEach(gemfirePropertyName -> {
String propertyName = normalizeGemFirePropertyName(gemfirePropertyName);
String propertyValue = environment.getProperty(gemfirePropertyName);
if (StringUtils.hasText(propertyValue)) {
gemfireProperties.setProperty(propertyName, propertyValue);
}
else {
getLogger().warn("Apache Geode Property [{}] was not set", propertyName);
}
});
cache.setProperties(gemfireProperties);
}
}
protected Logger getLogger() {
return this.logger;
}
private boolean isGemFireDotPrefixedProperty(@NonNull String propertyName) {
return StringUtils.hasText(propertyName) && propertyName.startsWith(GEMFIRE_PROPERTY_PREFIX);
} | private boolean isNotSet(Properties gemfireProperties, String propertyName) {
return !gemfireProperties.containsKey(normalizeGemFirePropertyName(propertyName));
}
private boolean isValidGemFireProperty(String propertyName) {
try {
GemFireProperties.from(normalizeGemFirePropertyName(propertyName));
return true;
}
catch (IllegalArgumentException cause) {
getLogger().warn(String.format("[%s] is not a valid Apache Geode property", propertyName));
// TODO: uncomment line below and replace line above when SBDG is rebased on SDG 2.3.0.RC2 or later.
//getLogger().warn(cause.getMessage());
return false;
}
}
private String normalizeGemFirePropertyName(@NonNull String propertyName) {
int index = propertyName.lastIndexOf(".");
return index > -1 ? propertyName.substring(index + 1) : propertyName;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\EnvironmentSourcedGemFirePropertiesAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setC_InvoiceLine_ID (int C_InvoiceLine_ID)
{
if (C_InvoiceLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID));
}
/** Get Rechnungsposition.
@return Rechnungszeile
*/
@Override
public int getC_InvoiceLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rechnungsdatum.
@param DateInvoiced
Datum auf der Rechnung
*/
@Override
public void setDateInvoiced (java.sql.Timestamp DateInvoiced)
{
set_ValueNoCheck (COLUMNNAME_DateInvoiced, DateInvoiced);
}
/** Get Rechnungsdatum.
@return Datum auf der Rechnung
*/
@Override
public java.sql.Timestamp getDateInvoiced ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateInvoiced);
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
@Override
public void setIsSOTrx (boolean IsSOTrx)
{
set_ValueNoCheck (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
@Override
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{ | return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Einzelpreis.
@param PriceActual
Effektiver Preis
*/
@Override
public void setPriceActual (java.math.BigDecimal PriceActual)
{
set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual);
}
/** Get Einzelpreis.
@return Effektiver Preis
*/
@Override
public java.math.BigDecimal getPriceActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats_Invoice_Online_V.java | 1 |
请完成以下Java代码 | public class RemoveService {
/**
* 设置集合名称
*/
private static final String COLLECTION_NAME = "users";
@Resource
private MongoTemplate mongoTemplate;
/**
* 删除集合中【符合条件】的【一个]或[多个】文档
*
* @return 删除用户信息的结果
*/
public Object remove() {
// 设置查询条件参数
int age = 30;
String sex = "男";
// 创建条件对象
Criteria criteria = Criteria.where("age").is(age).and("sex").is(sex);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的全部文档信息
DeleteResult result = mongoTemplate.remove(query, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "成功删除 " + result.getDeletedCount() + " 条文档信息";
log.info(resultInfo);
return resultInfo;
}
/**
* 删除【符合条件】的【单个文档】,并返回删除的文档。
*
* @return 删除的用户信息
*/
public Object findAndRemove() {
// 设置查询条件参数 | String name = "zhangsansan";
// 创建条件对象
Criteria criteria = Criteria.where("name").is(name);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的第一条文档,并返回删除的文档信息
User result = mongoTemplate.findAndRemove(query, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "成功删除文档信息,文档内容为:" + result;
log.info(resultInfo);
return result;
}
/**
* 删除【符合条件】的【全部文档】,并返回删除的文档。
*
* @return 删除的全部用户信息
*/
public Object findAllAndRemove() {
// 设置查询条件参数
int age = 22;
// 创建条件对象
Criteria criteria = Criteria.where("age").is(age);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的全部文档,并返回删除的全部文档信息
List<User> resultList = mongoTemplate.findAllAndRemove(query, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "成功删除文档信息,文档内容为:" + resultList;
log.info(resultInfo);
return resultList;
}
} | repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\RemoveService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersistenceUserAutoConfiguration {
@Autowired
private Environment env;
public PersistenceUserAutoConfiguration() {
super();
}
//
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean userEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(userDataSource());
em.setPackagesToScan("com.baeldung.multipledb.model.user");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); | properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource userDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean
public PlatformTransactionManager userTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(userEntityManager().getObject());
return transactionManager;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\multipledb\PersistenceUserAutoConfiguration.java | 2 |
请完成以下Java代码 | private CommissionPoints extractInvoicedCommissionPoints(@NonNull final I_C_Invoice_Candidate icRecord)
{
final CommissionPoints commissionPointsToInvoice = CommissionPoints.of(icRecord.getNetAmtInvoiced());
return deductTaxAmount(commissionPointsToInvoice, icRecord);
}
@NonNull
private CommissionPoints deductTaxAmount(
@NonNull final CommissionPoints commissionPoints,
@NonNull final I_C_Invoice_Candidate icRecord)
{
if (commissionPoints.isZero())
{
return commissionPoints; // don't bother going to the DAO layer
}
final int effectiveTaxRepoId = firstGreaterThanZero(icRecord.getC_Tax_Override_ID(), icRecord.getC_Tax_ID());
if (effectiveTaxRepoId <= 0)
{
logger.debug("Invoice candidate has effective C_Tax_ID={}; -> return undedacted commissionPoints={}", effectiveTaxRepoId, commissionPoints);
return commissionPoints;
}
final Tax taxRecord = taxDAO.getTaxById(effectiveTaxRepoId);
final CurrencyPrecision precision = invoiceCandBL.extractPricePrecision(icRecord);
final BigDecimal taxAdjustedAmount = taxRecord.calculateBaseAmt(
commissionPoints.toBigDecimal(),
icRecord.isTaxIncluded(),
precision.toInt()); | return CommissionPoints.of(taxAdjustedAmount);
}
@NonNull
private Optional<BPartnerId> getSalesRepId(@NonNull final I_C_Invoice_Candidate icRecord)
{
final BPartnerId invoiceCandidateSalesRepId = BPartnerId.ofRepoIdOrNull(icRecord.getC_BPartner_SalesRep_ID());
if (invoiceCandidateSalesRepId != null)
{
return Optional.of(invoiceCandidateSalesRepId);
}
final I_C_BPartner customerBPartner = bPartnerDAO.getById(icRecord.getBill_BPartner_ID());
if (customerBPartner.isSalesRep())
{
return Optional.of(BPartnerId.ofRepoId(customerBPartner.getC_BPartner_ID()));
}
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\commissiontrigger\salesinvoicecandidate\SalesInvoiceCandidateFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
@Override
public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{ | return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
}
@Override
public void setS_IssueLabel_ID (final int S_IssueLabel_ID)
{
if (S_IssueLabel_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_IssueLabel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_IssueLabel_ID, S_IssueLabel_ID);
}
@Override
public int getS_IssueLabel_ID()
{
return get_ValueAsInt(COLUMNNAME_S_IssueLabel_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_IssueLabel.java | 2 |
请完成以下Java代码 | public boolean overlapsWith(Interval other)
{
return this.start <= other.getEnd() &&
this.end >= other.getStart();
}
/**
* 区间是否覆盖了这个点
* @param point
* @return
*/
public boolean overlapsWith(int point)
{
return this.start <= point && point <= this.end;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Intervalable))
{
return false;
}
Intervalable other = (Intervalable) o;
return this.start == other.getStart() &&
this.end == other.getEnd();
}
@Override | public int hashCode()
{
return this.start % 100 + this.end % 100;
}
@Override
public int compareTo(Object o)
{
if (!(o instanceof Intervalable))
{
return -1;
}
Intervalable other = (Intervalable) o;
int comparison = this.start - other.getStart();
return comparison != 0 ? comparison : this.end - other.getEnd();
}
@Override
public String toString()
{
return this.start + ":" + this.end;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\Interval.java | 1 |
请完成以下Java代码 | public boolean isHighVolume()
{
return true;
}
@Override
public boolean isAllowAnyValue()
{
return true;
}
@Override
public Evaluatee prepareContext(final IAttributeSet attributeSet)
{
return Evaluatees.empty();
}
@Override
public List<? extends NamePair> getAvailableValues(final Evaluatee evalCtx_NOTUSED)
{
// NOTE: the only reason why we are fetching and returning the vendors instead of returning NULL,
// is because user needs to set it in purchase order's ASI.
return getCachedVendors();
}
@Nullable
private static BPartnerId normalizeValueKey(@Nullable final Object valueKey)
{
if (valueKey == null)
{
return null;
}
else if (valueKey instanceof Number)
{
final int valueInt = ((Number)valueKey).intValue();
return BPartnerId.ofRepoIdOrNull(valueInt);
}
else
{
final int valueInt = NumberUtils.asInt(valueKey.toString(), -1);
return BPartnerId.ofRepoIdOrNull(valueInt);
}
}
@Override
@Nullable
public KeyNamePair getAttributeValueOrNull(final Evaluatee evalCtx_NOTUSED, final Object valueKey)
{
final BPartnerId bpartnerId = normalizeValueKey(valueKey);
if (bpartnerId == null)
{
return null;
}
return getCachedVendors()
.stream()
.filter(vnp -> vnp.getKey() == bpartnerId.getRepoId())
.findFirst()
.orElseGet(() -> retrieveBPartnerKNPById(bpartnerId));
}
@Nullable
private KeyNamePair retrieveBPartnerKNPById(@NonNull final BPartnerId bpartnerId) | {
final I_C_BPartner bpartner = bpartnerDAO.getByIdOutOfTrx(bpartnerId);
return bpartner != null ? toKeyNamePair(bpartner) : null;
}
@Nullable
@Override
public AttributeValueId getAttributeValueIdOrNull(final Object valueKey)
{
return null;
}
private List<KeyNamePair> getCachedVendors()
{
final ImmutableList<KeyNamePair> vendors = vendorsCache.getOrLoad(0, this::retrieveVendorKeyNamePairs);
return ImmutableList.<KeyNamePair>builder()
.add(staticNullValue())
.addAll(vendors)
.build();
}
private QueryLimit getMaxVendors()
{
final int maxVendorsInt = sysconfigBL.getIntValue(SYSCONFIG_MAX_VENDORS, DEFAULT_MAX_VENDORS);
return QueryLimit.ofInt(maxVendorsInt);
}
private ImmutableList<KeyNamePair> retrieveVendorKeyNamePairs()
{
return bpartnerDAO.retrieveVendors(getMaxVendors())
.stream()
.map(HUVendorBPartnerAttributeValuesProvider::toKeyNamePair)
.sorted(Comparator.comparing(KeyNamePair::getName))
.collect(ImmutableList.toImmutableList());
}
private static KeyNamePair toKeyNamePair(@NonNull final I_C_BPartner bpartner)
{
return KeyNamePair.of(bpartner.getC_BPartner_ID(), bpartner.getName(), bpartner.getDescription());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUVendorBPartnerAttributeValuesProvider.java | 1 |
请完成以下Java代码 | public class DownloadMediaResponse extends BaseResponse {
private static final Logger LOG = LoggerFactory.getLogger(DownloadMediaResponse.class);
private String fileName;
private byte[] content;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setContent(InputStream content, Integer length) {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
try {
StreamUtil.copy(content, byteOutputStream);
byte[] temp = byteOutputStream.toByteArray();
if (temp.length > length) {
this.content = new byte[length];
System.arraycopy(temp, 0, this.content, 0, length);
} else { | this.content = temp;
}
} catch (IOException e) {
LOG.error("异常", e);
}
}
/**
* 如果成功,则可以靠这个方法将数据输出
*
* @param out 调用者给的输出流
* @throws IOException 写流出现异常
*/
public void writeTo(OutputStream out) throws IOException {
out.write(this.content);
out.flush();
out.close();
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\response\DownloadMediaResponse.java | 1 |
请完成以下Java代码 | public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
public String modelFileFolder() {
return outputFolder() + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder() + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
/**
* Use this callback to extend the standard set of lambdas available to templates. | * @return
*/
@Override
protected ImmutableMap.Builder<String, Mustache.Lambda> addMustacheLambdas() {
// Start with parent lambdas
ImmutableMap.Builder<String, Mustache.Lambda> builder = super.addMustacheLambdas();
// Add custom lambda to convert operationIds in suitable java constants
return builder.put("javaconstant", new JavaConstantLambda())
.put("path", new PathLambda());
}
static final List<String> JAVA_RESERVED_WORDS = Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "continue", "const", "default", "do", "double", "else", "enum", "exports", "extends", "final", "finally",
"float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "module", "native", "new", "package", "private", "protected", "public", "requires", "return", "short", "static", "strictfp", "super", "switch",
"synchronized", "this", "throw", "throws", "transient", "try", "var", "void", "volatile", "while");
} | repos\tutorials-master\spring-swagger-codegen-modules\openapi-custom-generator\src\main\java\com\baeldung\openapi\generators\camelclient\JavaCamelClientGenerator.java | 1 |
请完成以下Java代码 | public FlowElement getSourceFlowElement() {
return sourceFlowElement;
}
public void setSourceFlowElement(FlowElement sourceFlowElement) {
this.sourceFlowElement = sourceFlowElement;
}
public FlowElement getTargetFlowElement() {
return targetFlowElement;
}
public void setTargetFlowElement(FlowElement targetFlowElement) {
this.targetFlowElement = targetFlowElement;
}
public List<Integer> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<Integer> waypoints) {
this.waypoints = waypoints;
} | public String toString() {
return sourceRef + " --> " + targetRef;
}
public SequenceFlow clone() {
SequenceFlow clone = new SequenceFlow();
clone.setValues(this);
return clone;
}
public void setValues(SequenceFlow otherFlow) {
super.setValues(otherFlow);
setConditionExpression(otherFlow.getConditionExpression());
setSourceRef(otherFlow.getSourceRef());
setTargetRef(otherFlow.getTargetRef());
setSkipExpression(otherFlow.getSkipExpression());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SequenceFlow.java | 1 |
请完成以下Java代码 | public class Result<T> implements Serializable {
private static final long serialVersionUID = 5925101851082556646L;
private T data;
@ApiModelProperty(value = "状态码",example = "SUCCESS")
private Status status;
@ApiModelProperty(value = "错误编码",example = "4001")
private String code;
private String message;
public static Result success() {
Result result = new Result<>();
result.setCode("200");
result.setStatus(Status.SUCCESS);
result.setMessage(Status.SUCCESS.name());
return result;
}
public static <T> Result success(T data) {
Result<T> result = new Result<>();
result.setCode("200");
result.setStatus(Status.SUCCESS);
result.setMessage(Status.SUCCESS.name());
result.setData(data);
return result;
}
public static <T> Result error(String msg) {
Result<T> result = new Result<>();
result.setCode("500");
result.setStatus(Status.ERROR);
result.setMessage(msg);
return result;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message; | }
public void setMessage(String message) {
this.message = message;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public static enum Status {
SUCCESS("OK"),
ERROR("ERROR");
private String code;
private Status(String code) {
this.code = code;
}
public String code() {
return this.code;
}
}
} | repos\spring-boot-student-master\spring-boot-student-swagger\src\main\java\com\xiaolyuh\Result.java | 1 |
请完成以下Java代码 | public class AnnotationConfigReactiveWebApplicationContext extends AnnotationConfigApplicationContext
implements ConfigurableReactiveWebApplicationContext {
/**
* Create a new AnnotationConfigReactiveWebApplicationContext that needs to be
* populated through {@link #register} calls and then manually {@linkplain #refresh
* refreshed}.
*/
public AnnotationConfigReactiveWebApplicationContext() {
}
/**
* Create a new AnnotationConfigApplicationContext with the given
* DefaultListableBeanFactory.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
* @since 2.2.0
*/
public AnnotationConfigReactiveWebApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
}
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions from the
* given annotated classes and automatically refreshing the context.
* @param annotatedClasses one or more annotated classes, e.g.
* {@link Configuration @Configuration} classes
* @since 2.2.0
*/
public AnnotationConfigReactiveWebApplicationContext(Class<?>... annotatedClasses) {
super(annotatedClasses);
}
/**
* Create a new AnnotationConfigApplicationContext, scanning for bean definitions in
* the given packages and automatically refreshing the context.
* @param basePackages the packages to check for annotated classes
* @since 2.2.0 | */
public AnnotationConfigReactiveWebApplicationContext(String... basePackages) {
super(basePackages);
}
@Override
protected ConfigurableEnvironment createEnvironment() {
return new StandardReactiveWebEnvironment();
}
@Override
protected Resource getResourceByPath(String path) {
// We must be careful not to expose classpath resources
return new FilteredReactiveWebContextResource(path);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\context\reactive\AnnotationConfigReactiveWebApplicationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductsRestController
{
private static final Logger logger = LogManager.getLogger(ProductsRestController.class);
private final ProductsServicesFacade productsServicesFacade;
public ProductsRestController(@NonNull final ProductsServicesFacade productsServicesFacade)
{
this.productsServicesFacade = productsServicesFacade;
}
@GetMapping
public ResponseEntity<JsonGetProductsResponse> getProducts()
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
try
{
final JsonGetProductsResponse response = GetProductsCommand.builder()
.servicesFacade(productsServicesFacade) | .adLanguage(adLanguage)
.execute();
return ResponseEntity.ok(response);
}
catch (final Exception ex)
{
logger.debug("Got exception", ex);
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(JsonGetProductsResponse.error(ex, adLanguage));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\ProductsRestController.java | 2 |
请完成以下Java代码 | public Integer getPermissionId() {
return permissionId;
}
/**
* 设置 权限ID.
*
* @param permissionId 权限ID.
*/
public void setPermissionId(Integer permissionId) {
this.permissionId = permissionId;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间. | *
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\RolePermission.java | 1 |
请完成以下Java代码 | public BigDecimal getTotalLinesWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLinesWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalTaxBaseAmt (final @Nullable BigDecimal TotalTaxBaseAmt)
{
set_Value (COLUMNNAME_TotalTaxBaseAmt, TotalTaxBaseAmt);
}
@Override
public BigDecimal getTotalTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalTaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVat (final @Nullable BigDecimal TotalVat)
{
set_Value (COLUMNNAME_TotalVat, TotalVat);
}
@Override
public BigDecimal getTotalVat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVatWithSurchargeAmt (final BigDecimal TotalVatWithSurchargeAmt) | {
set_ValueNoCheck (COLUMNNAME_TotalVatWithSurchargeAmt, TotalVatWithSurchargeAmt);
}
@Override
public BigDecimal getTotalVatWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVatWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_v.java | 1 |
请完成以下Java代码 | public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
public static String reverseUsingIntStreamRangeMethod(String str) {
if (str == null) {
return null;
}
char[] charArray = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> charArray[str.length() - i - 1])
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
public static String reverseUsingStreamOfMethod(String str) {
if (str == null) {
return null;
} | return Stream.of(str)
.map(string -> new StringBuilder(string).reverse())
.collect(Collectors.joining());
}
public static String reverseUsingCharsMethod(String str) {
if (str == null) {
return null;
}
return str.chars()
.mapToObj(c -> (char) c)
.reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2);
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms\src\main\java\com\baeldung\reverse\ReverseStringExamples.java | 1 |
请完成以下Java代码 | private FactLine createFactLine(final FactLine baseLine, final GLDistributionResultLine glDistributionLine)
{
final BigDecimal amount = glDistributionLine.getAmount();
if (amount.signum() == 0)
{
return null;
}
final AccountDimension accountDimension = glDistributionLine.getAccountDimension();
final MAccount account = MAccount.get(Env.getCtx(), accountDimension);
final FactLine factLine = FactLine.builder()
.services(baseLine.getServices())
.doc(baseLine.getDoc())
.docLine(baseLine.getDocLine())
.docRecordRef(baseLine.getDocRecordRef())
.Line_ID(baseLine.getLine_ID())
.SubLine_ID(baseLine.getSubLine_ID())
.postingType(baseLine.getPostingType())
.acctSchema(baseLine.getAcctSchema())
.account(account)
.accountConceptualName(null)
.additionalDescription(glDistributionLine.getDescription())
.qty(baseLine.getQty() != null ? Quantitys.of(glDistributionLine.getQty(), baseLine.getQty().getUomId()) : null)
.build();
//
// Update accounting dimensions
factLine.updateFromDimension(AccountDimension.builder()
.applyOverrides(accountDimension)
.clearC_AcctSchema_ID()
.clearSegmentValue(AcctSegmentType.Account)
.build());
// Amount
setAmountToFactLine(glDistributionLine, factLine);
logger.debug("{}", factLine);
return factLine;
}
private void setAmountToFactLine(
@NonNull final GLDistributionResultLine glDistributionLine,
@NonNull final FactLine factLine)
{
final Money amount = Money.of(glDistributionLine.getAmount(), glDistributionLine.getCurrencyId()); | switch (glDistributionLine.getAmountSign())
{
case CREDIT:
factLine.setAmtSource(null, amount);
break;
case DEBIT:
factLine.setAmtSource(amount, null);
break;
case DETECT:
if (amount.signum() < 0)
{
factLine.setAmtSource(null, amount.negate());
}
else
{
factLine.setAmtSource(amount, null);
}
break;
}
factLine.convert();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactGLDistributor.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws Exception {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;
new HttpServer(port).run();
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception { | ChannelPipeline p = ch.pipeline();
p.addLast(new HttpRequestDecoder());
p.addLast(new HttpResponseEncoder());
p.addLast(new CustomHttpServerHandler());
}
});
ChannelFuture f = b.bind(port)
.sync();
f.channel()
.closeFuture()
.sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
} | repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\http\server\HttpServer.java | 1 |
请完成以下Java代码 | LocalDate getLocalDateFromClock() {
LocalDate localDate = LocalDate.now();
return localDate;
}
LocalDate getNextDay(LocalDate localDate) {
return localDate.plusDays(1);
}
LocalDate getPreviousDay(LocalDate localDate) {
return localDate.minus(1, ChronoUnit.DAYS);
}
DayOfWeek getDayOfWeek(LocalDate localDate) {
DayOfWeek day = localDate.getDayOfWeek();
return day;
}
LocalDate getFirstDayOfMonth() {
LocalDate firstDayOfMonth = LocalDate.now()
.with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
boolean isLeapYear(LocalDate localDate) {
return localDate.isLeapYear();
}
LocalDateTime getStartOfDay(LocalDate localDate) {
LocalDateTime startofDay = localDate.atStartOfDay();
return startofDay;
}
LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) {
LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT); | return startofDay;
}
LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) {
LocalDateTime startofDay = localDate.atTime(LocalTime.MIN);
return startofDay;
}
LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) {
LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT);
return startofDay;
}
LocalDateTime getEndOfDay(LocalDate localDate) {
LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX);
return endOfDay;
}
LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) {
LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate);
return endOfDate;
}
} | repos\tutorials-master\core-java-modules\core-java-8-datetime\src\main\java\com\baeldung\datetime\UseLocalDate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultTbDomainService extends AbstractTbEntityService implements TbDomainService {
private final DomainService domainService;
@Override
public Domain save(Domain domain, List<OAuth2ClientId> oAuth2Clients, User user) throws Exception {
ActionType actionType = domain.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = domain.getTenantId();
try {
Domain savedDomain = checkNotNull(domainService.saveDomain(tenantId, domain));
if (CollectionUtils.isNotEmpty(oAuth2Clients)) {
domainService.updateOauth2Clients(domain.getTenantId(), savedDomain.getId(), oAuth2Clients);
}
logEntityActionService.logEntityAction(tenantId, savedDomain.getId(), savedDomain, actionType, user, oAuth2Clients);
return savedDomain;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DOMAIN), domain, actionType, user, e, oAuth2Clients);
throw e;
}
}
@Override
public void updateOauth2Clients(Domain domain, List<OAuth2ClientId> oAuth2ClientIds, User user) {
ActionType actionType = ActionType.UPDATED;
TenantId tenantId = domain.getTenantId();
DomainId domainId = domain.getId(); | try {
domainService.updateOauth2Clients(tenantId, domainId, oAuth2ClientIds);
logEntityActionService.logEntityAction(tenantId, domainId, domain, actionType, user, oAuth2ClientIds);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, domainId, domain, actionType, user, e, oAuth2ClientIds);
throw e;
}
}
@Override
public void delete(Domain domain, User user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = domain.getTenantId();
DomainId domainId = domain.getId();
try {
domainService.deleteDomainById(tenantId, domainId);
logEntityActionService.logEntityAction(tenantId, domainId, domain, actionType, user);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, domainId, domain, actionType, user, e);
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\domain\DefaultTbDomainService.java | 2 |
请完成以下Java代码 | public final @Nullable String getLoginUrl() {
return this.loginUrl;
}
public final ServiceProperties getServiceProperties() {
return this.serviceProperties;
}
public final void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public final void setServiceProperties(ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
}
/**
* Sets whether to encode the service url with the session id or not.
* @param encodeServiceUrlWithSessionId whether to encode the service url with the
* session id or not.
*/
public final void setEncodeServiceUrlWithSessionId(boolean encodeServiceUrlWithSessionId) { | this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
}
/**
* Sets whether to encode the service url with the session id or not.
* @return whether to encode the service url with the session id or not.
*
*/
protected boolean getEncodeServiceUrlWithSessionId() {
return this.encodeServiceUrlWithSessionId;
}
/**
* Sets the {@link RedirectStrategy} to use
* @param redirectStrategy the {@link RedirectStrategy} to use
* @since 6.3
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasAuthenticationEntryPoint.java | 1 |
请完成以下Java代码 | public void setPP_Order_ID (int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_Value (COLUMNNAME_PP_Order_ID, null);
else
set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID));
}
/** Get Produktionsauftrag.
@return Produktionsauftrag */
@Override
public int getPP_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set PP_Order_ProductAttribute.
@param PP_Order_ProductAttribute_ID PP_Order_ProductAttribute */
@Override
public void setPP_Order_ProductAttribute_ID (int PP_Order_ProductAttribute_ID)
{
if (PP_Order_ProductAttribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ProductAttribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ProductAttribute_ID, Integer.valueOf(PP_Order_ProductAttribute_ID));
}
/** Get PP_Order_ProductAttribute.
@return PP_Order_ProductAttribute */
@Override
public int getPP_Order_ProductAttribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ProductAttribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel. | @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Zahlwert.
@param ValueNumber
Numeric Value
*/
@Override
public void setValueNumber (java.math.BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
/** Get Zahlwert.
@return Numeric Value
*/
@Override
public java.math.BigDecimal getValueNumber ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_ProductAttribute.java | 1 |
请完成以下Java代码 | public class RelationEdgeProcessor extends BaseRelationProcessor implements RelationProcessor {
@Override
public ListenableFuture<Void> processRelationMsgFromEdge(TenantId tenantId, Edge edge, RelationUpdateMsg relationUpdateMsg) {
log.trace("[{}] executing processRelationMsgFromEdge [{}] from edge [{}]", tenantId, relationUpdateMsg, edge.getId());
try {
edgeSynchronizationManager.getEdgeId().set(edge.getId());
return processRelationMsg(tenantId, relationUpdateMsg);
} finally {
edgeSynchronizationManager.getEdgeId().remove();
}
}
@Override
public ListenableFuture<Void> processEntityNotification(TenantId tenantId, TransportProtos.EdgeNotificationMsgProto edgeNotificationMsg) {
EntityRelation relation = JacksonUtil.fromString(edgeNotificationMsg.getBody(), EntityRelation.class);
if (relation == null) {
return Futures.immediateFuture(null);
}
EdgeId originatorEdgeId = safeGetEdgeId(edgeNotificationMsg.getOriginatorEdgeIdMSB(), edgeNotificationMsg.getOriginatorEdgeIdLSB());
Set<EdgeId> uniqueEdgeIds = new HashSet<>();
uniqueEdgeIds.addAll(edgeCtx.getEdgeService().findAllRelatedEdgeIds(tenantId, relation.getTo()));
uniqueEdgeIds.addAll(edgeCtx.getEdgeService().findAllRelatedEdgeIds(tenantId, relation.getFrom()));
uniqueEdgeIds.remove(originatorEdgeId);
if (uniqueEdgeIds.isEmpty()) {
return Futures.immediateFuture(null);
}
List<ListenableFuture<Void>> futures = new ArrayList<>();
for (EdgeId edgeId : uniqueEdgeIds) {
futures.add(saveEdgeEvent(tenantId,
edgeId,
EdgeEventType.RELATION,
EdgeEventActionType.valueOf(edgeNotificationMsg.getAction()),
null,
JacksonUtil.valueToTree(relation)));
}
return Futures.transform(Futures.allAsList(futures), voids -> null, dbCallbackExecutorService); | }
@Override
public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) {
EntityRelation entityRelation = JacksonUtil.convertValue(edgeEvent.getBody(), EntityRelation.class);
UpdateMsgType msgType = getUpdateMsgType(edgeEvent.getAction());
RelationUpdateMsg relationUpdateMsg = EdgeMsgConstructorUtils.constructRelationUpdatedMsg(msgType, entityRelation);
return DownlinkMsg.newBuilder()
.setDownlinkMsgId(EdgeUtils.nextPositiveInt())
.addRelationUpdateMsg(relationUpdateMsg)
.build();
}
@Override
public EdgeEventType getEdgeEventType() {
return EdgeEventType.RELATION;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\relation\RelationEdgeProcessor.java | 1 |
请完成以下Java代码 | public double getBestFitness() {
return bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode());
result = prime * result + ((random == null) ? 0 : random.hashCode());
result = prime * result + Arrays.hashCode(swarms);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Multiswarm other = (Multiswarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (fitnessFunction == null) {
if (other.fitnessFunction != null) | return false;
} else if (!fitnessFunction.equals(other.fitnessFunction))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
if (!Arrays.equals(swarms, other.swarms))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]";
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Multiswarm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static PrePostAdviceReactiveMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source,
MethodSecurityExpressionHandler handler) {
ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(handler);
ExpressionBasedPreInvocationAdvice preAdvice = new ExpressionBasedPreInvocationAdvice();
preAdvice.setExpressionHandler(handler);
return new PrePostAdviceReactiveMethodInterceptor(source, preAdvice, postAdvice);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Fallback
static DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler(
ReactiveMethodSecurityConfiguration configuration) {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
if (configuration.grantedAuthorityDefaults != null) {
handler.setDefaultRolePrefix(configuration.grantedAuthorityDefaults.getRolePrefix()); | }
return handler;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName())
.get("order");
}
@Autowired(required = false)
void setGrantedAuthorityDefaults(GrantedAuthorityDefaults grantedAuthorityDefaults) {
this.grantedAuthorityDefaults = grantedAuthorityDefaults;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\ReactiveMethodSecurityConfiguration.java | 2 |
请完成以下Java代码 | protected IScriptFactory createScriptFactory()
{
return new WorkspaceScriptFactory();
}
@Override
protected IScriptScanner createScriptScanner(final IScriptScannerFactory IGNORED)
{
final WorkspaceScriptScanner scanner = WorkspaceScriptScanner.builder()
.workspaceDir(config.getWorkspaceDir())
.supportedScriptTypes(scriptExecutorFactory.getSupportedScriptTypes())
.acceptLabels(config.getLabels())
.build();
return new GloballyOrderedScannerDecorator(scanner);
}
@Override
protected IScriptExecutorFactory createScriptExecutorFactory()
{
return scriptExecutorFactory;
}
@Override
protected void configureScriptExecutorFactory(final IScriptExecutorFactory scriptExecutorFactory)
{
scriptExecutorFactory.setDryRunMode(config.isDryRunMode());
}
@Override
protected IDatabase createDatabase()
{
return new SQLDatabase(config.getDbUrl(), config.getDbUsername(), config.getDbPassword());
} | @Override
protected ScriptsApplier createScriptApplier(final IDatabase database)
{
final ScriptsApplier scriptApplier = super.createScriptApplier(database);
scriptApplier.setSkipExecutingAfterScripts(config.isSkipExecutingAfterScripts());
return scriptApplier;
}
@Override
protected IScriptsApplierListener createScriptsApplierListener()
{
switch (config.getOnScriptFailure())
{
case FAIL:
return NullScriptsApplierListener.instance;
case ASK:
if (GraphicsEnvironment.isHeadless())
{
return ConsoleScriptsApplierListener.instance;
}
return new SwingUIScriptsApplierListener();
default:
throw new RuntimeException("Unexpected WorkspaceMigrateConfig.onScriptFailure=" + config.getOnScriptFailure());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\WorkspaceScriptsApplier.java | 1 |
请完成以下Java代码 | public class Pizza {
private static String cookedCount;
private boolean isThinCrust;
// Accessible globally
public static class PizzaSalesCounter {
private static String orderedCount;
public static String deliveredCount;
PizzaSalesCounter() {
System.out.println("Static field of enclosing class is "
+ Pizza.cookedCount);
System.out.println("Non-static field of enclosing class is "
+ new Pizza().isThinCrust); | }
}
Pizza() {
System.out.println("Non private static field of static class is "
+ PizzaSalesCounter.deliveredCount);
System.out.println("Private static field of static class is "
+ PizzaSalesCounter.orderedCount);
}
public static void main(String[] a) {
// Create instance of the static class without an instance of enclosing class
new PizzaSalesCounter();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\staticclass\Pizza.java | 1 |
请完成以下Java代码 | public class InvoiceSourceDAO implements IInvoiceSourceDAO
{
@Override
public Timestamp retrieveDueDate(final org.compiere.model.I_C_Invoice invoice)
{
final String trxName = InterfaceWrapperHelper.getTrxName(invoice);
return DB.getSQLValueTSEx(trxName, "SELECT paymentTermDueDate(?,?)", invoice.getC_PaymentTerm_ID(), invoice.getDateInvoiced());
}
@Override
public int retrieveDueDays(
@NonNull final PaymentTermId paymentTermId,
final Date dateInvoiced,
final Date date)
{
return DB.getSQLValueEx(ITrx.TRXNAME_None, "SELECT paymentTermDueDays(?,?,?)", paymentTermId.getRepoId(), dateInvoiced, date);
}
@Override
public Iterator<I_C_Dunning_Candidate_Invoice_v1> retrieveDunningCandidateInvoices(final IDunningContext context)
{
final Properties ctx = context.getCtx();
final String trxName = context.getTrxName();
final IQueryBL queryBL = Services.get(IQueryBL.class);
final I_C_DunningLevel dunningLevel = context.getC_DunningLevel();
Check.assumeNotNull(dunningLevel, "Context shall have DuningLevel set: {}", context);
Check.assumeNotNull(context.getDunningDate(), "Context shall have DunningDate set: {}", context);
final Date dunningDate = TimeUtil.getDay(context.getDunningDate()); | final ICompositeQueryFilter<I_C_Dunning_Candidate_Invoice_v1> dunningGraceFilter = queryBL
.createCompositeQueryFilter(I_C_Dunning_Candidate_Invoice_v1.class)
.setJoinOr()
.addEqualsFilter(I_C_Dunning_Candidate_Invoice_v1.COLUMN_DunningGrace, null)
.addCompareFilter(I_C_Dunning_Candidate_Invoice_v1.COLUMN_DunningGrace, Operator.LESS, dunningDate);
return queryBL.createQueryBuilder(I_C_Dunning.class, ctx, trxName)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient(ctx)
.addEqualsFilter(I_C_Dunning.COLUMNNAME_C_Dunning_ID, dunningLevel.getC_Dunning_ID()) // Dunning Level is for current assigned Dunning
.andCollectChildren(I_C_Dunning_Candidate_Invoice_v1.COLUMN_C_Dunning_ID)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient(ctx)
.filter(dunningGraceFilter) // Validate Dunning Grace (if any)
.orderBy()
.addColumn(I_C_Dunning_Candidate_Invoice_v1.COLUMN_C_Invoice_ID).endOrderBy()
.setOption(IQuery.OPTION_IteratorBufferSize, 1000 /* iterator shall load 1000 records at a time */)
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, false /* the result is not changing while the iterator is iterated */)
.create()
.iterate(I_C_Dunning_Candidate_Invoice_v1.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\api\impl\InvoiceSourceDAO.java | 1 |
请完成以下Java代码 | public void alphanumericRegex(Blackhole blackhole) {
final Matcher matcher = PATTERN.matcher(TEST_STRING);
boolean result = matcher.matches();
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericRegexDirectlyOnString(Blackhole blackhole) {
boolean result = TEST_STRING.matches(REGEX);
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIteration(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!isAlphanumeric(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCharacterChecks(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!Character.isAlphabetic(codePoint) || !Character.isDigit(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCopy(Blackhole blackhole) {
boolean result = true;
for (final char c : TEST_STRING.toCharArray()) { | if (!isAlphanumeric(c)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithStream(Blackhole blackhole) {
boolean result = TEST_STRING.chars().allMatch(this::isAlphanumeric);
blackhole.consume(result);
}
public boolean isAlphanumeric(final int codePoint) {
return (codePoint >= 65 && codePoint <= 90) ||
(codePoint >= 97 && codePoint <= 122) ||
(codePoint >= 48 && codePoint <= 57);
}
} | repos\tutorials-master\core-java-modules\core-java-regex\src\main\java\com\baeldung\alphanumeric\AlphanumericPerformanceBenchmark.java | 1 |
请完成以下Java代码 | public class MovieWithNullValue {
private String imdbId;
@JsonIgnore
private String director;
private List<ActorJackson> actors;
public MovieWithNullValue(String imdbID, String director, List<ActorJackson> actors) {
super();
this.imdbId = imdbID;
this.director = director;
this.actors = actors;
}
public String getImdbID() {
return imdbId;
} | public void setImdbID(String imdbID) {
this.imdbId = imdbID;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorJackson> getActors() {
return actors;
}
public void setActors(List<ActorJackson> actors) {
this.actors = actors;
}
} | repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\jacksonvsgson\MovieWithNullValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedSparePartsTaskIds(final @NonNull IProcessPreconditionsContext context)
{
final ImmutableSet<ServiceRepairProjectTaskId> taskIds = getSelectedTaskIds(context);
return projectService.retainIdsOfTypeSpareParts(taskIds);
}
protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds(final @NonNull IProcessPreconditionsContext context)
{
final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
if (projectId == null)
{
return ImmutableSet.of();
}
return context.getSelectedIncludedRecords() | .stream()
.filter(recordRef -> I_C_Project_Repair_Task.Table_Name.equals(recordRef.getTableName()))
.map(recordRef -> ServiceRepairProjectTaskId.ofRepoId(projectId, recordRef.getRecord_ID()))
.collect(ImmutableSet.toImmutableSet());
}
protected List<ServiceRepairProjectTask> getSelectedTasks(final @NonNull IProcessPreconditionsContext context)
{
return projectService.getTasksByIds(getSelectedTaskIds(context));
}
protected List<ServiceRepairProjectTask> getSelectedTasks()
{
return projectService.getTasksByIds(getSelectedTaskIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\ServiceOrRepairProjectBasedProcess.java | 2 |
请完成以下Java代码 | public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public String getPassword() {
return password;
}
@Override
public void setPassword(String password) {
this.password = password;
}
@Override | public boolean isPictureSet() {
return pictureByteArrayRef != null && pictureByteArrayRef.getId() != null;
}
@Override
public ByteArrayRef getPictureByteArrayRef() {
return pictureByteArrayRef;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityImpl.java | 1 |
请完成以下Java代码 | public void traversePreOrder(Node node) {
if (node != null) {
visit(node.value);
traversePreOrder(node.left);
traversePreOrder(node.right);
}
}
public void traversePostOrder(Node node) {
if (node != null) {
traversePostOrder(node.left);
traversePostOrder(node.right);
visit(node.value);
}
}
public void traverseLevelOrder() {
if (root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
System.out.print(" " + node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
nodes.add(node.right);
}
}
}
public void traverseInOrderWithoutRecursion() {
Stack<Node> stack = new Stack<>();
Node current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
Node top = stack.pop();
visit(top.value);
current = top.right;
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<>();
Node current = root;
stack.push(root);
while (current != null && !stack.isEmpty()) { | current = stack.pop();
visit(current.value);
if (current.right != null)
stack.push(current.right);
if (current.left != null)
stack.push(current.left);
}
}
public void traversePostOrderWithoutRecursion() {
Stack<Node> stack = new Stack<>();
Node prev = root;
Node current = root;
stack.push(root);
while (current != null && !stack.isEmpty()) {
current = stack.peek();
boolean hasChild = (current.left != null || current.right != null);
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
if (!hasChild || isPrevLastChild) {
current = stack.pop();
visit(current.value);
prev = current;
} else {
if (current.right != null) {
stack.push(current.right);
}
if (current.left != null) {
stack.push(current.left);
}
}
}
}
private void visit(int value) {
System.out.print(" " + value);
}
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
right = null;
left = null;
}
}
} | repos\tutorials-master\data-structures\src\main\java\com\baeldung\tree\BinaryTree.java | 1 |
请完成以下Java代码 | public String index() {
return "index";
}
@GetMapping(path = "/sba-settings.js", produces = "application/javascript")
public String sbaSettings() {
return "sba-settings.js";
}
@GetMapping(path = "/variables.css", produces = "text/css")
public String variablesCss() {
return "variables.css";
}
@GetMapping(path = "/login", produces = MediaType.TEXT_HTML_VALUE)
public String login() {
return "login";
}
@lombok.Data
@lombok.Builder
public static class Settings {
private final String title;
private final String brand;
private final String loginIcon;
private final String favicon;
private final String faviconDanger;
private final PollTimer pollTimer;
private final UiTheme theme;
private final boolean notificationFilterEnabled;
private final boolean rememberMeEnabled;
private final List<String> availableLanguages;
private final List<String> routes;
private final List<ExternalView> externalViews;
private final List<ViewSettings> viewSettings;
private final Boolean enableToasts;
private final Boolean hideInstanceUrl;
private final Boolean disableInstanceUrl;
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ExternalView {
/**
* Label to be shown in the navbar.
*/
private final String label;
/**
* Url for the external view to be linked
*/
private final String url;
/**
* Order in the navbar.
*/
private final Integer order;
/**
* Should the page shown as an iframe or open in a new window.
*/
private final boolean iframe; | /**
* A list of child views.
*/
private final List<ExternalView> children;
public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) {
Assert.hasText(label, "'label' must not be empty");
if (isEmpty(children)) {
Assert.hasText(url, "'url' must not be empty");
}
this.label = label;
this.url = url;
this.order = order;
this.iframe = iframe;
this.children = children;
}
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ViewSettings {
/**
* Name of the view to address.
*/
private final String name;
/**
* Set view enabled.
*/
private boolean enabled;
public ViewSettings(String name, boolean enabled) {
Assert.hasText(name, "'name' must not be empty");
this.name = name;
this.enabled = enabled;
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java | 1 |
请完成以下Java代码 | public void setCurrentSubProcess(SubProcess subProcess) {
currentSubprocessStack.push(subProcess);
}
public SubProcess getCurrentSubProcess() {
return currentSubprocessStack.peek();
}
public void removeCurrentSubProcess() {
currentSubprocessStack.pop();
}
public void setCurrentScope(ScopeImpl scope) {
currentScopeStack.push(scope);
}
public ScopeImpl getCurrentScope() { | return currentScopeStack.peek();
}
public void removeCurrentScope() {
currentScopeStack.pop();
}
public BpmnParse setSourceSystemId(String systemId) {
sourceSystemId = systemId;
return this;
}
public String getSourceSystemId() {
return this.sourceSystemId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java | 1 |
请完成以下Java代码 | public void setOldCostPrice (final BigDecimal OldCostPrice)
{
set_Value (COLUMNNAME_OldCostPrice, OldCostPrice);
}
@Override
public BigDecimal getOldCostPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OldCostPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RevaluationType AD_Reference_ID=541641
* Reference name: M_CostRevaluation_Detail_RevaluationType
*/
public static final int REVALUATIONTYPE_AD_Reference_ID=541641;
/** CurrentCostBeforeRevaluation = CCB */
public static final String REVALUATIONTYPE_CurrentCostBeforeRevaluation = "CCB";
/** CurrentCostAfterRevaluation = CCA */
public static final String REVALUATIONTYPE_CurrentCostAfterRevaluation = "CCA";
/** CostDetailAdjustment = CDA */
public static final String REVALUATIONTYPE_CostDetailAdjustment = "CDA";
@Override
public void setRevaluationType (final java.lang.String RevaluationType)
{
set_Value (COLUMNNAME_RevaluationType, RevaluationType); | }
@Override
public java.lang.String getRevaluationType()
{
return get_ValueAsString(COLUMNNAME_RevaluationType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluation_Detail.java | 1 |
请完成以下Java代码 | public String getRole() {
return role;
}
/**
* 设置 角色名称.
*
* @param role 角色名称.
*/
public void setRole(String role) {
this.role = role;
}
/**
* 获取 角色说明.
*
* @return 角色说明.
*/
public String getDescription() {
return description;
}
/**
* 设置 角色说明.
*
* @param description 角色说明.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
} | /**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Role.java | 1 |
请完成以下Java代码 | private void markAsSaved() {
this.alreadySaved = true;
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() { | return author;
}
public void setAuthor(String author) {
this.author = author;
}
public boolean isAlreadySaved() {
return alreadySaved;
}
public void setAlreadySaved(boolean alreadySaved) {
this.alreadySaved = alreadySaved;
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\returnedvalueofsave\entity\BaeldungArticle.java | 1 |
请完成以下Java代码 | public Object getBeanIfExists() {
return this.bean;
}
/**
* Sets the given callback used to destroy the managed bean.
*
* @param destructionCallback The destruction callback to use.
*/
public void setDestructionCallback(final Runnable destructionCallback) {
this.destructionCallback = destructionCallback;
}
/**
* Executes the destruction callback if set and clears the internal bean references.
*/ | public synchronized void destroy() {
Runnable callback = this.destructionCallback;
if (callback != null) {
callback.run();
}
this.bean = null;
this.destructionCallback = null;
}
@Override
public String toString() {
return "ScopedBeanReference [objectFactory=" + this.objectFactory + ", bean=" + this.bean + "]";
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\scope\GrpcRequestScope.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TodoController {
public TodoController(TodoService todoService) {
super();
this.todoService = todoService;
}
private final TodoService todoService;
@RequestMapping("list-todos")
public String listAllTodos(ModelMap model) {
String username = getLoggedInUsername(model);
List<Todo> todos = todoService.findByUsername(username);
model.addAttribute("todos", todos);
return "listTodos";
}
//GET, POST
@RequestMapping(value="add-todo", method = RequestMethod.GET)
public String showNewTodoPage(ModelMap model) {
String username = getLoggedInUsername(model);
Todo todo = new Todo(0, username, "", LocalDate.now().plusYears(1), false);
model.put("todo", todo);
return "todo";
}
@RequestMapping(value="add-todo", method = RequestMethod.POST)
public String addNewTodo(ModelMap model, @Valid Todo todo, BindingResult result) {
if(result.hasErrors()) {
return "todo";
}
String username = getLoggedInUsername(model);
todoService.addTodo(username, todo.getDescription(),
LocalDate.now().plusYears(1), false);
return "redirect:list-todos";
}
@RequestMapping("delete-todo")
public String deleteTodo(@RequestParam int id) {
//Delete todo
todoService.deleteById(id);
return "redirect:list-todos";
} | @RequestMapping(value="update-todo", method = RequestMethod.GET)
public String showUpdateTodoPage(@RequestParam int id, ModelMap model) {
Todo todo = todoService.findById(id);
model.addAttribute("todo", todo);
return "todo";
}
@RequestMapping(value="update-todo", method = RequestMethod.POST)
public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) {
if(result.hasErrors()) {
return "todo";
}
String username = getLoggedInUsername(model);
todo.setUsername(username);
todoService.updateTodo(todo);
return "redirect:list-todos";
}
private String getLoggedInUsername(ModelMap model) {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
}
} | repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\TodoController.java | 2 |
请完成以下Java代码 | public ObjectNode parseElement(FlowElement flowElement, ObjectNode flowElementNode, ObjectMapper mapper) {
ObjectNode resultNode = mapper.createObjectNode();
resultNode.put(ELEMENT_ID, flowElement.getId());
resultNode.put(ELEMENT_TYPE, flowElement.getClass().getSimpleName());
if (supports(flowElement)) {
resultNode.set(ELEMENT_PROPERTIES, createPropertiesNode(flowElement, flowElementNode, mapper));
}
return resultNode;
}
protected void putPropertyValue(String key, String value, ObjectNode propertiesNode) {
if (StringUtils.isNotBlank(value)) {
propertiesNode.put(key, value);
}
}
protected void putPropertyValue(String key, List<String> values, ObjectNode propertiesNode) {
// we don't set a node value if the collection is null.
// An empty collection is a indicator. if a task has candidate users you can only overrule it by putting an empty array as dynamic candidate users
if (values != null) {
ArrayNode arrayNode = propertiesNode.putArray(key); | for (String value : values) {
arrayNode.add(value);
}
}
}
protected void putPropertyValue(String key, JsonNode node, ObjectNode propertiesNode) {
if (node != null) {
if (!node.isMissingNode() && !node.isNull()) {
propertiesNode.set(key, node);
}
}
}
protected abstract ObjectNode createPropertiesNode(FlowElement flowElement, ObjectNode flowElementNode, ObjectMapper objectMapper);
@Override
public abstract boolean supports(FlowElement flowElement);
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\dynamic\BasePropertiesParser.java | 1 |
请完成以下Java代码 | private ObjectIdentity mapObjectIdentityRow(ResultSet rs) throws SQLException {
String javaType = rs.getString("class");
Serializable identifier = (Serializable) rs.getObject("obj_id");
identifier = this.aclClassIdUtils.identifierFrom(identifier, rs);
return this.objectIdentityGenerator.createObjectIdentity(identifier, javaType);
}
@Override
public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException {
Map<ObjectIdentity, Acl> map = readAclsById(Collections.singletonList(object), sids);
Assert.isTrue(map.containsKey(object),
() -> "There should have been an Acl entry for ObjectIdentity " + object);
return map.get(object);
}
@Override
public Acl readAclById(ObjectIdentity object) throws NotFoundException {
return readAclById(object, null);
}
@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException {
return readAclsById(objects, null);
}
@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids)
throws NotFoundException {
Map<ObjectIdentity, Acl> result = this.lookupStrategy.readAclsById(objects, sids);
// Check every requested object identity was found (throw NotFoundException if
// needed)
for (ObjectIdentity oid : objects) {
if (!result.containsKey(oid)) {
throw new NotFoundException("Unable to find ACL information for object identity '" + oid + "'");
}
}
return result;
}
/**
* Allows customization of the SQL query used to find child object identities.
* @param findChildrenSql
*/
public void setFindChildrenQuery(String findChildrenSql) {
this.findChildrenSql = findChildrenSql;
}
public void setAclClassIdSupported(boolean aclClassIdSupported) {
this.aclClassIdSupported = aclClassIdSupported;
if (aclClassIdSupported) {
// Change the default children select if it hasn't been overridden | if (this.findChildrenSql.equals(DEFAULT_SELECT_ACL_WITH_PARENT_SQL)) {
this.findChildrenSql = DEFAULT_SELECT_ACL_WITH_PARENT_SQL_WITH_CLASS_ID_TYPE;
}
else {
log.debug("Find children statement has already been overridden, so not overridding the default");
}
}
}
public void setConversionService(ConversionService conversionService) {
this.aclClassIdUtils = new AclClassIdUtils(conversionService);
}
public void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) {
Assert.notNull(objectIdentityGenerator, "objectIdentityGenerator cannot be null");
this.objectIdentityGenerator = objectIdentityGenerator;
}
protected boolean isAclClassIdSupported() {
return this.aclClassIdSupported;
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcAclService.java | 1 |
请完成以下Java代码 | public ClusterFlowConfig getClusterConfig() {
return clusterConfig;
}
public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) {
this.clusterConfig = clusterConfig;
return this;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public FlowRule toRule() { | FlowRule flowRule = new FlowRule();
flowRule.setCount(this.count);
flowRule.setGrade(this.grade);
flowRule.setResource(this.resource);
flowRule.setLimitApp(this.limitApp);
flowRule.setRefResource(this.refResource);
flowRule.setStrategy(this.strategy);
if (this.controlBehavior != null) {
flowRule.setControlBehavior(controlBehavior);
}
if (this.warmUpPeriodSec != null) {
flowRule.setWarmUpPeriodSec(warmUpPeriodSec);
}
if (this.maxQueueingTimeMs != null) {
flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs);
}
flowRule.setClusterMode(clusterMode);
flowRule.setClusterConfig(clusterConfig);
return flowRule;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CompositeSaveHandlers
{
@NonNull private final ImmutableMap<String, SaveHandler> byTableName;
@NonNull private final DefaultSaveHandler defaultHandler;
CompositeSaveHandlers(@NonNull final Optional<List<SaveHandler>> optionalHandlers)
{
this.defaultHandler = new DefaultSaveHandler();
this.byTableName = indexByTableName(optionalHandlers);
}
@NotNull
private static ImmutableMap<String, SaveHandler> indexByTableName(@NotNull final Optional<List<SaveHandler>> optionalHandlers)
{
final ImmutableMap.Builder<String, SaveHandler> builder = ImmutableMap.builder();
optionalHandlers.ifPresent(handlers -> {
for (SaveHandler handler : handlers)
{
final Set<String> handledTableNames = handler.getHandledTableName();
if (handledTableNames.isEmpty())
{
throw new AdempiereException("SaveHandler " + handler + " has no handled table names");
}
handledTableNames.forEach(handledTableName -> builder.put(handledTableName, handler));
} | });
return builder.build();
}
private SaveHandler getHandler(@NonNull final String tableName) {return byTableName.getOrDefault(tableName, defaultHandler);}
public boolean isReadonly(@NonNull final GridTabVO gridTabVO)
{
final String tableName = gridTabVO.getTableName();
return getHandler(tableName).isReadonly(gridTabVO);
}
public SaveHandler.SaveResult save(@NonNull final Document document)
{
final String tableName = document.getEntityDescriptor().getTableName();
return getHandler(tableName).save(document);
}
public void delete(final Document document)
{
final String tableName = document.getEntityDescriptor().getTableName();
getHandler(tableName).delete(document);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\save\CompositeSaveHandlers.java | 2 |
请完成以下Java代码 | private static Instant convertClientSecretExpiresAt(Object clientSecretExpiresAt) {
if (clientSecretExpiresAt != null && String.valueOf(clientSecretExpiresAt).equals("0")) {
// 0 indicates that client_secret_expires_at does not expire
return null;
}
return (Instant) INSTANT_CONVERTER.convert(clientSecretExpiresAt);
}
private static List<String> convertScope(Object scope) {
if (scope == null) {
return Collections.emptyList();
}
return Arrays.asList(StringUtils.delimitedListToStringArray(scope.toString(), " "));
}
}
private static final class OAuth2ClientRegistrationMapConverter
implements Converter<OAuth2ClientRegistration, Map<String, Object>> {
@Override
public Map<String, Object> convert(OAuth2ClientRegistration source) {
Map<String, Object> responseClaims = new LinkedHashMap<>(source.getClaims()); | if (source.getClientIdIssuedAt() != null) {
responseClaims.put(OAuth2ClientMetadataClaimNames.CLIENT_ID_ISSUED_AT,
source.getClientIdIssuedAt().getEpochSecond());
}
if (source.getClientSecret() != null) {
long clientSecretExpiresAt = 0;
if (source.getClientSecretExpiresAt() != null) {
clientSecretExpiresAt = source.getClientSecretExpiresAt().getEpochSecond();
}
responseClaims.put(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT, clientSecretExpiresAt);
}
if (!CollectionUtils.isEmpty(source.getScopes())) {
responseClaims.put(OAuth2ClientMetadataClaimNames.SCOPE,
StringUtils.collectionToDelimitedString(source.getScopes(), " "));
}
return responseClaims;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\http\converter\OAuth2ClientRegistrationHttpMessageConverter.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
final FavoriteItem item = component2item.get(e.getSource());
if(item == null)
{
return;
}
container.fireItemClicked(item);
}
};
public FavoritesGroup(final FavoritesGroupContainer container, final MTreeNode ndTop)
{
super();
Check.assumeNotNull(container, "container not null");
this.container = container;
Check.assumeNotNull(ndTop, "ndTop not null");
topNodeId = ndTop.getNode_ID();
// barPart.setAnimated(true); // use Theme setting
panel.setLayout(new BorderLayout());
panel.setTitle(ndTop.getName().trim());
toolbar = new JToolBar(SwingConstants.VERTICAL);
toolbar.setOpaque(false);
toolbar.setFloatable(false);
toolbar.setRollover(true);
toolbar.setBorder(BorderFactory.createEmptyBorder());
panel.add(toolbar, BorderLayout.NORTH);
}
public JXTaskPane getComponent()
{
return panel;
}
public int getTopNodeId()
{
return topNodeId;
}
public void removeAllItems() | {
toolbar.removeAll();
}
public void addFavorite(final MTreeNode node)
{
if (node2item.get(node) != null)
{
// already added
return;
}
final FavoriteItem item = new FavoriteItem(this, node);
item.addMouseListener(itemMouseListener);
item.addActionListener(itemActionListener);
final JComponent itemComp = item.getComponent();
node2item.put(node, item);
component2item.put(itemComp, item);
node.setOnBar(true);
toolbar.add(itemComp);
}
public boolean isEmpty()
{
return node2item.isEmpty();
}
public void removeItem(final FavoriteItem item)
{
Check.assumeNotNull(item, "item not null");
final MTreeNode node = item.getNode();
final JComponent itemComp = item.getComponent();
node2item.remove(node);
component2item.remove(itemComp);
node.setOnBar(false);
toolbar.remove(itemComp);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\FavoritesGroup.java | 1 |
请完成以下Java代码 | default boolean isAnyComponentIssueOrCoProduct(final I_PP_Cost_Collector cc)
{
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
final PPOrderBOMLineId orderBOMLineId = PPOrderBOMLineId.ofRepoIdOrNull(cc.getPP_Order_BOMLine_ID());
return costCollectorType.isAnyComponentIssueOrCoProduct(orderBOMLineId);
}
/**
* Create and process material issue cost collector. The given qtys are converted to the UOM of the given <code>orderBOMLine</code>. The Cost collector's type is determined from the given
* <code>orderBOMLine</code> alone.
* <p>
* Note that this method is also used internally to handle the case of a "co-product receipt".
*
* @return processed cost collector
*/
I_PP_Cost_Collector createIssue(ComponentIssueCreateRequest request);
/**
* Create Receipt (finished good or co/by-products). If the given <code>candidate</code>'s {@link PP_Order_BOMLine} is not <code>!= null</code>, then a finished product receipt is created.
* Otherwise a co-product receipt is created. Note that under the hood a co-product receipt is a "negative issue".
*
* @param candidate the candidate to create the receipt from.
*
* @return processed cost collector
*/
I_PP_Cost_Collector createReceipt(ReceiptCostCollectorCandidate candidate);
void createActivityControl(ActivityControlCreateRequest request);
void createMaterialUsageVariance(I_PP_Order ppOrder, I_PP_Order_BOMLine line);
void createResourceUsageVariance(I_PP_Order ppOrder, PPOrderRoutingActivity activity); | /**
* Checks if given cost collector is a reversal.
*
* We consider given cost collector as a reversal if it's ID is bigger then the Reversal_ID.
*
* @param cc cost collector
* @return true if given cost collector is actually a reversal.
*/
boolean isReversal(I_PP_Cost_Collector cc);
boolean isFloorStock(I_PP_Cost_Collector cc);
void updateCostCollectorFromOrder(I_PP_Cost_Collector cc, I_PP_Order order);
List<I_PP_Cost_Collector> getByOrderId(PPOrderId ppOrderId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\IPPCostCollectorBL.java | 1 |
请完成以下Java代码 | public Set<CtxName> getParameters()
{
return parametersAsCtxName;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
try
{
return StringExpressionsHelper.evaluateParam(parameter, ctx, onVariableNotFound);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
@Override
public IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException | {
try
{
final String value = StringExpressionsHelper.evaluateParam(parameter, ctx, OnVariableNotFound.ReturnNoResult);
if (value == null || value == EMPTY_RESULT)
{
return this;
}
return ConstantStringExpression.of(value);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SingleParameterStringExpression.java | 1 |
请完成以下Java代码 | public class ZxingBarcodeGenerator {
public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception {
UPCAWriter barcodeWriter = new UPCAWriter();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.UPC_A, 300, 150);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception {
EAN13Writer barcodeWriter = new EAN13Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.EAN_13, 300, 150);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception {
Code128Writer barcodeWriter = new Code128Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, 300, 150);
return MatrixToImageWriter.toBufferedImage(bitMatrix); | }
public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception {
PDF417Writer barcodeWriter = new PDF417Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.PDF_417, 700, 700);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\barcodes\generators\ZxingBarcodeGenerator.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
@Override
public void setType(String type) {
this.type = type;
}
@Override
public String getImplementation() {
return implementation;
}
@Override
public void setImplementation(String implementation) {
this.implementation = implementation;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} | @Override
public String getResourceName() {
return resourceName;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String toString() {
return "ChannelDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ChannelDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public class SecurityUser implements UserDetails {
private String userName;
private String password;
private List<GrantedAuthority> grantedAuthorityList;
private boolean accessToRestrictedPolicy;
public static SecurityUser builder() {
return new SecurityUser();
}
public SecurityUser withAccessToRestrictedPolicy(boolean restrictedPolicy) {
this.accessToRestrictedPolicy = restrictedPolicy;
return this;
}
public boolean hasAccessToRestrictedPolicy() {
return accessToRestrictedPolicy;
}
public SecurityUser withGrantedAuthorityList(List<GrantedAuthority> grantedAuthorityList) {
this.grantedAuthorityList = grantedAuthorityList;
return this;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.grantedAuthorityList;
}
public SecurityUser withPassword(String password) {
this.password = password;
return this;
}
@Override
public String getPassword() {
return this.password;
} | public SecurityUser withUserName(String userName) {
this.userName = userName;
return this;
}
@Override
public String getUsername() {
return this.userName;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-4\src\main\java\com\baeldung\enablemethodsecurity\user\SecurityUser.java | 1 |
请完成以下Java代码 | default String getWebsite() {
return this.getClaimAsString(StandardClaimNames.WEBSITE);
}
/**
* Returns the user's preferred e-mail address {@code (email)}.
* @return the user's preferred e-mail address
*/
default String getEmail() {
return this.getClaimAsString(StandardClaimNames.EMAIL);
}
/**
* Returns {@code true} if the user's e-mail address has been verified
* {@code (email_verified)}, otherwise {@code false}.
* @return {@code true} if the user's e-mail address has been verified, otherwise
* {@code false}
*/
default Boolean getEmailVerified() {
return this.getClaimAsBoolean(StandardClaimNames.EMAIL_VERIFIED);
}
/**
* Returns the user's gender {@code (gender)}.
* @return the user's gender
*/
default String getGender() {
return this.getClaimAsString(StandardClaimNames.GENDER);
}
/**
* Returns the user's birth date {@code (birthdate)}.
* @return the user's birth date
*/
default String getBirthdate() {
return this.getClaimAsString(StandardClaimNames.BIRTHDATE);
}
/**
* Returns the user's time zone {@code (zoneinfo)}.
* @return the user's time zone
*/
default String getZoneInfo() {
return this.getClaimAsString(StandardClaimNames.ZONEINFO);
}
/**
* Returns the user's locale {@code (locale)}.
* @return the user's locale
*/
default String getLocale() {
return this.getClaimAsString(StandardClaimNames.LOCALE);
}
/**
* Returns the user's preferred phone number {@code (phone_number)}.
* @return the user's preferred phone number
*/
default String getPhoneNumber() {
return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER);
}
/** | * Returns {@code true} if the user's phone number has been verified
* {@code (phone_number_verified)}, otherwise {@code false}.
* @return {@code true} if the user's phone number has been verified, otherwise
* {@code false}
*/
default Boolean getPhoneNumberVerified() {
return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED);
}
/**
* Returns the user's preferred postal address {@code (address)}.
* @return the user's preferred postal address
*/
default AddressStandardClaim getAddress() {
Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS);
return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build()
: new DefaultAddressStandardClaim.Builder().build());
}
/**
* Returns the time the user's information was last updated {@code (updated_at)}.
* @return the time the user's information was last updated
*/
default Instant getUpdatedAt() {
return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT);
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Object mkParamValueObj(final String valueStr, final int displayType)
{
final Object result;
if (displayType == DisplayType.String)
{
result = valueStr;
}
else if (displayType == DisplayType.Integer)
{
result = Integer.parseInt(valueStr);
}
else if (displayType == DisplayType.Number)
{
result = new BigDecimal(valueStr);
}
else if (displayType == DisplayType.YesNo)
{
result = "Y".equals(valueStr);
}
else
{
throw new IllegalArgumentException("Illegal displayType " + displayType);
}
return result;
}
private String mkParamValueStr(final Object valueObj, final int displayType)
{
final String result;
if (displayType == DisplayType.String)
{
result = (String)valueObj;
} | else if (displayType == DisplayType.Integer)
{
result = Integer.toString((Integer)valueObj);
}
else if (displayType == DisplayType.Number)
{
result = ((BigDecimal)valueObj).toString();
}
else if (displayType == DisplayType.YesNo)
{
result = ((Boolean)valueObj) ? "Y" : "N";
}
else
{
throw new IllegalArgumentException("Illegal displayType " + displayType);
}
return result;
}
@Override
public void deleteParameters(final Object parent, final String parameterTable)
{
for (final IParameterPO paramPO : Services.get(IParametersDAO.class).retrieveParamPOs(parent, parameterTable))
{
InterfaceWrapperHelper.delete(paramPO);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\ParameterBL.java | 2 |
请完成以下Java代码 | public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = eventId;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) { | this.eventType = eventType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
} | repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\model\MonitoringEvent.java | 1 |
请完成以下Java代码 | public class JsonConverterV1
{
public static final GlobalQRCodeVersion GLOBAL_QRCODE_VERSION = GlobalQRCodeVersion.ofInt(1);
public static GlobalQRCode toGlobalQRCode(@NonNull final LocatorQRCode qrCode)
{
return GlobalQRCode.of(LocatorQRCodeJsonConverter.GLOBAL_QRCODE_TYPE, GLOBAL_QRCODE_VERSION, toJson(qrCode));
}
private static JsonLocatorQRCodePayloadV1 toJson(@NonNull final LocatorQRCode qrCode)
{
return JsonLocatorQRCodePayloadV1.builder()
.warehouseId(qrCode.getLocatorId().getWarehouseId().getRepoId())
.locatorId(qrCode.getLocatorId().getRepoId())
.caption(qrCode.getCaption())
.build();
} | public static LocatorQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
Check.assumeEquals(globalQRCode.getVersion(), GLOBAL_QRCODE_VERSION, "QR Code version");
final JsonLocatorQRCodePayloadV1 payload = globalQRCode.getPayloadAs(JsonLocatorQRCodePayloadV1.class);
return fromJson(payload);
}
private static LocatorQRCode fromJson(@NonNull final JsonLocatorQRCodePayloadV1 json)
{
return LocatorQRCode.builder()
.locatorId(LocatorId.ofRepoId(json.getWarehouseId(), json.getLocatorId()))
.caption(json.getCaption())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\v1\JsonConverterV1.java | 1 |
请完成以下Java代码 | public static PPOrderLineType cast(final IViewRowType type)
{
return (PPOrderLineType)type;
}
public boolean canReceive()
{
return canReceive;
}
public boolean canIssue()
{
return canIssue;
}
public boolean isBOMLine()
{
return this == BOMLine_Component
|| this == BOMLine_Component_Service
|| this == BOMLine_ByCoProduct;
}
public boolean isMainProduct()
{
return this == MainProduct; | }
public boolean isHUOrHUStorage()
{
return this == HU_LU
|| this == HU_TU
|| this == HU_VHU
|| this == HU_Storage;
}
public static PPOrderLineType ofHUEditorRowType(final HUEditorRowType huType)
{
final PPOrderLineType type = huType2type.get(huType);
if (type == null)
{
throw new IllegalArgumentException("No type found for " + huType);
}
return type;
}
private static final ImmutableMap<HUEditorRowType, PPOrderLineType> huType2type = Stream.of(values())
.filter(type -> type.huType != null)
.collect(GuavaCollectors.toImmutableMapByKey(type -> type.huType));
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineType.java | 1 |
请完成以下Java代码 | public class ProcessUtils {
public static String getClassPath() {
String cp = System.getProperty("java.class.path");
// System.out.println("ClassPath is " + cp);
return cp;
}
public static File getJavaCmd() throws IOException {
String javaHome = System.getProperty("java.home");
File javaCmd;
if (System.getProperty("os.name").startsWith("Win")) {
javaCmd = new File(javaHome, "bin/java.exe");
} else {
javaCmd = new File(javaHome, "bin/java");
}
if (javaCmd.canExecute()) {
return javaCmd; | } else {
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
}
}
public static String getMainClass() {
return System.getProperty("sun.java.command");
}
public static String getSystemProperties() {
StringBuilder sb = new StringBuilder();
System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2));
return sb.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\java9\process\ProcessUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long setSize(String key) {
return setOperations.size(key);
}
public long setRemove(String key, Object... values) {
return setOperations.remove(key, values);
}
//===============================list=================================
public List<Object> lGet(String key, long start, long end) {
return listOperations.range(key, start, end);
}
public long listSize(String key) {
return listOperations.size(key);
}
public Object listIndex(String key, long index) {
return listOperations.index(key, index);
}
public void listRightPush(String key, Object value) {
listOperations.rightPush(key, value);
}
public boolean listRightPush(String key, Object value, long milliseconds) {
listOperations.rightPush(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
} | public long listRightPushAll(String key, List<Object> value) {
return listOperations.rightPushAll(key, value);
}
public boolean listRightPushAll(String key, List<Object> value, long milliseconds) {
listOperations.rightPushAll(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public void listSet(String key, long index, Object value) {
listOperations.set(key, index, value);
}
public long listRemove(String key, long count, Object value) {
return listOperations.remove(key, count, value);
}
//===============================zset=================================
public boolean zsAdd(String key, Object value, double score) {
return zSetOperations.add(key, value, score);
}
} | repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java | 2 |
请完成以下Java代码 | public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionParentDeploymentId() {
return processDefinitionParentDeploymentId;
}
public String getMessageName() {
return messageName;
}
public String getStartEventId() {
return startEventId;
}
public String getProcessInstanceName() {
return processInstanceName;
}
public String getBusinessKey() {
return businessKey;
}
public String getBusinessStatus() {
return businessStatus;
}
public String getCallbackId() {
return callbackId;
}
public String getCallbackType() {
return callbackType;
}
public String getReferenceId() {
return referenceId;
}
public String getReferenceType() {
return referenceType;
}
public String getStageInstanceId() {
return stageInstanceId;
}
public String getTenantId() {
return tenantId;
}
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
public String getPredefinedProcessInstanceId() {
return predefinedProcessInstanceId;
} | public String getOwnerId() {
return ownerId;
}
public String getAssigneeId() {
return assigneeId;
}
public Map<String, Object> getVariables() {
return variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
public Map<String, Object> getStartFormVariables() {
return startFormVariables;
}
public String getOutcome() {
return outcome;
}
public Map<String, Object> getExtraFormVariables() {
return extraFormVariables;
}
public FormInfo getExtraFormInfo() {
return extraFormInfo;
}
public String getExtraFormOutcome() {
return extraFormOutcome;
}
public boolean isFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | public NamePair get (final IValidationContext evalCtx, Object value)
{
if (value == null)
return null;
MLocation loc = getLocation (value, null);
if (loc == null)
return null;
return new KeyNamePair (loc.getC_Location_ID(), loc.toString());
} // get
/**
* The Lookup contains the key
* @param key Location_ID
* @return true if key known
*/
@Override
public boolean containsKey (final IValidationContext evalCtx, final Object key)
{
return getLocation(key, ITrx.TRXNAME_None) != null;
} // containsKey
/**************************************************************************
* Get Location
* @param key ID as string or integer
* @param trxName transaction
* @return Location
*/
public MLocation getLocation (Object key, String trxName)
{
if (key == null)
return null;
int C_Location_ID = 0;
if (key instanceof Integer)
C_Location_ID = ((Integer)key).intValue();
else if (key != null)
C_Location_ID = Integer.parseInt(key.toString());
//
return getLocation(C_Location_ID, trxName);
} // getLocation
/**
* Get Location
* @param C_Location_ID id
* @param trxName transaction
* @return Location
*/
public MLocation getLocation (int C_Location_ID, String trxName)
{
return MLocation.get(m_ctx, C_Location_ID, trxName);
} // getC_Location_ID
@Override | public String getTableName()
{
return I_C_Location.Table_Name;
}
@Override
public String getColumnName()
{
return I_C_Location.Table_Name + "." + I_C_Location.COLUMNNAME_C_Location_ID;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return I_C_Location.COLUMNNAME_C_Location_ID;
}
/**
* Return data as sorted Array - not implemented
* @param mandatory mandatory
* @param onlyValidated only validated
* @param onlyActive only active
* @param temporary force load for temporary display
* @return null
*/
@Override
public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary)
{
log.error("not implemented");
return null;
} // getArray
} // MLocation | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocationLookup.java | 1 |
请完成以下Java代码 | public int getM_ProductMember_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductMember_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicType.java | 1 |
请完成以下Java代码 | public String getSourceState() {
return sourceState;
}
public void setSourceState(String sourceState) {
this.sourceState = sourceState;
}
public String getTargetState() {
return targetState;
}
public void setTargetState(String targetState) {
this.targetState = targetState;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public String getOnTransaction() {
return onTransaction;
}
public void setOnTransaction(String onTransaction) {
this.onTransaction = onTransaction;
}
/**
* Return the script info, if present.
* <p>
* ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when
* implementationType is 'script'.
* </p>
*/
public ScriptInfo getScriptInfo() {
return scriptInfo;
}
/**
* Sets the script info
*
* @see #getScriptInfo()
*/
public void setScriptInfo(ScriptInfo scriptInfo) { | this.scriptInfo = scriptInfo;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
@Override
public FlowableListener clone() {
FlowableListener clone = new FlowableListener();
clone.setValues(this);
return clone;
}
public void setValues(FlowableListener otherListener) {
super.setValues(otherListener);
setEvent(otherListener.getEvent());
setSourceState(otherListener.getSourceState());
setTargetState(otherListener.getTargetState());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
setOnTransaction(otherListener.getOnTransaction());
Optional.ofNullable(otherListener.getScriptInfo()).map(ScriptInfo::clone).ifPresent(this::setScriptInfo);
fieldExtensions = new ArrayList<>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\FlowableListener.java | 1 |
请完成以下Java代码 | public void requestHeadersStart(Call call) {
logTimedEvent("requestHeadersStart");
}
@Override
public void requestHeadersEnd(Call call, Request request) {
logTimedEvent("requestHeadersEnd");
}
@Override
public void requestBodyStart(Call call) {
logTimedEvent("requestBodyStart");
}
@Override
public void requestBodyEnd(Call call, long byteCount) {
logTimedEvent("requestBodyEnd");
}
@Override
public void requestFailed(Call call, IOException ioe) {
logTimedEvent("requestFailed");
}
@Override
public void responseHeadersStart(Call call) {
logTimedEvent("responseHeadersStart");
}
@Override
public void responseHeadersEnd(Call call, Response response) {
logTimedEvent("responseHeadersEnd");
}
@Override
public void responseBodyStart(Call call) {
logTimedEvent("responseBodyStart");
}
@Override
public void responseBodyEnd(Call call, long byteCount) { | logTimedEvent("responseBodyEnd");
}
@Override
public void responseFailed(Call call, IOException ioe) {
logTimedEvent("responseFailed");
}
@Override
public void callEnd(Call call) {
logTimedEvent("callEnd");
}
@Override
public void callFailed(Call call, IOException ioe) {
logTimedEvent("callFailed");
}
@Override
public void canceled(Call call) {
logTimedEvent("canceled");
}
} | repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\okhttp\events\EventTimer.java | 1 |
请完成以下Java代码 | public static Date getThisWeekStartDay() {
Date today = new Date();
return DateUtil.beginOfWeek(today);
}
/**
* 获得本周最后一天 周日 23:59:59
*/
public static Date getThisWeekEndDay() {
Date today = new Date();
return DateUtil.endOfWeek(today);
}
/**
* 获得下周第一天 周一 00:00:00
*/
public static Date getNextWeekStartDay() {
return DateUtil.beginOfWeek(DateUtil.nextWeek());
}
/**
* 获得下周最后一天 周日 23:59:59
*/
public static Date getNextWeekEndDay() {
return DateUtil.endOfWeek(DateUtil.nextWeek());
}
/**
* 过去七天开始时间(不含今天)
*
* @return
*/
public static Date getLast7DaysStartTime() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, -7);
return DateUtil.beginOfDay(calendar.getTime());
}
/**
* 过去七天结束时间(不含今天)
*
* @return
*/
public static Date getLast7DaysEndTime() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getLast7DaysStartTime());
calendar.add(Calendar.DATE, 6);
return DateUtil.endOfDay(calendar.getTime());
}
/**
* 昨天开始时间
*
* @return
*/
public static Date getYesterdayStartTime() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, -1);
return DateUtil.beginOfDay(calendar.getTime());
} | /**
* 昨天结束时间
*
* @return
*/
public static Date getYesterdayEndTime() {
return DateUtil.endOfDay(getYesterdayStartTime());
}
/**
* 明天开始时间
*
* @return
*/
public static Date getTomorrowStartTime() {
return DateUtil.beginOfDay(DateUtil.tomorrow());
}
/**
* 明天结束时间
*
* @return
*/
public static Date getTomorrowEndTime() {
return DateUtil.endOfDay(DateUtil.tomorrow());
}
/**
* 今天开始时间
*
* @return
*/
public static Date getTodayStartTime() {
return DateUtil.beginOfDay(new Date());
}
/**
* 今天结束时间
*
* @return
*/
public static Date getTodayEndTime() {
return DateUtil.endOfDay(new Date());
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateRangeUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private class MsgPackCallback implements TbQueueCallback {
private final AtomicInteger msgCount;
private final TransportServiceCallback<Void> callback;
public MsgPackCallback(Integer msgCount, TransportServiceCallback<Void> callback) {
this.msgCount = new AtomicInteger(msgCount);
this.callback = callback;
}
@Override
public void onSuccess(TbQueueMsgMetadata metadata) {
if (msgCount.decrementAndGet() <= 0) {
DefaultTransportService.this.transportCallbackExecutor.submit(() -> callback.onSuccess(null));
}
}
@Override
public void onFailure(Throwable t) {
DefaultTransportService.this.transportCallbackExecutor.submit(() -> callback.onError(t));
}
}
private class ApiStatsProxyCallback<T> implements TransportServiceCallback<T> {
private final TenantId tenantId;
private final CustomerId customerId;
private final int dataPoints;
private final TransportServiceCallback<T> callback;
public ApiStatsProxyCallback(TenantId tenantId, CustomerId customerId, int dataPoints, TransportServiceCallback<T> callback) {
this.tenantId = tenantId;
this.customerId = customerId;
this.dataPoints = dataPoints;
this.callback = callback;
}
@Override
public void onSuccess(T msg) {
try {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_MSG_COUNT, 1);
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_DP_COUNT, dataPoints); | } finally {
callback.onSuccess(msg);
}
}
@Override
public void onError(Throwable e) {
callback.onError(e);
}
}
@Override
public ExecutorService getCallbackExecutor() {
return transportCallbackExecutor;
}
@Override
public boolean hasSession(TransportProtos.SessionInfoProto sessionInfo) {
return sessions.containsKey(toSessionId(sessionInfo));
}
@Override
public void createGaugeStats(String statsName, AtomicInteger number) {
statsFactory.createGauge(StatsType.TRANSPORT + "." + statsName, number);
statsMap.put(statsName, number);
}
@Scheduled(fixedDelayString = "${transport.stats.print-interval-ms:60000}")
public void printStats() {
if (statsEnabled && !statsMap.isEmpty()) {
String values = statsMap.entrySet().stream()
.map(kv -> kv.getKey() + " [" + kv.getValue() + "]").collect(Collectors.joining(", "));
log.info("Transport Stats: {}", values);
}
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportService.java | 2 |
请完成以下Java代码 | public static void printLogNodes(List<ObjectNode> logNodes, String logLevel) {
if (logNodes == null) {
return;
}
StringBuilder logBuilder = new StringBuilder("\n");
for (ObjectNode logNode : logNodes) {
logBuilder.append(logNode.get(LoggingSessionUtil.TIMESTAMP).asString()).append(": ");
String scopeType = null;
if (logNode.has("scopeType")) {
scopeType = logNode.get("scopeType").asString();
if (ScopeTypes.BPMN.equals(scopeType)) {
logBuilder.append("(").append(logNode.get("scopeId").asString());
if (logNode.has("subScopeId")) {
logBuilder.append(",").append(logNode.get("subScopeId").asString());
}
logBuilder.append(") ");
}
}
logBuilder.append(logNode.get("message").asString());
if (ScopeTypes.BPMN.equals(scopeType)) {
logBuilder.append(" (processInstanceId: '").append(logNode.get("scopeId").asString());
if (logNode.has("subScopeId")) {
logBuilder.append("', executionId: '").append(logNode.get("subScopeId").asString());
}
logBuilder.append("', processDefinitionId: '").append(logNode.get("scopeDefinitionId").asString()).append("'");
}
if (logNode.has("elementId")) {
logBuilder.append(", elementId: '").append(logNode.get("elementId").asString());
if (logNode.has("elementName")) {
logBuilder.append("', elementName: '").append(logNode.get("elementName").asString());
} | logBuilder.append("', elementType: '").append(logNode.get("elementType").asString()).append("'");
}
logBuilder.append(")\n");
}
log(logBuilder.toString(), logLevel);
}
protected static void log(String message, String logLevel) {
if ("info".equalsIgnoreCase(logLevel)) {
LOGGER.info(message);
} else if ("error".equalsIgnoreCase(logLevel)) {
LOGGER.error(message);
} else if ("warn".equalsIgnoreCase(logLevel)) {
LOGGER.warn(message);
} else if ("debug".equalsIgnoreCase(logLevel)) {
LOGGER.debug(message);
} else if ("trace".equalsIgnoreCase(logLevel)) {
LOGGER.trace(message);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSessionLoggerOutput.java | 1 |
请完成以下Java代码 | private static boolean declaresToBuilder(Authentication authentication) {
for (Method method : authentication.getClass().getDeclaredMethods()) {
if (method.getName().equals("toBuilder") && method.getParameterTypes().length == 0) {
return true;
}
}
return false;
}
@Override
protected String getAlreadyFilteredAttributeName() {
String name = getFilterName();
if (name == null) {
name = getClass().getName().concat("-" + System.identityHashCode(this));
}
return name + ALREADY_FILTERED_SUFFIX;
}
private void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
this.securityContextHolderStrategy.clearContext();
this.failureHandler.onAuthenticationFailure(request, response, failed);
} | private void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authentication) throws IOException, ServletException {
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
this.securityContextRepository.saveContext(context, request, response);
this.successHandler.onAuthenticationSuccess(request, response, chain, authentication);
}
private @Nullable Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, ServletException {
Authentication authentication = this.authenticationConverter.convert(request);
if (authentication == null) {
return null;
}
AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request);
Authentication authenticationResult = authenticationManager.authenticate(authentication);
if (authenticationResult == null) {
throw new ServletException("AuthenticationManager should not return null Authentication object.");
}
return authenticationResult;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AuthenticationFilter.java | 1 |
请完成以下Java代码 | public class ProprietaryReference1 {
@XmlElement(name = "Tp", required = true)
protected String tp;
@XmlElement(name = "Ref", required = true)
protected String ref;
/**
* Gets the value of the tp property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTp(String value) {
this.tp = value;
}
/**
* Gets the value of the ref property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getRef() {
return ref;
}
/**
* Sets the value of the ref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRef(String value) {
this.ref = 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\ProprietaryReference1.java | 1 |
请完成以下Java代码 | private CellValue getValueAt(final int row, final int col)
{
final GridField f = m_tab.getField(col);
final Object key = m_tab.getValue(row, f.getColumnName());
Object value = key;
Lookup lookup = f.getLookup();
if (lookup != null)
{
// nothing to do
}
else if (f.getDisplayType() == DisplayType.Button)
{
lookup = getButtonLookup(f);
}
if (lookup != null)
{
value = lookup.getDisplay(key);
}
final int displayType = f.getDisplayType();
return CellValues.toCellValue(value, displayType);
}
@Override
public boolean isColumnPrinted(final int col)
{
final GridField f = m_tab.getField(col);
// Hide not displayed fields
if (!f.isDisplayed(GridTabLayoutMode.Grid))
{
return false;
}
// Hide encrypted fields
if (f.isEncrypted())
{
return false;
}
// Hide simple button fields without a value
if (f.getDisplayType() == DisplayType.Button && f.getAD_Reference_Value_ID() == null)
{
return false;
}
// Hide included tab fields (those are only placeholders for included tabs, always empty)
if (f.getIncluded_Tab_ID() > 0)
{
return false;
}
//
return true;
}
@Override
public boolean isFunctionRow(final int row)
{
return false;
}
@Override
public boolean isPageBreak(final int row, final int col)
{ | return false;
}
private final HashMap<String, MLookup> m_buttonLookups = new HashMap<>();
private MLookup getButtonLookup(final GridField mField)
{
MLookup lookup = m_buttonLookups.get(mField.getColumnName());
if (lookup != null)
{
return lookup;
}
// TODO: refactor with org.compiere.grid.ed.VButton.setField(GridField)
if (mField.getColumnName().endsWith("_ID") && !IColumnBL.isRecordIdColumnName(mField.getColumnName()))
{
lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.Search);
}
else if (mField.getAD_Reference_Value_ID() != null)
{
// Assuming List
lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.List);
}
//
m_buttonLookups.put(mField.getColumnName(), lookup);
return lookup;
}
@Override
protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\impexp\spreadsheet\excel\GridTabExcelExporter.java | 1 |
请完成以下Java代码 | public String validate()
{
return "";
} // validate
/**
* Check whether all Elements exist
* @return true if updated
*/
protected boolean checkElements () {
X_CM_Template thisTemplate = new X_CM_Template(getCtx(), this.getCM_Template_ID(), get_TrxName());
StringBuffer thisElementList = new StringBuffer(thisTemplate.getElements());
while (thisElementList.indexOf("\n")>=0) {
String thisElement = thisElementList.substring(0,thisElementList.indexOf("\n"));
thisElementList.delete(0,thisElementList.indexOf("\n")+1);
checkElement(thisElement);
}
String thisElement = thisElementList.toString();
checkElement(thisElement);
return true;
}
/**
* Check single Element, if not existing create it...
* @param elementName
*/
protected void checkElement(String elementName) {
int [] tableKeys = X_CM_CStage_Element.getAllIDs("CM_CStage_Element", "CM_CStage_ID=" + this.get_ID() + " AND Name like '" + elementName + "'", get_TrxName());
if (tableKeys==null || tableKeys.length==0) {
X_CM_CStage_Element thisElement = new X_CM_CStage_Element(getCtx(), 0, get_TrxName());
thisElement.setAD_Client_ID(getAD_Client_ID());
thisElement.setAD_Org_ID(getAD_Org_ID());
thisElement.setCM_CStage_ID(this.get_ID());
thisElement.setContentHTML(" ");
thisElement.setName(elementName);
thisElement.save(get_TrxName());
}
}
/**
* Check whether all Template Table records exits
* @return true if updated
*/ | protected boolean checkTemplateTable () {
int [] tableKeys = X_CM_TemplateTable.getAllIDs("CM_TemplateTable", "CM_Template_ID=" + this.getCM_Template_ID(), get_TrxName());
if (tableKeys!=null) {
for (int i=0;i<tableKeys.length;i++) {
X_CM_TemplateTable thisTemplateTable = new X_CM_TemplateTable(getCtx(), tableKeys[i], get_TrxName());
int [] existingKeys = X_CM_CStageTTable.getAllIDs("CM_CStageTTable", "CM_TemplateTable_ID=" + thisTemplateTable.get_ID(), get_TrxName());
if (existingKeys==null || existingKeys.length==0) {
X_CM_CStageTTable newCStageTTable = new X_CM_CStageTTable(getCtx(), 0, get_TrxName());
newCStageTTable.setAD_Client_ID(getAD_Client_ID());
newCStageTTable.setAD_Org_ID(getAD_Org_ID());
newCStageTTable.setCM_CStage_ID(get_ID());
newCStageTTable.setCM_TemplateTable_ID(thisTemplateTable.get_ID());
newCStageTTable.setDescription(thisTemplateTable.getDescription());
newCStageTTable.setName(thisTemplateTable.getName());
newCStageTTable.setOtherClause(thisTemplateTable.getOtherClause());
newCStageTTable.setWhereClause(thisTemplateTable.getWhereClause());
newCStageTTable.save();
}
}
}
return true;
}
} // MCStage | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MCStage.java | 1 |
请完成以下Spring Boot application配置 | server.port=${port:8080}
management.endpoint.health.group.custom.include=diskSpace,ping
management.endpoint.health.group.custom.show-components=always
management.endpoint.health.group.custom.show-details=always
management.endpoint.health.group.custom.status.http-mapping.up=207
management.endpoints.web.exposure.include=*
logging.file.name=logs/app.log
logging.file.path=logs
spring.ssl.bundle.jks.server.keystore.location= | classpath:ssl/baeldung.p12
spring.ssl.bundle.jks.server.keystore.password=password
spring.ssl.bundle.jks.server.keystore.type=PKCS12
server.ssl.bundle=server
server.ssl.enabled=false | repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public JSONResetPassword getResetPasswordInfo(@PathVariable("token") final String token)
{
return resetPasswordInitByToken(token);
}
@PostMapping("/resetPassword/{token}/init")
public JSONResetPassword resetPasswordInitByToken(@PathVariable("token") final String token)
{
userSession.assertNotLoggedIn();
final I_AD_User user = usersService.getByPasswordResetCode(token);
final String userADLanguage = user.getAD_Language();
if (userADLanguage != null && !Check.isBlank(userADLanguage))
{
userSession.setAD_Language(userADLanguage);
}
return JSONResetPassword.builder()
.fullname(user.getName())
.email(user.getEMail())
.token(token)
.build();
}
@GetMapping("/resetPassword/{token}/avatar")
public ResponseEntity<byte[]> getUserAvatar(
@PathVariable("token") final String token,
@RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth,
@RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight)
{
final I_AD_User user = usersService.getByPasswordResetCode(token); | final WebuiImageId avatarId = WebuiImageId.ofRepoIdOrNull(user.getAvatar_ID());
if (avatarId == null)
{
return imageService.getEmptyImage();
}
return imageService.getWebuiImage(avatarId, maxWidth, maxHeight)
.toResponseEntity();
}
@PostMapping("/resetPassword/{token}")
public JSONLoginAuthResponse resetPasswordComplete(
@PathVariable("token") final String token,
@RequestBody final JSONResetPasswordCompleteRequest request)
{
userSession.assertNotLoggedIn();
if (!Objects.equals(token, request.getToken()))
{
throw new AdempiereException("@Invalid@ @PasswordResetCode@");
}
final I_AD_User user = usersService.resetPassword(token, request.getPassword());
final String username = usersService.extractUserLogin(user);
final HashableString password = usersService.extractUserPassword(user);
return authenticate(username, password, null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\login\LoginRestController.java | 1 |
请完成以下Java代码 | public class CountingSort {
public static int[] sort(int[] input, int k) {
verifyPreconditions(input, k);
if (input.length == 0) return input;
int[] c = countElements(input, k);
int[] sorted = new int[input.length];
for (int i = input.length - 1; i >= 0; i--) {
int current = input[i];
sorted[c[current] - 1] = current;
c[current] -= 1;
}
return sorted;
}
static int[] countElements(int[] input, int k) {
int[] c = new int[k + 1];
Arrays.fill(c, 0);
for (int i : input) {
c[i] += 1; | }
for (int i = 1; i < c.length; i++) {
c[i] += c[i - 1];
}
return c;
}
private static void verifyPreconditions(int[] input, int k) {
if (input == null) {
throw new IllegalArgumentException("Input is required");
}
int min = IntStream.of(input).min().getAsInt();
int max = IntStream.of(input).max().getAsInt();
if (min < 0 || max > k) {
throw new IllegalArgumentException("The input numbers should be between zero and " + k);
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\counting\CountingSort.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
@JsonIgnore
public boolean isCustomTenantSet() {
return tenantId != null && !StringUtils.isEmpty(tenantId);
}
@ApiModelProperty(value = "Name of the signal")
public String getSignalName() {
return signalName;
} | public void setSignalName(String signalName) {
this.signalName = signalName;
}
public void setAsync(boolean async) {
this.async = async;
}
@ApiModelProperty(value = "If true, handling of the signal will happen asynchronously. Return code will be 202 - Accepted to indicate the request is accepted but not yet executed. If false,\n"
+ " handling the signal will be done immediately and result (200 - OK) will only return after this completed successfully. Defaults to false if omitted.")
public boolean isAsync() {
return async;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\SignalEventReceivedRequest.java | 2 |
请完成以下Java代码 | public Boolean isYldd() {
return yldd;
}
/**
* Sets the value of the yldd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setYldd(Boolean value) {
this.yldd = value;
}
/**
* Gets the value of the valTp property.
*
* @return
* possible object is
* {@link PriceValueType1Code } | *
*/
public PriceValueType1Code getValTp() {
return valTp;
}
/**
* Sets the value of the valTp property.
*
* @param value
* allowed object is
* {@link PriceValueType1Code }
*
*/
public void setValTp(PriceValueType1Code value) {
this.valTp = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\YieldedOrValueType1Choice.java | 1 |
请完成以下Java代码 | public class BatchSetVariablesHandler extends AbstractBatchJobHandler<BatchConfiguration> {
public static final BatchJobDeclaration JOB_DECLARATION =
new BatchJobDeclaration(Batch.TYPE_SET_VARIABLES);
@Override
public void executeHandler(BatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
String batchId = batchConfiguration.getBatchId();
Map<String, ?> variables = VariableUtil.findBatchVariablesSerialized(batchId, commandContext);
List<String> processInstanceIds = batchConfiguration.getIds();
for (String processInstanceId : processInstanceIds) {
commandContext.executeWithOperationLogPrevented(
new SetExecutionVariablesCmd(processInstanceId, variables, false, true, false));
}
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override
protected BatchConfiguration createJobConfiguration(BatchConfiguration configuration,
List<String> processIdsForJob) {
return new BatchConfiguration(processIdsForJob);
}
@Override
protected SetVariablesJsonConverter getJsonConverterInstance() {
return SetVariablesJsonConverter.INSTANCE;
} | @Override
public String getType() {
return Batch.TYPE_SET_VARIABLES;
}
@Override
protected void postProcessJob(BatchConfiguration configuration, JobEntity job, BatchConfiguration jobConfiguration) {
// if there is only one process instance to adjust, set its ID to the job so exclusive scheduling is possible
if (jobConfiguration.getIds() != null && jobConfiguration.getIds().size() == 1) {
job.setProcessInstanceId(jobConfiguration.getIds().get(0));
}
}
protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) {
return commandContext.getDbEntityManager()
.selectById(ByteArrayEntity.class, byteArrayId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\variables\BatchSetVariablesHandler.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Country country = (Country) o;
return id == country.id && name.equals(country.name); | }
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "Country{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\java\com\baeldung\h2db\springboot\models\Country.java | 1 |
请完成以下Java代码 | public Integer visitAssign(LabeledExprParser.AssignContext ctx) {
String id = ctx.ID().getText(); // id is left-hand side of '='
int value = visit(ctx.expr()); // compute value of expression on right
memory.put(id, value); // store it in our memory
return value;
}
/** expr : expr op=('*'|'/') expr */
@Override
public Integer visitMulDiv(LabeledExprParser.MulDivContext ctx) {
int left = visit(ctx.expr(0)); // get value of left subexpression
int right = visit(ctx.expr(1)); // get value of right subexpression
if (ctx.op.getType() == LabeledExprParser.MUL) return left * right;
return left / right; // must be DIV
}
/** expr : expr op=('+'|'-') expr */
@Override
public Integer visitAddSub(LabeledExprParser.AddSubContext ctx) {
int left = visit(ctx.expr(0)); // get value of left subexpression
int right = visit(ctx.expr(1)); // get value of right subexpression
if (ctx.op.getType() == LabeledExprParser.ADD) return left + right;
return left - right; // must be SUB
}
/** expr : INT */ | @Override
public Integer visitInt(LabeledExprParser.IntContext ctx) {
return Integer.valueOf(ctx.INT().getText());
}
/** expr : ID */
@Override
public Integer visitId(LabeledExprParser.IdContext ctx) {
String id = ctx.ID().getText();
if (memory.containsKey(id)) return memory.get(id);
return 0; // default value if the variable is not found
}
/** expr : '(' expr ')' */
@Override
public Integer visitParens(LabeledExprParser.ParensContext ctx) {
return visit(ctx.expr()); // return child expr's value
}
/** stat : NEWLINE */
@Override
public Integer visitBlank(LabeledExprParser.BlankContext ctx) {
return 0; // return dummy value
}
} | repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\EvalVisitor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class BarHibernateDAO {
@Autowired
private SessionFactory sessionFactory;
public TestEntity findEntity(int id) {
return getCurrentSession().find(TestEntity.class, 1);
}
public void createEntity(TestEntity entity) {
getCurrentSession().save(entity);
}
public void createEntity(int id, String newDescription) { | TestEntity entity = findEntity(id);
entity.setDescription(newDescription);
getCurrentSession().save(entity);
}
public void deleteEntity(int id) {
TestEntity entity = findEntity(id);
getCurrentSession().delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\bootstrap\BarHibernateDAO.java | 2 |
请完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final String parameterName = parameter.getColumnName();
if (PARAM_M_LocatorTo_ID.equals(parameterName))
{
final IViewRow row = getSingleSelectedRow();
return row.getFieldValueAsInt(I_DD_OrderLine.COLUMNNAME_M_LocatorTo_ID, -1);
}
else if (PARAM_M_HU_ID.equals(parameterName))
{
final DDOrderLineId ddOrderLineId = DDOrderLineId.ofRepoId(getSingleSelectedRow().getId().toInt());
final List<HuId> huIds = ddOrderMoveScheduleService.retrieveHUIdsScheduledButNotMovedYet(ddOrderLineId);
if (Check.isEmpty(huIds))
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
final HuId huId = huIds.iterator().next();
final I_M_HU hu = handlingUnitsBL.getById(huId);
return IntegerLookupValue.of(huId, TranslatableStrings.anyLanguage(hu.getValue()));
}
else
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
@RunOutOfTrx
protected String doIt()
{
final DDOrderLineId ddOrderLineId = DDOrderLineId.ofRepoId(getSingleSelectedRow().getId().toInt());
final I_DD_OrderLine ddOrderLine = ddOrderService.getLineById(ddOrderLineId);
final I_M_HU hu = handlingUnitsBL.getById(p_M_HU_ID);
ddOrderService.prepareAllocateFullHUsAndMove() | .toDDOrderLine(ddOrderLine)
.failIfCannotAllocate()
.allocateHUAndPrepareGeneratingMovements(hu)
.locatorToIdOverride(p_M_LocatorTo_ID > 0 ? warehouseBL.getLocatorIdByRepoId(p_M_LocatorTo_ID) : null)
.generateDirectMovements();
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
getView().invalidateRowById(getSelectedRowIds().getSingleDocumentId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ddorder\process\WEBUI_DD_OrderLine_MoveHU.java | 1 |
请完成以下Java代码 | public <X> JacksonJsonSerde<X> copyWithType(JavaType newTargetType) {
return new JacksonJsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
// Fluent API
/**
* Designate this Serde for serializing/deserializing keys (default is values).
* @return the serde.
*/
public JacksonJsonSerde<T> forKeys() {
this.jsonSerializer.forKeys();
this.jsonDeserializer.forKeys();
return this;
}
/**
* Configure the serializer to not add type information.
* @return the serde.
*/
public JacksonJsonSerde<T> noTypeInfo() {
this.jsonSerializer.noTypeInfo();
return this;
}
/**
* Don't remove type information headers after deserialization.
* @return the serde.
*/
public JacksonJsonSerde<T> dontRemoveTypeHeaders() {
this.jsonDeserializer.dontRemoveTypeHeaders();
return this;
}
/** | * Ignore type information headers and use the configured target class.
* @return the serde.
*/
public JacksonJsonSerde<T> ignoreTypeHeaders() {
this.jsonDeserializer.ignoreTypeHeaders();
return this;
}
/**
* Use the supplied {@link JacksonJavaTypeMapper}.
* @param mapper the mapper.
* @return the serde.
*/
public JacksonJsonSerde<T> typeMapper(JacksonJavaTypeMapper mapper) {
this.jsonSerializer.setTypeMapper(mapper);
this.jsonDeserializer.setTypeMapper(mapper);
return this;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JacksonJsonSerde.java | 1 |
请完成以下Java代码 | public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return Boolean.TRUE.equals(active);
} | @InstanceName
@DependsOnProperties({"firstName", "lastName", "username"})
public String getDisplayName() {
return String.format("%s %s [%s]", (firstName != null ? firstName : ""),
(lastName != null ? lastName : ""), username).trim();
}
@Override
public String getTimeZoneId() {
return timeZoneId;
}
public void setTimeZoneId(final String timeZoneId) {
this.timeZoneId = timeZoneId;
}
} | repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java | 1 |
请完成以下Java代码 | public Incident handleIncident(IncidentContext context, String message) {
return createIncident(context, message);
}
public Incident createIncident(IncidentContext context, String message) {
IncidentEntity newIncident = IncidentEntity.createAndInsertIncident(type, context, message);
if(context.getExecutionId() != null) {
newIncident.createRecursiveIncidents();
}
return newIncident;
}
public void resolveIncident(IncidentContext context) {
removeIncident(context, true);
}
public void deleteIncident(IncidentContext context) {
removeIncident(context, false); | }
protected void removeIncident(IncidentContext context, boolean incidentResolved) {
List<Incident> incidents = Context
.getCommandContext()
.getIncidentManager()
.findIncidentByConfiguration(context.getConfiguration());
for (Incident currentIncident : incidents) {
IncidentEntity incident = (IncidentEntity) currentIncident;
if (incidentResolved) {
incident.resolve();
} else {
incident.delete();
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\incident\DefaultIncidentHandler.java | 1 |
请完成以下Java代码 | public void notifySegmentChanged(@NonNull final IShipmentScheduleSegment segment)
{
notifySegmentsChanged(ImmutableSet.of(segment));
}
@Override
public void notifySegmentsChanged(@NonNull final Collection<IShipmentScheduleSegment> segments)
{
if (segments.isEmpty())
{
return;
}
final ImmutableList<IShipmentScheduleSegment> segmentsEffective = segments.stream()
.filter(segment -> !segment.isInvalid())
.flatMap(this::explodeByPickingBOMs)
.collect(ImmutableList.toImmutableList());
if (segmentsEffective.isEmpty())
{
return;
}
final ShipmentScheduleSegmentChangedProcessor collector = ShipmentScheduleSegmentChangedProcessor.getOrCreateIfThreadInheritedElseNull(this);
if (collector != null)
{
collector.addSegments(segmentsEffective); // they will be flagged for recompute after commit
}
else
{
final ITaskExecutorService taskExecutorService = Services.get(ITaskExecutorService.class);
taskExecutorService.submit(
() -> flagSegmentForRecompute(segmentsEffective), | this.getClass().getSimpleName());
}
}
private Stream<IShipmentScheduleSegment> explodeByPickingBOMs(final IShipmentScheduleSegment segment)
{
if (segment.isAnyProduct())
{
return Stream.of(segment);
}
final PickingBOMsReversedIndex pickingBOMsReversedIndex = pickingBOMService.getPickingBOMsReversedIndex();
final Set<ProductId> componentIds = ProductId.ofRepoIds(segment.getProductIds());
final ImmutableSet<ProductId> pickingBOMProductIds = pickingBOMsReversedIndex.getBOMProductIdsByComponentIds(componentIds);
if (pickingBOMProductIds.isEmpty())
{
return Stream.of(segment);
}
final ImmutableShipmentScheduleSegment pickingBOMsSegment = ImmutableShipmentScheduleSegment.builder()
.productIds(ProductId.toRepoIds(pickingBOMProductIds))
.anyBPartner()
.locatorIds(segment.getLocatorIds())
.build();
return Stream.of(segment, pickingBOMsSegment);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\impl\ShipmentScheduleInvalidateBL.java | 1 |
请完成以下Java代码 | protected boolean onLoginSuccess(
AuthenticationToken token,
Subject subject,
ServletRequest request,
ServletResponse response) throws Exception {
ShiroUser user = (ShiroUser) subject.getPrincipal();
user.setToken(subject.getSession().getId().toString());
return true;
}
/**
* 创建包含第三方accessToken的shiro token。
*
* @param request
* @param response
* @return
*/
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
String username = getUsername(request);
String password = getPassword(request);
String accessToken = request.getParameter(Constants.THIRD_PARTY_ACCESS_TOKEN_NAME);
//shiro后续流程可能会用到username,所以如果用accessToken登录时赋值username为它的值。
if (StringUtils.isBlank(username)) {
username = accessToken;
}
return new ThirdPartySupportedToken(username, password, accessToken);
}
/**
* 直接构造HttpResponse,不再执行后续的所有方法。
* | * @param response
* @param entity
* @return
*/
private boolean responseDirectly(HttpServletResponse response, ResponseEntity entity) {
response.reset();
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//设置跨域信息。
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
try {
response.getWriter().write(JSON.toJSONString(entity));
} catch (IOException e) {
logger.error("ResponseError ex:{}", ExceptionUtils.getStackTrace(e));
}
return false;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\filter\ShiroFormAuthenticationFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void packRemainingQtyToDestination()
{
if (!hasPackToDestination())
{
return;
}
if (!isQtyToPackEnforced())
{
return;
}
final Quantity qtyToPack = getQtyToPackRemaining();
if (qtyToPack.signum() <= 0)
{
return;
}
packItem(
qtyToPack,
part -> DeliveryRule.FORCE.equals(part.getDeliveryRule()), // We are accepting only those shipment schedules which have Force Delivery
this::packItemToDestination);
}
private void packItemToDestination(final IPackingItem item)
{
item.getParts()
.toList()
.forEach(this::packItemPartToDestination);
}
private void packItemPartToDestination(final PackingItemPart part)
{
final IAllocationRequest request = createShipmentScheduleAllocationRequest(getHUContext(), part);
final IAllocationSource source = createAllocationSourceFromShipmentScheduleId(part.getShipmentScheduleId());
final IAllocationDestination destination = getPackToDestination();
//
// Move Qty from shipment schedules to current HU
final IAllocationResult result = HULoader.of(source, destination)
.load(request); | // Make sure result is completed
// NOTE: this shall not happen because "forceQtyAllocation" is set to true
if (!result.isCompleted())
{
final String errmsg = MessageFormat.format(ERR_CANNOT_FULLY_LOAD, destination);
throw new AdempiereException(errmsg);
}
}
private IAllocationSource createAllocationSourceFromShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule schedule = shipmentSchedulesSupplier.getShipmentScheduleById(shipmentScheduleId);
final ShipmentScheduleQtyPickedProductStorage shipmentScheduleQtyPickedStorage = ShipmentScheduleQtyPickedProductStorage.of(schedule);
return new GenericAllocationSourceDestination(shipmentScheduleQtyPickedStorage, schedule);
}
public Map<HuId, PickedHuAndQty> getPickedHUs()
{
return pickedHus;
}
//
//
//
//
//
public static class HU2PackingItemsAllocatorBuilder
{
public HU2PackingItemsAllocator allocate()
{
return build().allocate();
}
public HU2PackingItemsAllocatorBuilder packToHU(final I_M_HU hu)
{
return packToDestination(HUListAllocationSourceDestination.of(hu));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\impl\HU2PackingItemsAllocator.java | 2 |
请完成以下Java代码 | public class TaskCandidateGroupAddedListenerDelegate implements ActivitiEventListener {
private final List<TaskRuntimeEventListener<TaskCandidateGroupAddedEvent>> listeners;
private final ToAPITaskCandidateGroupAddedEventConverter converter;
public TaskCandidateGroupAddedListenerDelegate(
List<TaskRuntimeEventListener<TaskCandidateGroupAddedEvent>> listeners,
ToAPITaskCandidateGroupAddedEventConverter converter
) {
this.listeners = listeners;
this.converter = converter;
}
@Override
public void onEvent(ActivitiEvent event) { | if (event instanceof ActivitiEntityEvent) {
converter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (TaskRuntimeEventListener<TaskCandidateGroupAddedEvent> listener : listeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskCandidateGroupAddedListenerDelegate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
private final IUserService userService;
@Autowired
public UserController(IUserService userService) {
this.userService = userService;
}
@PostMapping("/user")
public Dict save(@RequestBody User user) {
Boolean save = userService.save(user);
return Dict.create().set("code", save ? 200 : 500).set("msg", save ? "成功" : "失败").set("data", save ? user : null);
}
@DeleteMapping("/user/{id}")
public Dict delete(@PathVariable Long id) {
Boolean delete = userService.delete(id);
return Dict.create().set("code", delete ? 200 : 500).set("msg", delete ? "成功" : "失败");
} | @PutMapping("/user/{id}")
public Dict update(@RequestBody User user, @PathVariable Long id) {
Boolean update = userService.update(user, id);
return Dict.create().set("code", update ? 200 : 500).set("msg", update ? "成功" : "失败").set("data", update ? user : null);
}
@GetMapping("/user/{id}")
public Dict getUser(@PathVariable Long id) {
User user = userService.getUser(id);
return Dict.create().set("code", 200).set("msg", "成功").set("data", user);
}
@GetMapping("/user")
public Dict getUser(User user) {
List<User> userList = userService.getUser(user);
return Dict.create().set("code", 200).set("msg", "成功").set("data", userList);
}
} | repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\controller\UserController.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.