instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
|
public List<Contact> getContactDetails() {
return contactDetails;
}
public void setContactDetails(List<Contact> contactDetails) {
this.contactDetails = contactDetails;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
}
|
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\snakeyaml\Customer.java
| 1
|
请完成以下Java代码
|
private <T> boolean isApplicable(final ICopyHandler<?> handler, final T from, final T to)
{
final String tTypeTableName = InterfaceWrapperHelper.getModelTableNameOrNull(from);
if (Check.isEmpty(tTypeTableName))
{
return false; // actually shouldn't happen
}
final Class<?> handlerClazz = handler2Class.get(handler);
if (Util.same(NullDocLineCopyHandler.class, handlerClazz))
{
return false; // we are dealing with the null handler. Nothing to do.
}
final String handlerTableName = InterfaceWrapperHelper.getTableNameOrNull(handlerClazz);
if (!Objects.equals(handlerTableName, tTypeTableName))
{
return false; // not applicable, because the handler was registered for a different table
}
if (!handlerClazz.isAssignableFrom(from.getClass()))
{
|
return false; // not applicable, because the handler was registered for a class that is (despite having the same table!) not compatible with the class of 'from' and 'to' example: handler
// has registered for the "commission" order line and 'from' and 'to' are "HU" order lines.
}
@SuppressWarnings("unchecked")
// if reached this point we made sure that the cast won't fail.
final IQueryFilter<IPair<T, T>> filter = (IQueryFilter<IPair<T, T>>)handler2Filter.get(handler);
return filter.accept(ImmutablePair.of(from, to));
}
@SuppressWarnings("unchecked")
@Override
public <T> IDocLineCopyHandler<T> getNullDocLineCopyHandler()
{
return (IDocLineCopyHandler<T>)NullDocLineCopyHandler.instance;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\CopyHandlerBL.java
| 1
|
请完成以下Java代码
|
public class ReadTsKvQueryResult {
private final int queryId;
// Holds the data list;
private final List<TsKvEntry> data;
// Holds the max ts of the records that match aggregation intervals (not the ts of the aggregation window, but the ts of the last record among all the intervals)
private final long lastEntryTs;
public TsValue[] toTsValues() {
if (data != null && !data.isEmpty()) {
List<TsValue> queryValues = new ArrayList<>();
for (TsKvEntry v : data) {
queryValues.add(v.toTsValue()); // TODO: add count here.
}
return queryValues.toArray(new TsValue[queryValues.size()]);
} else {
return new TsValue[0];
}
}
public TsValue toTsValue(ReadTsKvQuery query) {
|
if (data == null || data.isEmpty()) {
if (Aggregation.SUM.equals(query.getAggregation()) || Aggregation.COUNT.equals(query.getAggregation())) {
long ts = query.getStartTs() + (query.getEndTs() - query.getStartTs()) / 2;
return new TsValue(ts, "0");
} else {
return TsValue.EMPTY;
}
}
if (data.size() > 1) {
throw new RuntimeException("Query Result has multiple data points!");
}
return data.get(0).toTsValue();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\ReadTsKvQueryResult.java
| 1
|
请完成以下Java代码
|
private final class CitiesSource implements ResultItemSource
{
private ArrayKey lastQueryKey = null;
private List<CityVO> lastResult = null;
private int countryId = -1;
private int regionId = -1;
@Override
public List<CityVO> query(String searchText, int limit)
{
final int adClientId = getAD_Client_ID();
final int countryId = getC_Country_ID();
final int regionId = getC_Region_ID();
final ArrayKey queryKey = Util.mkKey(adClientId, countryId, regionId);
if (lastQueryKey != null && lastQueryKey.equals(queryKey))
{
return lastResult;
}
final Iterator<CityVO> allCitiesIterator = retrieveAllCities(adClientId, countryId, regionId);
List<CityVO> result = null;
try
{
result = ImmutableList.copyOf(allCitiesIterator);
}
finally
{
IteratorUtils.close(allCitiesIterator);
}
this.lastResult = result;
this.lastQueryKey = queryKey;
return result;
}
private Iterator<CityVO> retrieveAllCities(final int adClientId, final int countryId, final int regionId)
{
if (countryId <= 0)
{
return Collections.emptyIterator();
}
final List<Object> sqlParams = new ArrayList<Object>();
final StringBuilder sql = new StringBuilder(
"SELECT cy.C_City_ID, cy.Name, cy.C_Region_ID, r.Name"
+ " FROM C_City cy"
+ " LEFT OUTER JOIN C_Region r ON (r.C_Region_ID=cy.C_Region_ID)"
+ " WHERE cy.AD_Client_ID IN (0,?)");
sqlParams.add(adClientId);
if (regionId > 0)
{
sql.append(" AND cy.C_Region_ID=?");
sqlParams.add(regionId);
|
}
if (countryId > 0)
{
sql.append(" AND COALESCE(cy.C_Country_ID, r.C_Country_ID)=?");
sqlParams.add(countryId);
}
sql.append(" ORDER BY cy.Name, r.Name");
return IteratorUtils.asIterator(new AbstractPreparedStatementBlindIterator<CityVO>()
{
@Override
protected PreparedStatement createPreparedStatement() throws SQLException
{
final PreparedStatement pstmt = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
return pstmt;
}
@Override
protected CityVO fetch(ResultSet rs) throws SQLException
{
final CityVO vo = new CityVO(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
return vo;
}
});
}
private int getAD_Client_ID()
{
return Env.getAD_Client_ID(Env.getCtx());
}
private int getC_Country_ID()
{
return countryId;
}
public void setC_Country_ID(final int countryId)
{
this.countryId = countryId > 0 ? countryId : -1;
}
public int getC_Region_ID()
{
return regionId;
}
public void setC_Region_ID(final int regionId)
{
this.regionId = regionId > 0 ? regionId : -1;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\CityAutoCompleter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Program fulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram)
{
this.fulfillmentProgram = fulfillmentProgram;
return this;
}
/**
* Get fulfillmentProgram
*
* @return fulfillmentProgram
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public EbayFulfillmentProgram getFulfillmentProgram()
{
return fulfillmentProgram;
}
public void setFulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram)
{
this.fulfillmentProgram = fulfillmentProgram;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Program program = (Program)o;
return Objects.equals(this.authenticityVerification, program.authenticityVerification) &&
Objects.equals(this.fulfillmentProgram, program.fulfillmentProgram);
}
@Override
public int hashCode()
{
return Objects.hash(authenticityVerification, fulfillmentProgram);
}
@Override
|
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Program {\n");
sb.append(" authenticityVerification: ").append(toIndentedString(authenticityVerification)).append("\n");
sb.append(" fulfillmentProgram: ").append(toIndentedString(fulfillmentProgram)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Program.java
| 2
|
请完成以下Java代码
|
protected List<I_C_Period> retrievePeriods(
final Properties ctx,
final int calendarId,
final Timestamp begin,
final Timestamp end,
final String trxName)
{
Check.assume(begin != null, "Param 'begin' is not null");
Check.assume(end != null, "Param 'end' is not null");
final String wc =
I_C_Period.COLUMNNAME_C_Year_ID + " IN ("
+ " select " + I_C_Year.COLUMNNAME_C_Year_ID + " from " + I_C_Year.Table_Name + " where " + I_C_Year.COLUMNNAME_C_Calendar_ID + "=?"
+ ") AND "
+ I_C_Period.COLUMNNAME_EndDate + ">=? AND "
+ I_C_Period.COLUMNNAME_StartDate + "<=?";
return new Query(ctx, I_C_Period.Table_Name, wc, trxName)
.setParameters(calendarId, begin, end)
.setOnlyActiveRecords(true)
.setClient_ID()
// .setApplyAccessFilter(true) isn't required here and case cause problems when running from ad_scheduler
.setOrderBy(I_C_Period.COLUMNNAME_StartDate)
.list(I_C_Period.class);
}
@Override
public List<I_C_Year> retrieveYearsOfCalendar(final I_C_Calendar calendar)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(calendar);
final String trxName = InterfaceWrapperHelper.getTrxName(calendar);
final String whereClause = I_C_Year.COLUMNNAME_C_Calendar_ID + "=?";
return new Query(ctx, I_C_Year.Table_Name, whereClause, trxName)
.setParameters(calendar.getC_Calendar_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
.setOrderBy(I_C_Year.COLUMNNAME_C_Year_ID)
.list(I_C_Year.class);
}
@Override
public I_C_Period retrieveFirstPeriodOfTheYear(final I_C_Year year)
|
{
final Properties ctx = InterfaceWrapperHelper.getCtx(year);
final String trxName = InterfaceWrapperHelper.getTrxName(year);
return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName)
.setParameters(year.getC_Year_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
.setOrderBy(I_C_Period.COLUMNNAME_StartDate)
.first(I_C_Period.class);
}
@Override
public I_C_Period retrieveLastPeriodOfTheYear(final I_C_Year year)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(year);
final String trxName = InterfaceWrapperHelper.getTrxName(year);
return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName)
.setParameters(year.getC_Year_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
.setOrderBy(I_C_Period.COLUMNNAME_StartDate + " DESC ")
.first(I_C_Period.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\CalendarDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Context map(Context context) {
return this.commonKeyValuesFilter.map(context);
}
@Override
public boolean test(String name, Context context) {
return lookupWithFallbackToAll(this.properties.getEnable(), name, true);
}
private static <T> T lookupWithFallbackToAll(Map<String, T> values, String name, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, name, () -> values.getOrDefault("all", defaultValue));
}
private static <T> T doLookup(Map<String, T> values, String name, Supplier<T> defaultValue) {
while (StringUtils.hasLength(name)) {
T result = values.get(name);
if (result != null) {
return result;
|
}
int lastDot = name.lastIndexOf('.');
name = (lastDot != -1) ? name.substring(0, lastDot) : "";
}
return defaultValue.get();
}
private static ObservationFilter createCommonKeyValuesFilter(ObservationProperties properties) {
if (properties.getKeyValues().isEmpty()) {
return (context) -> context;
}
KeyValues keyValues = KeyValues.of(properties.getKeyValues().entrySet(), Entry::getKey, Entry::getValue);
return (context) -> context.addLowCardinalityKeyValues(keyValues);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\PropertiesObservationFilterPredicate.java
| 2
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Time Type.
@param S_TimeType_ID
Type of time recorded
|
*/
public void setS_TimeType_ID (int S_TimeType_ID)
{
if (S_TimeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeType_ID, Integer.valueOf(S_TimeType_ID));
}
/** Get Time Type.
@return Type of time recorded
*/
public int getS_TimeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeType_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_S_TimeType.java
| 1
|
请完成以下Java代码
|
public class TaiwanToTraditionalChineseDictionary extends BaseChineseDictionary
{
static AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<String>();
static
{
long start = System.currentTimeMillis();
String datPath = HanLP.Config.tcDictionaryRoot + "tw2t";
if (!loadDat(datPath, trie))
{
TreeMap<String, String> tw2t = new TreeMap<String, String>();
if (!load(tw2t, true, HanLP.Config.tcDictionaryRoot + "t2tw.txt"))
{
throw new IllegalArgumentException("台湾繁体转繁体加载失败");
}
trie.build(tw2t);
|
saveDat(datPath, trie, tw2t.entrySet());
}
logger.info("台湾繁体转繁体加载成功,耗时" + (System.currentTimeMillis() - start) + "ms");
}
public static String convertToTraditionalChinese(String traditionalTaiwanChineseString)
{
return segLongest(traditionalTaiwanChineseString.toCharArray(), trie);
}
public static String convertToTraditionalChinese(char[] traditionalTaiwanChineseString)
{
return segLongest(traditionalTaiwanChineseString, trie);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\TaiwanToTraditionalChineseDictionary.java
| 1
|
请完成以下Java代码
|
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public boolean getIsLeaf() {
return isLeaf;
}
public void setIsLeaf(boolean isLeaf) {
this.isLeaf = isLeaf;
}
|
public String getPermsType() {
return permsType;
}
public void setPermsType(String permsType) {
this.permsType = permsType;
}
public java.lang.String getStatus() {
return status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
/*update_begin author:wuxianquan date:20190908 for:get set方法 */
public boolean isInternalOrExternal() {
return internalOrExternal;
}
public void setInternalOrExternal(boolean internalOrExternal) {
this.internalOrExternal = internalOrExternal;
}
/*update_end author:wuxianquan date:20190908 for:get set 方法 */
public boolean isHideTab() {
return hideTab;
}
public void setHideTab(boolean hideTab) {
this.hideTab = hideTab;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
| 1
|
请完成以下Java代码
|
protected final void handleException(final String methodName, final ICalloutRecord calloutRecord, final Exception e)
{
logger.warn("{}'s {} failed but ignored for {}", tabCallout, methodName, calloutRecord, e);
}
@Override
public void onIgnore(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onIgnore(calloutRecord);
}
catch (final Exception e)
{
handleException("onIgnore", calloutRecord, e);
}
}
@Override
public void onNew(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onNew(calloutRecord);
}
catch (final Exception e)
{
handleException("onNew", calloutRecord, e);
}
}
@Override
public void onSave(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onSave(calloutRecord);
}
catch (final Exception e)
{
handleException("onSave", calloutRecord, e);
}
}
@Override
public void onDelete(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onDelete(calloutRecord);
}
catch (final Exception e)
{
handleException("onDelete", calloutRecord, e);
}
}
@Override
public void onRefresh(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onRefresh(calloutRecord);
}
catch (final Exception e)
{
handleException("onRefresh", calloutRecord, e);
}
}
@Override
public void onRefreshAll(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onRefreshAll(calloutRecord);
|
}
catch (final Exception e)
{
handleException("onRefreshAll", calloutRecord, e);
}
}
@Override
public void onAfterQuery(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onAfterQuery(calloutRecord);
}
catch (final Exception e)
{
handleException("onAfterQuery", calloutRecord, e);
}
}
private static final class StatefulExceptionHandledTabCallout extends ExceptionHandledTabCallout implements IStatefulTabCallout
{
private StatefulExceptionHandledTabCallout(final IStatefulTabCallout tabCallout)
{
super(tabCallout);
}
@Override
public void onInit(final ICalloutRecord calloutRecord)
{
try
{
((IStatefulTabCallout)tabCallout).onInit(calloutRecord);
}
catch (final Exception e)
{
handleException("onInit", calloutRecord, e);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\ExceptionHandledTabCallout.java
| 1
|
请完成以下Java代码
|
protected final PricingConditionsRowsLoaderBuilder preparePricingConditionsRowData()
{
return PricingConditionsRowsLoader.builder()
.lookups(lookups);
}
@Override
public PricingConditionsView filterView(
@NonNull final IView view,
@NonNull final JSONFilterViewRequest filterViewRequest,
final Supplier<IViewsRepository> viewsRepo_IGNORED)
{
return PricingConditionsView.cast(view)
.filter(filtersFactory.extractFilters(filterViewRequest));
}
private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClass(processClass))
|
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
protected final DocumentFilterList extractFilters(final CreateViewRequest request)
{
return filtersFactory.extractFilters(request);
}
@lombok.Value(staticConstructor = "of")
private static final class ViewLayoutKey
{
WindowId windowId;
JSONViewDataType viewDataType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SmsTwoFaProvider extends OtpBasedTwoFaProvider<SmsTwoFaProviderConfig, SmsTwoFaAccountConfig> {
private final SmsService smsService;
private final AuditLogService auditLogService;
public SmsTwoFaProvider(CacheManager cacheManager, SmsService smsService, AuditLogService auditLogService) {
super(cacheManager);
this.smsService = smsService;
this.auditLogService = auditLogService;
}
@Override
public SmsTwoFaAccountConfig generateNewAccountConfig(User user, SmsTwoFaProviderConfig providerConfig) {
return new SmsTwoFaAccountConfig();
}
@Override
protected void sendVerificationCode(SecurityUser user, String verificationCode, SmsTwoFaProviderConfig providerConfig, SmsTwoFaAccountConfig accountConfig) throws ThingsboardException {
Map<String, String> messageData = Map.of(
"code", verificationCode,
"userEmail", user.getEmail()
);
String message = TbNodeUtils.processTemplate(providerConfig.getSmsVerificationMessageTemplate(), messageData);
String phoneNumber = accountConfig.getPhoneNumber();
try {
smsService.sendSms(user.getTenantId(), user.getCustomerId(), new String[]{phoneNumber}, message);
auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), user, ActionType.SMS_SENT, null, phoneNumber);
|
} catch (ThingsboardException e) {
auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), user, ActionType.SMS_SENT, e, phoneNumber);
throw e;
}
}
@Override
public void check(TenantId tenantId) throws ThingsboardException {
if (!smsService.isConfigured(tenantId)) {
throw new ThingsboardException("SMS service is not configured", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
}
@Override
public TwoFaProviderType getType() {
return TwoFaProviderType.SMS;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\SmsTwoFaProvider.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PrinterRoutingId implements RepoIdAware
{
@JsonCreator
public static PrinterRoutingId ofRepoId(final int repoId)
{
return new PrinterRoutingId(repoId);
}
public static PrinterRoutingId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PrinterRoutingId(repoId) : null;
}
public static int toRepoId(final PrinterRoutingId printerRoutingId)
{
return printerRoutingId != null ? printerRoutingId.getRepoId() : -1;
|
}
int repoId;
private PrinterRoutingId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\PrinterRoutingId.java
| 2
|
请完成以下Java代码
|
private boolean isValid(int[][] board, int row, int column) {
return rowConstraint(board, row) &&
columnConstraint(board, column) &&
subsectionConstraint(board, row, column);
}
private boolean subsectionConstraint(int[][] board, int row, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
if (!checkConstraint(board, r, constraint, c)) return false;
}
}
return true;
}
private boolean columnConstraint(int[][] board, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
if (!checkConstraint(board, row, constraint, column)) {
return false;
}
}
return true;
}
|
private boolean rowConstraint(int[][] board, int row) {
boolean[] constraint = new boolean[BOARD_SIZE];
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
if (!checkConstraint(board, row, constraint, column)) {
return false;
}
}
return true;
}
private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) {
if (board[row][column] != NO_VALUE) {
if (!constraint[board[row][column] - 1]) {
constraint[board[row][column] - 1] = true;
} else {
return false;
}
}
return true;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\BacktrackingAlgorithm.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getJobExecutorAcquisitionName() {
Object object = getFoxLegacyProperties().get(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
if(object == null) {
return "default";
} else {
return (String) object;
}
}
/**
* validates the configuration and throws {@link ProcessEngineException}
* if the configuration is invalid.
*/
public void validate() {
StringBuilder validationErrorBuilder = new StringBuilder("Process engine configuration is invalid: \n");
boolean isValid = true;
if(datasourceJndiName == null || datasourceJndiName.isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'datasource' cannot be null \n");
}
if(engineName == null || engineName.isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'engineName' cannot be null \n");
}
for (int i = 0; i < pluginConfigurations.size(); i++) {
ProcessEnginePluginXml pluginConfiguration = pluginConfigurations.get(i);
if (pluginConfiguration.getPluginClass() == null || pluginConfiguration.getPluginClass().isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'class' in plugin[" + i + "] cannot be null \n");
}
}
if(!isValid) {
throw new ProcessEngineException(validationErrorBuilder.toString());
}
}
private Map<String, String> selectProperties(Map<String, String> allProperties, boolean selectFoxProperties) {
|
Map<String, String> result = null;
if (selectFoxProperties) {
result = new HashMap<String, String>();
String isAutoSchemaUpdate = allProperties.get(PROP_IS_AUTO_SCHEMA_UPDATE);
String isActivateJobExecutor = allProperties.get(PROP_IS_ACTIVATE_JOB_EXECUTOR);
String isIdentityUsed = allProperties.get(PROP_IS_IDENTITY_USED);
String dbTablePrefix = allProperties.get(PROP_DB_TABLE_PREFIX);
String jobExecutorAcquisitionName = allProperties.get(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
if (isAutoSchemaUpdate != null) {
result.put(PROP_IS_AUTO_SCHEMA_UPDATE, isAutoSchemaUpdate);
}
if (isActivateJobExecutor != null) {
result.put(PROP_IS_ACTIVATE_JOB_EXECUTOR, isActivateJobExecutor);
}
if (isIdentityUsed != null) {
result.put(PROP_IS_IDENTITY_USED, isIdentityUsed);
}
if (dbTablePrefix != null) {
result.put(PROP_DB_TABLE_PREFIX, dbTablePrefix);
}
if (jobExecutorAcquisitionName != null) {
result.put(PROP_JOB_EXECUTOR_ACQUISITION_NAME, jobExecutorAcquisitionName);
}
} else {
result = new HashMap<String, String>(allProperties);
result.remove(PROP_IS_AUTO_SCHEMA_UPDATE);
result.remove(PROP_IS_ACTIVATE_JOB_EXECUTOR);
result.remove(PROP_IS_IDENTITY_USED);
result.remove(PROP_DB_TABLE_PREFIX);
result.remove(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
}
return result;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\config\ManagedProcessEngineMetadata.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class HelloReceiver {
@RabbitListener(queues = "hello")
public void process(String hello) {
System.out.println("Receiver : " + hello);
}
@RabbitListener(queues = {"topic.one"})
public void receiveTopic1(@Payload String fileBody) {
log.info("topic1:" + fileBody);
}
@RabbitListener(queues = {"topic.two"})
public void receiveTopic2(@Payload String fileBody) {
|
log.info("topic2:" + fileBody);
}
@RabbitListener(queues = {"fanout.A"})
public void fanoutA(@Payload String fileBody) {
log.info("fanoutA:" + fileBody);
}
@RabbitListener(queues = {"fanout.B"})
public void fanoutB(@Payload String fileBody) {
log.info("fanoutB:" + fileBody);
}
@RabbitListener(queues = {"fanout.C"})
public void fanoutC(@Payload String fileBody) {
log.info("fanoutC:" + fileBody);
}
}
|
repos\springboot-demo-master\rabbitmq\src\main\java\com\et\rabbitmq\receiver\HelloReceiver.java
| 2
|
请完成以下Java代码
|
private Object toJsonValue_PrettyValues(
@Nullable final Object value,
@NonNull final KPIJsonOptions jsonOpts)
{
if (value == null)
{
return null;
}
try
{
if (valueType == KPIFieldValueType.Date)
{
if (value instanceof String)
{
final Date date = TimeUtil.asDate(DateTimeConverters.fromObjectToZonedDateTime(value));
final Language language = Language.getLanguage(jsonOpts.getAdLanguage());
return DisplayType.getDateFormat(DisplayType.Date, language)
.format(date);
}
else if (value instanceof Date)
{
final Date date = (Date)value;
final Language language = Language.getLanguage(jsonOpts.getAdLanguage());
return DisplayType.getDateFormat(DisplayType.Date, language)
.format(date);
}
else if (value instanceof Number)
{
final long millis = ((Number)value).longValue();
final Date date = new Date(millis);
final Language language = Language.getLanguage(jsonOpts.getAdLanguage());
return DisplayType.getDateFormat(DisplayType.Date, language)
.format(date);
}
else
{
return value.toString();
}
}
else if (valueType == KPIFieldValueType.DateTime)
{
if (value instanceof String)
{
final Date date = TimeUtil.asDate(DateTimeConverters.fromObjectToZonedDateTime(value));
final Language language = Language.getLanguage(jsonOpts.getAdLanguage());
return DisplayType.getDateFormat(DisplayType.DateTime, language)
.format(date);
}
else if (value instanceof Date)
{
final Date date = (Date)value;
final Language language = Language.getLanguage(jsonOpts.getAdLanguage());
return DisplayType.getDateFormat(DisplayType.DateTime, language)
.format(date);
}
else if (value instanceof Number)
{
final long millis = ((Number)value).longValue();
final Date date = new Date(millis);
final Language language = Language.getLanguage(jsonOpts.getAdLanguage());
return DisplayType.getDateFormat(DisplayType.DateTime, language)
.format(date);
|
}
else
{
return value.toString();
}
}
else
{
return toJsonValue_NoFormat(value, jsonOpts);
}
}
catch (final Exception ex)
{
logger.warn("Failed converting {} for field {}", value, this, ex);
return value.toString();
}
}
private BigDecimal roundToPrecision(final BigDecimal bd)
{
if (numberPrecision == null)
{
return bd;
}
else
{
return bd.setScale(numberPrecision, RoundingMode.HALF_UP);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataValue.java
| 1
|
请完成以下Java代码
|
private void writeModifiers(IndentingWriter writer, Map<Predicate<Integer>, String> availableModifiers,
int declaredModifiers) {
String modifiers = availableModifiers.entrySet()
.stream()
.filter((entry) -> entry.getKey().test(declaredModifiers))
.map(Entry::getValue)
.collect(Collectors.joining(" "));
if (!modifiers.isEmpty()) {
writer.print(modifiers);
writer.print(" ");
}
}
private Set<String> determineImports(JavaCompilationUnit compilationUnit) {
List<String> imports = new ArrayList<>();
for (JavaTypeDeclaration typeDeclaration : compilationUnit.getTypeDeclarations()) {
imports.add(typeDeclaration.getExtends());
imports.addAll(typeDeclaration.getImplements());
imports.addAll(appendImports(typeDeclaration.annotations().values(), Annotation::getImports));
for (JavaFieldDeclaration fieldDeclaration : typeDeclaration.getFieldDeclarations()) {
imports.add(fieldDeclaration.getReturnType());
imports.addAll(appendImports(fieldDeclaration.annotations().values(), Annotation::getImports));
}
for (JavaMethodDeclaration methodDeclaration : typeDeclaration.getMethodDeclarations()) {
imports.add(methodDeclaration.getReturnType());
imports.addAll(appendImports(methodDeclaration.annotations().values(), Annotation::getImports));
for (Parameter parameter : methodDeclaration.getParameters()) {
imports.add(parameter.getType());
imports.addAll(appendImports(parameter.annotations().values(), Annotation::getImports));
}
imports.addAll(methodDeclaration.getCode().getImports());
}
}
return imports.stream()
.filter((candidate) -> isImportCandidate(compilationUnit, candidate))
.sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
}
|
private <T> List<String> appendImports(Stream<T> candidates, Function<T, Collection<String>> mapping) {
return candidates.map(mapping).flatMap(Collection::stream).collect(Collectors.toList());
}
private String getUnqualifiedName(String name) {
if (!name.contains(".")) {
return name;
}
return name.substring(name.lastIndexOf(".") + 1);
}
private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) {
if (name == null || !name.contains(".")) {
return false;
}
String packageName = name.substring(0, name.lastIndexOf('.'));
return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName);
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaSourceCodeWriter.java
| 1
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Posted.
@param Posted
Posting status
*/
public void setPosted (boolean Posted)
{
set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
/** Get Posted.
@return Posting status
*/
public boolean isPosted ()
{
Object oo = get_Value(COLUMNNAME_Posted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public org.eevolution.model.I_HR_Process getReversal() throws RuntimeException
{
return (org.eevolution.model.I_HR_Process)MTable.get(getCtx(), org.eevolution.model.I_HR_Process.Table_Name)
.getPO(getReversal_ID(), get_TrxName()); }
/** Set Reversal ID.
@param Reversal_ID
ID of document reversal
*/
public void setReversal_ID (int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID));
}
/** Get Reversal ID.
@return ID of document reversal
*/
public int getReversal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_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\eevolution\model\X_HR_Process.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
if (I_M_Tour.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_tour = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_Tour.class, ITrx.TRXNAME_None);
}
if (I_M_TourVersion.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_tourVersion = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_TourVersion.class, ITrx.TRXNAME_None);
p_tour = p_tourVersion.getM_Tour();
}
}
@Override
protected String doIt() throws Exception
{
Check.assumeNotNull(p_DateFrom, "p_DateFrom not null");
Check.assumeNotNull(p_DateTo, "p_DateTo not null");
Check.assumeNotNull(p_tour, "p_tour not null");
//
// Create generator instance and configure it
final IDeliveryDayGenerator generator = tourBL.createDeliveryDayGenerator(this);
generator.setDateFrom(TimeUtil.asLocalDate(p_DateFrom));
generator.setDateTo(TimeUtil.asLocalDate(p_DateTo));
generator.setM_Tour(p_tour);
//
|
// Generate delivery days
if (p_tourVersion == null)
{
generator.generate(getTrxName());
}
else
{
generator.generateForTourVersion(getTrxName(), p_tourVersion);
}
final int countGeneratedDeliveryDays = generator.getCountGeneratedDeliveryDays();
//
// Return result
return "@Created@ #" + countGeneratedDeliveryDays;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\GenerateDeliveryDays.java
| 1
|
请完成以下Java代码
|
private PickingCandidateIssueToBOMLine toPickingCandidateIssueToBOMLine(final IssueToPickingOrderRequest request)
{
return PickingCandidateIssueToBOMLine.builder()
.issueToOrderBOMLineId(request.getIssueToOrderBOMLineId())
.issueFromHUId(request.getIssueFromHUId())
.productId(request.getProductId())
.qtyToIssue(request.getQtyToIssue())
.build();
}
private Quantity getQtyToPick()
{
if (qtyToPick != null)
{
return qtyToPick;
}
else
{
return getQtyFromHU();
}
}
private Quantity getQtyFromHU()
{
final I_M_HU pickFromHU = handlingUnitsDAO.getById(pickFrom.getHuId());
final ProductId productId = getProductId();
final IHUProductStorage productStorage = huContextFactory
.createMutableHUContext()
.getHUStorageFactory()
.getStorage(pickFromHU)
.getProductStorageOrNull(productId);
// Allow empty storage. That's the case when we are adding a newly created HU
if (productStorage == null)
{
final I_C_UOM uom = getShipmentScheduleUOM();
return Quantity.zero(uom);
}
|
return productStorage.getQty();
}
private I_M_ShipmentSchedule getShipmentSchedule()
{
if (_shipmentSchedule == null)
{
_shipmentSchedule = shipmentSchedulesRepo.getById(shipmentScheduleId, I_M_ShipmentSchedule.class);
}
return _shipmentSchedule;
}
private I_C_UOM getShipmentScheduleUOM()
{
return shipmentScheduleBL.getUomOfProduct(getShipmentSchedule());
}
private void allocatePickingSlotIfPossible()
{
if (pickingSlotId == null)
{
return;
}
final I_M_ShipmentSchedule shipmentSchedule = getShipmentSchedule();
final BPartnerLocationId bpartnerAndLocationId = shipmentScheduleEffectiveBL.getBPartnerLocationId(shipmentSchedule);
huPickingSlotBL.allocatePickingSlotIfPossible(PickingSlotAllocateRequest.builder()
.pickingSlotId(pickingSlotId)
.bpartnerAndLocationId(bpartnerAndLocationId)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PickHUCommand.java
| 1
|
请完成以下Java代码
|
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
|
/**
* ProjectCategory AD_Reference_ID=288
* Reference name: C_ProjectType Category
*/
public static final int PROJECTCATEGORY_AD_Reference_ID=288;
/** General = N */
public static final String PROJECTCATEGORY_General = "N";
/** AssetProject = A */
public static final String PROJECTCATEGORY_AssetProject = "A";
/** WorkOrderJob = W */
public static final String PROJECTCATEGORY_WorkOrderJob = "W";
/** ServiceChargeProject = S */
public static final String PROJECTCATEGORY_ServiceChargeProject = "S";
/** ServiceOrRepair = R */
public static final String PROJECTCATEGORY_ServiceOrRepair = "R";
/** SalesPurchaseOrder = O */
public static final String PROJECTCATEGORY_SalesPurchaseOrder = "O";
@Override
public void setProjectCategory (final java.lang.String ProjectCategory)
{
set_ValueNoCheck (COLUMNNAME_ProjectCategory, ProjectCategory);
}
@Override
public java.lang.String getProjectCategory()
{
return get_ValueAsString(COLUMNNAME_ProjectCategory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void setMemberName(String memberName) {
this.memberName = Optional.ofNullable(memberName)
.filter(StringUtils::hasText)
.orElse(this.memberName);
}
protected Optional<String> getMemberName() {
return Optional.ofNullable(this.memberName)
.filter(StringUtils::hasText);
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE) // apply first (e.g. before CacheNameAutoConfiguration)
ClientCacheConfigurer clientCacheMemberNameConfigurer(Environment environment) {
return (beanName, clientCacheFactoryBean) -> configureMemberName(environment, clientCacheFactoryBean);
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE) // apply first (e.g. before CacheNameAutoConfiguration)
PeerCacheConfigurer peerCacheMemberNameConfigurer(Environment environment) {
|
return (beanName, peerCacheFactoryBean) -> configureMemberName(environment, peerCacheFactoryBean);
}
private void configureMemberName(Environment environment, CacheFactoryBean cacheFactoryBean) {
getMemberName()
.filter(memberName -> namePropertiesNotPresent(environment))
.ifPresent(memberName ->
cacheFactoryBean.getProperties().setProperty(GEMFIRE_NAME_PROPERTY, memberName));
}
private boolean namePropertiesArePresent(Environment environment) {
return NAME_PROPERTIES.stream()
.anyMatch(environment::containsProperty);
}
private boolean namePropertiesNotPresent(Environment environment) {
return !namePropertiesArePresent(environment);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\MemberNameConfiguration.java
| 2
|
请完成以下Java代码
|
public class MicrosoftTeamsDeliveryMethodNotificationTemplate extends DeliveryMethodNotificationTemplate implements HasSubject {
private String subject;
private String themeColor;
private Button button;
private final List<TemplatableValue> templatableValues = List.of(
TemplatableValue.of(this::getBody, this::setBody),
TemplatableValue.of(this::getSubject, this::setSubject),
TemplatableValue.of(() -> button != null ? button.getText() : null,
processed -> { if (button != null) button.setText(processed); }),
TemplatableValue.of(() -> button != null ? button.getLink() : null,
processed -> { if (button != null) button.setLink(processed); })
);
public MicrosoftTeamsDeliveryMethodNotificationTemplate(MicrosoftTeamsDeliveryMethodNotificationTemplate other) {
super(other);
this.subject = other.subject;
this.themeColor = other.themeColor;
this.button = other.button != null ? new Button(other.button) : null;
}
@Override
public NotificationDeliveryMethod getMethod() {
return NotificationDeliveryMethod.MICROSOFT_TEAMS;
}
@Override
public MicrosoftTeamsDeliveryMethodNotificationTemplate copy() {
return new MicrosoftTeamsDeliveryMethodNotificationTemplate(this);
}
@Data
|
@NoArgsConstructor
public static class Button {
private boolean enabled;
private String text;
private LinkType linkType;
private String link;
private UUID dashboardId;
private String dashboardState;
private boolean setEntityIdInState;
public Button(Button other) {
this.enabled = other.enabled;
this.text = other.text;
this.linkType = other.linkType;
this.link = other.link;
this.dashboardId = other.dashboardId;
this.dashboardState = other.dashboardState;
this.setEntityIdInState = other.setEntityIdInState;
}
public enum LinkType {
LINK, DASHBOARD
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\template\MicrosoftTeamsDeliveryMethodNotificationTemplate.java
| 1
|
请完成以下Java代码
|
public Collection<AttributeKvEntry> getServerSidePublicAttributes() {
return serverPublicAttributesMap.values();
}
public Optional<AttributeKvEntry> getClientSideAttribute(String attribute) {
return Optional.ofNullable(clientSideAttributesMap.get(attribute));
}
public Optional<AttributeKvEntry> getServerPrivateAttribute(String attribute) {
return Optional.ofNullable(serverPrivateAttributesMap.get(attribute));
}
public Optional<AttributeKvEntry> getServerPublicAttribute(String attribute) {
return Optional.ofNullable(serverPublicAttributesMap.get(attribute));
}
public void remove(AttributeKey key) {
Map<String, AttributeKvEntry> map = getMapByScope(key.getScope());
if (map != null) {
map.remove(key.getAttributeKey());
}
}
public void update(String scope, List<AttributeKvEntry> values) {
Map<String, AttributeKvEntry> map = getMapByScope(scope);
values.forEach(v -> map.put(v.getKey(), v));
}
private Map<String, AttributeKvEntry> getMapByScope(String scope) {
|
Map<String, AttributeKvEntry> map = null;
if (scope.equalsIgnoreCase(DataConstants.CLIENT_SCOPE)) {
map = clientSideAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SHARED_SCOPE)) {
map = serverPublicAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SERVER_SCOPE)) {
map = serverPrivateAttributesMap;
}
return map;
}
@Override
public String toString() {
return "DeviceAttributes{" +
"clientSideAttributesMap=" + clientSideAttributesMap +
", serverPrivateAttributesMap=" + serverPrivateAttributesMap +
", serverPublicAttributesMap=" + serverPublicAttributesMap +
'}';
}
}
|
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\rule\engine\DeviceAttributes.java
| 1
|
请完成以下Java代码
|
public java.lang.String getTimeZone()
{
return get_ValueAsString(COLUMNNAME_TimeZone);
}
@Override
public void setTransferBank_ID (final int TransferBank_ID)
{
if (TransferBank_ID < 1)
set_Value (COLUMNNAME_TransferBank_ID, null);
else
set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID);
}
@Override
public int getTransferBank_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferBank_ID);
}
@Override
public org.compiere.model.I_C_CashBook getTransferCashBook()
{
return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class);
}
|
@Override
public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook)
{
set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook);
}
@Override
public void setTransferCashBook_ID (final int TransferCashBook_ID)
{
if (TransferCashBook_ID < 1)
set_Value (COLUMNNAME_TransferCashBook_ID, null);
else
set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID);
}
@Override
public int getTransferCashBook_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java
| 1
|
请完成以下Java代码
|
public void setUPC (java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
/** Set Verwendet für Kunden.
@param UsedForCustomer Verwendet für Kunden */
@Override
public void setUsedForCustomer (boolean UsedForCustomer)
|
{
set_Value (COLUMNNAME_UsedForCustomer, Boolean.valueOf(UsedForCustomer));
}
/** Get Verwendet für Kunden.
@return Verwendet für Kunden */
@Override
public boolean isUsedForCustomer ()
{
Object oo = get_Value(COLUMNNAME_UsedForCustomer);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_EDI_M_Product_Lookup_UPC_v.java
| 1
|
请完成以下Java代码
|
default AttributeValueId getAttributeValueIdOrNull(final AttributeCode attributeCode)
{
return null;
}
default boolean isValueSet(final Attribute attribute)
{
if (!hasAttribute(attribute))
{
return false;
}
final String value = getValueAsStringOrNull(attribute.getAttributeCode());
return value != null && !Check.isBlank(value);
}
/**
* Set attribute's value and propagate to its parent/child attribute sets.
*
* @throws AttributeNotFoundException if given attribute was not found or is not supported
*/
void setValue(AttributeCode attributeCode, Object value);
default void setValue(@NonNull final String attribute, final Object value)
{
setValue(AttributeCode.ofString(attribute), value);
}
|
void setValue(AttributeId attributeId, Object value);
default void setValue(final @NonNull I_M_Attribute attribute, final Object value)
{
setValue(attribute.getValue(), value);
}
/**
* @return {@link IAttributeValueCallout} instance; never return null
*/
IAttributeValueCallout getAttributeValueCallout(final I_M_Attribute attribute);
/**
* @return true if the given <code>attribute</code>'s value was newly generated
*/
boolean isNew(final I_M_Attribute attribute);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\IAttributeSet.java
| 1
|
请完成以下Java代码
|
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public String getComentTmp() {
return comentTmp;
}
public void setComentTmp(String comentTmp) {
this.comentTmp = comentTmp;
}
public List<String> getComment() {
return comment;
}
public void setComment(List<String> comment) {
this.comment = comment;
}
public String getUrl() {
return url;
|
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlMd5() {
return urlMd5;
}
public void setUrlMd5(String urlMd5) {
this.urlMd5 = urlMd5;
}
@Override
public String toString() {
return "Blog{" + "title='" + title + '\'' + ", publishDate=" + publishDate + ", readCountStr='" + readCountStr
+ '\'' + ", readCount=" + readCount + ", content='" + content + '\'' + ", likeCount=" + likeCount
+ ", comentTmp='" + comentTmp + '\'' + ", url='" + url + '\'' + ", comment=" + comment + '}';
}
}
|
repos\spring-boot-quick-master\quick-vw-crawler\src\main\java\com\crawler\vw\entity\Blog.java
| 1
|
请完成以下Java代码
|
public ServerResponse body(Object body) {
return GatewayEntityResponseBuilder.fromObject(body)
.status(this.statusCode)
.headers(headers -> headers.putAll(this.headers))
.cookies(cookies -> cookies.addAll(this.cookies))
.build();
}
@Override
public <T> ServerResponse body(T body, ParameterizedTypeReference<T> bodyType) {
return GatewayEntityResponseBuilder.fromObject(body, bodyType)
.status(this.statusCode)
.headers(headers -> headers.putAll(this.headers))
.cookies(cookies -> cookies.addAll(this.cookies))
.build();
}
@Override
public ServerResponse render(String name, Object... modelAttributes) {
return new GatewayRenderingResponseBuilder(name).status(this.statusCode)
.headers(headers -> headers.putAll(this.headers))
.cookies(cookies -> cookies.addAll(this.cookies))
.modelAttributes(modelAttributes)
.build();
}
@Override
public ServerResponse render(String name, Map<String, ?> model) {
return new GatewayRenderingResponseBuilder(name).status(this.statusCode)
.headers(headers -> headers.putAll(this.headers))
.cookies(cookies -> cookies.addAll(this.cookies))
.modelAttributes(model)
.build();
}
|
@Override
public ServerResponse stream(Consumer<ServerResponse.StreamBuilder> streamConsumer) {
return GatewayStreamingServerResponse.create(this.statusCode, this.headers, this.cookies, streamConsumer, null);
}
private static class WriteFunctionResponse extends AbstractGatewayServerResponse {
private final WriteFunction writeFunction;
WriteFunctionResponse(HttpStatusCode statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies,
WriteFunction writeFunction) {
super(statusCode, headers, cookies);
Objects.requireNonNull(writeFunction, "WriteFunction must not be null");
this.writeFunction = writeFunction;
}
@Override
protected @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response,
Context context) throws Exception {
return this.writeFunction.write(request, response);
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponseBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setFormDefinitionId(String formDefinitionId) {
this.formDefinitionId = formDefinitionId;
}
@ApiModelProperty(value = "Optional outcome value when completing a task with a form", example = "accepted/rejected")
public String getOutcome() {
return outcome;
}
public void setOutcome(String outcome) {
this.outcome = outcome;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
@ApiModelProperty(value = "If action is complete, you can use this parameter to set variables ")
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getVariables() {
return variables;
}
@ApiModelProperty(value = "If action is complete, you can use this parameter to set transient variables ")
|
public List<RestVariable> getTransientVariables() {
return transientVariables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public void setTransientVariables(List<RestVariable> transientVariables) {
this.transientVariables = transientVariables;
}
@Override
@ApiModelProperty(value = "Action to perform: Either complete, claim, delegate or resolve", example = "complete", required = true)
public String getAction() {
return super.getAction();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskActionRequest.java
| 2
|
请完成以下Java代码
|
public class EntityExportData<E extends ExportableEntity<? extends EntityId>> {
public static final Comparator<EntityRelation> relationsComparator = Comparator
.comparing(EntityRelation::getFrom, Comparator.comparing(EntityId::getId))
.thenComparing(EntityRelation::getTo, Comparator.comparing(EntityId::getId))
.thenComparing(EntityRelation::getTypeGroup)
.thenComparing(EntityRelation::getType);
public static final Comparator<AttributeExportData> attrComparator = Comparator
.comparing(AttributeExportData::getKey).thenComparing(AttributeExportData::getLastUpdateTs);
public static final Comparator<CalculatedField> calculatedFieldsComparator = Comparator.comparing(CalculatedField::getName);
@JsonProperty(index = 2)
@JsonTbEntity
private E entity;
@JsonProperty(index = 1)
private EntityType entityType;
@JsonProperty(index = 100)
private List<EntityRelation> relations;
@JsonProperty(index = 101)
private Map<String, List<AttributeExportData>> attributes;
@JsonProperty(index = 102)
@JsonIgnoreProperties({"id", "entityId", "createdTime", "version"})
private List<CalculatedField> calculatedFields;
public EntityExportData<E> sort() {
if (relations != null && !relations.isEmpty()) {
relations.sort(relationsComparator);
}
if (attributes != null && !attributes.isEmpty()) {
attributes.values().forEach(list -> list.sort(attrComparator));
}
if (calculatedFields != null && !calculatedFields.isEmpty()) {
|
calculatedFields.sort(calculatedFieldsComparator);
}
return this;
}
@JsonIgnore
public EntityId getExternalId() {
return entity.getExternalId() != null ? entity.getExternalId() : entity.getId();
}
@JsonIgnore
public boolean hasCredentials() {
return false;
}
@JsonIgnore
public boolean hasAttributes() {
return attributes != null;
}
@JsonIgnore
public boolean hasRelations() {
return relations != null;
}
@JsonIgnore
public boolean hasCalculatedFields() {
return calculatedFields != null && !calculatedFields.isEmpty();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\sync\ie\EntityExportData.java
| 1
|
请完成以下Java代码
|
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Reply.
@param Reply
Reply or Answer
*/
public void setReply (String Reply)
{
set_Value (COLUMNNAME_Reply, Reply);
}
/** Get Reply.
|
@return Reply or Answer
*/
public String getReply ()
{
return (String)get_Value(COLUMNNAME_Reply);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AccessLog.java
| 1
|
请完成以下Java代码
|
public void setC_DunningRun_ID (int C_DunningRun_ID)
{
if (C_DunningRun_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DunningRun_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DunningRun_ID, Integer.valueOf(C_DunningRun_ID));
}
/** Get Dunning Run.
@return Dunning Run
*/
public int getC_DunningRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Dunning Date.
@param DunningDate
Date of Dunning
*/
public void setDunningDate (Timestamp DunningDate)
{
set_Value (COLUMNNAME_DunningDate, DunningDate);
}
/** Get Dunning Date.
@return Date of Dunning
*/
public Timestamp getDunningDate ()
{
return (Timestamp)get_Value(COLUMNNAME_DunningDate);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getDunningDate()));
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
|
@return The document has been processed
*/
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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Send.
@param SendIt Send */
public void setSendIt (String SendIt)
{
set_Value (COLUMNNAME_SendIt, SendIt);
}
/** Get Send.
@return Send */
public String getSendIt ()
{
return (String)get_Value(COLUMNNAME_SendIt);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
| 1
|
请完成以下Java代码
|
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Java Class Type.
@param AD_JavaClass_Type_ID Java Class Type */
@Override
public void setAD_JavaClass_Type_ID (int AD_JavaClass_Type_ID)
{
if (AD_JavaClass_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_JavaClass_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_JavaClass_Type_ID, Integer.valueOf(AD_JavaClass_Type_ID));
}
/** Get Java Class Type.
@return Java Class Type */
@Override
public int getAD_JavaClass_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_JavaClass_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
|
@Override
public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass_Type.java
| 1
|
请完成以下Java代码
|
public HistoricMilestoneInstanceQuery milestoneInstanceTenantId(String tenantId) {
if (tenantId == null) {
throw new FlowableIllegalArgumentException("tenant id is null");
}
this.tenantId = tenantId;
return this;
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceTenantIdLike(String tenantIdLike) {
if (tenantIdLike == null) {
throw new FlowableIllegalArgumentException("tenant id is null");
}
this.tenantIdLike = tenantIdLike;
return this;
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstanceCountByQueryCriteria(this);
}
@Override
public List<HistoricMilestoneInstance> executeList(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstancesByQueryCriteria(this);
}
@Override
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseDefinitionId() {
|
return caseDefinitionId;
}
public Date getReachedBefore() {
return reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricMilestoneInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public class ADTreeBL implements IADTreeBL
{
@Override
public boolean filterIds(final MTreeNode node, final List<Integer> ids)
{
Check.assumeNotNull(ids, "Param 'ids' is not null");
boolean atLeastOneChildIsDisplayed = false;
if (node == null)
{
return false; // nothing to do
}
for (final MTreeNode currentChild : node.getChildrenAll())
{
// recurse
|
atLeastOneChildIsDisplayed = filterIds(currentChild, ids) || atLeastOneChildIsDisplayed;
}
if (ids.contains(node.getNode_ID()) || atLeastOneChildIsDisplayed)
{
node.setDisplayed(true);
atLeastOneChildIsDisplayed = true;
}
else
{
node.setDisplayed(false);
}
return atLeastOneChildIsDisplayed;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\impl\ADTreeBL.java
| 1
|
请完成以下Java代码
|
protected void parseConfiguration(JsonNode jsonConfiguration) {
parseCacheImplementationClass(jsonConfiguration);
parseCacheConfigurations(jsonConfiguration);
}
protected void parseCacheImplementationClass(JsonNode jsonConfiguration) {
JsonNode jsonNode = jsonConfiguration.get(CONFIG_CACHE_IMPLEMENTATION);
if (jsonNode != null) {
String cacheImplementationClassName = jsonNode.textValue();
Class<?> cacheImplementationClass = loadClass(cacheImplementationClassName);
setCacheImplementationClass(cacheImplementationClass);
}
else {
throw new HalRelationCacheConfigurationException("Unable to find the " + CONFIG_CACHE_IMPLEMENTATION + " parameter");
}
}
protected void parseCacheConfigurations(JsonNode jsonConfiguration) {
JsonNode jsonNode = jsonConfiguration.get(CONFIG_CACHES);
if (jsonNode != null) {
Iterator<Entry<String, JsonNode>> cacheConfigurations = jsonNode.fields();
while (cacheConfigurations.hasNext()) {
Entry<String, JsonNode> cacheConfiguration = cacheConfigurations.next();
parseCacheConfiguration(cacheConfiguration.getKey(), cacheConfiguration.getValue());
}
}
}
|
@SuppressWarnings("unchecked")
protected void parseCacheConfiguration(String halResourceClassName, JsonNode jsonConfiguration) {
try {
Class<?> halResourceClass = loadClass(halResourceClassName);
Map<String, Object> configuration = objectMapper.treeToValue(jsonConfiguration, Map.class);
addCacheConfiguration(halResourceClass, configuration);
} catch (IOException e) {
throw new HalRelationCacheConfigurationException("Unable to parse cache configuration for HAL resource " + halResourceClassName);
}
}
protected Class<?> loadClass(String className) {
try {
// use classloader which loaded the REST api classes
return Class.forName(className, true, HalRelationCacheConfiguration.class.getClassLoader());
}
catch (ClassNotFoundException e) {
throw new HalRelationCacheConfigurationException("Unable to load class of cache configuration " + className, e);
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalRelationCacheConfiguration.java
| 1
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Password.
@param Password
Password of any length (case sensitive)
*/
public void setPassword (String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Password.
@return Password of any length (case sensitive)
*/
public String getPassword ()
{
return (String)get_Value(COLUMNNAME_Password);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
|
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
public void setUserName (String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
public String getUserName ()
{
return (String)get_Value(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
| 1
|
请完成以下Java代码
|
public class DefaultDataTypeTransformerRegistry implements DmnDataTypeTransformerRegistry {
protected static final DmnEngineLogger LOG = DmnLogger.ENGINE_LOGGER;
protected static final Map<String, DmnDataTypeTransformer> transformers = getDefaultTransformers();
protected static Map<String, DmnDataTypeTransformer> getDefaultTransformers() {
Map<String, DmnDataTypeTransformer> transformers = new HashMap<String, DmnDataTypeTransformer>();
transformers.put("string", new StringDataTypeTransformer());
transformers.put("boolean", new BooleanDataTypeTransformer());
transformers.put("integer", new IntegerDataTypeTransformer());
transformers.put("long", new LongDataTypeTransformer());
transformers.put("double", new DoubleDataTypeTransformer());
transformers.put("date", new DateDataTypeTransformer());
return transformers;
}
|
public void addTransformer(String typeName, DmnDataTypeTransformer transformer) {
transformers.put(typeName, transformer);
}
public DmnDataTypeTransformer getTransformer(String typeName) {
if(typeName != null && transformers.containsKey(typeName.toLowerCase())) {
return transformers.get(typeName.toLowerCase());
} else {
LOG.unsupportedTypeDefinitionForClause(typeName);
}
return new IdentityDataTypeTransformer();
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\type\DefaultDataTypeTransformerRegistry.java
| 1
|
请完成以下Java代码
|
private BigDecimal extractBreakValue(final PricingConditionsBreakQuery query)
{
if (!isBreaksDiscountType())
{
throw new AdempiereException("DiscountType shall be Breaks: " + this);
}
else if (breakValueType == BreakValueType.QUANTITY)
{
return query.getQty();
}
else if (breakValueType == BreakValueType.AMOUNT)
{
return query.getAmt();
}
else if (breakValueType == BreakValueType.ATTRIBUTE)
{
final ImmutableAttributeSet attributes = query.getAttributes();
if (attributes.hasAttribute(breakAttributeId))
{
return attributes.getValueAsBigDecimal(breakAttributeId);
}
else
{
return null;
}
}
|
else
{
throw new AdempiereException("Unknown break value type: " + breakValueType);
}
}
public Stream<PricingConditionsBreak> streamBreaksMatchingAnyOfProducts(final Set<ProductAndCategoryAndManufacturerId> products)
{
Check.assumeNotEmpty(products, "products is not empty");
return getBreaks()
.stream()
.filter(schemaBreak -> schemaBreak.getMatchCriteria().productMatchesAnyOf(products));
}
public PricingConditionsBreak getBreakById(@NonNull final PricingConditionsBreakId breakId)
{
PricingConditionsBreakId.assertMatching(getId(), breakId);
return getBreaks()
.stream()
.filter(schemaBreak -> breakId.equals(schemaBreak.getId()))
.findFirst()
.orElseThrow(() -> new AdempiereException("No break found for " + breakId + " in " + this));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BatchPartQuery orderByCreateTime() {
return orderBy(BatchPartQueryProperty.CREATE_TIME);
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public String getBatchId() {
return batchId;
}
public String getSearchKey() {
return searchKey;
}
public String getSearchKey2() {
return searchKey2;
}
public String getBatchType() {
return batchType;
}
public String getBatchSearchKey() {
return batchSearchKey;
}
public String getBatchSearchKey2() {
return batchSearchKey2;
}
public String getStatus() {
return status;
}
public String getScopeId() {
return scopeId;
}
public String getSubScopeId() {
|
return subScopeId;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public boolean isCompleted() {
return completed;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchPartQueryImpl.java
| 2
|
请完成以下Java代码
|
protected void prepare()
{
final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = createQueryBuilder();
final int selectionCount = createSelection(queryBuilder, getPinstanceId());
if (selectionCount <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
@Override
protected Iterable<I_C_Flatrate_Term> getFlatrateTermsToChange()
{
return retrieveSelection(getPinstanceId());
}
private IQueryBuilder<I_C_Flatrate_Term> createQueryBuilder()
{
final IQueryFilter<I_C_Flatrate_Term> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
|
.createQueryBuilder(I_C_Flatrate_Term.class)
.filter(userSelectionFilter)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient();
}
private Iterable<I_C_Flatrate_Term> retrieveSelection(final PInstanceId adPInstanceId)
{
return () -> queryBL
.createQueryBuilder(I_C_Flatrate_Term.class)
.setOnlySelection(adPInstanceId)
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMN_C_Flatrate_Term_ID)
.endOrderBy()
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, false)
.setOption(IQuery.OPTION_IteratorBufferSize, 50)
.iterate(I_C_Flatrate_Term.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change.java
| 1
|
请完成以下Java代码
|
default boolean isConstantTrue()
{
return isConstant() && constantValue() == true;
}
/**
* @return true if the expression is constant and it's value is false
*/
default boolean isConstantFalse()
{
return isConstant() && constantValue() == false;
}
default OptionalBoolean toOptionalBoolean()
{
return isConstant()
? OptionalBoolean.ofBoolean(constantValue())
: OptionalBoolean.UNKNOWN;
}
@Override
default boolean isNoResult(final Object result)
{
// because evaluation is throwing exception in case of failure, the only "no result" would be the NULL
return result == null;
}
@Override
default boolean isNullExpression()
{
// there is no such thing for logic expressions
return false;
}
/**
|
* Compose this logic expression with the given one, using logic AND and return it
*/
default ILogicExpression and(final ILogicExpression expression)
{
return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_AND, expression);
}
default ILogicExpression andNot(final ILogicExpression expression)
{
return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_AND, expression.negate());
}
/**
* Compose this logic expression with the given one, using logic OR and return it
*/
default ILogicExpression or(final ILogicExpression expression)
{
return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_OR, expression);
}
default ILogicExpression negate()
{
// NOTE: because we don't have unary operator support atm, we will use XOR as : !a = a XOR true
//return xor(TRUE); fails, TRUE==null !!
return xor(ConstantLogicExpression.TRUE); // works, not null!
}
default ILogicExpression xor(@NonNull final ILogicExpression expression)
{
return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_XOR, expression);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ILogicExpression.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Song {
@Id
private long id;
private String name;
@Column(name = "length_in_seconds")
private int lengthInSeconds;
private String compositor;
private String singer;
private LocalDateTime released;
private String genre;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLengthInSeconds() {
return lengthInSeconds;
}
public void setLengthInSeconds(int lengthInSeconds) {
this.lengthInSeconds = lengthInSeconds;
}
|
public String getCompositor() {
return compositor;
}
public void setCompositor(String compositor) {
this.compositor = compositor;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
public LocalDateTime getReleased() {
return released;
}
public void setReleased(LocalDateTime released) {
this.released = released;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\jpa\domain\Song.java
| 2
|
请完成以下Java代码
|
public PI addInstruction(String name, String value) {
addAttribute(name, value);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public PI addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public PI addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
|
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public PI addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public PI addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public PI removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\PI.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<I_M_HU_QRCode> getByUniqueId(final @NonNull HUQRCodeUniqueId uniqueId)
{
return queryByQRCode(uniqueId)
.create()
.firstOnlyOptional(I_M_HU_QRCode.class);
}
private void removeAssignment(@NonNull final I_M_HU_QRCode qrCode, @NonNull final ImmutableSet<HuId> huIdsToRemove)
{
streamAssignmentForQrAndHuIds(ImmutableSet.of(HUQRCodeRepoId.ofRepoId(qrCode.getM_HU_QRCode_ID())), huIdsToRemove)
.forEach(InterfaceWrapperHelper::delete);
}
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMN_M_HU_QRCode_ID, huQrCodeIds)
.create()
.stream();
}
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrAndHuIds(
@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds,
|
@NonNull final ImmutableSet<HuId> huIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_QRCode_ID, huQrCodeIds)
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_ID, huIds)
.create()
.stream();
}
private static HUQRCode toHUQRCode(final I_M_HU_QRCode record)
{
return HUQRCode.fromGlobalQRCodeJsonString(record.getRenderedQRCode());
}
public Stream<HUQRCode> streamQRCodesLike(@NonNull final String like)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode.class)
.addOnlyActiveRecordsFilter()
.addStringLikeFilter(I_M_HU_QRCode.COLUMNNAME_RenderedQRCode, like, false)
.orderBy(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID)
.create()
.stream()
.map(HUQRCodesRepository::toHUQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesRepository.java
| 2
|
请完成以下Java代码
|
private static @Nullable String getUniformCode(@Nullable String code) {
if (code == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
builder.append(Character.toLowerCase(ch));
}
}
return builder.toString();
}
/**
|
* {@link Comparator} used to order {@link Status}.
*/
private final class StatusComparator implements Comparator<Status> {
@Override
public int compare(Status s1, Status s2) {
List<String> order = SimpleStatusAggregator.this.order;
int i1 = order.indexOf(getUniformCode(s1.getCode()));
int i2 = order.indexOf(getUniformCode(s2.getCode()));
return (i1 < i2) ? -1 : (i1 != i2) ? 1 : s1.getCode().compareTo(s2.getCode());
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\SimpleStatusAggregator.java
| 1
|
请完成以下Java代码
|
public static <T extends IDeviceResponse> List<IDeviceRequest<T>> getAllRequestsFor(
final DeviceConfig deviceConfig,
final AttributeCode attributeCode,
final Class<T> responseClazz)
{
final Collection<String> requestClassnames = deviceConfig.getRequestClassnames(attributeCode);
if (requestClassnames.isEmpty())
{
logger.warn("Possible configuration issue on {} for attribute '{}': no request classnames found", deviceConfig, attributeCode);
return ImmutableList.of();
}
final List<IDeviceRequest<T>> result = new ArrayList<>();
for (final String currentRequestClassName : requestClassnames)
{
@SuppressWarnings("rawtypes") final IDeviceRequest request = Util.getInstance(IDeviceRequest.class, currentRequestClassName);
if (responseClazz == null || responseClazz.isAssignableFrom(request.getResponseClass()))
{
//noinspection unchecked
result.add(request);
}
}
return result;
}
|
@NonNull
public static ImmutableList<BeforeAcquireValueHook> instantiateHooks(@NonNull final DeviceConfig deviceConfig)
{
return deviceConfig.getBeforeHooksClassname()
.stream()
.map(classname -> {
try
{
return Util.getInstance(BeforeAcquireValueHook.class, classname);
}
catch (final Exception e)
{
throw DeviceConfigException.permanentFailure("Failed instantiating BeforeAcquireValueHook: " + classname, e);
}
})
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceInstanceUtils.java
| 1
|
请完成以下Java代码
|
public void setIsShipConfirm (final boolean IsShipConfirm)
{
set_Value (COLUMNNAME_IsShipConfirm, IsShipConfirm);
}
@Override
public boolean isShipConfirm()
{
return get_ValueAsBoolean(COLUMNNAME_IsShipConfirm);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setIsSplitWhenDifference (final boolean IsSplitWhenDifference)
{
set_Value (COLUMNNAME_IsSplitWhenDifference, IsSplitWhenDifference);
}
@Override
public boolean isSplitWhenDifference()
{
return get_ValueAsBoolean(COLUMNNAME_IsSplitWhenDifference);
}
@Override
public org.compiere.model.I_AD_Sequence getLotNo_Sequence()
{
return get_ValueAsPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class);
}
@Override
public void setLotNo_Sequence(final org.compiere.model.I_AD_Sequence LotNo_Sequence)
{
set_ValueFromPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, LotNo_Sequence);
}
@Override
public void setLotNo_Sequence_ID (final int LotNo_Sequence_ID)
{
if (LotNo_Sequence_ID < 1)
set_Value (COLUMNNAME_LotNo_Sequence_ID, null);
else
set_Value (COLUMNNAME_LotNo_Sequence_ID, LotNo_Sequence_ID);
}
@Override
public int getLotNo_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_LotNo_Sequence_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPrintName (final java.lang.String PrintName)
{
|
set_Value (COLUMNNAME_PrintName, PrintName);
}
@Override
public java.lang.String getPrintName()
{
return get_ValueAsString(COLUMNNAME_PrintName);
}
@Override
public org.compiere.model.I_R_RequestType getR_RequestType()
{
return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class);
}
@Override
public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType)
{
set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType);
}
@Override
public void setR_RequestType_ID (final int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID);
}
@Override
public int getR_RequestType_ID()
{
return get_ValueAsInt(COLUMNNAME_R_RequestType_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPurchaseUnit() {
return purchaseUnit;
}
/**
* Sets the value of the purchaseUnit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPurchaseUnit(String value) {
this.purchaseUnit = value;
}
/**
* Gets the value of the salesUnit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSalesUnit() {
return salesUnit;
}
|
/**
* Sets the value of the salesUnit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSalesUnit(String value) {
this.salesUnit = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PRICATListLineItemExtensionType.java
| 2
|
请完成以下Java代码
|
public class MultiMethodRabbitListenerEndpoint extends MethodRabbitListenerEndpoint {
private final List<Method> methods;
private final @Nullable Method defaultMethod;
private @Nullable Validator validator;
/**
* Construct an instance for the provided methods, default method and bean.
* @param methods the methods.
* @param defaultMethod the default method.
* @param bean the bean.
* @since 2.0.3
*/
@SuppressWarnings("this-escape")
public MultiMethodRabbitListenerEndpoint(List<Method> methods, @Nullable Method defaultMethod, Object bean) {
this.methods = methods;
this.defaultMethod = defaultMethod;
setBean(bean);
}
/**
* Set a payload validator.
* @param validator the validator.
* @since 2.3.7
*/
public void setValidator(Validator validator) {
this.validator = validator;
}
@Override
protected HandlerAdapter configureListenerAdapter(MessagingMessageListenerAdapter messageListener) {
List<InvocableHandlerMethod> invocableHandlerMethods = new ArrayList<>(this.methods.size());
InvocableHandlerMethod defaultHandler = null;
MessageHandlerMethodFactory messageHandlerMethodFactory = getMessageHandlerMethodFactory();
Assert.state(messageHandlerMethodFactory != null,
|
"Could not create message listener - MessageHandlerMethodFactory not set");
Object beanToUse = getBean();
for (Method method : this.methods) {
InvocableHandlerMethod handler = messageHandlerMethodFactory
.createInvocableHandlerMethod(beanToUse, method);
invocableHandlerMethods.add(handler);
if (method.equals(this.defaultMethod)) {
defaultHandler = handler;
}
}
DelegatingInvocableHandler delegatingHandler = new DelegatingInvocableHandler(invocableHandlerMethods,
defaultHandler, getBean(), getResolver(), getBeanExpressionContext(), this.validator);
return new HandlerAdapter(delegatingHandler);
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\MultiMethodRabbitListenerEndpoint.java
| 1
|
请完成以下Java代码
|
public MetasfreshId asMetasfreshId()
{
Check.assume(Type.METASFRESH_ID.equals(type), "The type of this instance needs to be {}; this={}", Type.METASFRESH_ID, this);
final int repoId = Integer.parseInt(value);
return MetasfreshId.of(repoId);
}
public JsonMetasfreshId asJsonMetasfreshId()
{
Check.assume(Type.METASFRESH_ID.equals(type), "The type of this instance needs to be {}; this={}", Type.METASFRESH_ID, this);
final int repoId = Integer.parseInt(value);
return JsonMetasfreshId.of(repoId);
}
public <T extends RepoIdAware> T asMetasfreshId(@NonNull final IntFunction<T> mapper)
{
Check.assume(Type.METASFRESH_ID.equals(type), "The type of this instance needs to be {}; this={}", Type.METASFRESH_ID, this);
final int repoId = Integer.parseInt(value);
return mapper.apply(repoId);
}
public GLN asGLN()
{
Check.assume(Type.GLN.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN, this);
return GLN.ofString(value);
}
public GlnWithLabel asGlnWithLabel()
{
Check.assume(Type.GLN_WITH_LABEL.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN_WITH_LABEL, this);
return GlnWithLabel.ofString(value);
}
|
public String asDoc()
{
Check.assume(Type.DOC.equals(type), "The type of this instance needs to be {}; this={}", Type.DOC, this);
return value;
}
public String asValue()
{
Check.assume(Type.VALUE.equals(type), "The type of this instance needs to be {}; this={}", Type.VALUE, this);
return value;
}
public String asInternalName()
{
Check.assume(Type.INTERNALNAME.equals(type), "The type of this instance needs to be {}; this={}", Type.INTERNALNAME, this);
return value;
}
public boolean isMetasfreshId()
{
return Type.METASFRESH_ID.equals(type);
}
public boolean isExternalId()
{
return Type.EXTERNAL_ID.equals(type);
}
public boolean isValue()
{
return Type.VALUE.equals(type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\IdentifierString.java
| 1
|
请完成以下Java代码
|
public class HostRoutePredicateFactory extends AbstractRoutePredicateFactory<HostRoutePredicateFactory.Config> {
private boolean includePort = true;
private PathMatcher pathMatcher = new AntPathMatcher(".");
public HostRoutePredicateFactory() {
this(true);
}
public HostRoutePredicateFactory(boolean includePort) {
super(Config.class);
this.includePort = includePort;
}
public void setPathMatcher(PathMatcher pathMatcher) {
this.pathMatcher = pathMatcher;
}
/* for testing */ void setIncludePort(boolean includePort) {
this.includePort = includePort;
}
@Override
public List<String> shortcutFieldOrder() {
return Collections.singletonList("patterns");
}
@Override
public ShortcutType shortcutType() {
return ShortcutType.GATHER_LIST;
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
String host;
if (includePort) {
host = exchange.getRequest().getHeaders().getFirst("Host");
}
else {
InetSocketAddress address = exchange.getRequest().getHeaders().getHost();
if (address != null) {
host = address.getHostString();
}
else {
return false;
}
}
if (host == null) {
return false;
}
String match = null;
for (int i = 0; i < config.getPatterns().size(); i++) {
String pattern = config.getPatterns().get(i);
if (pathMatcher.match(pattern, host)) {
|
match = pattern;
break;
}
}
if (match != null) {
Map<String, String> variables = pathMatcher.extractUriTemplateVariables(match, host);
ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);
return true;
}
return false;
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Hosts: %s", config.getPatterns());
}
};
}
public static class Config {
private List<String> patterns = new ArrayList<>();
public List<String> getPatterns() {
return patterns;
}
public Config setPatterns(List<String> patterns) {
this.patterns = patterns;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append("patterns", patterns).toString();
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HostRoutePredicateFactory.java
| 1
|
请完成以下Java代码
|
public String finishEditArticle(Model model, ArticleEditDto articleDto, RedirectAttributes redirectAttrs) {
model.addAttribute("msg", "Add a new article");
//TODO:validate and return to GET:/edit/{id} on errors
articleService.update(articleDto);
redirectAttrs.addFlashAttribute("success", "Article with title " + articleDto.getTitle() + " is updated");
return "redirect:/article/";
}
@PostMapping("/addComment")
public String addComment(NewCommentDto dto, RedirectAttributes redirectAttrs) {
//TODO:validate and return to GET:/add on errors
commentService.save(dto);
|
redirectAttrs.addFlashAttribute("success", "Comment saved. Its currently under review.");
return "redirect:/article/read/" + dto.getArticleId();
}
@GetMapping("/read/{id}")
public String read(@PathVariable Long id, Model model) {
ArticleReadDto dto = articleService.read(id);
//TODO: fix ordering -- ordering is not consistent
model.addAttribute("article", dto);
return "article/read-article";
}
}
|
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\web\mvc\ArticleController.java
| 1
|
请完成以下Java代码
|
public int getQueueSize() {
return getConfiguration().getQueueSize();
}
public void setQueueSize(int queueSize) {
getConfiguration().setQueueSize(queueSize);
}
public boolean isAllowCoreThreadTimeout() {
return getConfiguration().isAllowCoreThreadTimeout();
}
public void setAllowCoreThreadTimeout(boolean allowCoreThreadTimeout) {
getConfiguration().setAllowCoreThreadTimeout(allowCoreThreadTimeout);
}
public long getSecondsToWaitOnShutdown() {
return getConfiguration().getAwaitTerminationPeriod().getSeconds();
}
public void setSecondsToWaitOnShutdown(long secondsToWaitOnShutdown) {
getConfiguration().setAwaitTerminationPeriod(Duration.ofSeconds(secondsToWaitOnShutdown));
}
public BlockingQueue<Runnable> getThreadPoolQueue() {
return threadPoolQueue;
}
public void setThreadPoolQueue(BlockingQueue<Runnable> threadPoolQueue) {
this.threadPoolQueue = threadPoolQueue;
}
public String getThreadPoolNamingPattern() {
return getConfiguration().getThreadPoolNamingPattern();
}
|
public void setThreadPoolNamingPattern(String threadPoolNamingPattern) {
getConfiguration().setThreadPoolNamingPattern(threadPoolNamingPattern);
}
public ThreadFactory getThreadFactory() {
return threadFactory;
}
public void setThreadFactory(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
public RejectedExecutionHandler getRejectedExecutionHandler() {
return rejectedExecutionHandler;
}
public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) {
this.rejectedExecutionHandler = rejectedExecutionHandler;
}
@Override
public int getRemainingCapacity() {
return threadPoolQueue.remainingCapacity();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\async\DefaultAsyncTaskExecutor.java
| 1
|
请完成以下Java代码
|
public R get() {
return this.value;
}
/**
* Return the result of the invocation or the given fallback if the callback
* wasn't suitable.
* @param fallback the fallback to use when there is no result
* @return the result of the invocation or the fallback
*/
public R get(R fallback) {
return (this != NONE) ? this.value : fallback;
}
/**
* Create a new {@link InvocationResult} instance with the specified value.
* @param value the value (may be {@code null})
* @param <R> the result type
* @return an {@link InvocationResult}
*/
public static <R> InvocationResult<R> of(R value) {
return new InvocationResult<>(value);
|
}
/**
* Return an {@link InvocationResult} instance representing no result.
* @param <R> the result type
* @return an {@link InvocationResult}
*/
@SuppressWarnings("unchecked")
public static <R> InvocationResult<R> noResult() {
return (InvocationResult<R>) NONE;
}
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\util\LambdaSafe.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void createPayWay(String payProductCode, String payWayCode, String payTypeCode, Double payRate) throws PayBizException {
RpPayWay payWay = getByPayWayTypeCode(payProductCode,payWayCode,payTypeCode);
if(payWay!=null){
throw new PayBizException(PayBizException.PAY_TYPE_IS_EXIST,"支付渠道已存在");
}
RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(payProductCode, null);
if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){
throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法绑定!");
}
RpPayWay rpPayWay = new RpPayWay();
rpPayWay.setPayProductCode(payProductCode);
rpPayWay.setPayRate(payRate);
rpPayWay.setPayWayCode(payWayCode);
rpPayWay.setPayWayName(PayWayEnum.getEnum(payWayCode).getDesc());
rpPayWay.setPayTypeCode(payTypeCode);
rpPayWay.setPayTypeName(PayTypeEnum.getEnum(payTypeCode).getDesc());
rpPayWay.setStatus(PublicStatusEnum.ACTIVE.name());
rpPayWay.setCreateTime(new Date());
rpPayWay.setId(StringUtil.get32UUID());
saveData(rpPayWay);
}
|
/**
* 根据支付产品获取支付方式
*/
@Override
public List<RpPayWay> listByProductCode(String payProductCode){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("payProductCode", payProductCode);
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpPayWayDao.listBy(paramMap);
}
/**
* 获取所有支付方式
*/
@Override
public List<RpPayWay> listAll(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpPayWayDao.listBy(paramMap);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpPayWayServiceImpl.java
| 2
|
请完成以下Java代码
|
private IHandlingUnitsInfo getHandlingUnitsInfoToSet()
{
if (_handlingUnitsInfoSet)
{
return _handlingUnitsInfo;
}
return null;
}
@Override
public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
_handlingUnitsInfo = handlingUnitsInfo;
_handlingUnitsInfoSet = true;
return this;
}
|
private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet()
{
if (_handlingUnitsInfoProjectedSet)
{
return _handlingUnitsInfoProjected;
}
return null;
}
@Override
public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
_handlingUnitsInfoProjected = handlingUnitsInfo;
_handlingUnitsInfoProjectedSet = true;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java
| 1
|
请完成以下Java代码
|
public void addFileToIndex(String filepath) throws IOException, URISyntaxException {
Path path = Paths.get(getClass().getClassLoader().getResource(filepath).toURI());
File file = path.toFile();
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
IndexWriter indexWriter = new IndexWriter(indexDirectory, indexWriterConfig);
Document document = new Document();
FileReader fileReader = new FileReader(file);
document.add(new TextField("contents", fileReader));
document.add(new StringField("path", file.getPath(), Field.Store.YES));
document.add(new StringField("filename", file.getName(), Field.Store.YES));
indexWriter.addDocument(document);
indexWriter.close();
}
public List<Document> searchFiles(String inField, String queryString) {
try {
Query query = new QueryParser(inField, analyzer).parse(queryString);
|
IndexReader indexReader = DirectoryReader.open(indexDirectory);
IndexSearcher searcher = new IndexSearcher(indexReader);
TopDocs topDocs = searcher.search(query, 10);
List<Document> documents = new ArrayList<>();
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
documents.add(searcher.doc(scoreDoc.doc));
}
return documents;
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
}
|
repos\tutorials-master\lucene\src\main\java\com\baeldung\lucene\LuceneFileSearch.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SignatureVerificationResultType {
@XmlElement(name = "SignatureCheck")
protected int signatureCheck;
@XmlElement(name = "CertificateCheck")
protected int certificateCheck;
@XmlElement(name = "SignatureManifestCheck")
protected int signatureManifestCheck;
/**
* Gets the value of the signatureCheck property.
*
*/
public int getSignatureCheck() {
return signatureCheck;
}
/**
* Sets the value of the signatureCheck property.
*
*/
public void setSignatureCheck(int value) {
this.signatureCheck = value;
}
/**
* Gets the value of the certificateCheck property.
*
*/
public int getCertificateCheck() {
return certificateCheck;
}
/**
* Sets the value of the certificateCheck property.
*
|
*/
public void setCertificateCheck(int value) {
this.certificateCheck = value;
}
/**
* Gets the value of the signatureManifestCheck property.
*
*/
public int getSignatureManifestCheck() {
return signatureManifestCheck;
}
/**
* Sets the value of the signatureManifestCheck property.
*
*/
public void setSignatureManifestCheck(int value) {
this.signatureManifestCheck = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SignatureVerificationResultType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void addPolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
}
@Override
public void removePolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
}
@Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
throw new Error("not implemented");
}
private void loadPolicyClassPath(Model model, Helper.loadPolicyLineHandler<String, Model> handler) {
InputStream is = IsAdapter.class.getResourceAsStream(classPath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
|
String line;
try {
while((line = br.readLine()) != null) {
handler.accept(line, model);
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("IO error occurred");
}
}
}
|
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\IsAdapter.java
| 2
|
请完成以下Java代码
|
public void setVersion(int version) {
this.version = version;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<IdentityLinkEntity> getIdentityLinks() {
if (!isIdentityLinksInitialized) {
definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration()
.getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true;
}
return definitionIdentityLinkEntities;
|
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java
| 1
|
请完成以下Java代码
|
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final LookupValuesPage page = lookupValues.apply(evalCtx);
return page.getValues().getById(evalCtx.getSingleIdToFilterAsObject());
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
return lookupValues.apply(evalCtx);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
//
//
//
//
//
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static class Builder
{
private LookupSource lookupSourceType = LookupSource.list;
private boolean numericKey;
private Function<LookupDataSourceContext, LookupValuesPage> lookupValues;
private Set<String> dependsOnFieldNames;
private Optional<String> lookupTableName = Optional.empty();
private Builder()
{
}
public ListLookupDescriptor build()
{
return new ListLookupDescriptor(this);
}
public Builder setLookupSourceType(@NonNull final LookupSource lookupSourceType)
{
this.lookupSourceType = lookupSourceType;
return this;
}
public Builder setLookupValues(final boolean numericKey, final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
this.numericKey = numericKey;
|
this.lookupValues = lookupValues;
return this;
}
public Builder setIntegerLookupValues(final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
setLookupValues(true, lookupValues);
return this;
}
public Builder setDependsOnFieldNames(final String[] dependsOnFieldNames)
{
this.dependsOnFieldNames = ImmutableSet.copyOf(dependsOnFieldNames);
return this;
}
public Builder setLookupTableName(final String lookupTableName)
{
this.lookupTableName = Check.isEmpty(lookupTableName, true) ? Optional.empty() : Optional.of(lookupTableName);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\ListLookupDescriptor.java
| 1
|
请完成以下Java代码
|
public long findHistoricCaseInstanceCountByQueryCriteria(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
if (isHistoryEnabled()) {
configureHistoricCaseInstanceQuery(historicCaseInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectHistoricCaseInstanceCountByQueryCriteria", historicCaseInstanceQuery);
}
return 0;
}
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findHistoricCaseInstancesByQueryCriteria(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery, Page page) {
if (isHistoryEnabled()) {
configureHistoricCaseInstanceQuery(historicCaseInstanceQuery);
return getDbEntityManager().selectList("selectHistoricCaseInstancesByQueryCriteria", historicCaseInstanceQuery, page);
}
return Collections.EMPTY_LIST;
}
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findHistoricCaseInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbEntityManager().selectListWithRawParameter("selectHistoricCaseInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricCaseInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbEntityManager().selectOne("selectHistoricCaseInstanceCountByNativeQuery", parameterMap);
}
protected void configureHistoricCaseInstanceQuery(HistoricCaseInstanceQueryImpl query) {
getTenantManager().configureQuery(query);
}
@SuppressWarnings("unchecked")
public List<String> findHistoricCaseInstanceIdsForCleanup(int batchSize, int minuteFrom, int minuteTo) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("currentTimestamp", ClockUtil.getCurrentTime());
if (minuteTo - minuteFrom + 1 < 60) {
|
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
ListQueryParameterObject parameterObject = new ListQueryParameterObject(parameters, 0, batchSize);
return getDbEntityManager().selectList("selectHistoricCaseInstanceIdsForCleanup", parameterObject);
}
@SuppressWarnings("unchecked")
public List<CleanableHistoricCaseInstanceReportResult> findCleanableHistoricCaseInstancesReportByCriteria(CleanableHistoricCaseInstanceReportImpl query, Page page) {
query.setCurrentTimestamp(ClockUtil.getCurrentTime());
getTenantManager().configureQuery(query);
return getDbEntityManager().selectList("selectFinishedCaseInstancesReportEntities", query, page);
}
public long findCleanableHistoricCaseInstancesReportCountByCriteria(CleanableHistoricCaseInstanceReportImpl query) {
query.setCurrentTimestamp(ClockUtil.getCurrentTime());
getTenantManager().configureQuery(query);
return (Long) getDbEntityManager().selectOne("selectFinishedCaseInstancesReportEntitiesCount", query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricCaseInstanceManager.java
| 1
|
请完成以下Java代码
|
public WFProcess closeTUPickingTarget(
@NonNull final WFProcessId wfProcessId,
@Nullable final PickingJobLineId lineId,
@NonNull final UserId callerId)
{
return changeWFProcessById(
wfProcessId,
(wfProcess, pickingJob) -> {
wfProcess.assertHasAccess(callerId);
return pickingJobRestService.closeTUPickingTarget(pickingJob, lineId);
});
}
public boolean hasClosedLUs(
@NonNull final WFProcessId wfProcessId,
@Nullable final PickingJobLineId lineId,
@NonNull final UserId callerId)
{
return !getClosedLUs(wfProcessId, lineId, callerId).isEmpty();
}
@NonNull
public List<HuId> getClosedLUs(
@NonNull final WFProcessId wfProcessId,
@Nullable final PickingJobLineId lineId,
@NonNull final UserId callerId)
{
final WFProcess wfProcess = getWFProcessById(wfProcessId);
wfProcess.assertHasAccess(callerId);
final PickingJob pickingJob = getPickingJob(wfProcess);
return pickingJobRestService.getClosedLUs(pickingJob, lineId);
}
|
public WFProcess pickAll(@NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId)
{
final PickingJobId pickingJobId = toPickingJobId(wfProcessId);
final PickingJob pickingJob = pickingJobRestService.pickAll(pickingJobId, callerId);
return toWFProcess(pickingJob);
}
public PickingJobQtyAvailable getQtyAvailable(final WFProcessId wfProcessId, final @NotNull UserId callerId)
{
final PickingJobId pickingJobId = toPickingJobId(wfProcessId);
return pickingJobRestService.getQtyAvailable(pickingJobId, callerId);
}
public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(final @NonNull JsonGetNextEligibleLineRequest request, final @NotNull UserId callerId)
{
final GetNextEligibleLineToPackResponse response = pickingJobRestService.getNextEligibleLineToPack(
GetNextEligibleLineToPackRequest.builder()
.callerId(callerId)
.pickingJobId(toPickingJobId(request.getWfProcessId()))
.excludeLineId(request.getExcludeLineId())
.huScannedCode(request.getHuScannedCode())
.build()
);
return JsonGetNextEligibleLineResponse.builder()
.lineId(response.getLineId())
.logs(response.getLogs())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\PickingMobileApplication.java
| 1
|
请完成以下Java代码
|
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIndexName() {
return this.indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public int getMaxAttempts() {
return this.maxAttempts;
}
public void setMaxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
}
|
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = cleanUri(uri);
}
private static String cleanUri(String contextPath) {
if (StringUtils.hasText(contextPath) && contextPath.endsWith("/")) {
return contextPath.substring(0, contextPath.length() - 1);
}
return contextPath;
}
}
}
|
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\StatsProperties.java
| 1
|
请完成以下Java代码
|
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public boolean equals(Object o) {
|
if (this == o) {
return true;
}
if (!(o instanceof Phone)) {
return false;
}
Phone phone = (Phone) o;
return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode())
&& getNumber().equals(phone.getNumber());
}
@Override
public int hashCode() {
return Objects.hash(getType(), getAreaCode(), getNumber());
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise-2\src\main\java\com\baeldung\elementcollection\model\Phone.java
| 1
|
请完成以下Java代码
|
public void setMaxAsyncJobsDuePerAcquisition(int maxAsyncJobsDuePerAcquisition) {
this.maxAsyncJobsDuePerAcquisition = maxAsyncJobsDuePerAcquisition;
}
public int getDefaultTimerJobAcquireWaitTimeInMillis() {
return defaultTimerJobAcquireWaitTimeInMillis;
}
public void setDefaultTimerJobAcquireWaitTimeInMillis(int defaultTimerJobAcquireWaitTimeInMillis) {
this.defaultTimerJobAcquireWaitTimeInMillis = defaultTimerJobAcquireWaitTimeInMillis;
}
public int getDefaultAsyncJobAcquireWaitTimeInMillis() {
return defaultAsyncJobAcquireWaitTimeInMillis;
}
public void setDefaultAsyncJobAcquireWaitTimeInMillis(int defaultAsyncJobAcquireWaitTimeInMillis) {
this.defaultAsyncJobAcquireWaitTimeInMillis = defaultAsyncJobAcquireWaitTimeInMillis;
}
public void setTimerJobRunnable(AcquireTimerJobsRunnable timerJobRunnable) {
this.timerJobRunnable = timerJobRunnable;
}
public int getDefaultQueueSizeFullWaitTimeInMillis() {
return defaultQueueSizeFullWaitTime;
}
public void setDefaultQueueSizeFullWaitTimeInMillis(int defaultQueueSizeFullWaitTime) {
this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime;
}
public void setAsyncJobsDueRunnable(AcquireAsyncJobsDueRunnable asyncJobsDueRunnable) {
this.asyncJobsDueRunnable = asyncJobsDueRunnable;
}
public void setResetExpiredJobsRunnable(ResetExpiredJobsRunnable resetExpiredJobsRunnable) {
this.resetExpiredJobsRunnable = resetExpiredJobsRunnable;
}
|
public int getRetryWaitTimeInMillis() {
return retryWaitTimeInMillis;
}
public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis;
}
public int getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public ExecuteAsyncRunnableFactory getExecuteAsyncRunnableFactory() {
return executeAsyncRunnableFactory;
}
public void setExecuteAsyncRunnableFactory(ExecuteAsyncRunnableFactory executeAsyncRunnableFactory) {
this.executeAsyncRunnableFactory = executeAsyncRunnableFactory;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\DefaultAsyncJobExecutor.java
| 1
|
请完成以下Java代码
|
public class ConcatRowsExample {
private static final Logger logger = LoggerFactory.getLogger(ConcatRowsExample.class);
public static void main(String[] args) {
SparkSession spark = SparkSession.builder()
.appName("Row-wise Concatenation Example")
.master("local[*]")
.getOrCreate();
try {
// Create sample data
List<Person> data1 = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob")
);
List<Person> data2 = Arrays.asList(
new Person(3, "Charlie"),
new Person(4, "Diana")
);
Dataset<Row> df1 = spark.createDataFrame(data1, Person.class);
Dataset<Row> df2 = spark.createDataFrame(data2, Person.class);
logger.info("First DataFrame:");
df1.show();
logger.info("Second DataFrame:");
df2.show();
// Row-wise concatenation using reusable method
Dataset<Row> combined = concatenateDataFrames(df1, df2);
logger.info("After row-wise concatenation:");
combined.show();
} finally {
spark.stop();
}
}
/**
* Concatenates two DataFrames row-wise using unionByName.
* This method is extracted for reusability and testing.
*/
public static Dataset<Row> concatenateDataFrames(Dataset<Row> df1, Dataset<Row> df2) {
return df1.unionByName(df2);
}
public static class Person implements java.io.Serializable {
private int id;
private String name;
public Person() {
|
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
|
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\spark\dataframeconcat\ConcatRowsExample.java
| 1
|
请完成以下Java代码
|
public abstract class TransportContext {
protected final ObjectMapper mapper = new ObjectMapper();
@Autowired
protected TransportService transportService;
@Autowired
private TbServiceInfoProvider serviceInfoProvider;
@Autowired
private SchedulerComponent scheduler;
@Getter
private ExecutorService executor;
@Getter
@Autowired
private OtaPackageDataCache otaPackageDataCache;
@Autowired
private TransportResourceCache transportResourceCache;
@Autowired
protected TransportRateLimitService rateLimitService;
@PostConstruct
public void init() {
executor = ThingsBoardExecutors.newWorkStealingPool(50, getClass());
|
}
@PreDestroy
public void stop() {
if (executor != null) {
executor.shutdownNow();
}
}
public String getNodeId() {
return serviceInfoProvider.getServiceId();
}
}
|
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\TransportContext.java
| 1
|
请完成以下Java代码
|
private void dynamicDisplay(final int fieldIndex)
{
final Properties ctx = model.getCtx();
final GridField gridField = model.getField(fieldIndex); // allways not null
final VEditor editor = fieldEditors.get(fieldIndex);
final VEditor editorTo = fieldEditorsTo.get(fieldIndex);
final JLabel separator = fieldSeparators.get(fieldIndex);
final JLabel label = fieldLabels.get(fieldIndex);
// Visibility
final boolean editorVisible = (editor != null) && gridField.isDisplayed(ctx);
final boolean editorToVisible = (editorTo != null) && editorVisible;
final boolean labelVisible = editorVisible || editorToVisible;
final boolean separatorVisible = editorVisible || editorToVisible;
// Read-Only/Read-Write
final boolean editorRW = editorVisible && gridField.isEditablePara(ctx);
final boolean editorToRW = editorToVisible && editorRW;
// Update fields
if (label != null)
{
label.setVisible(labelVisible);
}
if (editor != null)
{
editor.setVisible(editorVisible);
editor.setReadWrite(editorRW);
}
if (separator != null)
{
separator.setVisible(separatorVisible);
}
if (editorTo != null)
{
editorTo.setVisible(editorToVisible);
editorTo.setReadWrite(editorToRW);
}
}
public List<ProcessInfoParameter> createParameters()
{
//
// Make sure all editor values are pushed back to model (GridFields)
for (final VEditor editor : fieldEditorsAll)
{
final GridField gridField = editor.getField();
if (gridField == null)
{
// guard agaist null, shall not happen
continue;
}
final Object value = editor.getValue();
model.setFieldValue(gridField, value);
}
//
|
// Ask the model to create the parameters
return model.createProcessInfoParameters();
}
/**
* #782 Request focus on the first process parameter (if possible)
*/
public void focusFirstParameter()
{
if (fieldEditors.isEmpty())
{
// there are no parameters in this process. Nothing to focus
return;
}
for (final VEditor fieldEditor : fieldEditors)
{
final boolean focusGained = getComponent(fieldEditor).requestFocusInWindow();
if (focusGained)
{
return;
}
}
}
} // ProcessParameterPanel
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessParametersPanel.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("field", field)
.add("type", type)
.add("source", source)
.add("emptyText", emptyText)
.add("clearValueText", clearValueText)
.add("actions", devices.isEmpty() ? null : devices)
.add("newRecordWindowId", newRecordWindowId)
.add("advSearchWindowId", advSearchWindowId)
.add("supportZoomInto", supportZoomInto)
.toString();
}
@Nullable
private static DocumentEntityDescriptor findNewRecordEntityDescriptor(
@NonNull final DocumentLayoutElementFieldDescriptor fieldDescriptor,
final JSONDocumentLayoutOptions jsonOpts)
{
if (fieldDescriptor.isForbidNewRecordCreation())
{
return null;
}
final String lookupTableName = fieldDescriptor.getLookupTableName().orElse(null);
if (lookupTableName == null)
{
return null;
}
final NewRecordDescriptorsProvider newRecordDescriptorsProvider = jsonOpts.getNewRecordDescriptorsProvider();
if (newRecordDescriptorsProvider == null)
{
return null;
}
return newRecordDescriptorsProvider.getNewRecordEntityDescriptorIfAvailable(lookupTableName);
}
void setAdvSearchWindow(
final @NonNull WindowId windowId,
final @Nullable DetailId tabId,
final @NonNull JSONDocumentLayoutOptions jsonOpts)
{
if (lookupTableName == null)
{
return;
}
// avoid enabling advanced search assistant for included tabs,
|
// because atm frontend does not support it.
if (tabId != null)
{
return;
}
final AdvancedSearchDescriptorsProvider provider = jsonOpts.getAdvancedSearchDescriptorsProvider();
if (provider == null)
{
return;
}
final DocumentEntityDescriptor advancedSearchEntityDescriptor = provider.getAdvancedSearchDescriptorIfAvailable(lookupTableName);
if (advancedSearchEntityDescriptor != null)
{
advSearchWindowId = advancedSearchEntityDescriptor.getDocumentTypeId().toJson();
advSearchCaption = advancedSearchEntityDescriptor.getCaption().translate(jsonOpts.getAdLanguage());
}
else
{
advSearchWindowId = null;
advSearchCaption = null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutElementField.java
| 1
|
请完成以下Spring Boot application配置
|
canal:
mode: simple
filter: # 过滤表名,可以为空
batch-size: 1
timeout: 1
server: 127.0.0.1:11111
destination: example # canal-server中定义的实例名,不可以为空
user-name: root
passw
|
ord: root
async: true # 必须是true,设为false在启动时会报MessageHandler bean找不到,具体原因没看
|
repos\springboot-demo-master\canal\src\main\resources\application.yaml
| 2
|
请完成以下Spring Boot application配置
|
logging.structured.format.file=ecs
logging.file.name=log.json
logging.structured.ecs.service.name=BaeldungService
logging.structured.ecs.service.version=1
logging.structured.ecs.s
|
ervice.environment=Production
logging.structured.ecs.service.node-name=Primary
|
repos\tutorials-master\spring-boot-modules\spring-boot-3-4\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
QName other = (QName) obj;
if (localName == null) {
if (other.localName != null) {
return false;
}
|
} else if (!localName.equals(other.localName)) {
return false;
}
if (qualifier == null) {
if (other.qualifier != null) {
return false;
}
} else if (!qualifier.equals(other.qualifier)) {
return false;
}
return true;
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\QName.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class VoidInvoicesRelatedToOrderHandler implements VoidOrderAndRelatedDocsHandler
{
@Override
public RecordsToHandleKey getRecordsToHandleKey()
{
return RecordsToHandleKey.of(I_C_Invoice.Table_Name);
}
@Override
public void handleOrderVoided(@NonNull final VoidOrderAndRelatedDocsRequest request)
{
final IPair<RecordsToHandleKey, List<ITableRecordReference>> recordsToHandle = request.getRecordsToHandle();
final List<I_C_Invoice> invoiceRecordsToHandle = TableRecordReference.getModels(recordsToHandle.getRight(), I_C_Invoice.class);
final IDocumentBL documentBL = Services.get(IDocumentBL.class);
for (final I_C_Invoice invoiceRecord : invoiceRecordsToHandle)
{
final DocStatus invoiceDocStatus = DocStatus.ofCode(invoiceRecord.getDocStatus());
if (invoiceDocStatus.isReversedOrVoided())
{
continue; // nothing to do
}
|
if (invoiceDocStatus.isCompleted())
{
documentBL.processEx(invoiceRecord, IDocument.ACTION_Reverse_Correct, DocStatus.Reversed.getCode());
saveRecord(invoiceRecord);
}
else
{
final ITranslatableString errorMsg = VoidOrderAndRelatedDocsHandler.createInvalidDocStatusErrorMessage(
request.getOrderId(),
I_C_Invoice.COLUMNNAME_C_Invoice_ID,
invoiceRecord.getDocumentNo(),
invoiceDocStatus);
throw new AdempiereException(errorMsg,Services.get(IMsgBL.class).getErrorCode(VoidOrderAndRelatedDocsHandler.Msg_OrderDocumentCancelNotAllowed_4P) );
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\order\restart\VoidInvoicesRelatedToOrderHandler.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class JobEntityManagerImpl
extends JobInfoEntityManagerImpl<JobEntity, JobDataManager>
implements JobEntityManager {
public JobEntityManagerImpl(JobServiceConfiguration jobServiceConfiguration, JobDataManager jobDataManager) {
super(jobServiceConfiguration, jobDataManager);
}
@Override
public boolean insertJobEntity(JobEntity timerJobEntity) {
return doInsert(timerJobEntity, true);
}
@Override
public void insert(JobEntity jobEntity, boolean fireCreateEvent) {
doInsert(jobEntity, fireCreateEvent);
}
protected boolean doInsert(JobEntity jobEntity, boolean fireCreateEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
boolean handledJob = serviceConfiguration.getInternalJobManager().handleJobInsert(jobEntity);
if (!handledJob) {
return false;
}
}
jobEntity.setCreateTime(getClock().getCurrentTime());
if (jobEntity.getCorrelationId() == null) {
jobEntity.setCorrelationId(serviceConfiguration.getIdGenerator().getNextId());
}
super.insert(jobEntity, fireCreateEvent);
return true;
}
@Override
public JobEntity findJobByCorrelationId(String correlationId) {
return dataManager.findJobByCorrelationId(correlationId);
}
@Override
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery) {
return dataManager.findJobsByQueryCriteria(jobQuery);
}
@Override
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return dataManager.findJobCountByQueryCriteria(jobQuery);
}
@Override
|
public void delete(JobEntity jobEntity) {
delete(jobEntity, false);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef());
// Send event
FlowableEventDispatcher eventDispatcher = getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity),
serviceConfiguration.getEngineName());
}
}
@Override
public void delete(JobEntity entity, boolean fireDeleteEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobDelete(entity);
}
super.delete(entity, fireDeleteEvent);
}
@Override
public void deleteJobsByExecutionId(String executionId) {
dataManager.deleteJobsByExecutionId(executionId);
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\JobEntityManagerImpl.java
| 2
|
请完成以下Java代码
|
public List<HistoricEntityLink> getHistoricEntityLinkChildrenForTask(String taskId) {
return commandExecutor.execute(new GetHistoricEntityLinkChildrenForTaskCmd(taskId));
}
@Override
public List<HistoricEntityLink> getHistoricEntityLinkParentsForTask(String taskId) {
return commandExecutor.execute(new GetHistoricEntityLinkParentsForTaskCmd(taskId));
}
@Override
public void deleteHistoricTaskLogEntry(long logNumber) {
commandExecutor.execute(new CmmnDeleteHistoricTaskLogEntryCmd(logNumber, configuration));
}
@Override
public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder(TaskInfo task) {
return new HistoricTaskLogEntryBuilderImpl(commandExecutor, task, configuration.getTaskServiceConfiguration());
}
|
@Override
public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder() {
return new HistoricTaskLogEntryBuilderImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
@Override
public HistoricTaskLogEntryQuery createHistoricTaskLogEntryQuery() {
return new HistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
@Override
public NativeHistoricTaskLogEntryQuery createNativeHistoricTaskLogEntryQuery() {
return new NativeHistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnHistoryServiceImpl.java
| 1
|
请完成以下Java代码
|
public class Block {
private static Logger logger = Logger.getLogger(Block.class.getName());
private String hash;
private String previousHash;
private String data;
private long timeStamp;
private int nonce;
public Block(String data, String previousHash, long timeStamp) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = timeStamp;
this.hash = calculateBlockHash();
}
public String mineBlock(int prefix) {
String prefixString = new String(new char[prefix]).replace('\0', '0');
while (!hash.substring(0, prefix)
.equals(prefixString)) {
nonce++;
hash = calculateBlockHash();
}
return hash;
}
public String calculateBlockHash() {
String dataToHash = previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data;
MessageDigest digest = null;
|
byte[] bytes = null;
try {
digest = MessageDigest.getInstance("SHA-256");
bytes = digest.digest(dataToHash.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
logger.log(Level.SEVERE, ex.getMessage());
}
StringBuffer buffer = new StringBuffer();
for (byte b : bytes) {
buffer.append(String.format("%02x", b));
}
return buffer.toString();
}
public String getHash() {
return this.hash;
}
public String getPreviousHash() {
return this.previousHash;
}
public void setData(String data) {
this.data = data;
}
}
|
repos\tutorials-master\java-blockchain\src\main\java\com\baeldung\blockchain\Block.java
| 1
|
请完成以下Java代码
|
public static class ExternalView {
/**
* Label to be shown in the navbar.
*/
private final String label;
/**
* Url for the external view to be linked
*/
private final String url;
/**
* Order in the navbar.
*/
private final Integer order;
/**
* Should the page shown as an iframe or open in a new window.
*/
private final boolean iframe;
/**
* A list of child views.
*/
private final List<ExternalView> children;
public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) {
Assert.hasText(label, "'label' must not be empty");
if (isEmpty(children)) {
Assert.hasText(url, "'url' must not be empty");
}
this.label = label;
this.url = url;
this.order = order;
this.iframe = iframe;
this.children = children;
}
}
|
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ViewSettings {
/**
* Name of the view to address.
*/
private final String name;
/**
* Set view enabled.
*/
private boolean enabled;
public ViewSettings(String name, boolean enabled) {
Assert.hasText(name, "'name' must not be empty");
this.name = name;
this.enabled = enabled;
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UidService {
@Resource
private IdService idService;
// 若没有建立UidConfig类来专门引入ext/vesta/vesta-rest-main.xml文件,则用下面这种方式来手工获取bean也是可以的!!!
// public UidService() {
// ApplicationContext ac = new ClassPathXmlApplicationContext(
// "ext/vesta/vesta-rest-main.xml");
//
// idService = (IdService) ac.getBean("idService");
// }
public long genId() {
return idService.genId();
}
public Id explainId( long id ) {
return idService.expId(id);
}
public String transTime( long time ) {
return idService.transTime(time).toString();
}
public long makeId( long version, long type, long genMethod, long machine, long time, long seq ) {
long madeId = -1;
if (time == -1 || seq == -1)
throw new IllegalArgumentException( "Both time and seq are required." );
else if (version == -1) {
if (type == -1) {
if (genMethod == -1) {
if (machine == -1) {
madeId = idService.makeId(time, seq);
} else {
|
madeId = idService.makeId(machine, time, seq);
}
} else {
madeId = idService.makeId(genMethod, machine, time, seq);
}
} else {
madeId = idService.makeId(type, genMethod, machine, time, seq);
}
} else {
madeId = idService.makeId(version, type, genMethod, time,
seq, machine);
}
return madeId;
}
}
|
repos\Spring-Boot-In-Action-master\springbt_vesta\src\main\java\cn\codesheep\springbt_vesta\service\UidService.java
| 2
|
请完成以下Java代码
|
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_Storage getM_HU_Storage()
{
return get_ValueAsPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class);
}
@Override
public void setM_HU_Storage(final de.metas.handlingunits.model.I_M_HU_Storage M_HU_Storage)
{
set_ValueFromPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class, M_HU_Storage);
}
@Override
public void setM_HU_Storage_ID (final int M_HU_Storage_ID)
{
if (M_HU_Storage_ID < 1)
set_Value (COLUMNNAME_M_HU_Storage_ID, null);
else
set_Value (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID);
}
@Override
public int getM_HU_Storage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID);
}
@Override
|
public void setM_HU_Storage_Snapshot_ID (final int M_HU_Storage_Snapshot_ID)
{
if (M_HU_Storage_Snapshot_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Storage_Snapshot_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Storage_Snapshot_ID, M_HU_Storage_Snapshot_ID);
}
@Override
public int getM_HU_Storage_Snapshot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Storage_Snapshot_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Storage_Snapshot.java
| 1
|
请完成以下Java代码
|
private final GridTab getGridTab()
{
return gridTabWrapper.getGridTab();
}
private final GridField getGridField(final String columnName)
{
return getGridTab().getField(columnName);
}
@Override
public Set<String> getColumnNames()
{
final ImmutableSet.Builder<String> columnNames = ImmutableSet.builder();
for (final GridField gridField : getGridTab().getFields())
{
columnNames.add(gridField.getColumnName());
}
return columnNames.build();
}
@Override
public int getColumnIndex(final String columnName)
{
throw new UnsupportedOperationException("GridTabWrapper has no supported for column indexes");
}
@Override
public boolean isVirtualColumn(final String columnName)
{
final GridField field = getGridField(columnName);
return field != null && field.isVirtualColumn();
}
@Override
public boolean isKeyColumnName(final String columnName)
{
final GridField field = getGridField(columnName);
return field != null && field.isKey();
}
@Override
public boolean isCalculated(final String columnName)
{
final GridField field = getGridField(columnName);
return field != null && field.getVO().isCalculated();
}
@Override
public boolean hasColumnName(final String columnName)
{
return gridTabWrapper.hasColumnName(columnName);
}
@Override
public Object getValue(final String columnName, final int columnIndex, final Class<?> returnType)
{
return gridTabWrapper.getValue(columnName, returnType);
}
@Override
public Object getValue(final String columnName, final Class<?> returnType)
{
return gridTabWrapper.getValue(columnName, returnType);
}
|
@Override
public boolean setValue(final String columnName, final Object value)
{
gridTabWrapper.setValue(columnName, value);
return true;
}
@Override
public boolean setValueNoCheck(final String columnName, final Object value)
{
gridTabWrapper.setValue(columnName, value);
return true;
}
@Override
public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
// TODO: implement
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\GridTabModelInternalAccessor.java
| 1
|
请完成以下Java代码
|
public class ArticleContents {
@Embedded
private ArticleTitle title;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private String body;
@JoinTable(name = "articles_tags",
joinColumns = @JoinColumn(name = "article_id", referencedColumnName = "id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false))
@ManyToMany(fetch = EAGER, cascade = PERSIST)
private Set<Tag> tags = new HashSet<>();
public ArticleContents(String description, ArticleTitle title, String body, Set<Tag> tags) {
this.description = description;
this.title = title;
this.body = body;
this.tags = tags;
}
protected ArticleContents() {
}
public ArticleTitle getTitle() {
return title;
|
}
public String getDescription() {
return description;
}
public String getBody() {
return body;
}
public Set<Tag> getTags() {
return tags;
}
void updateArticleContentsIfPresent(ArticleUpdateRequest updateRequest) {
updateRequest.getTitleToUpdate().ifPresent(titleToUpdate -> title = titleToUpdate);
updateRequest.getDescriptionToUpdate().ifPresent(descriptionToUpdate -> description = descriptionToUpdate);
updateRequest.getBodyToUpdate().ifPresent(bodyToUpdate -> body = bodyToUpdate);
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
}
|
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\ArticleContents.java
| 1
|
请完成以下Java代码
|
private List<I_AD_MigrationData> getMigrationData()
{
if (m_migrationData == null)
{
m_migrationData = Services.get(IMigrationDAO.class).retrieveMigrationData(getAD_MigrationStep());
m_migrationDataKeys = null;
}
return m_migrationData;
}
private List<I_AD_MigrationData> getKeyData()
{
if (m_migrationDataKeys != null)
{
return m_migrationDataKeys;
}
final List<I_AD_MigrationData> dataKeys = new ArrayList<I_AD_MigrationData>();
final List<I_AD_MigrationData> dataParents = new ArrayList<I_AD_MigrationData>();
for (final I_AD_MigrationData data : getMigrationData())
{
final I_AD_Column column = data.getAD_Column();
if (column == null)
{
logger.warn("Column is null for data: {}", new Object[] { data });
continue;
}
if (column.isKey())
{
dataKeys.add(data);
}
|
if (column.isParent())
{
dataParents.add(data);
}
}
if (dataKeys.size() == 1)
{
m_migrationDataKeys = dataKeys;
}
else if (!dataParents.isEmpty())
{
m_migrationDataKeys = dataParents;
}
else
{
throw new AdempiereException("Invalid key/parent constraints. Keys: " + dataKeys + ", Parents: " + dataParents);
}
return m_migrationDataKeys;
}
private void syncDBColumn(final I_AD_Column column, final boolean drop)
{
final IMigrationExecutorContext migrationCtx = getMigrationExecutorContext();
final ColumnSyncDDLExecutable ddlExecutable = new ColumnSyncDDLExecutable(AdColumnId.ofRepoId(column.getAD_Column_ID()), drop);
migrationCtx.addPostponedExecutable(ddlExecutable);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\POMigrationStepExecutor.java
| 1
|
请完成以下Java代码
|
private List<I_M_HU_Attribute> retrieveAttributes(final I_M_HU hu, @NonNull final AttributeId attributeId)
{
final List<I_M_HU_Attribute> huAttributes = Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Attribute.class, hu)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_Attribute.COLUMNNAME_M_HU_ID, hu.getM_HU_ID())
.addEqualsFilter(I_M_HU_Attribute.COLUMNNAME_M_Attribute_ID, attributeId)
.create()
.list(I_M_HU_Attribute.class);
// Optimization: set M_HU link
for (final I_M_HU_Attribute huAttribute : huAttributes)
{
huAttribute.setM_HU(hu);
}
return huAttributes;
}
@Override
@Nullable
public I_M_HU_Attribute retrieveAttribute(final I_M_HU hu, final AttributeId attributeId)
{
final List<I_M_HU_Attribute> huAttributes = retrieveAttributes(hu, attributeId);
if (huAttributes.isEmpty())
|
{
return null;
}
else if (huAttributes.size() == 1)
{
return huAttributes.get(0);
}
else
{
throw new AdempiereException("More than one HU Attributes were found for '" + attributeId + "' on " + hu.getM_HU_ID() + ": " + huAttributes);
}
}
@Override
public void flush()
{
// nothing because there is no internal cache
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUAttributesDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class ResetStockPInstanceId implements RepoIdAware
{
@JsonCreator
public static ResetStockPInstanceId ofRepoId(final int repoId)
{
return new ResetStockPInstanceId(repoId);
}
public static ResetStockPInstanceId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ResetStockPInstanceId(repoId) : null;
}
public static ResetStockPInstanceId ofPInstanceId(@NonNull final PInstanceId pinstanceId)
{
return ofRepoId(pinstanceId.getRepoId());
}
public static int toRepoId(@Nullable final ResetStockPInstanceId id)
{
return id != null ? id.getRepoId() : -1;
|
}
int repoId;
private ResetStockPInstanceId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\stock\ResetStockPInstanceId.java
| 2
|
请完成以下Java代码
|
public ProcessInstanceChangeState setLocalVariables(Map<String, Map<String, Object>> localVariables) {
this.localVariables = localVariables;
return this;
}
public List<EnableActivityContainer> getEnableActivityContainers() {
return enableActivityContainers;
}
public ProcessInstanceChangeState setEnableActivityContainers(List<EnableActivityContainer> enableActivityContainers) {
this.enableActivityContainers = enableActivityContainers;
return this;
}
public List<MoveExecutionEntityContainer> getMoveExecutionEntityContainers() {
return moveExecutionEntityContainers;
}
public ProcessInstanceChangeState setMoveExecutionEntityContainers(List<MoveExecutionEntityContainer> moveExecutionEntityContainers) {
this.moveExecutionEntityContainers = moveExecutionEntityContainers;
return this;
}
public HashMap<String, ExecutionEntity> getCreatedEmbeddedSubProcesses() {
return createdEmbeddedSubProcess;
}
public Optional<ExecutionEntity> getCreatedEmbeddedSubProcessByKey(String key) {
return Optional.ofNullable(createdEmbeddedSubProcess.get(key));
}
public void addCreatedEmbeddedSubProcess(String key, ExecutionEntity executionEntity) {
this.createdEmbeddedSubProcess.put(key, executionEntity);
}
public HashMap<String, ExecutionEntity> getCreatedMultiInstanceRootExecution() {
return createdMultiInstanceRootExecution;
}
public void setCreatedMultiInstanceRootExecution(HashMap<String, ExecutionEntity> createdMultiInstanceRootExecution) {
this.createdMultiInstanceRootExecution = createdMultiInstanceRootExecution;
}
public void addCreatedMultiInstanceRootExecution(String key, ExecutionEntity executionEntity) {
this.createdMultiInstanceRootExecution.put(key, executionEntity);
|
}
public Map<String, List<ExecutionEntity>> getProcessInstanceActiveEmbeddedExecutions() {
return processInstanceActiveEmbeddedExecutions;
}
public ProcessInstanceChangeState setProcessInstanceActiveEmbeddedExecutions(Map<String, List<ExecutionEntity>> processInstanceActiveEmbeddedExecutions) {
this.processInstanceActiveEmbeddedExecutions = processInstanceActiveEmbeddedExecutions;
return this;
}
public HashMap<StartEvent, ExecutionEntity> getPendingEventSubProcessesStartEvents() {
return pendingEventSubProcessesStartEvents;
}
public void addPendingEventSubProcessStartEvent(StartEvent startEvent, ExecutionEntity eventSubProcessParent) {
this.pendingEventSubProcessesStartEvents.put(startEvent, eventSubProcessParent);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\ProcessInstanceChangeState.java
| 1
|
请完成以下Java代码
|
private SubscriptionChain createSubscriptionChain(GraphQlTransport transport) {
SubscriptionChain chain = (request) -> transport
.executeSubscription(request)
.map((response) -> new DefaultClientGraphQlResponse(request, response, getEncoder(), getDecoder()));
return this.interceptors.stream()
.reduce(GraphQlClientInterceptor::andThen)
.map((i) -> (SubscriptionChain) (request) -> i.interceptSubscription(request, chain))
.orElse(chain);
}
private Encoder<?> getEncoder() {
Assert.notNull(this.jsonEncoder, "jsonEncoder has not been set");
return this.jsonEncoder;
}
private Decoder<?> getDecoder() {
Assert.notNull(this.jsonDecoder, "jsonDecoder has not been set");
return this.jsonDecoder;
}
protected static class DefaultJacksonCodecs {
private static final JsonMapper JSON_MAPPER = JsonMapper.builder()
.addModule(new GraphQlJacksonModule()).build();
static Encoder<?> encoder() {
return new JacksonJsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON);
}
static Decoder<?> decoder() {
return new JacksonJsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE);
}
|
}
@SuppressWarnings("removal")
protected static class DefaultJackson2Codecs {
private static final com.fasterxml.jackson.databind.ObjectMapper JSON_MAPPER =
Jackson2ObjectMapperBuilder.json().modulesToInstall(new GraphQlJackson2Module()).build();
static Encoder<?> encoder() {
return new Jackson2JsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON);
}
static Decoder<?> decoder() {
return new Jackson2JsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE);
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
// 该对象用来支持 password 模式
@Autowired
AuthenticationManager authenticationManager;
// 该对象用来将令牌信息存储到内存中
/* @Autowired(required = false)
TokenStore inMemoryTokenStore;*/
@Autowired
RedisConnectionFactory redisConnectionFactory;
// 该对象将为刷新token提供支持
@Autowired
UserDetailsService userDetailsService;
// 指定密码的加密方式
@Bean
PasswordEncoder passwordEncoder() {
// 使用BCrypt强哈希函数加密方案(密钥迭代次数默认为10)
return new BCryptPasswordEncoder();
}
// 配置 password 授权模式
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
|
clients.inMemory()
.withClient("password")
.authorizedGrantTypes("password", "refresh_token") //授权模式为password和refresh_token两种
.accessTokenValiditySeconds(1800) // 配置access_token的过期时间
.resourceIds("rid") //配置资源id
.scopes("all")
.secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq"); //123加密后的密码
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//endpoints.tokenStore(inMemoryTokenStore) //配置令牌的存储(这里存放在内存中)
endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
// 表示支持 client_id 和 client_secret 做登录认证
security.allowFormAuthenticationForClients();
}
}
|
repos\springboot-demo-master\oatuth2\src\main\java\com\et\oauth2\config\AuthorizationServerConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getOutputFolder() {
return outputFolder;
}
public void setOutputFolder(String outputFolder) {
this.outputFolder = outputFolder;
}
@Override
public String toString() {
return "Compiler{" +
"timeout='" + timeout + '\'' +
", outputFolder='" + outputFolder + '\'' +
'}';
}
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public List<Menu> getMenus() {
return menus;
}
|
public void setMenus(List<Menu> menus) {
this.menus = menus;
}
public Compiler getCompiler() {
return compiler;
}
public void setCompiler(Compiler compiler) {
this.compiler = compiler;
}
@Override
public String toString() {
return "AppProperties{" +
"error='" + error + '\'' +
", menus=" + menus +
", compiler=" + compiler +
'}';
}
}
|
repos\spring-boot-master\spring-boot-externalize-config\src\main\java\com\mkyong\global\AppProperties.java
| 2
|
请完成以下Java代码
|
public void start() {
synchronized (lifeCycleMonitor) {
if (!isRunning()) {
enginesBuild.forEach(name -> autoDeployResources(AppEngines.getAppEngine(name)));
running = true;
}
}
}
public Collection<AutoDeploymentStrategy<AppEngine>> getDeploymentStrategies() {
return deploymentStrategies;
}
public void setDeploymentStrategies(Collection<AutoDeploymentStrategy<AppEngine>> deploymentStrategies) {
this.deploymentStrategies = deploymentStrategies;
}
@Override
public void stop() {
synchronized (lifeCycleMonitor) {
|
running = false;
}
}
@Override
public boolean isRunning() {
return running;
}
@Override
public String getDeploymentName() {
return null;
}
@Override
public void setDeploymentName(String deploymentName) {
// not supported
throw new FlowableException("Setting a deployment name is not supported for apps");
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine-spring\src\main\java\org\flowable\app\spring\SpringAppEngineConfiguration.java
| 1
|
请完成以下Java代码
|
public Object get(Object key) {
Object result = null;
if(wrappedBindings.containsKey(key)) {
result = wrappedBindings.get(key);
} else {
for (Resolver scriptResolver: scriptResolvers) {
if (scriptResolver.containsKey(key)) {
result = scriptResolver.get(key);
}
}
}
return result;
}
public Object put(String name, Object value) {
if(autoStoreScriptVariables) {
if (!UNSTORED_KEYS.contains(name)) {
Object oldValue = variableScope.getVariable(name);
variableScope.setVariable(name, value);
return oldValue;
}
}
return wrappedBindings.put(name, value);
}
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return calculateBindingMap().entrySet();
}
public Set<String> keySet() {
return calculateBindingMap().keySet();
}
public int size() {
return calculateBindingMap().size();
}
public Collection<Object> values() {
return calculateBindingMap().values();
}
public void putAll(Map< ? extends String, ? extends Object> toMerge) {
for (java.util.Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return wrappedBindings.remove(key);
}
public void clear() {
|
wrappedBindings.clear();
}
public boolean containsValue(Object value) {
return calculateBindingMap().containsValue(value);
}
public boolean isEmpty() {
return calculateBindingMap().isEmpty();
}
protected Map<String, Object> calculateBindingMap() {
Map<String, Object> bindingMap = new HashMap<String, Object>();
for (Resolver resolver : scriptResolvers) {
for (String key : resolver.keySet()) {
bindingMap.put(key, resolver.get(key));
}
}
Set<java.util.Map.Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet();
for (Entry<String, Object> entry : wrappedBindingsEntries) {
bindingMap.put(entry.getKey(), entry.getValue());
}
return bindingMap;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\ScriptBindings.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public R<List<Tenant>> select(Tenant tenant, BladeUser bladeUser) {
QueryWrapper<Tenant> queryWrapper = Condition.getQueryWrapper(tenant);
List<Tenant> list = tenantService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Tenant::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(list);
}
/**
* 自定义分页
*/
@GetMapping("/page")
@Operation(summary = "分页", description = "传入tenant")
public R<IPage<Tenant>> page(Tenant tenant, Query query) {
IPage<Tenant> pages = tenantService.selectTenantPage(Condition.getPage(query), tenant);
return R.data(pages);
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@Operation(summary = "新增或修改", description = "传入tenant")
public R submit(@Valid @RequestBody Tenant tenant) {
return R.status(tenantService.saveTenant(tenant));
}
/**
* 删除
*/
|
@PostMapping("/remove")
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(tenantService.deleteLogic(Func.toLongList(ids)));
}
/**
* 根据域名查询信息
*
* @param domain 域名
*/
@GetMapping("/info")
@Operation(summary = "配置信息", description = "传入domain")
public R<Kv> info(String domain) {
Tenant tenant = tenantService.getOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getDomain, domain));
Kv kv = Kv.init();
if (tenant != null) {
kv.set("tenantId", tenant.getTenantId()).set("domain", tenant.getDomain());
}
return R.data(kv);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TenantController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
|
this.testOnReturn = testOnReturn;
}
public boolean isPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
public String getConnectionProperties() {
return connectionProperties;
}
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidConfig.java
| 2
|
请完成以下Java代码
|
private ClassPathScanningCandidateComponentProvider getScanner(BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.setEnvironment(this.environment);
scanner.setResourceLoader(this.resourceLoader);
scanner.addIncludeFilter(new AnnotationTypeFilter(ConfigurationProperties.class));
TypeExcludeFilter typeExcludeFilter = new TypeExcludeFilter();
typeExcludeFilter.setBeanFactory((BeanFactory) registry);
scanner.addExcludeFilter(typeExcludeFilter);
return scanner;
}
private void register(ConfigurationPropertiesBeanRegistrar registrar, String className) throws LinkageError {
try {
register(registrar, ClassUtils.forName(className, null));
}
|
catch (ClassNotFoundException ex) {
// Ignore
}
}
private void register(ConfigurationPropertiesBeanRegistrar registrar, Class<?> type) {
if (!isComponent(type)) {
registrar.register(type);
}
}
private boolean isComponent(Class<?> type) {
return MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY).isPresent(Component.class);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesScanRegistrar.java
| 1
|
请完成以下Java代码
|
protected void setSubject(Email email, String subject) {
email.setSubject(subject != null ? subject : "");
}
protected void setMailServerProperties(Email email) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
String host = processEngineConfiguration.getMailServerHost();
ensureNotNull("Could not send email: no SMTP host is configured", "host", host);
email.setHostName(host);
int port = processEngineConfiguration.getMailServerPort();
email.setSmtpPort(port);
email.setTLS(processEngineConfiguration.getMailServerUseTLS());
String user = processEngineConfiguration.getMailServerUsername();
String password = processEngineConfiguration.getMailServerPassword();
if (user != null && password != null) {
email.setAuthentication(user, password);
}
}
protected void setCharset(Email email, String charSetStr) {
if (charset != null) {
email.setCharset(charSetStr);
}
}
|
protected String[] splitAndTrim(String str) {
if (str != null) {
String[] splittedStrings = str.split(",");
for (int i = 0; i < splittedStrings.length; i++) {
splittedStrings[i] = splittedStrings[i].trim();
}
return splittedStrings;
}
return null;
}
protected String getStringFromField(Expression expression, DelegateExecution execution) {
if(expression != null) {
Object value = expression.getValue(execution);
if(value != null) {
return value.toString();
}
}
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\MailActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void asyncSend(String topic, Message<?> message, SendCallback sendCallback, long timeout) {
rocketMQTemplate.asyncSend(topic, message, sendCallback, timeout);
}
/**
* 发送异步消息
*
* @param topic 消息Topic
* @param message 消息实体
* @param sendCallback 回调函数
* @param timeout 超时时间
* @param delayLevel 延迟消息的级别
*/
public void asyncSend(String topic, Message<?> message, SendCallback sendCallback, long timeout, int delayLevel) {
rocketMQTemplate.asyncSend(topic, message, sendCallback, timeout, delayLevel);
}
/**
* 发送顺序消息
*
* @param message
* @param topic
* @param hashKey
*/
public void syncSendOrderly(Enum topic, Message<?> message, String hashKey) {
syncSendOrderly(topic.name(), message, hashKey);
}
/**
* 发送顺序消息
*
* @param message
* @param topic
* @param hashKey
*/
public void syncSendOrderly(String topic, Message<?> message, String hashKey) {
LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey);
rocketMQTemplate.syncSendOrderly(topic, message, hashKey);
}
/**
* 发送顺序消息
*
* @param message
* @param topic
* @param hashKey
* @param timeout
*/
public void syncSendOrderly(String topic, Message<?> message, String hashKey, long timeout) {
LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey + ",timeout:" + timeout);
rocketMQTemplate.syncSendOrderly(topic, message, hashKey, timeout);
}
/**
* 默认CallBack函数
*
* @return
*/
|
private SendCallback getDefaultSendCallBack() {
return new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
LOG.info("---发送MQ成功---");
}
@Override
public void onException(Throwable throwable) {
throwable.printStackTrace();
LOG.error("---发送MQ失败---"+throwable.getMessage(), throwable.getMessage());
}
};
}
@PreDestroy
public void destroy() {
LOG.info("---RocketMq助手注销---");
}
}
|
repos\springboot-demo-master\rocketmq\src\main\java\demo\et59\rocketmq\util\RocketMqHelper.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.