instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setC_BP_Group_Match(final org.compiere.model.I_C_BP_Group C_BP_Group_Match)
{
set_ValueFromPO(COLUMNNAME_C_BP_Group_Match_ID, org.compiere.model.I_C_BP_Group.class, C_BP_Group_Match);
}
@Override
public void setC_BP_Group_Match_ID (final int C_BP_Group_Match_ID)
{
if (C_BP_Group_Match_ID < 1)
set_Value (COLUMNNAME_C_BP_Group_Match_ID, null);
else
set_Value (COLUMNNAME_C_BP_Group_Match_ID, C_BP_Group_Match_ID);
}
@Override
public int getC_BP_Group_Match_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_Group_Match_ID);
}
@Override
public de.metas.contracts.commission.model.I_C_LicenseFeeSettings getC_LicenseFeeSettings()
{
return get_ValueAsPO(COLUMNNAME_C_LicenseFeeSettings_ID, de.metas.contracts.commission.model.I_C_LicenseFeeSettings.class);
}
@Override
public void setC_LicenseFeeSettings(final de.metas.contracts.commission.model.I_C_LicenseFeeSettings C_LicenseFeeSettings)
{
set_ValueFromPO(COLUMNNAME_C_LicenseFeeSettings_ID, de.metas.contracts.commission.model.I_C_LicenseFeeSettings.class, C_LicenseFeeSettings);
}
@Override
public void setC_LicenseFeeSettings_ID (final int C_LicenseFeeSettings_ID)
{
if (C_LicenseFeeSettings_ID < 1)
set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, null);
else
set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, C_LicenseFeeSettings_ID);
}
@Override
public int getC_LicenseFeeSettings_ID()
{ | return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID);
}
@Override
public void setC_LicenseFeeSettingsLine_ID (final int C_LicenseFeeSettingsLine_ID)
{
if (C_LicenseFeeSettingsLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, C_LicenseFeeSettingsLine_ID);
}
@Override
public int getC_LicenseFeeSettingsLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettingsLine_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettingsLine.java | 1 |
请完成以下Java代码 | public class Task {
public static Random random = new Random();
@Async("taskExecutor")
public void doTaskOne() throws Exception {
log.info("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskTwo() throws Exception {
log.info("开始做任务二");
long start = System.currentTimeMillis(); | Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务二,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskThree() throws Exception {
log.info("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务三,耗时:" + (end - start) + "毫秒");
}
} | repos\SpringBoot-Learning-master\1.x\Chapter4-1-3\src\main\java\com\didispace\async\Task.java | 1 |
请完成以下Java代码 | public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public long getTotalPage() {
return totalPage;
}
public void setTotalPage(long totalPage) {
this.totalPage = totalPage;
}
public long getTotalNumber() {
return totalNumber;
}
public void setTotalNumber(long totalNumber) {
this.totalNumber = totalNumber;
} | public List<E> getList() {
return list;
}
public void setList(List<E> list) {
this.list = list;
}
public static Page getNULL() {
return NULL;
}
public static void setNULL(Page NULL) {
Page.NULL = NULL;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-mybatis-annotation-druid\src\main\java\com\neo\result\Page.java | 1 |
请完成以下Java代码 | public void createDocOutbound(@NonNull final Object model)
{
enqueueModelForWorkpackageProcessor(model, DocOutboundWorkpackageProcessor.class);
}
@Override
public void voidDocOutbound(@NonNull final Object model)
{
enqueueModelForWorkpackageProcessor(model, ProcessPrintingQueueWorkpackageProcessor.class);
}
private void enqueueModelForWorkpackageProcessor(
@NonNull final Object model,
@NonNull final Class<? extends IWorkpackageProcessor> packageProcessorClass)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(model); | final I_C_Async_Batch asyncBatch = asyncBatchBL.getAsyncBatchId(model)
.map(asyncBatchBL::getAsyncBatchById)
.orElse(null);
workPackageQueueFactory
.getQueueForEnqueuing(ctx, packageProcessorClass)
.newWorkPackage()
.bindToThreadInheritedTrx()
.addElement(model)
.setC_Async_Batch(asyncBatch)
.setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null))
.buildAndEnqueue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\AbstractDocOutboundProducer.java | 1 |
请完成以下Spring Boot application配置 | main.datasource.url = jdbc:hsqldb:file:.jmix/hsqldb/expensetracker
main.datasource.username = sa
main.datasource.password =
main.liquibase.change-log=com/baeldung/jmix/expensetracker/liquibase/changelog.xml
jmix.ui.login-view-id = LoginView
jmix.ui.main-view-id = MainView
jmix.ui.menu-config = com/baeldung/jmix/expensetracker/menu.xml
jmix.ui.composite-menu = true
ui.login.defaultUsername = admin
ui.login.defaultPassword = admin
jmix.core.available-locales = en
# Launch the default browser when starting the application in development mode
vaadin.launch-browser = false
# Use pnpm to speed up project initialization and save disk space
vaadin.pnpm.enable = false
logging.level.org.atmosphere = warn
# 'debug' level logs SQL generated | by EclipseLink ORM
logging.level.eclipselink.logging.sql = info
# 'debug' level logs data store operations
logging.level.io.jmix.core.datastore = info
# 'debug' level logs access control constraints
logging.level.io.jmix.core.AccessLogger = debug
# 'debug' level logs all Jmix debug output
logging.level.io.jmix = info | repos\tutorials-master\spring-boot-modules\jmix\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setValue(final @NonNull String name, final int value, final @NonNull ClientAndOrgId clientAndOrgId)
{
setValue(name, String.valueOf(value), clientAndOrgId);
}
@Override
public void setValue(final @NonNull String name, final boolean value, final @NonNull ClientAndOrgId clientAndOrgId)
{
setValue(name, StringUtils.ofBoolean(value), clientAndOrgId);
}
@Override
public Optional<String> getValue(@NonNull final String name, @NonNull final ClientAndOrgId clientAndOrgId)
{
final Optional<String> value = SpringContextHolder.instance.getProperty(name);
if (value.isPresent())
{
return value;
}
return getMap().getValueAsString(name, clientAndOrgId);
}
@Override
public List<String> retrieveNamesForPrefix(
@NonNull final String prefix,
@NonNull final ClientAndOrgId clientAndOrgId)
{
return getMap().getNamesForPrefix(prefix, clientAndOrgId);
}
private SysConfigMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private SysConfigMap retrieveMap()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final ImmutableListMultimap<String, SysConfigEntryValue> entryValuesByName = retrieveSysConfigEntryValues();
final ImmutableMap<String, SysConfigEntry> entiresByName = entryValuesByName.asMap()
.entrySet()
.stream()
.map(e -> SysConfigEntry.builder()
.name(e.getKey())
.entryValues(e.getValue())
.build())
.collect(ImmutableMap.toImmutableMap(
SysConfigEntry::getName,
entry -> entry
));
final SysConfigMap result = new SysConfigMap(entiresByName);
logger.info("Retrieved {} in {}", result, stopwatch.stop());
return result;
}
protected ImmutableListMultimap<String, SysConfigEntryValue> retrieveSysConfigEntryValues()
{
final String sql = "SELECT Name, Value, AD_Client_ID, AD_Org_ID FROM AD_SysConfig"
+ " WHERE IsActive='Y'"
+ " ORDER BY Name, AD_Client_ID, AD_Org_ID";
PreparedStatement pstmt = null; | ResultSet rs = null;
try
{
final ImmutableListMultimap.Builder<String, SysConfigEntryValue> resultBuilder = ImmutableListMultimap.builder();
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
rs = pstmt.executeQuery();
while (rs.next())
{
final String name = rs.getString("Name");
final String value = rs.getString("Value");
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(
ClientId.ofRepoId(rs.getInt("AD_Client_ID")),
OrgId.ofRepoId(rs.getInt("AD_Org_ID")));
final SysConfigEntryValue entryValue = SysConfigEntryValue.of(value, clientAndOrgId);
resultBuilder.put(name, entryValue);
}
return resultBuilder.build();
}
catch (final SQLException ex)
{
throw new DBException(ex, sql);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigDAO.java | 2 |
请完成以下Java代码 | public void lockAll(final Collection<I_M_HU> hus, final LockOwner lockOwner)
{
if (hus.isEmpty())
{
return;
}
Preconditions.checkNotNull(lockOwner, "lockOwner is null");
Preconditions.checkArgument(!lockOwner.isAnyOwner(), "{} not allowed", lockOwner);
Services.get(ILockManager.class)
.lock()
.setOwner(lockOwner)
.setFailIfAlreadyLocked(false)
.setAllowAdditionalLocks(AllowAdditionalLocks.FOR_DIFFERENT_OWNERS)
.setAutoCleanup(false)
.addRecordsByModel(hus)
.acquire();
if (isUseVirtualColumn())
{
InterfaceWrapperHelper.refreshAll(hus);
}
}
@Override
public void unlock(final I_M_HU hu, final LockOwner lockOwner)
{
Preconditions.checkNotNull(hu, "hu is null");
Preconditions.checkNotNull(lockOwner, "lockOwner is null");
Preconditions.checkArgument(!lockOwner.isAnyOwner(), "%s not allowed", lockOwner);
final int huId = hu.getM_HU_ID();
unlock0(huId, lockOwner);
if (isUseVirtualColumn())
{
InterfaceWrapperHelper.refresh(hu);
}
}
@Override
public void unlockOnAfterCommit(
final int huId,
@NonNull final LockOwner lockOwner)
{
Preconditions.checkArgument(huId > 0, "huId shall be > 0");
Preconditions.checkArgument(!lockOwner.isAnyOwner(), "{} not allowed", lockOwner);
Services.get(ITrxManager.class)
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerWeakly(false) // register "hard", because that's how it was before
.invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed
.registerHandlingMethod(transaction -> unlock0(huId, lockOwner));
}
private void unlock0(final int huId, final LockOwner lockOwner)
{
Services.get(ILockManager.class)
.unlock()
.setOwner(lockOwner)
.setRecordByTableRecordId(I_M_HU.Table_Name, huId)
.release();
} | @Override
public void unlockAll(final Collection<I_M_HU> hus, final LockOwner lockOwner)
{
if (hus.isEmpty())
{
return;
}
Preconditions.checkNotNull(lockOwner, "lockOwner is null");
Preconditions.checkArgument(!lockOwner.isAnyOwner(), "{} not allowed", lockOwner);
Services.get(ILockManager.class)
.unlock()
.setOwner(lockOwner)
.setRecordsByModels(hus)
.release();
if (isUseVirtualColumn())
{
InterfaceWrapperHelper.refresh(hus);
}
}
@Override
public IQueryFilter<I_M_HU> isLockedFilter()
{
return Services.get(ILockManager.class).getLockedByFilter(I_M_HU.class, LockOwner.ANY);
}
@Override
public IQueryFilter<I_M_HU> isNotLockedFilter()
{
return Services.get(ILockManager.class).getNotLockedFilter(I_M_HU.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HULockBL.java | 1 |
请完成以下Java代码 | private void run(String[] args) {
Restarter.initialize(args, RestartInitializer.NONE);
SpringApplication application = new SpringApplication(RemoteClientConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
application.setBanner(getBanner());
application.setInitializers(getInitializers());
application.setListeners(getListeners());
application.run(args);
waitIndefinitely();
}
private Collection<ApplicationContextInitializer<?>> getInitializers() {
List<ApplicationContextInitializer<?>> initializers = new ArrayList<>();
initializers.add(new RestartScopeInitializer());
return initializers;
}
private Collection<ApplicationListener<?>> getListeners() {
List<ApplicationListener<?>> listeners = new ArrayList<>();
listeners.add(new AnsiOutputApplicationListener());
listeners.add(EnvironmentPostProcessorApplicationListener
.with(EnvironmentPostProcessorsFactory.of(ConfigDataEnvironmentPostProcessor.class)));
listeners.add(new LoggingApplicationListener());
listeners.add(new RemoteUrlPropertyExtractor());
return listeners;
}
private Banner getBanner() {
ClassPathResource banner = new ClassPathResource("remote-banner.txt", RemoteSpringApplication.class);
return new ResourceBanner(banner);
}
private void waitIndefinitely() { | while (true) {
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
/**
* Run the {@link RemoteSpringApplication}.
* @param args the program arguments (including the remote URL as a non-option
* argument)
*/
public static void main(String[] args) {
new RemoteSpringApplication().run(args);
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\RemoteSpringApplication.java | 1 |
请完成以下Java代码 | public class UserMenuFavoritesDAO implements IUserMenuFavoritesDAO
{
private static final Logger logger = LogManager.getLogger(UserMenuFavoritesDAO.class);
@Override
public void add(@NonNull final UserId adUserId, final int adMenuId)
{
final boolean exists = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_TreeBar.class)
.addEqualsFilter(I_AD_TreeBar.COLUMN_AD_User_ID, adUserId)
.addEqualsFilter(I_AD_TreeBar.COLUMN_Node_ID, adMenuId)
.create()
.anyMatch();
if (exists)
{
logger.warn("Not creating a favorite record for adUserId={}, adMenuId={} because another one already exists", adUserId, adMenuId);
return;
}
final I_AD_TreeBar favorite = InterfaceWrapperHelper.newInstance(I_AD_TreeBar.class);
favorite.setAD_User_ID(adUserId.getRepoId());
favorite.setNode_ID(adMenuId);
InterfaceWrapperHelper.save(favorite);
}
@Override
public boolean remove(@NonNull final UserId adUserId, final int adMenuId)
{
final int deleted = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_TreeBar.class)
.addEqualsFilter(I_AD_TreeBar.COLUMN_AD_User_ID, adUserId)
.addEqualsFilter(I_AD_TreeBar.COLUMN_Node_ID, adMenuId) | .create()
.deleteDirectly();
return deleted > 0;
}
@Override
public List<Integer> retrieveMenuIdsForUser(@NonNull final UserId adUserId)
{
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_TreeBar.class)
.addEqualsFilter(I_AD_TreeBar.COLUMN_AD_User_ID, adUserId)
.addOnlyActiveRecordsFilter()
.create()
.listDistinct(I_AD_TreeBar.COLUMNNAME_Node_ID, Integer.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserMenuFavoritesDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SampleTableController implements BaseController {
@Autowired
private SampleTableService sampleTableService;
@ResponseBody
@RequestMapping(value = "/list", method = RequestMethod.POST)
public BaseResp list(@RequestBody SampleTable page) {
return success(sampleTableService.pageList(page));
}
@ResponseBody
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public BaseResp<SampleTable> detail(@PathVariable String id) {
return success(sampleTableService.getById(id));
}
@ResponseBody
@RequestMapping(value = "save", method = RequestMethod.POST)
public BaseResp<Boolean> save(@RequestBody SampleTable sampleTable) {
sampleTableService.saveEntity(sampleTable);
return success();
} | @ResponseBody
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public BaseResp<Boolean> update(@PathVariable String id, @RequestBody SampleTable sampleTable) {
Assert.notEmpty(id, "ID不能为空");
sampleTableService.updateById(sampleTable);
return success();
}
@ResponseBody
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public BaseResp<Boolean> delete(@PathVariable String id) {
sampleTableService.delete(id);
return success();
}
} | repos\spring-boot-quick-master\quick-sample-server\sample-server\src\main\java\com\quick\controller\SampleTableController.java | 2 |
请完成以下Java代码 | public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getChannelType() {
return channelType;
} | public void setChannelType(String channelType) {
this.channelType = channelType;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public JsonNode getExtension() {
return extension;
}
public void setExtension(JsonNode extension) {
this.extension = extension;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\ChannelModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Integer id;
@Column
private String title;
@Column
private String author;
@Column
private String synopsis;
@Column
private String language;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getAuthor() {
return author; | }
public void setAuthor(String address) {
this.author = address;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\java\com\baeldung\spring\data\jpa\optionalfields\Book.java | 2 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Line No.
@param Line
Unique line for this document
*/
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Line No.
@return Unique line for this document
*/
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set BOM Line.
@param M_Product_BOM_ID BOM Line */
public void setM_Product_BOM_ID (int M_Product_BOM_ID)
{
if (M_Product_BOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_BOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_BOM_ID, Integer.valueOf(M_Product_BOM_ID));
}
/** Get BOM Line.
@return BOM Line */
public int getM_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_BOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_ProductBOM() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_ProductBOM_ID(), get_TrxName()); }
/** Set BOM Product.
@param M_ProductBOM_ID
Bill of Material Component Product
*/
public void setM_ProductBOM_ID (int M_ProductBOM_ID)
{
if (M_ProductBOM_ID < 1)
set_Value (COLUMNNAME_M_ProductBOM_ID, null);
else
set_Value (COLUMNNAME_M_ProductBOM_ID, Integer.valueOf(M_ProductBOM_ID));
}
/** Get BOM Product.
@return Bill of Material Component Product
*/
public int getM_ProductBOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductBOM_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_ProductBOM_ID()));
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_BOM.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MutiDataSourceProperties {
private String url;
private String username;
private String password;
public void config(DruidDataSource dataSource) {
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url; | }
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} | repos\SpringBootBucket-master\springboot-multisource\src\main\java\com\xncoding\pos\config\properties\MutiDataSourceProperties.java | 2 |
请完成以下Java代码 | public GroupQuery groupType(String type) {
ensureNotNull("Provided type", type);
this.type = type;
return this;
}
public GroupQuery groupMember(String userId) {
ensureNotNull("Provided userId", userId);
this.userId = userId;
return this;
}
public GroupQuery potentialStarter(String procDefId) {
ensureNotNull("Provided processDefinitionId", procDefId);
this.procDefId = procDefId;
return this;
}
public GroupQuery memberOfTenant(String tenantId) {
ensureNotNull("Provided tenantId", tenantId);
this.tenantId = tenantId;
return this;
}
//sorting ////////////////////////////////////////////////////////
public GroupQuery orderByGroupId() {
return orderBy(GroupQueryProperty.GROUP_ID);
}
public GroupQuery orderByGroupName() {
return orderBy(GroupQueryProperty.NAME);
}
public GroupQuery orderByGroupType() {
return orderBy(GroupQueryProperty.TYPE);
}
//getters ////////////////////////////////////////////////////////
public String getId() {
return id; | }
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getTenantId() {
return tenantId;
}
public String[] getIds() {
return ids;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\GroupQueryImpl.java | 1 |
请完成以下Java代码 | public class MessageReceiver {
private QueueConnectionFactory factory;
private QueueConnection connection;
private QueueSession session;
private QueueReceiver receiver;
public MessageReceiver() {
}
public void initialize() throws JMSException {
factory = new JMSSetup().createConnectionFactory();
connection = factory.createQueueConnection();
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("QUEUE1");
receiver = session.createReceiver(queue);
connection.start();
}
public void receiveMessage() {
try {
Message message = receiver.receive(1000);
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
long timestamp = message.getJMSTimestamp();
String messageId = message.getJMSMessageID();
int priority = message.getJMSPriority();
long expiration = message.getJMSExpiration();
log("Message received: " + textMessage.getText()); | log("Message ID: " + messageId);
log("Message timestamp: " + timestamp);
log("Message Priority: " + priority);
log("Expiration Time: " + expiration);
} else {
log("No text message received.");
}
} catch (JMSException e) {
// handle exception
} finally {
try {
if (receiver != null) {
receiver.close();
}
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
} catch (JMSException e) {
// handle exception
}
}
}
} | repos\tutorials-master\messaging-modules\ibm-mq\src\main\java\com\baeldung\ibmmq\MessageReceiver.java | 1 |
请完成以下Java代码 | public void updateExecutionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateExecutionTenantIdForDeployment", params);
}
@Override
public void updateProcessInstanceLockTime(String processInstanceId, Date lockDate, Date expirationTime) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("id", processInstanceId);
params.put("lockTime", lockDate);
params.put("expirationTime", expirationTime);
int result = getDbSqlSession().update("updateProcessInstanceLockTime", params);
if (result == 0) { | throw new ActivitiOptimisticLockingException("Could not lock process instance");
}
}
@Override
public void updateAllExecutionRelatedEntityCountFlags(boolean newValue) {
getDbSqlSession().update("updateExecutionRelatedEntityCountEnabled", newValue);
}
@Override
public void clearProcessInstanceLockTime(String processInstanceId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("id", processInstanceId);
getDbSqlSession().update("clearProcessInstanceLockTime", params);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void ensureInitialized() {
this.lock.lock();
try {
if (!this.initialized) {
initialize();
this.initialized = true;
}
}
finally {
this.lock.unlock();
}
}
@SuppressWarnings("deprecation")
private void initialize() {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
for (Location location : this.locations) {
if (!location.isClassPath()) {
continue;
}
Resource root = resolver.getResource(location.getDescriptor());
if (!root.exists()) {
if (this.failOnMissingLocations) {
throw new FlywayException("Location " + location.getDescriptor() + " doesn't exist");
} | continue;
}
Resource[] resources = getResources(resolver, location, root);
for (Resource resource : resources) {
this.locatedResources.add(new LocatedResource(resource, location));
}
}
}
private Resource[] getResources(PathMatchingResourcePatternResolver resolver, Location location, Resource root) {
try {
return resolver.getResources(root.getURI() + "/*");
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to list resources for " + location.getDescriptor(), ex);
}
}
private record LocatedResource(Resource resource, Location location) {
}
} | repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\NativeImageResourceProvider.java | 2 |
请完成以下Java代码 | public void onC_BPartner_ID(final I_DD_Order ddOrder, final ICalloutField calloutField)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(ddOrder.getC_BPartner_ID());
if (bpartnerId == null)
{
return;
}
//
// BPartner Location (i.e. ShipTo)
final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class);
final I_C_BPartner bpartner = bpartnerBL.getById(bpartnerId);
final I_C_BPartner_Location shipToLocation = CalloutInOut.suggestShipToLocation(calloutField, bpartner);
ddOrder.setC_BPartner_Location_ID(shipToLocation != null ? shipToLocation.getC_BPartner_Location_ID() : -1);
//
// BPartner Contact
final boolean isSOTrx = ddOrder.isSOTrx();
if (!isSOTrx)
{
I_AD_User contact = null;
if (shipToLocation != null)
{
contact = bpartnerBL.retrieveUserForLoc(shipToLocation);
}
if (contact == null)
{
contact = bpartnerBL.retrieveShipContact(bpartner);
}
ddOrder.setAD_User_ID(contact != null ? contact.getAD_User_ID() : -1);
}
}
@CalloutMethod(columnNames = { I_DD_Order.COLUMNNAME_C_Order_ID })
public void onC_Order_ID(final I_DD_Order ddOrder)
{
final I_C_Order order = ddOrder.getC_Order();
if (order == null || order.getC_Order_ID() <= 0)
{
return;
} | // Get Details
ddOrder.setDateOrdered(order.getDateOrdered());
ddOrder.setPOReference(order.getPOReference());
ddOrder.setAD_Org_ID(order.getAD_Org_ID());
ddOrder.setAD_OrgTrx_ID(order.getAD_OrgTrx_ID());
ddOrder.setC_Activity_ID(order.getC_Activity_ID());
ddOrder.setC_Campaign_ID(order.getC_Campaign_ID());
ddOrder.setC_Project_ID(order.getC_Project_ID());
ddOrder.setUser1_ID(order.getUser1_ID());
ddOrder.setUser2_ID(order.getUser2_ID());
// Warehouse (05251 begin: we need to use the advisor)
final WarehouseId warehouseId = Services.get(IWarehouseAdvisor.class).evaluateOrderWarehouse(order);
Check.assumeNotNull(warehouseId, "IWarehouseAdvisor finds a ware house for {}", order);
ddOrder.setM_Warehouse_ID(warehouseId.getRepoId());
//
ddOrder.setDeliveryRule(order.getDeliveryRule());
ddOrder.setDeliveryViaRule(order.getDeliveryViaRule());
ddOrder.setM_Shipper_ID(order.getM_Shipper_ID());
ddOrder.setFreightCostRule(order.getFreightCostRule());
ddOrder.setFreightAmt(order.getFreightAmt());
ddOrder.setC_BPartner_ID(order.getC_BPartner_ID());
ddOrder.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID());
ddOrder.setAD_User_ID(order.getAD_User_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\callout\DD_Order.java | 1 |
请完成以下Java代码 | public void setC_BPartner_QuickInput_ID (final int C_BPartner_QuickInput_ID)
{
if (C_BPartner_QuickInput_ID < 1)
set_Value (COLUMNNAME_C_BPartner_QuickInput_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_QuickInput_ID, C_BPartner_QuickInput_ID);
}
@Override
public int getC_BPartner_QuickInput_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_ID);
}
@Override
public void setC_BPartner_QuickInput_RelatedRecord1_ID (final int C_BPartner_QuickInput_RelatedRecord1_ID)
{
if (C_BPartner_QuickInput_RelatedRecord1_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_RelatedRecord1_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_RelatedRecord1_ID, C_BPartner_QuickInput_RelatedRecord1_ID);
} | @Override
public int getC_BPartner_QuickInput_RelatedRecord1_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_RelatedRecord1_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput_RelatedRecord1.java | 1 |
请完成以下Java代码 | public void setValues(VariableAggregationDefinition otherVariableDefinitionAggregation) {
setImplementationType(otherVariableDefinitionAggregation.getImplementationType());
setImplementation(otherVariableDefinitionAggregation.getImplementation());
setTarget(otherVariableDefinitionAggregation.getTarget());
setTargetExpression(otherVariableDefinitionAggregation.getTargetExpression());
List<Variable> otherDefinitions = otherVariableDefinitionAggregation.getDefinitions();
if (otherDefinitions != null) {
List<Variable> newDefinitions = new ArrayList<>(otherDefinitions.size());
for (Variable otherDefinition : otherDefinitions) {
newDefinitions.add(otherDefinition.clone());
}
setDefinitions(newDefinitions);
}
setStoreAsTransientVariable(otherVariableDefinitionAggregation.isStoreAsTransientVariable());
setCreateOverviewVariable(otherVariableDefinitionAggregation.isCreateOverviewVariable());
}
public static class Variable {
protected String source;
protected String target;
protected String targetExpression;
protected String sourceExpression;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getTargetExpression() {
return targetExpression;
}
public void setTargetExpression(String targetExpression) {
this.targetExpression = targetExpression;
} | public String getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(String sourceExpression) {
this.sourceExpression = sourceExpression;
}
@Override
public Variable clone() {
Variable definition = new Variable();
definition.setValues(this);
return definition;
}
public void setValues(Variable otherDefinition) {
setSource(otherDefinition.getSource());
setSourceExpression(otherDefinition.getSourceExpression());
setTarget(otherDefinition.getTarget());
setTargetExpression(otherDefinition.getTargetExpression());
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\VariableAggregationDefinition.java | 1 |
请完成以下Java代码 | public <T> List<T> getDeployedArtifacts(Class<T> clazz) {
if(deployedArtifacts == null) {
return null;
} else {
return (List<T>) deployedArtifacts.get(clazz);
}
}
public void removeArtifact(ResourceDefinitionEntity notDeployedArtifact) {
if (deployedArtifacts != null) {
List artifacts = deployedArtifacts.get(notDeployedArtifact.getClass());
if (artifacts != null) {
artifacts.remove(notDeployedArtifact);
if (artifacts.isEmpty()) {
deployedArtifacts.remove(notDeployedArtifact.getClass());
}
}
}
}
// getters and setters //////////////////////////////////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
}
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isValidatingSchema() {
return validatingSchema;
}
public void setValidatingSchema(boolean validatingSchema) {
this.validatingSchema = validatingSchema;
}
public boolean isNew() {
return isNew;
} | public void setNew(boolean isNew) {
this.isNew = isNew;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<ProcessDefinition> getDeployedProcessDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class);
}
@Override
public List<CaseDefinition> getDeployedCaseDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class);
}
@Override
public List<DecisionDefinition> getDeployedDecisionDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class);
}
@Override
public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class);
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", resources=" + resources
+ ", deploymentTime=" + deploymentTime
+ ", validatingSchema=" + validatingSchema
+ ", isNew=" + isNew
+ ", source=" + source
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@ApiModelProperty(example = "johnDoe")
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
@ApiModelProperty(example = "2018-04-17T10:17:43.902+0000", dataType = "string")
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@ApiModelProperty(example = "3")
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public void setSuperProcessInstanceId(String superProcessInstanceId) {
this.superProcessInstanceId = superProcessInstanceId;
}
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
@ApiModelProperty(example = "3")
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
@ApiModelProperty(example = "cmmn")
public String getCallbackType() { | return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
@ApiModelProperty(example = "123")
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@ApiModelProperty(example = "event-to-bpmn-2.0-process")
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
@ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage")
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "someTenantId")
public String getTenantId() {
return tenantId;
}
// Added by Ryan Johnston
public boolean isCompleted() {
return completed;
}
// Added by Ryan Johnston
public void setCompleted(boolean completed) {
this.completed = completed;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceResponse.java | 2 |
请完成以下Java代码 | private Class<?> getJavaTypeClassOrNull(final I_AD_JavaClass javaClassDef)
{
if (javaClassDef.getAD_JavaClass_Type_ID() <= 0)
{
return null;
}
final I_AD_JavaClass_Type javaClassTypeDef = javaClassDef.getAD_JavaClass_Type();
final String typeClassname = javaClassTypeDef.getClassname();
if (Check.isEmpty(typeClassname, true))
{
return null;
}
final Class<?> typeClass;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) | {
cl = getClass().getClassLoader();
}
try
{
typeClass = cl.loadClass(typeClassname.trim());
}
catch (final ClassNotFoundException e)
{
throw new AdempiereException("Classname not found: " + typeClassname, e);
}
return typeClass;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\impl\JavaClassBL.java | 1 |
请完成以下Java代码 | public IAttributeValuesProvider createAttributeValuesProvider(final AttributeId attributeId)
{
return attributesBL.createAttributeValuesProvider(attributeId);
}
//
//
//
//
//
private static class AttributesIncludedTabMap
{
private static final AttributesIncludedTabMap EMPTY = new AttributesIncludedTabMap(ImmutableList.of());
private final ImmutableListMultimap<AdTableId, AttributesIncludedTabDescriptor> byTableId;
private AttributesIncludedTabMap(final List<AttributesIncludedTabDescriptor> list)
{ | this.byTableId = list.stream()
.sorted(Comparator.comparing(AttributesIncludedTabDescriptor::getParentTableId)
.thenComparing(AttributesIncludedTabDescriptor::getSeqNo))
.collect(ImmutableListMultimap.toImmutableListMultimap(AttributesIncludedTabDescriptor::getParentTableId, tab -> tab));
}
public static AttributesIncludedTabMap of(final List<AttributesIncludedTabDescriptor> list)
{
return list.isEmpty() ? EMPTY : new AttributesIncludedTabMap(list);
}
public List<AttributesIncludedTabDescriptor> listBy(final @NonNull AdTableId adTableId)
{
return byTableId.get(adTableId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\attributes_included_tab\descriptor\AttributesIncludedTabDescriptorService.java | 1 |
请完成以下Java代码 | public HUConsolidationJob assignJob(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId)
{
return jobRepository.updateById(jobId, job -> job.withResponsibleId(callerId));
}
public void abort(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId)
{
AbortCommand.builder()
.jobRepository(jobRepository)
.targetCloser(targetCloser)
//
.jobId(jobId)
.callerId(callerId)
//
.build().execute();
}
public void abortAll(@NonNull final UserId callerId)
{
// TODO
}
public List<HUConsolidationTarget> getAvailableTargets(@NonNull final HUConsolidationJob job)
{
return availableTargetsFinder.getAvailableTargets(job.getCustomerId());
}
public HUConsolidationJob setTarget(@NonNull final HUConsolidationJobId jobId, @Nullable final HUConsolidationTarget target, @NonNull UserId callerId)
{
return SetTargetCommand.builder()
.jobRepository(jobRepository)
//
.callerId(callerId)
.jobId(jobId)
.target(target)
//
.build().execute();
}
public HUConsolidationJob closeTarget(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId)
{
return jobRepository.updateById(jobId, job -> {
job.assertUserCanEdit(callerId);
return targetCloser.closeTarget(job);
});
}
public void printTargetLabel(@NonNull final HUConsolidationJobId jobId, @NotNull final UserId callerId) | {
final HUConsolidationJob job = jobRepository.getById(jobId);
final HUConsolidationTarget currentTarget = job.getCurrentTargetNotNull();
labelPrinter.printLabel(currentTarget);
}
public HUConsolidationJob consolidate(@NonNull final ConsolidateRequest request)
{
return ConsolidateCommand.builder()
.jobRepository(jobRepository)
.huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService)
.request(request)
.build()
.execute();
}
public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId)
{
return GetPickingSlotContentCommand.builder()
.jobRepository(jobRepository)
.huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService)
.jobId(jobId)
.pickingSlotId(pickingSlotId)
.build()
.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobService.java | 1 |
请完成以下Java代码 | public URLConnection openConnection(URL url) throws IOException {
if (url.getPath() == null || url.getPath().trim().length() == 0) {
throw new MalformedURLException("Path can not be null or empty. Syntax: " + SYNTAX);
}
barXmlURL = new URL(url.getPath());
LOGGER.debug("bar xml URL is: [{}]", barXmlURL);
return new Connection(url);
}
public URL getBarXmlURL() {
return barXmlURL;
}
public class Connection extends URLConnection {
public Connection(URL url) {
super(url);
}
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException { | final PipedInputStream pin = new PipedInputStream();
final PipedOutputStream pout = new PipedOutputStream(pin);
new Thread() {
@Override
public void run() {
try {
BarTransformer.transform(barXmlURL, pout);
} catch (Exception e) {
LOGGER.warn("Bundle cannot be generated");
} finally {
try {
pout.close();
} catch (IOException ignore) {
// if we get here something is very wrong
LOGGER.error("Bundle cannot be generated", ignore);
}
}
}
}.start();
return pin;
}
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BarURLHandler.java | 1 |
请完成以下Java代码 | private static LookupValue toLookupValue(DeviceAccessor deviceAccessor)
{
return LookupValue.StringLookupValue.of(deviceAccessor.getId().getAsString(), deviceAccessor.getDisplayName());
}
@Override
protected String doIt()
{
final ImmutableList<PrintableQRCode> qrCodes = streamSelectedDevices()
.map(PrintDeviceQRCodes::toDeviceQRCode)
.map(DeviceQRCode::toPrintableQRCode)
.collect(ImmutableList.toImmutableList());
final QRCodePDFResource pdf = globalQRCodeService.createPDF(qrCodes);
getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType());
return MSG_OK;
}
private Stream<DeviceAccessor> streamSelectedDevices()
{
final DeviceId onlyDeviceId = StringUtils.trimBlankToOptional(p_deviceIdStr)
.map(DeviceId::ofString)
.orElse(null);
if (onlyDeviceId != null)
{
final DeviceAccessor deviceAccessor = deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub()
.getDeviceAccessorById(onlyDeviceId) | .orElseThrow(() -> new AdempiereException("No device found for id: " + onlyDeviceId));
return Stream.of(deviceAccessor);
}
else
{
return deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub()
.streamAllDeviceAccessors();
}
}
private static DeviceQRCode toDeviceQRCode(final DeviceAccessor deviceAccessor)
{
return DeviceQRCode.builder()
.deviceId(deviceAccessor.getId())
.caption(deviceAccessor.getDisplayName().getDefaultValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\devices\webui\process\PrintDeviceQRCodes.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HikariDataSource hikariDataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
config.setUsername("");
config.setPassword("");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("minimumPoolSize", "1");
config.addDataSourceProperty("maximumPoolSize", "3");
config.addDataSourceProperty("connectionTimeout", "1000");
return new HikariDataSource(config);
}
}
class ConnectionAcquireTimeThresholdExceededEventListener extends EventListener<ConnectionAcquireTimeThresholdExceededEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeThresholdExceededEventListener.class);
public ConnectionAcquireTimeThresholdExceededEventListener() {
super(ConnectionAcquireTimeThresholdExceededEvent.class);
}
@Override
public void on(ConnectionAcquireTimeThresholdExceededEvent event) {
LOGGER.info("ConnectionAcquireTimeThresholdExceededEvent Caught event {}", event);
}
}
class ConnectionLeaseTimeThresholdExceededEventListener extends EventListener<ConnectionLeaseTimeThresholdExceededEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLeaseTimeThresholdExceededEventListener.class);
public ConnectionLeaseTimeThresholdExceededEventListener() { | super(ConnectionLeaseTimeThresholdExceededEvent.class);
}
@Override
public void on(ConnectionLeaseTimeThresholdExceededEvent event) {
LOGGER.info("ConnectionLeaseTimeThresholdExceededEvent Caught event {}", event);
}
}
class ConnectionAcquireTimeoutEventListener extends EventListener<ConnectionAcquireTimeoutEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeoutEventListener.class);
public ConnectionAcquireTimeoutEventListener() {
super(ConnectionAcquireTimeoutEvent.class);
}
@Override
public void on(ConnectionAcquireTimeoutEvent event) {
LOGGER.info("ConnectionAcquireTimeoutEvent Caught event {}", event);
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\flexypool\FlexypoolConfig.java | 2 |
请完成以下Java代码 | public Iterator<I_C_Invoice_Candidate> retrieveInvoiceCandidates()
{
final Properties ctx = getCtx();
final String trxName = getTrxName();
final InvoiceCandRecomputeTag recomputeTag = getRecomputeTag();
return invoiceCandDAO.fetchInvalidInvoiceCandidates(ctx, recomputeTag, trxName);
}
@Override
public IInvoiceCandRecomputeTagger setContext(final Properties ctx, final String trxName)
{
this._ctx = ctx;
this._trxName = trxName;
return this;
}
@Override
public final Properties getCtx()
{
Check.assumeNotNull(_ctx, "_ctx not null");
return _ctx;
}
String getTrxName()
{
return _trxName;
}
@Override
public IInvoiceCandRecomputeTagger setRecomputeTag(final InvoiceCandRecomputeTag recomputeTag)
{
this._recomputeTagToUseForTagging = recomputeTag;
return this;
}
private void generateRecomputeTagIfNotSet()
{
// Do nothing if the recompute tag was already generated
if (!InvoiceCandRecomputeTag.isNull(_recomputeTag))
{
return;
}
// Use the recompute tag which was suggested
if (!InvoiceCandRecomputeTag.isNull(_recomputeTagToUseForTagging))
{
_recomputeTag = _recomputeTagToUseForTagging;
return;
}
// Generate a new recompute tag
_recomputeTag = invoiceCandDAO.generateNewRecomputeTag();
}
/**
* @return recompute tag; never returns null
*/
final InvoiceCandRecomputeTag getRecomputeTag()
{
Check.assumeNotNull(_recomputeTag, "_recomputeTag not null");
return _recomputeTag;
}
@Override
public InvoiceCandRecomputeTagger setLockedBy(final ILock lockedBy)
{
this._lockedBy = lockedBy;
return this;
}
/* package */ILock getLockedBy()
{
return _lockedBy;
}
@Override
public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag)
{
_taggedWith = tag;
return this;
}
@Override
public InvoiceCandRecomputeTagger setTaggedWithNoTag()
{
return setTaggedWith(InvoiceCandRecomputeTag.NULL);
} | @Override
public IInvoiceCandRecomputeTagger setTaggedWithAnyTag()
{
return setTaggedWith(null);
}
/* package */
@Nullable
InvoiceCandRecomputeTag getTaggedWith()
{
return _taggedWith;
}
@Override
public InvoiceCandRecomputeTagger setLimit(final int limit)
{
this._limit = limit;
return this;
}
/* package */int getLimit()
{
return _limit;
}
@Override
public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds)
{
this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds;
}
@Override
@Nullable
public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds()
{
return onlyInvoiceCandidateIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java | 1 |
请完成以下Java代码 | class ClickHouseR2dbcDockerComposeConnectionDetailsFactory
extends DockerComposeConnectionDetailsFactory<R2dbcConnectionDetails> {
ClickHouseR2dbcDockerComposeConnectionDetailsFactory() {
super("clickhouse/clickhouse-server", "io.r2dbc.spi.ConnectionFactoryOptions");
}
@Override
protected R2dbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new ClickhouseDbR2dbcDockerComposeConnectionDetails(source.getRunningService());
}
/**
* {@link R2dbcConnectionDetails} backed by a {@code clickhouse}
* {@link RunningService}.
*/
static class ClickhouseDbR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements R2dbcConnectionDetails {
private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder(
"clickhouse", 8123); | private final ConnectionFactoryOptions connectionFactoryOptions;
ClickhouseDbR2dbcDockerComposeConnectionDetails(RunningService service) {
super(service);
ClickHouseEnvironment environment = new ClickHouseEnvironment(service.env());
this.connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, environment.getDatabase(),
environment.getUsername(), environment.getPassword());
}
@Override
public ConnectionFactoryOptions getConnectionFactoryOptions() {
return this.connectionFactoryOptions;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\ClickHouseR2dbcDockerComposeConnectionDetailsFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderResponsePackageItemPartId
{
@JsonCreator
public static OrderResponsePackageItemPartId of(final String valueAsString)
{
return new OrderResponsePackageItemPartId(valueAsString);
}
public static OrderResponsePackageItemPartId random()
{
return new OrderResponsePackageItemPartId(UUID.randomUUID().toString());
}
private final String valueAsString;
private OrderResponsePackageItemPartId(@NonNull final String valueAsString)
{
if (valueAsString.isEmpty())
{
throw new IllegalArgumentException("value shall not be empty");
}
this.valueAsString = valueAsString;
} | /**
* @deprecated please use {@link #getValueAsString()}
*/
@Override
@Deprecated
public String toString()
{
return getValueAsString();
}
@JsonValue
public String toJson()
{
return getValueAsString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderResponsePackageItemPartId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Rule insert(Rule rule) {
rule.setCreateTime(new Date());
rule.setUpdateTime(new Date());
ruleMapper.insertSelective(rule);
return rule;
}
@Override
public KieSession getKieSessionByName(String ruleKey) {
StatefulKnowledgeSession kSession = null;
try {
long startTime = System.currentTimeMillis();
// TODO 可以缓存到本地,不用每次都去查数据库
Rule rule = ruleMapper.findByRuleKey(ruleKey);
KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
// 装入规则,可以装入多个
kb.add(ResourceFactory.newByteArrayResource(rule.getContent().getBytes("utf-8")), ResourceType.DRL);
// 检查错误
KnowledgeBuilderErrors errors = kb.getErrors();
for (KnowledgeBuilderError error : errors) {
System.out.println(error);
}
// TODO 没有找到替代方法
KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
kBase.addKnowledgePackages(kb.getKnowledgePackages());
// 创建kSession
kSession = kBase.newStatefulKnowledgeSession();
long endTime = System.currentTimeMillis();
logger.info("获取kSession耗时:{}", endTime - startTime);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return kSession;
}
// 不使用kieContainer这种方式,因为创建kSession的时候只能用kieContainer.newKieSession(),
// 不能指定要创建那个kSession,在执行规则的时候会把所有的规则都执行一次
@Override
public void reloadRule() {
KieContainer kieContainer = loadContainerFromString(findAll());
}
private KieContainer loadContainerFromString(List<Rule> rules) {
long startTime = System.currentTimeMillis(); | KieServices ks = KieServices.Factory.get();
KieRepository kr = ks.getRepository();
KieFileSystem kfs = ks.newKieFileSystem();
for (Rule rule : rules) {
String drl = rule.getContent();
kfs.write("src/main/resources/" + drl.hashCode() + ".drl", drl);
}
KieBuilder kb = ks.newKieBuilder(kfs);
kb.buildAll();
if (kb.getResults().hasMessages(Message.Level.ERROR)) {
throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
}
long endTime = System.currentTimeMillis();
System.out.println("Time to build rules : " + (endTime - startTime) + " ms");
startTime = System.currentTimeMillis();
KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
endTime = System.currentTimeMillis();
System.out.println("Time to load container: " + (endTime - startTime) + " ms");
return kContainer;
}
} | repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\service\impl\RuleServiceImpl.java | 2 |
请完成以下Java代码 | public Object transformTuple(Object[] os, String[] strings) {
Long authorId = ((Number) os[0]).longValue();
AuthorDto authorDto = authorsDtoMap.get(authorId);
if (authorDto == null) {
authorDto = new AuthorDto();
authorDto.setId(((Number) os[0]).longValue());
authorDto.setName((String) os[1]);
authorDto.setAge((int) os[2]);
}
BookDto bookDto = new BookDto();
bookDto.setId(((Number) os[3]).longValue()); | bookDto.setTitle((String) os[4]);
authorDto.addBook(bookDto);
authorsDtoMap.putIfAbsent(authorDto.getId(), authorDto);
return authorDto;
}
@Override
public List<AuthorDto> transformList(List list) {
return new ArrayList<>(authorsDtoMap.values());
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoCustomResultTransformer\src\main\java\com\bookstore\transformer\AuthorBookTransformer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Tweet {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String tweet;
private String owner;
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
@CollectionTable(name = "Tweet_Likes")
private Set<String> likes = new HashSet<>();
public Tweet() {
}
public Tweet(String tweet, String owner) {
this.tweet = tweet;
this.owner = owner;
}
public long getId() {
return id;
}
public void setId(long id) { | this.id = id;
}
public String getTweet() {
return tweet;
}
public void setTweet(String tweet) {
this.tweet = tweet;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Set<String> getLikes() {
return likes;
}
public void setLikes(Set<String> likes) {
this.likes = likes;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\models\Tweet.java | 2 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, DMN_ELEMENT_DEFINITIONS)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() {
public Definitions newInstance(ModelTypeInstanceContext instanceContext) {
return new DefinitionsImpl(instanceContext);
}
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
namespaceAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAMESPACE)
.required()
.build();
exporterAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER)
.build();
exporterVersionAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER_VERSION)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importCollection = sequenceBuilder.elementCollection(Import.class)
.build();
itemDefinitionCollection = sequenceBuilder.elementCollection(ItemDefinition.class)
.build(); | drgElementCollection = sequenceBuilder.elementCollection(DrgElement.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
elementCollectionCollection = sequenceBuilder.elementCollection(ElementCollection.class)
.build();
businessContextElementCollection = sequenceBuilder.elementCollection(BusinessContextElement.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DefinitionsImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String encode(CharSequence charSequence) {
System.out.println(charSequence.toString());
return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
}
//对密码进行判断匹配
@Override
public boolean matches(CharSequence charSequence, String s) {
String encode = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
boolean res = s.equals( encode );
return res;
}
} );
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
//因为使用JWT,所以不需要HttpSession
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
//OPTIONS请求全部放行
.antMatchers( HttpMethod.OPTIONS, "/**").permitAll()
//登录接口放行
.antMatchers("/auth/login").permitAll()
//其他接口全部接受验证
.anyRequest().authenticated();
//使用自定义的 Token过滤器 验证请求的Token是否合法
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); | http.headers().cacheControl();
}
@Bean
public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtTokenFilter();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\SecurityConfig.java | 2 |
请完成以下Java代码 | public SendEventActivityBehavior createSendEventActivityBehavior(PlanItem planItem, SendEventServiceTask sendEventServiceTask) {
return new SendEventActivityBehavior(sendEventServiceTask);
}
@Override
public ExternalWorkerTaskActivityBehavior createExternalWorkerActivityBehaviour(PlanItem planItem, ExternalWorkerServiceTask externalWorkerServiceTask) {
return new ExternalWorkerTaskActivityBehavior(externalWorkerServiceTask);
}
@Override
public ScriptTaskActivityBehavior createScriptTaskActivityBehavior(PlanItem planItem, ScriptServiceTask task) {
return new ScriptTaskActivityBehavior(task);
}
@Override
public CasePageTaskActivityBehaviour createCasePageTaskActivityBehaviour(PlanItem planItem, CasePageTask task) {
return new CasePageTaskActivityBehaviour(task);
}
public void setClassDelegateFactory(CmmnClassDelegateFactory classDelegateFactory) { | this.classDelegateFactory = classDelegateFactory;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
protected Expression createExpression(String refExpressionString) {
Expression expression = null;
if (StringUtils.isNotEmpty(refExpressionString)) {
expression = expressionManager.createExpression(refExpressionString);
}
return expression;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\DefaultCmmnActivityBehaviorFactory.java | 1 |
请完成以下Java代码 | public class TestingClassInstanceProvider implements IClassInstanceProvider
{
public static final TestingClassInstanceProvider instance = new TestingClassInstanceProvider();
private IClassInstanceProvider internalImpl = ClassInstanceProvider.instance;
private TestingClassInstanceProvider()
{
}
/**
* See {@link #throwExceptionForClassName(String, ReflectiveOperationException)}.
*/
private final Map<String, ReflectiveOperationException> className2Exception = new HashMap<String, ReflectiveOperationException>();
/**
* Allows unit tests to set exceptions that shall be thrown if certain classes are loaded using {@link #getInstance(Class, String)} and {@link #getInstanceOrNull(Class, String)}.
*/
public void throwExceptionForClassName(final String className, final ReflectiveOperationException exception)
{
className2Exception.put(className, exception);
}
/**
* See {@link #throwExceptionForClassName(String, RuntimeException)}.
*/
public void clearExceptionsForClassNames()
{
className2Exception.clear();
}
@Override
public Class<?> provideClass(final String className) throws ReflectiveOperationException | {
// for unit testing: allow us to test with class loading failures.
if (className2Exception.containsKey(className))
{
throw className2Exception.get(className);
}
return internalImpl.provideClass(className);
}
@Override
public <T> T provideInstance(final Class<T> interfaceClazz, final Class<?> instanceClazz) throws ReflectiveOperationException
{
// for unit testing: allow us to test with class loading failures.
if (className2Exception.containsKey(instanceClazz.getName()))
{
throw className2Exception.get(instanceClazz.getName());
}
return internalImpl.provideInstance(interfaceClazz, instanceClazz);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\TestingClassInstanceProvider.java | 1 |
请完成以下Java代码 | protected boolean isAssignable() {
return this.assignable;
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
this.delegates.values().forEach(del -> del.configure(configs, isKey));
}
@SuppressWarnings("NullAway") // Dataflow analysis limitation
@Override
public byte[] serialize(String topic, Object data) {
if (data == null) {
return null;
}
Serializer<Object> delegate = findDelegate(data);
return delegate.serialize(topic, data);
}
@SuppressWarnings("NullAway") // Dataflow analysis limitation
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
if (data == null) {
return null;
}
Serializer<Object> delegate = findDelegate(data);
return delegate.serialize(topic, headers, data);
}
protected <T> Serializer<T> findDelegate(T data) {
return findDelegate(data, this.delegates);
}
/**
* Determine the serializer for the data type.
* @param data the data.
* @param delegates the available delegates.
* @param <T> the data type
* @return the delegate.
* @throws SerializationException when there is no match.
* @since 2.8.3 | */
@SuppressWarnings("unchecked")
protected <T> Serializer<T> findDelegate(T data, Map<Class<?>, Serializer<?>> delegates) {
if (!this.assignable) {
Serializer<?> delegate = delegates.get(data.getClass());
if (delegate == null) {
throw new SerializationException("No matching delegate for type: " + data.getClass().getName()
+ "; supported types: " + delegates.keySet().stream()
.map(Class::getName)
.toList());
}
return (Serializer<T>) delegate;
}
else {
for (Entry<Class<?>, Serializer<?>> entry : delegates.entrySet()) {
if (entry.getKey().isAssignableFrom(data.getClass())) {
return (Serializer<T>) entry.getValue();
}
}
throw new SerializationException("No matching delegate for type: " + data.getClass().getName()
+ "; supported types: " + delegates.keySet().stream()
.map(Class::getName)
.toList());
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTypeSerializer.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj; | if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Foo.java | 1 |
请完成以下Java代码 | public void parse(XMLStreamReader xtr, Process activeProcess) throws Exception {
String resourceElement = XMLStreamReaderUtil.moveDown(xtr);
if (StringUtils.isNotEmpty(resourceElement) && "resourceAssignmentExpression".equals(resourceElement)) {
String expression = XMLStreamReaderUtil.moveDown(xtr);
if (StringUtils.isNotEmpty(expression) && "formalExpression".equals(expression)) {
List<String> assignmentList = new ArrayList<String>();
String assignmentText = xtr.getElementText();
if (assignmentText.contains(",")) {
String[] assignmentArray = assignmentText.split(",");
assignmentList = asList(assignmentArray);
} else {
assignmentList.add(assignmentText);
}
for (String assignmentValue : assignmentList) {
if (assignmentValue == null) continue;
assignmentValue = assignmentValue.trim();
if (assignmentValue.length() == 0) continue;
String userPrefix = "user(";
String groupPrefix = "group("; | if (assignmentValue.startsWith(userPrefix)) {
assignmentValue = assignmentValue
.substring(userPrefix.length(), assignmentValue.length() - 1)
.trim();
activeProcess.getCandidateStarterUsers().add(assignmentValue);
} else if (assignmentValue.startsWith(groupPrefix)) {
assignmentValue = assignmentValue
.substring(groupPrefix.length(), assignmentValue.length() - 1)
.trim();
activeProcess.getCandidateStarterGroups().add(assignmentValue);
} else {
activeProcess.getCandidateStarterGroups().add(assignmentValue);
}
}
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\PotentialStarterParser.java | 1 |
请完成以下Java代码 | public boolean hasChangesRecursivelly()
{
return false;
}
@Override
public void saveIfHasChanges()
{
}
@Override
public void markStaleAll()
{
}
@Override | public void markStale(final DocumentIdsSelection rowIds)
{
}
@Override
public boolean isStale()
{
return false;
}
@Override
public int getNextLineNo()
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadonlyIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | protected String autodetectProcessApplicationName() {
return beanName;
}
public ProcessApplicationReference getReference() {
return new ProcessApplicationReferenceImpl(this);
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
try {
// we only want to listen for context events of the main application
// context, not its children
if (event.getSource().equals(applicationContext)) {
if (event instanceof ContextRefreshedEvent && !isDeployed) {
// deploy the process application
afterPropertiesSet();
} else if (event instanceof ContextClosedEvent) {
// undeploy the process application
destroy();
} else {
// ignore
}
}
} catch (Exception e) { | throw new RuntimeException(e);
}
}
public void start() {
deploy();
}
public void stop() {
undeploy();
}
public void afterPropertiesSet() throws Exception {
// for backwards compatibility
start();
}
public void destroy() throws Exception {
// for backwards compatibility
stop();
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\application\SpringProcessApplication.java | 1 |
请完成以下Java代码 | class InfoUpdater implements Runnable
{
boolean stop = false;
@Override
public void run()
{
final int sleep = Services.get(ISysConfigBL.class).getIntValue("MENU_INFOUPDATER_SLEEP_MS", 60000, Env.getAD_Client_ID(Env.getCtx()));
while (stop == false)
{
updateInfo();
try
{
synchronized (this)
{
this.wait(sleep);
}
}
catch (InterruptedException ire)
{
}
}
}
}
private static AdTreeId retrieveMenuTreeId(final Properties ctx)
{
final IUserRolePermissions userRolePermissions = Env.getUserRolePermissions(ctx);
if (!userRolePermissions.hasPermission(IUserRolePermissions.PERMISSION_MenuAvailable))
{
return null;
}
return userRolePermissions.getMenuInfo().getAdTreeId();
}
public FormFrame startForm(final int AD_Form_ID)
{
// metas: tsa: begin: US831: Open one window per session per user (2010101810000044)
final Properties ctx = Env.getCtx();
final I_AD_Form form = InterfaceWrapperHelper.create(ctx, AD_Form_ID, I_AD_Form.class, ITrx.TRXNAME_None); | if (form == null)
{
ADialog.warn(0, null, "Error", msgBL.parseTranslation(ctx, "@NotFound@ @AD_Form_ID@"));
return null;
}
final WindowManager windowManager = getWindowManager();
// metas: tsa: end: US831: Open one window per session per user (2010101810000044)
if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW) || form.isOneInstanceOnly()) // metas: tsa: us831
{
final FormFrame ffExisting = windowManager.findForm(AD_Form_ID);
if (ffExisting != null)
{
AEnv.showWindow(ffExisting); // metas: tsa: use this method because toFront() is not working when window is minimized
// ff.toFront(); // metas: tsa: commented original code
return ffExisting;
}
}
final FormFrame ff = new FormFrame();
final boolean ok = ff.openForm(form); // metas: tsa: us831
if (!ok)
{
ff.dispose();
return null;
}
windowManager.add(ff);
// Center the window
ff.showFormWindow();
return ff;
} // startForm
} // AMenu | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AMenu.java | 1 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getActivityName() {
return activityName;
}
public String getActivityType() {
return activityType; | }
public String getAssignee() {
return assignee;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java | 1 |
请完成以下Java代码 | private boolean isScoreEqual() {
return server.pointsDifference(receiver) == 0;
}
private boolean isAdvantage() {
return leadingPlayer().hasScoreBiggerThan(Score.FORTY)
&& Math.abs(server.pointsDifference(receiver)) == 1;
}
private boolean isGameFinished() {
return leadingPlayer().hasScoreBiggerThan(Score.FORTY)
&& Math.abs(server.pointsDifference(receiver)) >= 2;
}
private Player leadingPlayer() {
if (server.pointsDifference(receiver) > 0) {
return server;
}
return receiver;
} | private boolean gameContinues() {
return !isGameFinished();
}
private String getSimpleScore() {
return String.format("%s-%s", server.score(), receiver.score());
}
private String getEqualScore() {
if (server.hasScoreBiggerThan(Score.THIRTY)) {
return "Deuce";
}
return String.format("%s-All", server.score());
}
} | repos\tutorials-master\patterns-modules\clean-architecture\src\main\java\com\baeldung\pattern\richdomainmodel\TennisGame.java | 1 |
请完成以下Java代码 | public void setQtyRanking (int QtyRanking)
{
set_ValueNoCheck (COLUMNNAME_QtyRanking, Integer.valueOf(QtyRanking));
}
/** Get Quantity Ranking.
@return Quantity Ranking */
@Override
public int getQtyRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_QtyRanking);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ranking.
@param Ranking
Relative Rank Number | */
@Override
public void setRanking (int Ranking)
{
set_ValueNoCheck (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_RV_C_RfQResponse.java | 1 |
请完成以下Java代码 | private void checkCosting(final I_C_AcctSchema acctSchema)
{
// Create Cost Type
if (acctSchema.getM_CostType_ID() <= 0)
{
final I_M_CostType costType = InterfaceWrapperHelper.newInstance(I_M_CostType.class);
costType.setAD_Org_ID(Env.CTXVALUE_AD_Org_ID_Any);
costType.setName(acctSchema.getName());
InterfaceWrapperHelper.save(costType);
acctSchema.setM_CostType_ID(costType.getM_CostType_ID());
}
// Create Cost Elements
final ClientId clientId = ClientId.ofRepoId(acctSchema.getAD_Client_ID());
costElementRepo.getOrCreateMaterialCostElement(clientId, CostingMethod.ofNullableCode(acctSchema.getCostingMethod()));
// Default Costing Level
if (acctSchema.getCostingLevel() == null)
{
acctSchema.setCostingLevel(CostingLevel.Client.getCode());
}
if (acctSchema.getCostingMethod() == null)
{
acctSchema.setCostingMethod(CostingMethod.StandardCosting.getCode()); | }
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_C_AcctSchema.COLUMNNAME_C_Currency_ID)
public void checkCurrency(final I_C_AcctSchema acctSchema)
{
if(DISABLE_CHECK_CURRENCY.getValue(acctSchema, Boolean.FALSE))
{
logger.debug("Skip currency check for {} because of dynamic attribute {}", acctSchema, DISABLE_CHECK_CURRENCY);
return;
}
final PO po = InterfaceWrapperHelper.getPO(acctSchema);
final CurrencyId previousCurrencyId = CurrencyId.ofRepoIdOrNull(po.get_ValueOldAsInt(I_C_AcctSchema.COLUMNNAME_C_Currency_ID));
if (previousCurrencyId != null && currentCostsRepository.hasCostsInCurrency(AcctSchemaId.ofRepoId(acctSchema.getC_AcctSchema_ID()), previousCurrencyId))
{
throw new AdempiereException(MSG_ACCT_SCHEMA_HAS_ASSOCIATED_COSTS);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_AcctSchema.java | 1 |
请完成以下Java代码 | public static List<LockedExternalTaskDto> fromLockedExternalTasks(List<LockedExternalTask> tasks) {
List<LockedExternalTaskDto> dtos = new ArrayList<>();
for (LockedExternalTask task : tasks) {
dtos.add(LockedExternalTaskDto.fromLockedExternalTask(task));
}
return dtos;
}
@Override
public String toString() {
return
"LockedExternalTaskDto [activityId=" + activityId
+ ", activityInstanceId=" + activityInstanceId
+ ", errorMessage=" + errorMessage
+ ", errorDetails=" + errorDetails
+ ", executionId=" + executionId | + ", id=" + id
+ ", lockExpirationTime=" + lockExpirationTime
+ ", createTime=" + createTime
+ ", processDefinitionId=" + processDefinitionId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", processDefinitionVersionTag=" + processDefinitionVersionTag
+ ", processInstanceId=" + processInstanceId
+ ", retries=" + retries
+ ", suspended=" + suspended
+ ", workerId=" + workerId
+ ", topicName=" + topicName
+ ", tenantId=" + tenantId
+ ", variables=" + variables
+ ", priority=" + priority
+ ", businessKey=" + businessKey + "]";
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\LockedExternalTaskDto.java | 1 |
请完成以下Java代码 | public StockQtyAndUOMQty minUomQty(
@NonNull final StockQtyAndUOMQty qtysToCompare1,
@NonNull final StockQtyAndUOMQty qtysToCompare2)
{
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final ProductId productId = extractCommonProductId(qtysToCompare1, qtysToCompare2);
final Quantity uomQty1 = qtysToCompare1.getUOMQtyNotNull();
final Quantity uomQty2 = uomConversionBL.convertQuantityTo(
qtysToCompare2.getUOMQtyNotNull(),
UOMConversionContext.of(productId),
qtysToCompare1.getUOMQtyNotNull().getUomId());
return uomQty1.compareTo(uomQty2) <= 0 ? qtysToCompare1 : qtysToCompare2;
}
/**
* @return The argument with the bigger UOM-quantity. If both have the same size, then the <b>first</b> argument is returned.
*/
public StockQtyAndUOMQty maxUomQty(
@NonNull final StockQtyAndUOMQty qtysToCompare1,
@NonNull final StockQtyAndUOMQty qtysToCompare2)
{
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final ProductId productId = extractCommonProductId(qtysToCompare1, qtysToCompare2);
final Quantity uomQty1 = qtysToCompare1.getUOMQtyNotNull();
final Quantity uomQty2 = uomConversionBL.convertQuantityTo( | qtysToCompare2.getUOMQtyNotNull(),
UOMConversionContext.of(productId),
qtysToCompare1.getUOMQtyNotNull().getUomId());
return uomQty1.compareTo(uomQty2) >= 0 ? qtysToCompare1 : qtysToCompare2;
}
public int compareUomQty(
@NonNull final StockQtyAndUOMQty qtysToCompare1,
@NonNull final StockQtyAndUOMQty qtysToCompare2)
{
final Quantity uomQty1 = qtysToCompare1.getUOMQtyNotNull();
final ProductId productId = extractCommonProductId(qtysToCompare1, qtysToCompare2);
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final Quantity uomQty2 = uomConversionBL.convertQuantityTo(
qtysToCompare2.getUOMQtyNotNull(),
UOMConversionContext.of(productId),
qtysToCompare1.getUOMQtyNotNull().getUomId());
return uomQty1.compareTo(uomQty2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\StockQtyAndUOMQtys.java | 1 |
请完成以下Java代码 | public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Write-off Amount.
@param WriteOffAmt
Amount to write-off
*/ | @Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Write-off Amount.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java | 1 |
请完成以下Java代码 | public final class PermissionsPolicyHeaderWriter implements HeaderWriter {
private static final String PERMISSIONS_POLICY_HEADER = "Permissions-Policy";
private @Nullable String policy;
/**
* Create a new instance of {@link PermissionsPolicyHeaderWriter}.
*/
public PermissionsPolicyHeaderWriter() {
}
/**
* Create a new instance of {@link PermissionsPolicyHeaderWriter} with supplied
* security policy.
* @param policy the security policy
* @throws IllegalArgumentException if policy is {@code null} or empty
*/
public PermissionsPolicyHeaderWriter(String policy) {
setPolicy(policy);
} | /**
* Sets the policy to be used in the response header.
* @param policy a permissions policy
* @throws IllegalArgumentException if policy is null
*/
public void setPolicy(String policy) {
Assert.hasLength(policy, "policy can not be null or empty");
this.policy = policy;
}
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (!response.containsHeader(PERMISSIONS_POLICY_HEADER)) {
response.setHeader(PERMISSIONS_POLICY_HEADER, this.policy);
}
}
@Override
public String toString() {
return getClass().getName() + " [policy=" + this.policy + "]";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\PermissionsPolicyHeaderWriter.java | 1 |
请完成以下Spring Boot application配置 | ##
server.port=9090
logging.level.root=INFO
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/world?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
## M | ybatis 配置
mybatis.typeAliasesPackage=com.quick.entity
## 需要注意的地方
mybatis.mapperLocations=classpath:mapper/*.xml | repos\spring-boot-quick-master\quick-package-assembly\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private boolean isStatusCodeToCache(ServerHttpResponse response) {
return statusesToCache.contains(response.getStatusCode());
}
boolean isRequestCacheable(ServerHttpRequest request) {
return HttpMethod.GET.equals(request.getMethod()) && !hasRequestBody(request) && isCacheControlAllowed(request);
}
private boolean isVaryWildcard(ServerHttpResponse response) {
HttpHeaders headers = response.getHeaders();
List<String> varyValues = headers.getOrEmpty(HttpHeaders.VARY);
return varyValues.stream().anyMatch(VARY_WILDCARD::equals);
}
private boolean isCacheControlAllowed(HttpMessage request) {
HttpHeaders headers = request.getHeaders();
List<String> cacheControlHeader = headers.getOrEmpty(HttpHeaders.CACHE_CONTROL);
return cacheControlHeader.stream().noneMatch(forbiddenCacheControlValues::contains);
}
private static boolean hasRequestBody(ServerHttpRequest request) { | return request.getHeaders().getContentLength() > 0;
}
private void saveInCache(String cacheKey, CachedResponse cachedResponse) {
try {
cache.put(cacheKey, cachedResponse);
}
catch (RuntimeException anyException) {
LOGGER.error("Error writing into cache. Data will not be cached", anyException);
}
}
private void saveMetadataInCache(String metadataKey, CachedResponseMetadata metadata) {
try {
cache.put(metadataKey, metadata);
}
catch (RuntimeException anyException) {
LOGGER.error("Error writing into cache. Data will not be cached", anyException);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SmsHomeBrandController {
@Autowired
private SmsHomeBrandService homeBrandService;
@ApiOperation("添加首页推荐品牌")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody List<SmsHomeBrand> homeBrandList) {
int count = homeBrandService.create(homeBrandList);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("修改推荐品牌排序")
@RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateSort(@PathVariable Long id, Integer sort) {
int count = homeBrandService.updateSort(id, sort);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("批量删除推荐品牌")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = homeBrandService.delete(ids);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed(); | }
@ApiOperation("批量修改推荐品牌状态")
@RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) {
int count = homeBrandService.updateRecommendStatus(ids, recommendStatus);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("分页查询推荐品牌")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsHomeBrand>> list(@RequestParam(value = "brandName", required = false) String brandName,
@RequestParam(value = "recommendStatus", required = false) Integer recommendStatus,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsHomeBrand> homeBrandList = homeBrandService.list(brandName, recommendStatus, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(homeBrandList));
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsHomeBrandController.java | 2 |
请完成以下Java代码 | private ImmutableList<ViewChanges> getAndClean()
{
if (viewChangesMap.isEmpty())
{
return ImmutableList.of();
}
final ImmutableList<ViewChanges> changesList = ImmutableList.copyOf(viewChangesMap.values());
viewChangesMap.clear();
return changesList;
}
private void sendToWebsocket(@NonNull final List<JSONViewChanges> jsonChangeEvents)
{
if (jsonChangeEvents.isEmpty())
{
return;
}
WebsocketSender websocketSender = _websocketSender;
if (websocketSender == null) | {
websocketSender = this._websocketSender = SpringContextHolder.instance.getBean(WebsocketSender.class);
}
try
{
websocketSender.convertAndSend(jsonChangeEvents);
logger.debug("Sent to websocket: {}", jsonChangeEvents);
}
catch (final Exception ex)
{
logger.warn("Failed sending to websocket {}: {}", jsonChangeEvents, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChangesCollector.java | 1 |
请完成以下Java代码 | public static EngineInfo getDmnEngineInfo(String dmnEngineName) {
return dmnEngineInfosByName.get(dmnEngineName);
}
public static DmnEngine getDefaultDmnEngine() {
return getDmnEngine(NAME_DEFAULT);
}
/**
* obtain a dmn engine by name.
*
* @param dmnEngineName
* is the name of the dmn engine or null for the default dmn engine.
*/
public static DmnEngine getDmnEngine(String dmnEngineName) {
if (!isInitialized()) {
init();
}
return dmnEngines.get(dmnEngineName);
}
/**
* retries to initialize a dmn engine that previously failed.
*/
public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initDmnEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to dmn engine to application clients in a managed server environment.
*/
public static Map<String, DmnEngine> getDmnEngines() {
return dmnEngines;
}
/**
* closes all dmn engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, DmnEngine> engines = new HashMap<>(dmnEngines); | dmnEngines = new HashMap<>();
for (String dmnEngineName : engines.keySet()) {
DmnEngine dmnEngine = engines.get(dmnEngineName);
try {
dmnEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (dmnEngineName == null ? "the default dmn engine" : "dmn engine " + dmnEngineName), e);
}
}
dmnEngineInfosByName.clear();
dmnEngineInfosByResourceUrl.clear();
dmnEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
DmnEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngines.java | 1 |
请完成以下Java代码 | public final class AllocablePackageable
{
@NonNull private final SourceDocumentInfo sourceDocumentInfo;
@NonNull private final BPartnerId customerId;
@NonNull private final ProductId productId;
@NonNull private final AttributeSetInstanceId asiId;
@NonNull private final Optional<ShipmentAllocationBestBeforePolicy> bestBeforePolicy;
@NonNull private final WarehouseId warehouseId;
@Nullable private final PPOrderId pickFromOrderId;
@Nullable private final IssueToBOMLine issueToBOMLine;
@NonNull private final Quantity qtyToAllocateTarget;
@NonNull private Quantity qtyToAllocate;
@Builder(toBuilder = true)
private AllocablePackageable(
@NonNull final SourceDocumentInfo sourceDocumentInfo,
@NonNull final BPartnerId customerId,
@NonNull final ProductId productId,
@Nullable final AttributeSetInstanceId asiId,
@Nullable final Optional<ShipmentAllocationBestBeforePolicy> bestBeforePolicy,
@NonNull final WarehouseId warehouseId,
@Nullable final PPOrderId pickFromOrderId,
@Nullable final IssueToBOMLine issueToBOMLine,
@NonNull final Quantity qtyToAllocateTarget)
{
this.sourceDocumentInfo = sourceDocumentInfo;
this.customerId = customerId;
this.productId = productId;
this.asiId = asiId != null ? asiId : AttributeSetInstanceId.NONE;
this.bestBeforePolicy = bestBeforePolicy != null ? bestBeforePolicy : Optional.empty();
this.warehouseId = warehouseId;
this.pickFromOrderId = pickFromOrderId; | this.issueToBOMLine = issueToBOMLine;
this.qtyToAllocateTarget = qtyToAllocateTarget;
this.qtyToAllocate = qtyToAllocateTarget;
}
public void allocateQty(@NonNull final Quantity qty)
{
qtyToAllocate = qtyToAllocate.subtract(qty);
}
public boolean isAllocated()
{
return getQtyToAllocate().signum() == 0;
}
public Optional<HUReservationDocRef> getReservationRef()
{
return Optional.ofNullable(sourceDocumentInfo.getSalesOrderLineId()).map(HUReservationDocRef::ofSalesOrderLineId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\AllocablePackageable.java | 1 |
请完成以下Java代码 | protected void removeAllDecisionRequirementsDefinitionsByDeploymentId(String deploymentId) {
// remove all decision requirements definitions for a specific deployment
List<DecisionRequirementsDefinition> allDefinitionsForDeployment = new DecisionRequirementsDefinitionQueryImpl()
.deploymentId(deploymentId)
.list();
for (DecisionRequirementsDefinition decisionRequirementsDefinition : allDefinitionsForDeployment) {
try {
removeDecisionDefinition(decisionRequirementsDefinition.getId());
} catch (Exception e) {
ProcessEngineLogger.PERSISTENCE_LOGGER
.removeEntryFromDeploymentCacheFailure("decision requirement", decisionRequirementsDefinition.getId(), e);
}
}
}
public CachePurgeReport purgeCache() {
CachePurgeReport result = new CachePurgeReport();
Cache<String, ProcessDefinitionEntity> processDefinitionCache = getProcessDefinitionCache();
if (!processDefinitionCache.isEmpty()) {
result.addPurgeInformation(CachePurgeReport.PROCESS_DEF_CACHE, processDefinitionCache.keySet());
processDefinitionCache.clear();
}
Cache<String, BpmnModelInstance> bpmnModelInstanceCache = getBpmnModelInstanceCache();
if (!bpmnModelInstanceCache.isEmpty()) {
result.addPurgeInformation(CachePurgeReport.BPMN_MODEL_INST_CACHE, bpmnModelInstanceCache.keySet());
bpmnModelInstanceCache.clear();
}
Cache<String, CaseDefinitionEntity> caseDefinitionCache = getCaseDefinitionCache();
if (!caseDefinitionCache.isEmpty()) {
result.addPurgeInformation(CachePurgeReport.CASE_DEF_CACHE, caseDefinitionCache.keySet());
caseDefinitionCache.clear();
}
Cache<String, CmmnModelInstance> cmmnModelInstanceCache = getCmmnModelInstanceCache();
if (!cmmnModelInstanceCache.isEmpty()) {
result.addPurgeInformation(CachePurgeReport.CASE_MODEL_INST_CACHE, cmmnModelInstanceCache.keySet());
cmmnModelInstanceCache.clear();
}
Cache<String, DecisionDefinitionEntity> decisionDefinitionCache = getDecisionDefinitionCache();
if (!decisionDefinitionCache.isEmpty()) { | result.addPurgeInformation(CachePurgeReport.DMN_DEF_CACHE, decisionDefinitionCache.keySet());
decisionDefinitionCache.clear();
}
Cache<String, DmnModelInstance> dmnModelInstanceCache = getDmnDefinitionCache();
if (!dmnModelInstanceCache.isEmpty()) {
result.addPurgeInformation(CachePurgeReport.DMN_MODEL_INST_CACHE, dmnModelInstanceCache.keySet());
dmnModelInstanceCache.clear();
}
Cache<String, DecisionRequirementsDefinitionEntity> decisionRequirementsDefinitionCache = getDecisionRequirementsDefinitionCache();
if (!decisionRequirementsDefinitionCache.isEmpty()) {
result.addPurgeInformation(CachePurgeReport.DMN_REQ_DEF_CACHE, decisionRequirementsDefinitionCache.keySet());
decisionRequirementsDefinitionCache.clear();
}
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\DeploymentCache.java | 1 |
请完成以下Java代码 | public SpinJsonNode element() {
try {
Object result = query.read(spinJsonNode.toString(), dataFormat.getJsonPathConfiguration());
JsonNode node;
if (result != null) {
node = dataFormat.createJsonNode(result);
} else {
node = dataFormat.createNullJsonNode();
}
return dataFormat.createWrapperInstance(node);
} catch(PathNotFoundException pex) {
throw LOG.unableToEvaluateJsonPathExpressionOnNode(spinJsonNode, pex);
} catch (ClassCastException cex) {
throw LOG.unableToCastJsonPathResultTo(SpinJsonNode.class, cex);
} catch(InvalidPathException iex) {
throw LOG.invalidJsonPath(SpinJsonNode.class, iex);
}
}
public SpinList<SpinJsonNode> elementList() {
JacksonJsonNode node = (JacksonJsonNode) element();
if(node.isArray()) {
return node.elements();
} else {
throw LOG.unableToParseValue(SpinList.class.getSimpleName(), node.getNodeType());
}
}
public String stringValue() {
JacksonJsonNode node = (JacksonJsonNode) element();
if(node.isString()) {
return node.stringValue();
} else {
throw LOG.unableToParseValue(String.class.getSimpleName(), node.getNodeType());
} | }
public Number numberValue() {
JacksonJsonNode node = (JacksonJsonNode) element();
if(node.isNumber()) {
return node.numberValue();
} else {
throw LOG.unableToParseValue(Number.class.getSimpleName(), node.getNodeType());
}
}
public Boolean boolValue() {
JacksonJsonNode node = (JacksonJsonNode) element();
if(node.isBoolean()) {
return node.boolValue();
} else {
throw LOG.unableToParseValue(Boolean.class.getSimpleName(), node.getNodeType());
}
}
} | repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\query\JacksonJsonPathQuery.java | 1 |
请完成以下Java代码 | private JsonErrorItem createJsonErrorItem(@NonNull final Exception ex)
{
final AdIssueId adIssueId = errorManager.createIssue(ex);
return JsonErrorItem.builder()
.message(ex.getLocalizedMessage())
.stackTrace(Trace.toOneLineStackTraceString(ex.getStackTrace()))
.adIssueId(JsonMetasfreshId.of(adIssueId.getRepoId()))
.errorCode(AdempiereException.extractErrorCodeOrNull(ex))
.throwable(ex)
.build();
}
private String toJsonString(@NonNull final Object obj)
{
try
{
return jsonObjectMapper.writeValueAsString(obj);
}
catch (final JsonProcessingException ex)
{
logger.warn("Failed converting {} to JSON. Returning toString()", obj, ex);
return obj.toString();
}
}
@Nullable | private static PPCostCollectorId extractCostCollectorId(@NonNull final JsonResponseIssueToManufacturingOrderDetail issueDetail)
{
return toPPCostCollectorId(issueDetail.getCostCollectorId());
}
@Nullable
private static PPCostCollectorId toPPCostCollectorId(@Nullable final JsonMetasfreshId id)
{
return id != null ? PPCostCollectorId.ofRepoIdOrNull(id.getValue()) : null;
}
@Nullable
private static JsonMetasfreshId toJsonMetasfreshId(@Nullable final PPCostCollectorId costCollectorId)
{
return costCollectorId != null ? JsonMetasfreshId.of(costCollectorId.getRepoId()) : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrderReportProcessCommand.java | 1 |
请完成以下Java代码 | protected List<String> getGroupsOfUser(ProcessEngine engine, String userId) {
List<Group> groups = engine.getIdentityService().createGroupQuery()
.groupMember(userId)
.list();
List<String> groupIds = new ArrayList<>();
for (Group group : groups) {
groupIds.add(group.getId());
}
return groupIds;
}
protected List<String> getTenantsOfUser(ProcessEngine engine, String userId) {
List<Tenant> tenants = engine.getIdentityService().createTenantQuery()
.userMember(userId)
.includingGroupsOfUser(true)
.list();
List<String> tenantIds = new ArrayList<>();
for(Tenant tenant : tenants) {
tenantIds.add(tenant.getId());
}
return tenantIds;
}
@POST
@Path("/{processEngineName}/logout")
public Response doLogout(@PathParam("processEngineName") String engineName) {
final Authentications authentications = Authentications.getCurrent();
ProcessEngine processEngine = ProcessEngineUtil.lookupProcessEngine(engineName);
if(processEngine == null) {
throw LOGGER.invalidRequestEngineNotFoundForName(engineName);
}
// remove authentication for process engine
if(authentications != null) {
UserAuthentication removedAuthentication = authentications.removeByEngineName(engineName);
if(isWebappsAuthenticationLoggingEnabled(processEngine) && removedAuthentication != null) {
LOGGER.infoWebappLogout(removedAuthentication.getName());
}
} | return Response.ok().build();
}
protected Response unauthorized() {
return Response.status(Status.UNAUTHORIZED).build();
}
protected Response forbidden() {
return Response.status(Status.FORBIDDEN).build();
}
protected Response notFound() {
return Response.status(Status.NOT_FOUND).build();
}
private boolean isWebappsAuthenticationLoggingEnabled(ProcessEngine processEngine) {
return ((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).isWebappsAuthenticationLoggingEnabled();
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\UserAuthenticationResource.java | 1 |
请完成以下Spring Boot application配置 | spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.packages.trusted=org.springframework.remoting.support,java.lang,com.baeldung.api
# Logging
logging.pattern.console=%d{mm:ss.SSS} %-5p [%-31t] [%-54logger{0}] %marker%m%ex{full} - %logger - %F:%L%n
logging.level.root=WARN |
logging.level.org.apache.activemq=DEBUG
logging.level.org.springframework.jms=DEBUG
logging.level.org.springframework=WARN | repos\tutorials-master\spring-remoting-modules\remoting-jms\remoting-jms-client\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public BatchPartBuilder searchKey(String searchKey) {
this.searchKey = searchKey;
return this;
}
@Override
public BatchPartBuilder searchKey2(String searchKey2) {
this.searchKey2 = searchKey2;
return this;
}
@Override
public BatchPartBuilder status(String status) {
if (status == null) {
throw new FlowableIllegalArgumentException("status is null");
}
this.status = status;
return this;
}
@Override
public BatchPartBuilder scopeId(String scopeId) {
if (scopeId == null) {
throw new FlowableIllegalArgumentException("scopeId is null");
}
this.scopeId = scopeId;
return this;
}
@Override
public BatchPartBuilder subScopeId(String subScopeId) {
if (subScopeId == null) {
throw new FlowableIllegalArgumentException("subScopeId is null");
}
this.subScopeId = subScopeId;
return this;
}
@Override
public BatchPartBuilder scopeType(String scopeType) {
if (scopeType == null) {
throw new FlowableIllegalArgumentException("scopeType is null");
}
this.scopeType = scopeType;
return this;
}
@Override
public BatchPart create() {
if (batch == null) {
throw new FlowableIllegalArgumentException("batch has to be provided");
}
if (type == null) {
throw new FlowableIllegalArgumentException("type has to be provided");
}
if (commandExecutor != null) {
return commandExecutor.execute(commandContext -> createSafe());
} else { | return createSafe();
}
}
protected BatchPart createSafe() {
BatchPartEntityManager partEntityManager = batchServiceConfiguration.getBatchPartEntityManager();
BatchPartEntity batchPart = partEntityManager.create();
batchPart.setBatchId(batch.getId());
batchPart.setBatchType(batch.getBatchType());
batchPart.setBatchSearchKey(batch.getBatchSearchKey());
batchPart.setBatchSearchKey2(batch.getBatchSearchKey2());
if (batch.getTenantId() != null) {
batchPart.setTenantId(batch.getTenantId());
}
batchPart.setType(type);
batchPart.setSearchKey(searchKey);
batchPart.setSearchKey2(searchKey2);
batchPart.setStatus(status);
batchPart.setScopeId(scopeId);
batchPart.setSubScopeId(subScopeId);
batchPart.setScopeType(scopeType);
batchPart.setCreateTime(batchServiceConfiguration.getClock().getCurrentTime());
partEntityManager.insert(batchPart);
return batchPart;
}
} | repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\BatchPartBuilderImpl.java | 2 |
请完成以下Java代码 | public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext;
int queueCapacity = DEFAULT_BLOCKING_QUEUE_CAPACITY;
if (servletContextEvent != null) {
servletContext = servletContextEvent.getServletContext();
if (servletContext != null) {
parseUniqueWorkerRequestParam(servletContext.getInitParameter(UNIQUE_WORKER_REQUEST_PARAM_NAME));
queueCapacity = parseBlockingQueueCapacityParam(servletContext.getInitParameter(BLOCKING_QUEUE_CAPACITY_PARAM_NAME));
}
}
initializeQueue(queueCapacity);
}
protected void parseUniqueWorkerRequestParam(String uniqueWorkerRequestParam) {
if (uniqueWorkerRequestParam != null) {
isUniqueWorkerRequest = Boolean.parseBoolean(uniqueWorkerRequestParam);
} else {
isUniqueWorkerRequest = false; // default configuration
}
}
protected void initializeQueue(int capacity) {
LOG.log(Level.FINEST, "Initializing queue with capacity [{0}]", capacity);
queue = new ArrayBlockingQueue<>(capacity);
} | private static int parseBlockingQueueCapacityParam(String queueSizeRequestParam) {
int capacity = DEFAULT_BLOCKING_QUEUE_CAPACITY;
if (queueSizeRequestParam != null) {
try {
final int parsedCapacity = Integer.parseInt(queueSizeRequestParam);
if (parsedCapacity <= 0) {
throw new NumberFormatException("Parameter " + BLOCKING_QUEUE_CAPACITY_PARAM_NAME + " has to be greater than zero");
}
capacity = parsedCapacity;
} catch (NumberFormatException e) {
LOG.log(Level.WARNING, "Invalid blocking queue capacity parameter: [" + queueSizeRequestParam + "], falling back to default value", e);
}
}
return capacity;
}
public List<FetchAndLockRequest> getPendingRequests() {
return pendingRequests;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\FetchAndLockHandlerImpl.java | 1 |
请完成以下Java代码 | public String getTableName()
{
return tableName;
}
@Override
public String getColumnName()
{
return columnName;
}
@Override
public String getParentTableName()
{
return parentTableName;
}
@Override
public String getParentColumnName()
{
return parentColumnName;
} | @Override
public String getParentColumnSQL()
{
return parentColumnSQL;
}
@Override
public String toString()
{
return "TableColumnPathElement ["
+"tableName=" + tableName + ", columnName=" + columnName
+ ", parentTableName=" + parentTableName + ", parentColumnName=" + parentColumnName
+ ", parentColumnSQL=" + parentColumnSQL
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\model\TableColumnPathElement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonHUClear
{
@NonNull
@JsonProperty("FLAG")
Integer flag;
@NonNull
@JsonProperty("METASFRESHID")
String metasfreshId;
@NonNull
@JsonProperty("CLEARANCE_STATUS")
String clearanceStatus;
@Nullable
@JsonProperty("CLEARANCE_NOTE")
String clearanceNote;
@Builder
public JsonHUClear(
@JsonProperty("FLAG") @NonNull final Integer flag, | @JsonProperty("METASFRESHID") @NonNull final String metasfreshId,
@JsonProperty("CLEARANCE_STATUS") @NonNull final String clearanceStatus,
@JsonProperty("CLEARANCE_NOTE") @Nullable final String clearanceNote)
{
this.flag = flag;
this.metasfreshId = metasfreshId;
this.clearanceStatus = clearanceStatus;
this.clearanceNote = clearanceNote;
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPOJOBuilder(withPrefix = "")
public static class JsonHUClearBuilder
{
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\api\model\JsonHUClear.java | 2 |
请完成以下Java代码 | public Optional<UserId> resolveUserExternalIdentifier(@NonNull final OrgId orgId, @NonNull final ExternalIdentifier externalIdentifier)
{
return bPartnerMasterdataProvider.resolveUserExternalIdentifier(orgId, externalIdentifier);
}
public boolean isAutoInvoice(@NonNull final JsonOLCandCreateRequest request, @NonNull final BPartnerId bpartnerId)
{
return bPartnerMasterdataProvider.isAutoInvoice(request, bpartnerId);
}
@Nullable
public PaymentRule getPaymentRule(final JsonOLCandCreateRequest request)
{
final JSONPaymentRule jsonPaymentRule = request.getPaymentRule();
if (jsonPaymentRule == null)
{
return null;
}
if (JSONPaymentRule.Paypal.equals(jsonPaymentRule))
{
return PaymentRule.PayPal;
}
if (JSONPaymentRule.OnCredit.equals(jsonPaymentRule))
{
return PaymentRule.OnCredit;
}
if (JSONPaymentRule.DirectDebit.equals(jsonPaymentRule))
{
return PaymentRule.DirectDebit;
}
throw MissingResourceException.builder()
.resourceName("paymentRule")
.resourceIdentifier(jsonPaymentRule.getCode())
.parentResource(request)
.build();
}
public PaymentTermId getPaymentTermId(@NonNull final IdentifierString paymentTerm, @NonNull final Object parent, @NonNull final OrgId orgId)
{
final PaymentTermQueryBuilder queryBuilder = PaymentTermQuery.builder();
queryBuilder.orgId(orgId);
switch (paymentTerm.getType())
{
case EXTERNAL_ID:
queryBuilder.externalId(paymentTerm.asExternalId());
break;
case VALUE:
queryBuilder.value(paymentTerm.asValue()); | break;
default:
throw new InvalidIdentifierException(paymentTerm);
}
final Optional<PaymentTermId> paymentTermId = paymentTermRepo.firstIdOnly(queryBuilder.build());
return paymentTermId.orElseThrow(() -> MissingResourceException.builder()
.resourceName("PaymentTerm")
.resourceIdentifier(paymentTerm.toJson())
.parentResource(parent).build());
}
@Nullable
public BPartnerId getSalesRepBPartnerId(@NonNull final BPartnerId bPartnerId)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId);
return BPartnerId.ofRepoIdOrNull(bPartner.getC_BPartner_SalesRep_ID());
}
@NonNull
public ExternalSystemId getExternalSystemId(@NonNull final ExternalSystemType type)
{
return externalSystemRepository.getIdByType(type);
}
@Nullable
public Incoterms getIncoterms(@NonNull final JsonOLCandCreateRequest request,
@NonNull final OrgId orgId,
@NonNull final BPartnerId bPartnerId)
{
return bPartnerMasterdataProvider.getIncoterms(request, orgId, bPartnerId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\MasterdataProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ExternalWorkerJobAcquireBuilder onlyCmmn() {
if (ScopeTypes.BPMN.equals(scopeType)) {
throw new FlowableIllegalArgumentException("Cannot combine onlyBpmn() with onlyCmmn() in the same query");
}
if (scopeType != null) {
throw new FlowableIllegalArgumentException("Cannot combine scopeType(String) with onlyCmmn() in the same query");
}
return scopeType(ScopeTypes.CMMN);
}
@Override
public ExternalWorkerJobAcquireBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public ExternalWorkerJobAcquireBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public ExternalWorkerJobAcquireBuilder forUserOrGroups(String userId, Collection<String> groups) {
if (userId == null && (groups == null || groups.isEmpty())) {
throw new FlowableIllegalArgumentException("at least one of userId or groups must be provided");
}
this.authorizedUser = userId;
this.authorizedGroups = groups;
return this;
}
@Override
public List<AcquiredExternalWorkerJob> acquireAndLock(int numberOfTasks, String workerId, int numberOfRetries) {
while (numberOfRetries > 0) {
try {
return commandExecutor.execute(new AcquireExternalWorkerJobsCmd(workerId, numberOfTasks, this, jobServiceConfiguration));
} catch (FlowableOptimisticLockingException ignored) {
// Query for jobs until there is no FlowableOptimisticLockingException
// It is potentially possible multiple workers to query in the exact same time
numberOfRetries--;
} | }
return Collections.emptyList();
}
public String getTopic() {
return topic;
}
public Duration getLockDuration() {
return lockDuration;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public String getAuthorizedUser() {
return authorizedUser;
}
public Collection<String> getAuthorizedGroups() {
return authorizedGroups;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\ExternalWorkerJobAcquireBuilderImpl.java | 2 |
请完成以下Java代码 | public void setIsTaxIncluded (boolean IsTaxIncluded)
{
set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded));
}
/** Get Price includes Tax.
@return Tax is included in the price
*/
public boolean isTaxIncluded ()
{
Object oo = get_Value(COLUMNNAME_IsTaxIncluded);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge.java | 1 |
请完成以下Java代码 | public List<I_PMM_Product> retrieveByBPartner(@NonNull final BPartnerId bpartnerId)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_PMM_Product.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PMM_Product.COLUMN_C_BPartner_ID, bpartnerId)
.create()
.list();
}
@Override
public List<I_PMM_Product> retrieveForDateAndProduct(
@NonNull final Date date,
@NonNull final ProductId productId,
@Nullable final BPartnerId partnerId,
final int huPIPId) | {
return retrievePMMProductsValidOnDateQuery(date)
.addInArrayOrAllFilter(I_PMM_Product.COLUMNNAME_C_BPartner_ID, partnerId, null) // for the given partner or Not bound to a particular partner (i.e. C_BPartner_ID is null)
.addEqualsFilter(I_PMM_Product.COLUMN_M_Product_ID, productId)
.addEqualsFilter(I_PMM_Product.COLUMN_M_HU_PI_Item_Product_ID, huPIPId)
.orderBy()
.addColumn(I_PMM_Product.COLUMNNAME_SeqNo, Direction.Ascending, Nulls.First)
.addColumn(I_PMM_Product.COLUMNNAME_ValidFrom, Direction.Descending, Nulls.Last)
.addColumn(I_PMM_Product.COLUMNNAME_PMM_Product_ID)
.endOrderBy()
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMProductDAO.java | 1 |
请完成以下Java代码 | public boolean hasNext()
{
return iterator.hasNext();
}
@Override
public Entry<String, V> next()
{
iterator.next();
return new AbstractMap.SimpleEntry<String, V>(iterator.key(), values.get(iterator.value()));
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(Entry<String, V> stringVEntry)
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) | {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends Entry<String, V>> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
MutableDoubleArrayTrie.this.clear();
}
};
}
@Override
public Iterator<Entry<String, V>> iterator()
{
return entrySet().iterator();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrie.java | 1 |
请完成以下Java代码 | public boolean isTaxIncluded()
{
return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded);
}
@Override
public void setIsWholeTax (final boolean IsWholeTax)
{
set_Value (COLUMNNAME_IsWholeTax, IsWholeTax);
}
@Override
public boolean isWholeTax()
{
return get_ValueAsBoolean(COLUMNNAME_IsWholeTax);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmt (final BigDecimal TaxBaseAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
@Override
public BigDecimal getTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceTax.java | 1 |
请完成以下Java代码 | public void notifyPostingError(
@NonNull final UserId recipientUserId,
@NonNull final TableRecordReference documentRef,
@NonNull final Exception exception)
{
notifyPostingError(recipientUserId, documentRef, AdempiereException.extractMessage(exception));
}
public void notifyPostingError(@NonNull final String message, final DocumentPostMultiRequest postRequests)
{
final List<UserNotificationRequest> notifications = postRequests.stream()
.map(postRequest -> toUserNotificationRequestOrNull(postRequest, message))
.filter(Objects::nonNull)
.collect(Collectors.toList());
userNotifications.sendAfterCommit(notifications);
}
public void notifyPostingError(
@NonNull final UserId recipientUserId,
@NonNull final TableRecordReference documentRef,
@NonNull final String message)
{
userNotifications.sendAfterCommit(toUserNotificationRequest(recipientUserId, documentRef, message));
}
private static UserNotificationRequest toUserNotificationRequestOrNull(
@NonNull final DocumentPostRequest postRequest,
@NonNull final String message)
{
final UserId recipientUserId = postRequest.getOnErrorNotifyUserId();
if (recipientUserId == null) {return null;}
return UserNotificationRequest.builder() | .topic(NOTIFICATIONS_TOPIC)
.recipientUserId(recipientUserId)
.contentPlain(message)
.targetAction(UserNotificationRequest.TargetRecordAction.of(postRequest.getRecord()))
.build();
}
private static UserNotificationRequest toUserNotificationRequest(
@NonNull final UserId recipientUserId,
@NonNull final TableRecordReference documentRef,
@NonNull final String message)
{
return UserNotificationRequest.builder()
.topic(NOTIFICATIONS_TOPIC)
.recipientUserId(recipientUserId)
.contentPlain(message)
.targetAction(UserNotificationRequest.TargetRecordAction.of(documentRef))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingUserNotificationService.java | 1 |
请完成以下Java代码 | public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
} | public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContactWithJavaUtilDate() {
}
public PlainContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\jsondateformat\PlainContactWithJavaUtilDate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public FlatFileItemReader<Product> fileReader() {
return new FlatFileItemReaderBuilder<Product>()
.name("fileReader")
.resource(new ClassPathResource("products.csv"))
.delimited()
.names("productId", "productName", "stock", "price")
.linesToSkip(1)
.targetType(Product.class)
.build();
}
@Bean
public JdbcCursorItemReader<Product> dbReader() {
return new JdbcCursorItemReaderBuilder<Product>()
.name("dbReader")
.dataSource(dataSource())
.sql("SELECT productid, productname, stock, price FROM products")
.rowMapper((rs, rowNum) -> new Product(
rs.getLong("productid"),
rs.getString("productname"),
rs.getInt("stock"),
rs.getBigDecimal("price")
))
.build();
}
@Bean
public CompositeItemReader<Product> compositeReader() {
return new CompositeItemReader<>(Arrays.asList(fileReader(), dbReader()));
}
@Bean | public ItemWriter<Product> productWriter() {
return items -> {
for (Product product : items) {
System.out.println("Writing product: " + product);
}
};
}
@Bean
public Step step(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("compositeReader") ItemReader<Product> compositeReader, ItemWriter<Product> productWriter) {
return new StepBuilder("productStep", jobRepository)
.<Product, Product>chunk(10, transactionManager)
.reader(compositeReader)
.writer(productWriter)
.build();
}
@Bean
public Job productJob(JobRepository jobRepository, Step step) {
return new JobBuilder("productJob", jobRepository)
.start(step)
.build();
}
} | repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\CompositeItemReaderConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TestController {
@Autowired
private UserService userService;
@GetMapping("user/{id}")
public User getUser(@PathVariable Long id) {
return userService.get(id);
}
@GetMapping("user")
public List<User> getUsers() {
return userService.get();
}
@PostMapping("user") | public void addUser() {
User user = new User(1L, "mrbird", "123456");
userService.add(user);
}
@PutMapping("user")
public void updateUser() {
User user = new User(1L, "mrbird", "123456");
userService.update(user);
}
@DeleteMapping("user/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
} | repos\SpringAll-master\33.Spring-Cloud-Feign-Declarative-REST-Client\Feign-Consumer\src\main\java\com\example\demo\controller\TestController.java | 2 |
请完成以下Java代码 | public abstract class PrimitiveValueSerializer<T extends PrimitiveValue<?>> extends AbstractTypedValueSerializer<T> {
public PrimitiveValueSerializer(PrimitiveValueType variableType) {
super(variableType);
}
public String getName() {
// default implementation returns the name of the type. This is OK since we assume that
// there is only a single serializer for a primitive variable type.
// If multiple serializers exist for the same type, they must override
// this method and return distinct values.
return valueType.getName();
}
public T readValue(ValueFields valueFields, boolean deserializeObjectValue, boolean asTransientValue) {
// primitive values are always deserialized | return readValue(valueFields, asTransientValue);
}
public abstract T readValue(ValueFields valueFields, boolean asTransientValue);
public PrimitiveValueType getType() {
return (PrimitiveValueType) super.getType();
}
protected boolean canWriteValue(TypedValue typedValue) {
Object value = typedValue.getValue();
Class<?> javaType = getType().getJavaType();
return value == null || javaType.isAssignableFrom(value.getClass());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\PrimitiveValueSerializer.java | 1 |
请完成以下Java代码 | public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
registerFunctionMapper(processEngineConfiguration);
registerScriptResolver(processEngineConfiguration);
registerSerializers(processEngineConfiguration);
registerValueTypes(processEngineConfiguration);
registerFallbackSerializer(processEngineConfiguration);
}
protected void registerFallbackSerializer(ProcessEngineConfigurationImpl processEngineConfiguration) {
processEngineConfiguration.setFallbackSerializerFactory(new SpinFallbackSerializerFactory());
}
protected void registerSerializers(ProcessEngineConfigurationImpl processEngineConfiguration) {
List<TypedValueSerializer<?>> spinDataFormatSerializers = lookupSpinSerializers();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
int javaObjectSerializerIdx = variableSerializers.getSerializerIndexByName(JavaObjectSerializer.NAME);
for (TypedValueSerializer<?> spinSerializer : spinDataFormatSerializers) {
// add before java object serializer
variableSerializers.addSerializer(spinSerializer, javaObjectSerializerIdx);
}
}
protected List<TypedValueSerializer<?>> lookupSpinSerializers() {
DataFormats globalFormats = DataFormats.getInstance();
List<TypedValueSerializer<?>> serializers =
SpinVariableSerializers.createObjectValueSerializers(globalFormats);
serializers.addAll(SpinVariableSerializers.createSpinValueSerializers(globalFormats));
return serializers;
} | protected void registerScriptResolver(ProcessEngineConfigurationImpl processEngineConfiguration) {
processEngineConfiguration.getEnvScriptResolvers().add(new SpinScriptEnvResolver());
}
protected void registerFunctionMapper(ProcessEngineConfigurationImpl processEngineConfiguration) {
ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
expressionManager.addFunction(SpinFunctions.S,
ReflectUtil.getMethod(Spin.class, SpinFunctions.S, Object.class));
expressionManager.addFunction(SpinFunctions.XML,
ReflectUtil.getMethod(Spin.class, SpinFunctions.XML, Object.class));
expressionManager.addFunction(SpinFunctions.JSON,
ReflectUtil.getMethod(Spin.class, SpinFunctions.JSON, Object.class));
}
protected void registerValueTypes(ProcessEngineConfigurationImpl processEngineConfiguration){
ValueTypeResolver resolver = processEngineConfiguration.getValueTypeResolver();
resolver.addType(JSON);
resolver.addType(XML);
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinProcessEnginePlugin.java | 1 |
请完成以下Java代码 | public HUEditorViewBuilder orderBys(@NonNull final DocumentQueryOrderByList orderBys)
{
this.orderBys = new ArrayList<>(orderBys.toList());
return this;
}
public HUEditorViewBuilder clearOrderBys()
{
this.orderBys = null;
return this;
}
private DocumentQueryOrderByList getOrderBys()
{
return DocumentQueryOrderByList.ofList(orderBys);
}
public HUEditorViewBuilder setParameter(final String name, @Nullable final Object value)
{
if (value == null)
{
if (parameters != null)
{
parameters.remove(name);
}
}
else
{
if (parameters == null)
{
parameters = new LinkedHashMap<>();
}
parameters.put(name, value);
}
return this;
}
public HUEditorViewBuilder setParameters(final Map<String, Object> parameters)
{
parameters.forEach(this::setParameter);
return this;
}
ImmutableMap<String, Object> getParameters()
{
return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of();
}
@Nullable
public <T> T getParameter(@NonNull final String name)
{
if (parameters == null)
{
return null; | }
@SuppressWarnings("unchecked") final T value = (T)parameters.get(name);
return value;
}
public void assertParameterSet(final String name)
{
final Object value = getParameter(name);
if (value == null)
{
throw new AdempiereException("Parameter " + name + " is expected to be set in " + parameters + " for " + this);
}
}
public HUEditorViewBuilder setHUEditorViewRepository(final HUEditorViewRepository huEditorViewRepository)
{
this.huEditorViewRepository = huEditorViewRepository;
return this;
}
HUEditorViewBuffer createRowsBuffer(@NonNull final SqlDocumentFilterConverterContext context)
{
final ViewId viewId = getViewId();
final DocumentFilterList stickyFilters = getStickyFilters();
final DocumentFilterList filters = getFilters();
if (HUEditorViewBuffer_HighVolume.isHighVolume(stickyFilters))
{
return new HUEditorViewBuffer_HighVolume(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context);
}
else
{
return new HUEditorViewBuffer_FullyCached(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context);
}
}
public HUEditorViewBuilder setUseAutoFilters(final boolean useAutoFilters)
{
this.useAutoFilters = useAutoFilters;
return this;
}
public boolean isUseAutoFilters()
{
return useAutoFilters;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CostElementAccountsRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, CostElementAccountsMap> cache = CCache.<Integer, CostElementAccountsMap>builder()
.tableName(I_M_CostElement_Acct.Table_Name)
.initialCapacity(1)
.build();
public CostElementAccounts getAccounts(
@NonNull final CostElementId costElementId,
@NonNull final AcctSchemaId acctSchemaId)
{
return getMap().getAccounts(costElementId, acctSchemaId);
}
public void deleteByCostElementId(@NonNull CostElementId costElementId)
{
queryBL.createQueryBuilder(I_M_CostElement_Acct.class)
.addEqualsFilter(I_M_CostElement_Acct.COLUMNNAME_M_CostElement_ID, costElementId)
.create()
.delete();
}
private CostElementAccountsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private CostElementAccountsMap retrieveMap()
{
final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map = queryBL
.createQueryBuilder(I_M_CostElement_Acct.class)
.addOnlyActiveRecordsFilter()
.stream()
.collect(ImmutableMap.toImmutableMap(
CostElementAccountsRepository::extractCostElementIdAndAcctSchemaId,
CostElementAccountsRepository::fromRecord));
return new CostElementAccountsMap(map);
}
private static CostElementIdAndAcctSchemaId extractCostElementIdAndAcctSchemaId(final I_M_CostElement_Acct record)
{
return CostElementIdAndAcctSchemaId.of(
CostElementId.ofRepoId(record.getM_CostElement_ID()),
AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()));
}
private static CostElementAccounts fromRecord(final I_M_CostElement_Acct record)
{
return CostElementAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.P_CostClearing_Acct(AccountId.ofRepoId(record.getP_CostClearing_Acct()))
.build();
} | @Value(staticConstructor = "of")
private static class CostElementIdAndAcctSchemaId
{
@NonNull CostElementId costTypeId;
@NonNull AcctSchemaId acctSchemaId;
}
private static class CostElementAccountsMap
{
private final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map;
public CostElementAccountsMap(
@NonNull final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map)
{
this.map = map;
}
public CostElementAccounts getAccounts(
@NonNull final CostElementId costElementId,
@NonNull final AcctSchemaId acctSchemaId)
{
final CostElementAccounts accounts = map.get(CostElementIdAndAcctSchemaId.of(costElementId, acctSchemaId));
if (accounts == null)
{
throw new AdempiereException("No accounts found for " + costElementId + " and " + acctSchemaId);
}
return accounts;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\CostElementAccountsRepository.java | 2 |
请完成以下Java代码 | public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(JsonSerializeBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(0)
.build();
Collection<RunResult> results = new Runner(opt).run();
ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");
}
@Benchmark
public void JsonLib() {
for (int i = 0; i < count; i++) {
JsonLibUtil.bean2Json(p);
}
}
@Benchmark
public void Gson() {
for (int i = 0; i < count; i++) {
GsonUtil.bean2Json(p);
}
}
@Benchmark
public void FastJson() {
for (int i = 0; i < count; i++) {
FastJsonUtil.bean2Json(p);
}
}
@Benchmark
public void Jackson() {
for (int i = 0; i < count; i++) {
JacksonUtil.bean2Json(p);
}
}
@Setup
public void prepare() { | List<Person> friends=new ArrayList<Person>();
friends.add(createAPerson("小明",null));
friends.add(createAPerson("Tony",null));
friends.add(createAPerson("陈小二",null));
p=createAPerson("邵同学",friends);
}
@TearDown
public void shutdown() {
}
private Person createAPerson(String name,List<Person> friends) {
Person newPerson=new Person();
newPerson.setName(name);
newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last"));
newPerson.setAge(24);
List<String> hobbies=new ArrayList<String>();
hobbies.add("篮球");
hobbies.add("游泳");
hobbies.add("coding");
newPerson.setHobbies(hobbies);
Map<String,String> clothes=new HashMap<String, String>();
clothes.put("coat", "Nike");
clothes.put("trousers", "adidas");
clothes.put("shoes", "安踏");
newPerson.setClothes(clothes);
newPerson.setFriends(friends);
return newPerson;
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\JsonSerializeBenchmark.java | 1 |
请完成以下Java代码 | public ActiveOrHistoricCurrencyAndAmount getTaxblBaseAmt() {
return taxblBaseAmt;
}
/**
* Sets the value of the taxblBaseAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTaxblBaseAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.taxblBaseAmt = value;
}
/**
* Gets the value of the ttlAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getTtlAmt() {
return ttlAmt;
}
/**
* Sets the value of the ttlAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlAmt = value;
}
/**
* Gets the value of the dtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the | * returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TaxRecordDetails1 }
*
*
*/
public List<TaxRecordDetails1> getDtls() {
if (dtls == null) {
dtls = new ArrayList<TaxRecordDetails1>();
}
return this.dtls;
}
} | 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\TaxAmount1.java | 1 |
请完成以下Java代码 | public void setStyleSheet(Reader r) {
StyleSheet css = new StyleSheet();
try {
css.loadRules(r, null);
/*
* new InputStreamReader(
* net.sf.memoranda.ui.htmleditor.HTMLEditor.class.getResourceAsStream("resources/css/default.css")),
*/
} catch (Exception ex) {
ex.printStackTrace();
}
editorKit.setStyleSheet(css);
}
public void reload() {
}
void doFind() {
FindDialog dlg = new FindDialog();
//dlg.setLocation(linkActionB.getLocationOnScreen());
Dimension dlgSize = dlg.getSize();
//dlg.setSize(400, 300);
Dimension frmSize = this.getSize();
Point loc = this.getLocationOnScreen();
dlg.setLocation(
(frmSize.width - dlgSize.width) / 2 + loc.x,
(frmSize.height - dlgSize.height) / 2 + loc.y);
dlg.setModal(true);
if (editor.getSelectedText() != null)
dlg.txtSearch.setText(editor.getSelectedText());
else if (Context.get("LAST_SEARCHED_WORD") != null)
dlg.txtSearch.setText(Context.get("LAST_SEARCHED_WORD").toString());
dlg.setVisible(true);
if (dlg.CANCELLED)
return;
Context.put("LAST_SEARCHED_WORD", dlg.txtSearch.getText());
String repl = null;
if (dlg.chkReplace.isSelected())
repl = dlg.txtReplace.getText();
Finder finder =
new Finder(
this,
dlg.txtSearch.getText(),
dlg.chkWholeWord.isSelected(),
dlg.chkCaseSens.isSelected(),
dlg.chkRegExp.isSelected(),
repl);
finder.start();
}
// metas: begin
public String getHtmlText()
{
try
{
StringWriter sw = new StringWriter();
new AltHTMLWriter(sw, this.document).write();
// new HTMLWriter(sw, editor.document).write();
String html = sw.toString();
return html;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public HTMLDocument getDocument()
{
return this.document;
}
@Override
public void requestFocus() | {
this.editor.requestFocus();
}
@Override
public boolean requestFocus(boolean temporary)
{
return this.editor.requestFocus(temporary);
}
@Override
public boolean requestFocusInWindow()
{
return this.editor.requestFocusInWindow();
}
public void setText(String html)
{
this.editor.setText(html);
}
public void setCaretPosition(int position)
{
this.editor.setCaretPosition(position);
}
public ActionMap getEditorActionMap()
{
return this.editor.getActionMap();
}
public InputMap getEditorInputMap(int condition)
{
return this.editor.getInputMap(condition);
}
public Keymap getEditorKeymap()
{
return this.editor.getKeymap();
}
public JTextComponent getTextComponent()
{
return this.editor;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java | 1 |
请完成以下Java代码 | public String getCommonJWorkManagerName() {
return commonJWorkManagerName;
}
public void setCommonJWorkManagerName(String commonJWorkManagerName) {
this.commonJWorkManagerName = commonJWorkManagerName;
}
// misc //////////////////////////////////////////////////////////////////
@Override
public int hashCode() {
return 17;
} | @Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (!(other instanceof JcaExecutorServiceConnector)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaExecutorServiceConnector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LicenseFeeSettingsLine
{
@Nullable
LicenseFeeSettingsLineId licenseFeeSettingsLineId;
@NonNull
LicenseFeeSettingsId licenseFeeSettingsId;
int seqNo;
@NonNull
Percent percentOfBasedPoints;
@Nullable
BPGroupId bpGroupIdMatch;
boolean active;
@Builder
public LicenseFeeSettingsLine(
@Nullable final LicenseFeeSettingsLineId licenseFeeSettingsLineId,
@NonNull final LicenseFeeSettingsId licenseFeeSettingsId,
final int seqNo,
@NonNull final Percent percentOfBasedPoints,
@Nullable final BPGroupId bpGroupIdMatch,
final boolean active) | {
this.licenseFeeSettingsLineId = licenseFeeSettingsLineId;
this.licenseFeeSettingsId = licenseFeeSettingsId;
this.seqNo = seqNo;
this.percentOfBasedPoints = percentOfBasedPoints;
this.bpGroupIdMatch = bpGroupIdMatch;
this.active = active;
}
public boolean appliesToBPGroup(@NonNull final BPGroupId bpGroupId)
{
return this.bpGroupIdMatch == null || this.bpGroupIdMatch.equals(bpGroupId);
}
@NonNull
public LicenseFeeSettingsLineId getIdNotNull()
{
if (this.licenseFeeSettingsLineId == null)
{
throw new AdempiereException("getIdNotNull() should be called only for already persisted LicenseFeeSettingsLine objects!")
.appendParametersToMessage()
.setParameter("LicenseFeeSettingsLine", this);
}
return licenseFeeSettingsLineId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\licensefee\model\LicenseFeeSettingsLine.java | 2 |
请完成以下Java代码 | public class FinancialInstitutionIdentificationSEPA2 {
@XmlElement(name = "Othr", required = true)
protected RestrictedFinancialIdentificationSEPA othr;
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link RestrictedFinancialIdentificationSEPA }
*
*/
public RestrictedFinancialIdentificationSEPA getOthr() {
return othr; | }
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link RestrictedFinancialIdentificationSEPA }
*
*/
public void setOthr(RestrictedFinancialIdentificationSEPA value) {
this.othr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\FinancialInstitutionIdentificationSEPA2.java | 1 |
请完成以下Java代码 | public class MetricPositionEntity {
private long id;
private Date gmtCreate;
private Date gmtModified;
private String app;
private String ip;
/**
* Sentinel在该应用上使用的端口
*/
private int port;
/**
* 机器名,冗余字段
*/
private String hostname;
/**
* 上一次拉取的最晚时间戳
*/
private Date lastFetch;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getIp() {
return ip;
} | public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Date getLastFetch() {
return lastFetch;
}
public void setLastFetch(Date lastFetch) {
this.lastFetch = lastFetch;
}
@Override
public String toString() {
return "MetricPositionEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", hostname='" + hostname + '\'' +
", lastFetch=" + lastFetch +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricPositionEntity.java | 1 |
请完成以下Java代码 | public class SlackUserErrorReporter implements ErrorReporter {
private static final Logger LOG = LoggerFactory.getLogger(SlackUserErrorReporter.class);
private final SlackClient slackClient;
private final String user;
public SlackUserErrorReporter(SlackClient slackClient, String user) {
this.slackClient = slackClient;
this.user = user;
}
@Override
public void reportProblem(String problem) {
LOG.debug("Sending message to user {}: {}", user, problem);
UsersInfoResponse usersInfoResponse = slackClient
.lookupUserByEmail(UserEmailParams.builder()
.setEmail(user)
.build() | ).join().unwrapOrElseThrow();
ImOpenResponse imOpenResponse = slackClient.openIm(ImOpenParams.builder()
.setUserId(usersInfoResponse.getUser().getId())
.build()
).join().unwrapOrElseThrow();
imOpenResponse.getChannel().ifPresent(channel -> {
slackClient.postMessage(
ChatPostMessageParams.builder()
.setText(problem)
.setChannelId(channel.getId())
.build()
).join().unwrapOrElseThrow();
});
}
} | repos\tutorials-master\saas-modules\slack\src\main\java\com\baeldung\examples\slack\SlackUserErrorReporter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SmsHomeAdvertiseController {
@Autowired
private SmsHomeAdvertiseService advertiseService;
@ApiOperation("添加广告")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody SmsHomeAdvertise advertise) {
int count = advertiseService.create(advertise);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("删除广告")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = advertiseService.delete(ids);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("修改上下线状态")
@RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateStatus(@PathVariable Long id, Integer status) {
int count = advertiseService.updateStatus(id, status);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed(); | }
@ApiOperation("获取广告详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<SmsHomeAdvertise> getItem(@PathVariable Long id) {
SmsHomeAdvertise advertise = advertiseService.getItem(id);
return CommonResult.success(advertise);
}
@ApiOperation("修改广告")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody SmsHomeAdvertise advertise) {
int count = advertiseService.update(id, advertise);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("分页查询广告")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsHomeAdvertise>> list(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "type", required = false) Integer type,
@RequestParam(value = "endTime", required = false) String endTime,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsHomeAdvertise> advertiseList = advertiseService.list(name, type, endTime, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(advertiseList));
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsHomeAdvertiseController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void putReportLanguage(String adLanguage)
{
put(PARAM_REPORT_LANGUAGE, adLanguage);
}
/**
* Extracts {@link Language} parameter
*
* @return {@link Language}; never returns null
*/
public Language getReportLanguageEffective()
{
final Object languageObj = get(PARAM_REPORT_LANGUAGE);
Language currLang = null;
if (languageObj instanceof String)
{
currLang = Language.getLanguage((String)languageObj);
}
else if (languageObj instanceof Language)
{
currLang = (Language)languageObj;
}
if (currLang == null)
{
currLang = Env.getLanguage(Env.getCtx());
}
return currLang;
}
public void putLocale(@Nullable final Locale locale)
{
put(JRParameter.REPORT_LOCALE, locale);
}
@Nullable
public Locale getLocale()
{ | return (Locale)get(JRParameter.REPORT_LOCALE);
}
public void putRecordId(final int recordId)
{
put(PARAM_RECORD_ID, recordId);
}
public void putTableId(final int tableId)
{
put(PARAM_AD_Table_ID, tableId);
}
public void putBarcodeURL(final String barcodeURL)
{
put(PARAM_BARCODE_URL, barcodeURL);
}
@Nullable
public String getBarcodeUrl()
{
final Object barcodeUrl = get(PARAM_BARCODE_URL);
return barcodeUrl != null ? barcodeUrl.toString() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java | 2 |
请完成以下Java代码 | public class Movie {
protected String imdbId;
protected String title;
public Movie(String imdbId, String title) {
this.imdbId = imdbId;
this.title = title;
}
public Movie() {}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o) | return true;
if (o == null || getClass() != o.getClass())
return false;
Movie movie = (Movie) o;
if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null)
return false;
return title != null ? title.equals(movie.title) : movie.title == null;
}
@Override
public int hashCode() {
int result = imdbId != null ? imdbId.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Movie{" +
"imdbId='" + imdbId + '\'' +
", title='" + title + '\'' +
'}';
}
} | repos\tutorials-master\web-modules\resteasy\src\main\java\com\baeldung\model\Movie.java | 1 |
请完成以下Java代码 | public void setapplicationID (final @Nullable java.lang.String applicationID)
{
set_Value (COLUMNNAME_applicationID, applicationID);
}
@Override
public java.lang.String getapplicationID()
{
return get_ValueAsString(COLUMNNAME_applicationID);
}
@Override
public void setApplicationToken (final @Nullable java.lang.String ApplicationToken)
{
set_Value (COLUMNNAME_ApplicationToken, ApplicationToken);
}
@Override
public java.lang.String getApplicationToken()
{
return get_ValueAsString(COLUMNNAME_ApplicationToken);
}
@Override
public void setdhl_api_url (final @Nullable java.lang.String dhl_api_url)
{
set_Value (COLUMNNAME_dhl_api_url, dhl_api_url);
}
@Override
public java.lang.String getdhl_api_url()
{
return get_ValueAsString(COLUMNNAME_dhl_api_url);
}
@Override
public void setDhl_LenghtUOM_ID (final int Dhl_LenghtUOM_ID)
{
if (Dhl_LenghtUOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_Dhl_LenghtUOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Dhl_LenghtUOM_ID, Dhl_LenghtUOM_ID);
}
@Override
public int getDhl_LenghtUOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Dhl_LenghtUOM_ID);
}
@Override
public void setDHL_Shipper_Config_ID (final int DHL_Shipper_Config_ID)
{
if (DHL_Shipper_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, DHL_Shipper_Config_ID);
}
@Override
public int getDHL_Shipper_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_DHL_Shipper_Config_ID);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper()
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
} | @Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setSignature (final @Nullable java.lang.String Signature)
{
set_Value (COLUMNNAME_Signature, Signature);
}
@Override
public java.lang.String getSignature()
{
return get_ValueAsString(COLUMNNAME_Signature);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_Shipper_Config.java | 1 |
请完成以下Java代码 | public final class QualityInspectionLineByTypeComparator implements Comparator<IQualityInspectionLine>
{
/**
* Maps {@link QualityInspectionLineType} to it's sorting priority.
*/
private final Map<QualityInspectionLineType, Integer> type2index = new HashMap<>();
/** Index to be used when type was not found */
private final static int INDEX_NotFound = 10000000;
public QualityInspectionLineByTypeComparator(final QualityInspectionLineType... inspectionLineTypes)
{
this(Arrays.asList(inspectionLineTypes));
}
public QualityInspectionLineByTypeComparator(final List<QualityInspectionLineType> inspectionLineTypes)
{
super();
Check.assumeNotEmpty(inspectionLineTypes, "inspectionLineTypes not empty");
//
// Build type to priority index map
for (int index = 0; index < inspectionLineTypes.size(); index++)
{
final QualityInspectionLineType type = inspectionLineTypes.get(index);
Check.assumeNotNull(type, "type not null");
final Integer indexOld = type2index.put(type, index);
if (indexOld != null)
{
throw new IllegalArgumentException("Duplicate type " + type + " found in " + inspectionLineTypes);
}
}
}
@Override
public int compare(final IQualityInspectionLine line1, final IQualityInspectionLine line2)
{
final int index1 = getIndex(line1);
final int index2 = getIndex(line2);
return index1 - index2;
}
private final int getIndex(final IQualityInspectionLine line)
{
Check.assumeNotNull(line, "line not null");
final QualityInspectionLineType type = line.getQualityInspectionLineType();
final Integer index = type2index.get(type);
if (index == null)
{
return INDEX_NotFound;
}
return index;
}
private final boolean hasType(final QualityInspectionLineType type)
{
return type2index.containsKey(type);
}
/**
* Remove from given lines those which their type is not specified in our list.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void filter(final List<IQualityInspectionLine> lines)
{ | for (final Iterator<IQualityInspectionLine> it = lines.iterator(); it.hasNext();)
{
final IQualityInspectionLine line = it.next();
final QualityInspectionLineType type = line.getQualityInspectionLineType();
if (!hasType(type))
{
it.remove();
}
}
}
/**
* Sort given lines with this comparator.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void sort(final List<IQualityInspectionLine> lines)
{
Collections.sort(lines, this);
}
/**
* Remove from given lines those which their type is not specified in our list. Then sort the result.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void filterAndSort(final List<IQualityInspectionLine> lines)
{
filter(lines);
sort(lines);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\QualityInspectionLineByTypeComparator.java | 1 |
请完成以下Java代码 | public class IdVector implements Comparable<IdVector>, ISentenceKey<IdVector>
{
public List<Long[]> idArrayList;
public IdVector(String sentence)
{
this(CoreSynonymDictionaryEx.convert(IndexTokenizer.segment(sentence), false));
}
public IdVector(List<Long[]> idArrayList)
{
this.idArrayList = idArrayList;
}
@Override
public int compareTo(IdVector o)
{
int len1 = idArrayList.size();
int len2 = o.idArrayList.size();
int lim = Math.min(len1, len2);
Iterator<Long[]> iterator1 = idArrayList.iterator();
Iterator<Long[]> iterator2 = o.idArrayList.iterator();
int k = 0;
while (k < lim)
{ | Long[] c1 = iterator1.next();
Long[] c2 = iterator2.next();
if (ArrayDistance.computeMinimumDistance(c1, c2) != 0)
{
return ArrayCompare.compare(c1, c2);
}
++k;
}
return len1 - len2;
}
@Override
public Double similarity(IdVector other)
{
Double score = 0.0;
for (Long[] a : idArrayList)
{
for (Long[] b : other.idArrayList)
{
Long distance = ArrayDistance.computeAverageDistance(a, b);
score += 1.0 / (0.1 + distance);
}
}
return score / other.idArrayList.size();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\suggest\scorer\lexeme\IdVector.java | 1 |
请完成以下Java代码 | public static SecretKey ofString(@NonNull String string)
{
return new SecretKey(string);
}
public static Optional<SecretKey> optionalOfString(@Nullable String string)
{
return StringUtils.trimBlankToOptional(string).map(SecretKey::new);
}
@Deprecated
@Override
public String toString() {return getAsString();}
public String getAsString() {return string;} | public boolean isValid(@NonNull final OTP otp)
{
return TOTPUtils.validate(this, otp);
}
public String toHexString()
{
final byte[] bytes = BaseEncoding.base32().decode(string);
//return java.util.HexFormat.of().formatHex(bytes);
return Hex.encodeHexString(bytes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\SecretKey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDATETO() {
return dateto;
}
/**
* Sets the value of the dateto property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATETO(String value) {
this.dateto = value;
}
/**
* Gets the value of the days property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDAYS() {
return days; | }
/**
* Sets the value of the days property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDAYS(String value) {
this.days = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DDATE1.java | 2 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataStoreReference.class, BPMN_ELEMENT_DATA_STORE_REFERENCE)
.namespaceUri(BPMN20_NS)
.extendsType(FlowElement.class)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<DataStoreReference>() {
@Override
public DataStoreReference newInstance(ModelTypeInstanceContext instanceContext) {
return new DataStoreReferenceImpl(instanceContext);
}
});
itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
dataStoreRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DATA_STORE_REF)
.idAttributeReference(DataStore.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataStateChild = sequenceBuilder.element(DataState.class)
.build();
typeBuilder.build();
}
public DataStoreReferenceImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public ItemDefinition getItemSubject() {
return itemSubjectRefAttribute.getReferenceTargetElement(this);
} | public void setItemSubject(ItemDefinition itemSubject) {
itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
public DataState getDataState() {
return dataStateChild.getChild(this);
}
public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
public DataStore getDataStore() {
return dataStoreRefAttribute.getReferenceTargetElement(this);
}
public void setDataStore(DataStore dataStore) {
dataStoreRefAttribute.setReferenceTargetElement(this, dataStore);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataStoreReferenceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void setDubboApplicationQosEnableProperty(Map<String, Object> defaultProperties) {
defaultProperties.put(DUBBO_APPLICATION_QOS_ENABLE_PROPERTY, Boolean.FALSE.toString());
}
/**
* Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be
* <code>true</code> as default.
*
* @param defaultProperties the default {@link Properties properties}
* @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY
* @since 2.7.1
*/
private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) {
defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString());
}
/**
* Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)
*
* @param propertySources {@link MutablePropertySources}
* @param map Default Dubbo Properties
*/
private void addOrReplace(MutablePropertySources propertySources,
Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) { | target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\env\DubboDefaultPropertiesEnvironmentPostProcessor.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.