instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setMessageSource(@NonNull MessageSource messageSource) {
Assert.notNull(messageSource, "Message source must not be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the user attributes which will be retrieved from the directory.
* @param userAttributes the set of user attributes to retrieve
*/
public void setUserAttributes(String[] userAttributes) {
Assert.notNull(userAttributes, "The userAttributes property cannot be set to null");
this.userAttributes = userAttributes;
}
/**
* Sets the pattern which will be used to supply a DN for the user. The pattern should
* be the name relative to the root DN. The pattern argument {0} will contain the
* username. An example would be "cn={0},ou=people".
* @param dnPattern the array of patterns which will be tried when converting a
* username to a DN.
*/ | public void setUserDnPatterns(String[] dnPattern) {
Assert.notNull(dnPattern, "The array of DN patterns cannot be set to null");
// this.userDnPattern = dnPattern;
this.userDnFormat = new MessageFormat[dnPattern.length];
for (int i = 0; i < dnPattern.length; i++) {
this.userDnFormat[i] = new MessageFormat(dnPattern[i]);
}
}
public void setUserSearch(LdapUserSearch userSearch) {
Assert.notNull(userSearch, "The userSearch cannot be set to null");
this.userSearch = userSearch;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\AbstractLdapAuthenticator.java | 1 |
请完成以下Java代码 | public int getM_ProductPriceVendorBreak_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPriceVendorBreak_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Limit Price.
@param PriceLimit
Lowest price for a product
*/
public void setPriceLimit (BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
/** Get Limit Price.
@return Lowest price for a product
*/
public BigDecimal getPriceLimit ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set List Price.
@param PriceList
List Price
*/
public void setPriceList (BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get List Price.
@return List Price
*/
public BigDecimal getPriceList ()
{ | BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standard Price.
@param PriceStd
Standard Price
*/
public void setPriceStd (BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standard Price.
@return Standard Price
*/
public BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPriceVendorBreak.java | 1 |
请完成以下Java代码 | private BooleanWithReason checkEligibleToAddAsSourceHU(@NonNull final I_M_HU hu)
{
if (!X_M_HU.HUSTATUS_Active.equals(hu.getHUStatus()))
{
return BooleanWithReason.falseBecause("HU is not active");
}
if (!handlingUnitsBL.isTopLevel(hu))
{
return BooleanWithReason.falseBecause("HU is not top level");
}
return BooleanWithReason.TRUE;
}
public BooleanWithReason checkEligibleToAddToManufacturingOrder(@NonNull final PPOrderId ppOrderId)
{
final I_PP_Order ppOrder = ppOrderBL.getById(ppOrderId);
final DocStatus ppOrderDocStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus());
if (!ppOrderDocStatus.isCompleted())
{
return BooleanWithReason.falseBecause(MSG_ManufacturingOrderNotCompleted, ppOrder.getDocumentNo()); | }
if (ppOrderIssueScheduleService.matchesByOrderId(ppOrderId))
{
return BooleanWithReason.falseBecause(MSG_ManufacturingJobAlreadyStarted, ppOrder.getDocumentNo());
}
return BooleanWithReason.TRUE;
}
@NonNull
public ImmutableSet<HuId> getSourceHUIds(@NonNull final PPOrderId ppOrderId)
{
return ppOrderSourceHURepository.getSourceHUIds(ppOrderId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHUService.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final Part other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(name, other.name)
.append(index, other.index)
.append(mandatory, other.mandatory)
.isEqual();
}
public String getName() | {
return name;
}
public boolean isMandatory()
{
return mandatory;
}
public int getIndex()
{
return index;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\LocationCaptureSequence.java | 1 |
请完成以下Java代码 | public void setWEBUI_Dashboard_ID (final int WEBUI_Dashboard_ID)
{
if (WEBUI_Dashboard_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, WEBUI_Dashboard_ID);
}
@Override
public int getWEBUI_Dashboard_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Dashboard_ID);
}
@Override
public void setWEBUI_DashboardItem_ID (final int WEBUI_DashboardItem_ID)
{
if (WEBUI_DashboardItem_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_DashboardItem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_DashboardItem_ID, WEBUI_DashboardItem_ID);
}
@Override
public int getWEBUI_DashboardItem_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_DashboardItem_ID);
}
/**
* WEBUI_DashboardWidgetType AD_Reference_ID=540697
* Reference name: WEBUI_DashboardWidgetType
*/
public static final int WEBUI_DASHBOARDWIDGETTYPE_AD_Reference_ID=540697;
/** Target = T */
public static final String WEBUI_DASHBOARDWIDGETTYPE_Target = "T";
/** KPI = K */
public static final String WEBUI_DASHBOARDWIDGETTYPE_KPI = "K"; | @Override
public void setWEBUI_DashboardWidgetType (final java.lang.String WEBUI_DashboardWidgetType)
{
set_Value (COLUMNNAME_WEBUI_DashboardWidgetType, WEBUI_DashboardWidgetType);
}
@Override
public java.lang.String getWEBUI_DashboardWidgetType()
{
return get_ValueAsString(COLUMNNAME_WEBUI_DashboardWidgetType);
}
@Override
public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class);
}
@Override
public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI)
{
set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_Value (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_Value (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_DashboardItem.java | 1 |
请完成以下Java代码 | protected boolean beforeSave(final boolean newRecord)
{
// Column AD_Element.ColumnName should be unique - teo_sarca [ 1613107 ]
final boolean columnNameChanged = newRecord || is_ValueChanged(COLUMNNAME_ColumnName);
if (columnNameChanged)
{
final String columnNameEffective = computeEffectiveColumnName(
getColumnName(),
AdElementId.ofRepoIdOrNull(getAD_Element_ID()));
setColumnName(columnNameEffective);
}
return true;
}
@Nullable
private static String computeEffectiveColumnName(@Nullable final String columnName, @Nullable final AdElementId adElementId)
{
if (columnName == null)
{
return null;
}
String columnNameNormalized = StringUtils.trimBlankToNull(columnName);
if (columnNameNormalized == null)
{
return null;
}
columnNameNormalized = StringUtils.ucFirst(columnNameNormalized);
assertColumnNameDoesNotExist(columnNameNormalized, adElementId);
return columnNameNormalized;
}
private static void assertColumnNameDoesNotExist(final String columnName, final AdElementId elementIdToExclude)
{
String sql = "select count(1) from AD_Element where UPPER(ColumnName)=UPPER(?)";
if (elementIdToExclude != null)
{
sql += " AND AD_Element_ID<>" + elementIdToExclude.getRepoId();
}
final int no = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, columnName);
if (no > 0)
{
throw new AdempiereException("@SaveErrorNotUnique@ @ColumnName@: " + columnName); | }
}
@Override
protected boolean afterSave(final boolean newRecord, final boolean success)
{
if (!newRecord)
{
// update dependent entries only in case of existing element.
// new elements are not used yet.
updateDependentADEntries();
}
return success;
}
private void updateDependentADEntries()
{
final AdElementId adElementId = AdElementId.ofRepoId(getAD_Element_ID());
if (is_ValueChanged(COLUMNNAME_ColumnName))
{
final String columnName = getColumnName();
Services.get(IADTableDAO.class).updateColumnNameByAdElementId(adElementId, columnName);
Services.get(IADProcessDAO.class).updateColumnNameByAdElementId(adElementId, columnName);
}
final IElementTranslationBL elementTranslationBL = Services.get(IElementTranslationBL.class);
final ILanguageDAO languageDAO = Services.get(ILanguageDAO.class);
final String baseADLanguage = languageDAO.retrieveBaseLanguage();
elementTranslationBL.propagateElementTrls(adElementId, baseADLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\M_Element.java | 1 |
请完成以下Java代码 | public Optional<CampaignId> getDefaultNewsletterCampaignId(final int orgId)
{
final CampaignId defaultCampaignId = queryBL.createQueryBuilder(I_MKTG_Campaign.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MKTG_Campaign.COLUMN_IsDefaultNewsletter, true)
.addInArrayFilter(I_MKTG_Campaign.COLUMNNAME_AD_Org_ID, orgId, 0)
.orderByDescending(I_MKTG_Campaign.COLUMNNAME_AD_Org_ID)
.create()
.firstId(CampaignId::ofRepoIdOrNull);
return Optional.ofNullable(defaultCampaignId);
}
public void removeContactPersonFromCampaign(
@NonNull final ContactPerson contactPerson,
@NonNull final Campaign campaign)
{ | final ContactPersonId contactPersonId = Check.assumeNotNull(contactPerson.getContactPersonId(), "contact shall be saved: {}", contactPerson);
queryBL.createQueryBuilder(I_MKTG_Campaign_ContactPerson.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_Campaign_ID, campaign.getCampaignId())
.addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_ContactPerson_ID, contactPersonId.getRepoId())
.create()
.delete();
}
public void removeAllContactPersonsFromCampaign(final CampaignId campaignId)
{
queryBL.createQueryBuilder(I_MKTG_Campaign_ContactPerson.class)
.addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_Campaign_ID, campaignId)
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\CampaignRepository.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 Send dunning letters.
@param SendDunningLetter
Indicates if dunning letters will be sent
*/
public void setSendDunningLetter (boolean SendDunningLetter)
{
set_Value (COLUMNNAME_SendDunningLetter, Boolean.valueOf(SendDunningLetter));
} | /** Get Send dunning letters.
@return Indicates if dunning letters will be sent
*/
public boolean isSendDunningLetter ()
{
Object oo = get_Value(COLUMNNAME_SendDunningLetter);
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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Dunning.java | 1 |
请完成以下Java代码 | private void setEnabledByCaptureSequence(final boolean enabledByCaptureSequence)
{
if (this.enabledByCaptureSequence == enabledByCaptureSequence)
{
return;
}
this.enabledByCaptureSequence = enabledByCaptureSequence;
update();
}
private final void update()
{
final boolean enabled = enabledCustom && enabledByCaptureSequence;
label.setEnabled(enabled);
label.setVisible(enabled);
field.setEnabled(enabled);
field.setVisible(enabled);
} | public void setLabelText(final String labelText)
{
label.setText(labelText);
}
public JLabel getLabel()
{
return label;
}
public JComponent getField()
{
return field;
}
}
} // VLocationDialog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocationDialog.java | 1 |
请完成以下Java代码 | public void setPP_Order_NodeNext_ID (int PP_Order_NodeNext_ID)
{
if (PP_Order_NodeNext_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_NodeNext_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_NodeNext_ID, Integer.valueOf(PP_Order_NodeNext_ID));
}
/** Get Manufacturing Order Activity Next.
@return Manufacturing Order Activity Next */
@Override
public int getPP_Order_NodeNext_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_NodeNext_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Transition Code.
@param TransitionCode
Code resulting in TRUE of FALSE
*/
@Override
public void setTransitionCode (java.lang.String TransitionCode)
{
set_Value (COLUMNNAME_TransitionCode, TransitionCode);
}
/** Get Transition Code.
@return Code resulting in TRUE of FALSE
*/
@Override
public java.lang.String getTransitionCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransitionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_NodeNext.java | 1 |
请完成以下Java代码 | private NamePair findValueDirectly(final String valueKey)
{
return attributeValuesNP_HighVolumeCache.computeIfAbsent(valueKey, key -> {
final AttributeListValue av = attributeDAO.retrieveAttributeValueOrNull(attribute, valueKey);
return av == null ? null : toValueNamePair(av);
});
}
@Override
public NamePair getNullValue()
{
return getAttributeValuesMap().getNullValue();
}
@Override
public boolean isHighVolume()
{
if (_highVolume == null)
{
_highVolume = attribute.isHighVolumeValuesList();
}
return _highVolume;
}
@Immutable
private static final class AttributeValuesMap
{
@Getter private final NamePair nullValue;
private final ImmutableMap<String, NamePair> valuesByKey;
private final ImmutableList<NamePair> valuesList;
private final ImmutableMap<String, AttributeValueId> attributeValueIdByKey;
private AttributeValuesMap(final Attribute attribute, final Collection<AttributeListValue> attributeValues)
{
final ImmutableMap.Builder<String, NamePair> valuesByKey = ImmutableMap.builder();
final ImmutableMap.Builder<String, AttributeValueId> attributeValueIdByKey = ImmutableMap.builder();
NamePair nullValue = null;
for (final AttributeListValue av : attributeValues)
{
if (!av.isActive())
{
continue;
}
final ValueNamePair vnp = toValueNamePair(av);
valuesByKey.put(vnp.getValue(), vnp);
attributeValueIdByKey.put(vnp.getValue(), av.getId());
//
// Null placeholder value (if defined)
if (av.isNullFieldValue())
{
Check.assumeNull(nullValue, "Only one null value shall be defined for {}, but we found: {}, {}",
attribute.getDisplayName().getDefaultValue(), nullValue, av);
nullValue = vnp; | }
}
this.valuesByKey = valuesByKey.build();
this.valuesList = ImmutableList.copyOf(this.valuesByKey.values());
this.attributeValueIdByKey = attributeValueIdByKey.build();
this.nullValue = nullValue;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("values", valuesList)
.add("nullValue", nullValue)
.toString();
}
public List<NamePair> getValues()
{
return valuesList;
}
public NamePair getValueByKeyOrNull(final String key)
{
return valuesByKey.get(key);
}
public AttributeValueId getAttributeValueId(final String valueKey)
{
final AttributeValueId attributeValueId = attributeValueIdByKey.get(valueKey);
if (attributeValueId == null)
{
throw new AdempiereException("No M_AttributeValue_ID found for '" + valueKey + "'");
}
return attributeValueId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\spi\impl\DefaultAttributeValuesProvider.java | 1 |
请完成以下Java代码 | public class SubProcessActivityBehavior extends AbstractBpmnActivityBehavior implements CompositeActivityBehavior {
@Override
public void execute(DelegateExecution execution) {
ActivityExecution activityExecution = (ActivityExecution) execution;
PvmActivity activity = activityExecution.getActivity();
ActivityImpl initialActivity = (ActivityImpl) activity.getProperty(BpmnParse.PROPERTYNAME_INITIAL);
if (initialActivity == null) {
throw new ActivitiException("No initial activity found for subprocess "
+ activityExecution.getActivity().getId());
}
// initialize the template-defined data objects as variables
initializeDataObjects(activityExecution, activity);
if (initialActivity.getActivityBehavior() != null
&& initialActivity.getActivityBehavior() instanceof NoneStartEventActivityBehavior) { // embedded subprocess: only none start allowed
((ExecutionEntity) execution).setActivity(initialActivity);
Context.getCommandContext().getHistoryManager().recordActivityStart((ExecutionEntity) execution);
}
activityExecution.executeActivity(initialActivity);
} | @Override
public void lastExecutionEnded(ActivityExecution execution) {
ScopeUtil.createEventScopeExecution((ExecutionEntity) execution);
// remove the template-defined data object variables
Map<String, Object> dataObjectVars = ((ActivityImpl) execution.getActivity()).getVariables();
if (dataObjectVars != null) {
execution.removeVariablesLocal(dataObjectVars.keySet());
}
bpmnActivityBehavior.performDefaultOutgoingBehavior(execution);
}
protected void initializeDataObjects(ActivityExecution execution, PvmActivity activity) {
Map<String, Object> dataObjectVars = ((ActivityImpl) activity).getVariables();
if (dataObjectVars != null) {
execution.setVariablesLocal(dataObjectVars);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\SubProcessActivityBehavior.java | 1 |
请完成以下Java代码 | public static StringDictionary load(String path)
{
return load(path, "=");
}
/**
* 合并词典,第一个为主词典
* @param args
* @return
*/
public static StringDictionary combine(StringDictionary... args)
{
StringDictionary[] dictionaries = args.clone();
StringDictionary mainDictionary = dictionaries[0];
for (int i = 1; i < dictionaries.length; ++i)
{
mainDictionary.combine(dictionaries[i]);
}
return mainDictionary; | }
public static StringDictionary combine(String... args)
{
String[] pathArray = args.clone();
List<StringDictionary> dictionaryList = new LinkedList<StringDictionary>();
for (String path : pathArray)
{
StringDictionary dictionary = load(path);
if (dictionary == null) continue;
dictionaryList.add(dictionary);
}
return combine(dictionaryList.toArray(new StringDictionary[0]));
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\StringDictionaryMaker.java | 1 |
请完成以下Java代码 | public final class ConversionHelper
{
private ConversionHelper()
{
super();
}
/**
* @param valueObj
* @return object converted to {@link BigDecimal}
* @throws IllegalArgumentException if value could not be converted to {@link BigDecimal}
*/
public static final BigDecimal toBigDecimal(final Object valueObj) throws IllegalArgumentException
{
if (valueObj == null)
{
return BigDecimal.ZERO;
}
else if (valueObj instanceof BigDecimal)
{
return (BigDecimal)valueObj;
}
else if (valueObj instanceof String)
{ | return new BigDecimal((String)valueObj);
}
else if (valueObj instanceof Integer)
{
final int valueInt = (Integer)valueObj;
return BigDecimal.valueOf(valueInt);
}
else if (valueObj instanceof Number)
{
final Number valueNum = (Number)valueObj;
return new BigDecimal(valueNum.toString());
}
else
{
throw new IllegalArgumentException("Invalid BigDecimal value: " + valueObj + " (class=" + valueObj.getClass() + ")");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\conversion\ConversionHelper.java | 1 |
请完成以下Java代码 | public class MultiplicationBenchmark {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(MultiplicationBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
private int smallValue = 255;
private int largeValue = 2187657;
@Benchmark
public int smallValueWithParentheses() {
return 2 * (smallValue * smallValue);
} | @Benchmark
public int smallValueWithoutParentheses() {
return 2 * smallValue * smallValue;
}
@Benchmark
public int largeValueWithParentheses() {
return 2 * (largeValue * largeValue);
}
@Benchmark
public int largeValueWithoutParentheses() {
return 2 * largeValue * largeValue;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-4\src\main\java\com\baeldung\math\fastermultiplication\MultiplicationBenchmark.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getMchId() {
return mchId;
}
public void setMchId(String mchId) {
this.mchId = mchId;
}
public String getDeviceInfo() {
return deviceInfo;
}
public void setDeviceInfo(String deviceInfo) {
this.deviceInfo = deviceInfo;
}
public String getNonceStr() {
return nonceStr;
}
public void setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
}
public String getOutTradeNo() {
return outTradeNo;
}
public void setOutTradeNo(String outTradeNo) {
this.outTradeNo = outTradeNo;
}
public String getFeeType() {
return feeType;
}
public void setFeeType(String feeType) {
this.feeType = feeType;
}
public Integer getTotalFee() {
return totalFee;
}
public void setTotalFee(Integer totalFee) {
this.totalFee = totalFee;
}
public String getSpbillCreateIp() {
return spbillCreateIp;
} | public void setSpbillCreateIp(String spbillCreateIp) {
this.spbillCreateIp = spbillCreateIp;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeExpire() {
return timeExpire;
}
public void setTimeExpire(String timeExpire) {
this.timeExpire = timeExpire;
}
public String getGoodsTag() {
return goodsTag;
}
public void setGoodsTag(String goodsTag) {
this.goodsTag = goodsTag;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public WeiXinTradeTypeEnum getTradeType() {
return tradeType;
}
public void setTradeType(WeiXinTradeTypeEnum tradeType) {
this.tradeType = tradeType;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getLimitPay() {
return limitPay;
}
public void setLimitPay(String limitPay) {
this.limitPay = limitPay;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java | 2 |
请完成以下Java代码 | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
} | public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", icon=").append(icon);
sb.append(", email=").append(email);
sb.append(", nickName=").append(nickName);
sb.append(", note=").append(note);
sb.append(", createTime=").append(createTime);
sb.append(", loginTime=").append(loginTime);
sb.append(", status=").append(status);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java | 1 |
请完成以下Java代码 | public void setReferrerPolicyHeaderValue(@Nullable String referrerPolicyHeaderValue) {
this.referrerPolicyHeaderValue = referrerPolicyHeaderValue;
}
public @Nullable String getContentSecurityPolicyHeaderValue() {
return contentSecurityPolicyHeaderValue;
}
public void setContentSecurityPolicyHeaderValue(@Nullable String contentSecurityPolicyHeaderValue) {
this.contentSecurityPolicyHeaderValue = contentSecurityPolicyHeaderValue;
}
public @Nullable String getDownloadOptionsHeaderValue() {
return downloadOptionsHeaderValue;
}
public void setDownloadOptionsHeaderValue(@Nullable String downloadOptionHeaderValue) {
this.downloadOptionsHeaderValue = downloadOptionHeaderValue;
}
public @Nullable String getPermittedCrossDomainPoliciesHeaderValue() {
return permittedCrossDomainPoliciesHeaderValue;
}
public void setPermittedCrossDomainPoliciesHeaderValue(
@Nullable String permittedCrossDomainPoliciesHeaderValue) {
this.permittedCrossDomainPoliciesHeaderValue = permittedCrossDomainPoliciesHeaderValue;
}
public @Nullable String getPermissionPolicyHeaderValue() {
return permissionPolicyHeaderValue;
}
public void setPermissionPolicyHeaderValue(@Nullable String permissionPolicyHeaderValue) {
this.permissionPolicyHeaderValue = permissionPolicyHeaderValue;
}
/**
* bind the route specific/opt-in header names to enable, in lower case.
*/
void setEnable(Set<String> enable) {
if (enable != null) {
this.routeFilterConfigProvided = true;
this.routeEnabledHeaders = enable.stream()
.map(String::toLowerCase)
.collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the route specific/opt-in header names to enable, in lower case.
*/
Set<String> getRouteEnabledHeaders() {
return routeEnabledHeaders;
}
/**
* bind the route specific/opt-out header names to disable, in lower case.
*/
void setDisable(Set<String> disable) {
if (disable != null) {
this.routeFilterConfigProvided = true;
this.routeDisabledHeaders = disable.stream()
.map(String::toLowerCase) | .collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the route specific/opt-out header names to disable, in lower case
*/
Set<String> getRouteDisabledHeaders() {
return routeDisabledHeaders;
}
/**
* @return the route specific/opt-out permission policies.
*/
protected @Nullable String getRoutePermissionsPolicyHeaderValue() {
return routePermissionsPolicyHeaderValue;
}
/**
* bind the route specific/opt-out permissions policy.
*/
void setPermissionsPolicy(@Nullable String permissionsPolicy) {
this.routeFilterConfigProvided = true;
this.routePermissionsPolicyHeaderValue = permissionsPolicy;
}
/**
* @return flag whether route specific arguments were bound.
*/
boolean isRouteFilterConfigProvided() {
return routeFilterConfigProvided;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public HuPackingInstructionsId getPackingInstructionsId()
{
HuPackingInstructionsId packingInstructionsId = this._packingInstructionsId;
if (packingInstructionsId == null)
{
packingInstructionsId = this._packingInstructionsId = handlingUnitsBL.getPackingInstructionsId(hu);
}
return packingInstructionsId;
}
}
//
//
// ------------------------------------
//
//
private static class PickFromHUsList
{
private final ArrayList<PickFromHU> list = new ArrayList<>();
PickFromHUsList() {}
public void add(@NonNull final PickFromHU pickFromHU) {list.add(pickFromHU);}
public List<I_M_HU> toHUsList() {return list.stream().map(PickFromHU::toM_HU).collect(ImmutableList.toImmutableList());}
public PickFromHU getSingleHU() {return CollectionUtils.singleElement(list);}
public boolean isSingleHUAlreadyPacked(
final boolean checkIfAlreadyPacked,
@NonNull final ProductId productId,
@NonNull final Quantity qty,
@Nullable final HuPackingInstructionsId packingInstructionsId)
{
if (list.size() != 1)
{
return false;
}
final PickFromHU hu = list.get(0);
// NOTE we check isGeneratedFromInventory because we want to avoid splitting an HU that we just generated it, even if checkIfAlreadyPacked=false
if (checkIfAlreadyPacked || hu.isGeneratedFromInventory())
{
return hu.isAlreadyPacked(productId, qty, packingInstructionsId);
} | else
{
return false;
}
}
}
//
//
// ------------------------------------
//
//
@Value(staticConstructor = "of")
@EqualsAndHashCode(doNotUseGetters = true)
private static class HuPackingInstructionsIdAndCaptionAndCapacity
{
@NonNull HuPackingInstructionsId huPackingInstructionsId;
@NonNull String caption;
@Nullable Capacity capacity;
@Nullable
public Capacity getCapacityOrNull() {return capacity;}
@SuppressWarnings("unused")
@NonNull
public Optional<Capacity> getCapacity() {return Optional.ofNullable(capacity);}
public TUPickingTarget toTUPickingTarget()
{
return TUPickingTarget.ofPackingInstructions(huPackingInstructionsId, caption);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackToHUsProducer.java | 1 |
请完成以下Java代码 | public Component getTableCellEditorComponent(final JTable table,
final Object valueModel,
final boolean isSelected,
int rowIndexView,
int columnIndexView)
{
final IInfoColumnController columnController = columnInfo.getColumnController();
//
// Ask Column Controller to customize this editor before it gets activated
if (columnController != null)
{
final int rowIndexModel = table.convertRowIndexToModel(rowIndexView);
final int columnIndexModel = table.convertColumnIndexToModel(columnIndexView);
columnController.prepareEditor(m_editor, valueModel, rowIndexModel, columnIndexModel);
}
// Set Value
final Object valueEditor = convertToEditorValue(valueModel);
m_editor.setValue(valueEditor);
// Set UI
m_editor.setBorder(null);
// m_editor.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
m_editor.setFont(table.getFont());
return (Component)m_editor;
} // getTableCellEditorComponent
@Override
public Object getCellEditorValue()
{
if (m_editor == null)
{
return null;
}
final Object valueEditor = m_editor.getValue();
//
// Check and convert the value if needed
final Object valueModel;
if (valueEditor instanceof Number && modelValueClass == KeyNamePair.class)
{
final int key = ((Number)valueEditor).intValue();
final String name = m_editor.getDisplay();
valueModel = new KeyNamePair(key, name);
}
else
{
valueModel = valueEditor;
}
return valueModel;
}
@Override | public boolean stopCellEditing()
{
try
{
return super.stopCellEditing();
}
catch (Exception e)
{
final Component comp = (Component)m_editor;
final int windowNo = Env.getWindowNo(comp);
Services.get(IClientUI.class).warn(windowNo, e);
}
return false;
}
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
}
private Object convertToEditorValue(final Object valueModel)
{
final Object valueEditor;
if (valueModel instanceof KeyNamePair && editorValueClass == Integer.class)
{
valueEditor = ((KeyNamePair)valueModel).getKey();
}
else
{
valueEditor = valueModel;
}
return valueEditor;
}
} // MiniCellEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\MiniCellEditor.java | 1 |
请完成以下Java代码 | protected void invokeNext() {
AtomicOperationInvocation invocation = queuedInvocations.remove(0);
try {
invocation.execute(bpmnStackTrace, processDataContext);
} catch(RuntimeException e) {
// log bpmn stacktrace
bpmnStackTrace.printStackTrace(Context.getProcessEngineConfiguration().isBpmnStacktraceVerbose());
// rethrow
throw e;
}
}
protected boolean requiresContextSwitch(ProcessApplicationReference processApplicationReference) {
return ProcessApplicationContextUtil.requiresContextSwitch(processApplicationReference);
}
protected ProcessApplicationReference getTargetProcessApplication(ExecutionEntity execution) {
return ProcessApplicationContextUtil.getTargetProcessApplication(execution);
}
public void rethrow() { | if (throwable != null) {
if (throwable instanceof Error) {
throw (Error) throwable;
} else if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else {
throw new ProcessEngineException("exception while executing command " + command, throwable);
}
}
}
public ProcessDataContext getProcessDataContext() {
return processDataContext;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandInvocationContext.java | 1 |
请完成以下Java代码 | User followUser(User followee) {
followingUsers.add(followee);
return this;
}
User unfollowUser(User followee) {
followingUsers.remove(followee);
return this;
}
public void deleteArticleComment(Article article, long commentId) {
article.removeCommentByUser(this, commentId);
}
public Set<Comment> viewArticleComments(Article article) {
return article.getComments().stream()
.map(this::viewComment)
.collect(toSet());
}
Comment viewComment(Comment comment) {
viewProfile(comment.getAuthor());
return comment;
}
Profile viewProfile(User user) {
return user.profile.withFollowing(followingUsers.contains(user));
}
public Profile getProfile() {
return profile;
}
boolean matchesPassword(String rawPassword, PasswordEncoder passwordEncoder) {
return password.matchesPassword(rawPassword, passwordEncoder);
}
void changeEmail(Email email) {
this.email = email;
}
void changePassword(Password password) {
this.password = password;
}
void changeName(UserName userName) {
profile.changeUserName(userName);
}
void changeBio(String bio) {
profile.changeBio(bio);
}
void changeImage(Image image) {
profile.changeImage(image);
} | public Long getId() {
return id;
}
public Email getEmail() {
return email;
}
public UserName getName() {
return profile.getUserName();
}
String getBio() {
return profile.getBio();
}
Image getImage() {
return profile.getImage();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final var user = (User) o;
return email.equals(user.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java | 1 |
请完成以下Java代码 | public class JuelScriptEngineFactory implements ScriptEngineFactory {
public static List<String> names;
private static List<String> extensions;
private static List<String> mimeTypes;
static {
names = Collections.unmodifiableList(Arrays.asList("juel"));
extensions = names;
mimeTypes = Collections.unmodifiableList(new ArrayList<String>(0));
}
public String getEngineName() {
return "juel";
}
public String getEngineVersion() {
return "1.0";
}
public List<String> getExtensions() {
return extensions;
}
public String getLanguageName() {
return "JSP 2.1 EL";
}
public String getLanguageVersion() {
return "2.1";
}
public String getMethodCallSyntax(String obj, String method, String... arguments) {
throw new UnsupportedOperationException("Method getMethodCallSyntax is not supported");
}
public List<String> getMimeTypes() {
return mimeTypes;
}
public List<String> getNames() {
return names;
}
public String getOutputStatement(String toDisplay) {
// We will use out:print function to output statements
StringBuilder stringBuffer = new StringBuilder();
stringBuffer.append("out:print(\"");
int length = toDisplay.length();
for (int i = 0; i < length; i++) {
char c = toDisplay.charAt(i);
switch (c) {
case '"':
stringBuffer.append("\\\"");
break; | case '\\':
stringBuffer.append("\\\\");
break;
default:
stringBuffer.append(c);
break;
}
}
stringBuffer.append("\")");
return stringBuffer.toString();
}
public String getParameter(String key) {
if (key.equals(ScriptEngine.NAME)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.ENGINE)) {
return getEngineName();
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return getEngineVersion();
} else if (key.equals(ScriptEngine.LANGUAGE)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return getLanguageVersion();
} else if (key.equals("THREADING")) {
return "MULTITHREADED";
} else {
return null;
}
}
public String getProgram(String... statements) {
// Each statement is wrapped in '${}' to comply with EL
StringBuilder buf = new StringBuilder();
if (statements.length != 0) {
for (int i = 0; i < statements.length; i++) {
buf.append("${");
buf.append(statements[i]);
buf.append("} ");
}
}
return buf.toString();
}
public ScriptEngine getScriptEngine() {
return new JuelScriptEngine(this);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\JuelScriptEngineFactory.java | 1 |
请完成以下Java代码 | public abstract class TextEscapeUtils {
public static String escapeEntities(String s) {
if (s == null || s.length() == 0) {
return s;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') {
sb.append(ch);
}
else if (ch == '<') {
sb.append("<");
}
else if (ch == '>') {
sb.append(">");
}
else if (ch == '&') {
sb.append("&");
}
else if (Character.isWhitespace(ch)) {
sb.append("&#").append((int) ch).append(";");
}
else if (Character.isISOControl(ch)) {
// ignore control chars
}
else if (Character.isHighSurrogate(ch)) {
if (i + 1 >= s.length()) {
// Unexpected end
throw new IllegalArgumentException("Missing low surrogate character at end of string");
}
char low = s.charAt(i + 1);
if (!Character.isLowSurrogate(low)) {
throw new IllegalArgumentException(
"Expected low surrogate character but found value = " + (int) low);
}
int codePoint = Character.toCodePoint(ch, low); | if (Character.isDefined(codePoint)) {
sb.append("&#").append(codePoint).append(";");
}
i++; // skip the next character as we have already dealt with it
}
else if (Character.isLowSurrogate(ch)) {
throw new IllegalArgumentException("Unexpected low surrogate character, value = " + (int) ch);
}
else if (Character.isDefined(ch)) {
sb.append("&#").append((int) ch).append(";");
}
// Ignore anything else
}
return sb.toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\TextEscapeUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ProjectLine changeProjectLine(
@NonNull final ProjectAndLineId projectLineId,
@NonNull final Consumer<ProjectLine> updater)
{
final I_C_ProjectLine record = retrieveLineRecordById(projectLineId);
final ProjectLine line = toProjectLine(record);
updater.accept(line);
updateRecord(record, line);
save(record);
return line;
}
public void linkToOrderLine(
@NonNull final ProjectAndLineId projectLineId,
@NonNull final OrderAndLineId orderLineId)
{
final I_C_ProjectLine record = retrieveLineRecordById(projectLineId);
record.setC_Order_ID(orderLineId.getOrderRepoId());
record.setC_OrderLine_ID(orderLineId.getOrderLineRepoId());
save(record);
} | public void markLinesAsProcessed(@NonNull final ProjectId projectId)
{
for (final I_C_ProjectLine lineRecord : queryLineRecordsByProjectId(projectId).list())
{
lineRecord.setProcessed(true);
InterfaceWrapperHelper.saveRecord(lineRecord);
}
}
public void markLinesAsNotProcessed(@NonNull final ProjectId projectId)
{
for (final I_C_ProjectLine lineRecord : queryLineRecordsByProjectId(projectId).list())
{
lineRecord.setProcessed(false);
InterfaceWrapperHelper.saveRecord(lineRecord);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\ProjectLineRepository.java | 2 |
请完成以下Java代码 | private InputStream in() throws IOException {
InputStream in = this.in;
if (in == null) {
synchronized (this) {
in = this.in;
if (in == null) {
in = getDelegateInputStream();
this.in = in;
}
}
}
return in;
}
@Override | public void close() throws IOException {
InputStream in = this.in;
if (in != null) {
synchronized (this) {
in = this.in;
if (in != null) {
in.close();
}
}
}
}
protected abstract InputStream getDelegateInputStream() throws IOException;
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\LazyDelegatingInputStream.java | 1 |
请完成以下Java代码 | public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public de.metas.elasticsearch.model.I_ES_FTS_Config getES_FTS_Config()
{
return get_ValueAsPO(COLUMNNAME_ES_FTS_Config_ID, de.metas.elasticsearch.model.I_ES_FTS_Config.class);
}
@Override
public void setES_FTS_Config(final de.metas.elasticsearch.model.I_ES_FTS_Config ES_FTS_Config)
{
set_ValueFromPO(COLUMNNAME_ES_FTS_Config_ID, de.metas.elasticsearch.model.I_ES_FTS_Config.class, ES_FTS_Config);
}
@Override
public void setES_FTS_Config_ID (final int ES_FTS_Config_ID)
{
if (ES_FTS_Config_ID < 1)
set_Value (COLUMNNAME_ES_FTS_Config_ID, null);
else
set_Value (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID);
}
@Override
public int getES_FTS_Config_ID()
{ | return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID);
}
@Override
public void setES_FTS_Filter_ID (final int ES_FTS_Filter_ID)
{
if (ES_FTS_Filter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, ES_FTS_Filter_ID);
}
@Override
public int getES_FTS_Filter_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Filter.java | 1 |
请完成以下Java代码 | public class BPartnerBL implements IBPartnerBL
{
@Override
public boolean isInvoiceEmailEnabled(@Nullable final I_C_BPartner bpartner, @Nullable final I_AD_User user)
{
if (bpartner == null)
{
return false; // gh #508: if the user does not have a C_BPartner, then there won't be any invoice to be emailed either.
}
final boolean matchingIsInvoiceEmailEnabled;
String isInvoiceEmailEnabled = bpartner.getIsInvoiceEmailEnabled();
//
// check flag from partner
if (Check.isBlank(isInvoiceEmailEnabled))
{
if (user == null)
{
return Boolean.TRUE;
}
// | // if is empty in partner, check it in user
isInvoiceEmailEnabled = user.getIsInvoiceEmailEnabled();
//
// if is empty also in user, return true - we do not want to let filtering by this if is not completed
if (Check.isBlank(isInvoiceEmailEnabled))
{
matchingIsInvoiceEmailEnabled = Boolean.TRUE;
}
else
{
matchingIsInvoiceEmailEnabled = BooleanUtils.toBoolean(isInvoiceEmailEnabled);
}
}
else
{
matchingIsInvoiceEmailEnabled = BooleanUtils.toBoolean(isInvoiceEmailEnabled);
}
return matchingIsInvoiceEmailEnabled;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\BPartnerBL.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InputSet.class, BPMN_ELEMENT_INPUT_SET)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<InputSet>() {
public InputSet newInstance(ModelTypeInstanceContext instanceContext) {
return new InputSetImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute("name")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataInputDataInputRefsCollection = sequenceBuilder.elementCollection(DataInputRefs.class)
.idElementReferenceCollection(DataInput.class)
.build();
optionalInputRefsCollection = sequenceBuilder.elementCollection(OptionalInputRefs.class)
.idElementReferenceCollection(DataInput.class)
.build();
whileExecutingInputRefsCollection = sequenceBuilder.elementCollection(WhileExecutingInputRefs.class)
.idElementReferenceCollection(DataInput.class)
.build();
outputSetOutputSetRefsCollection = sequenceBuilder.elementCollection(OutputSetRefs.class)
.idElementReferenceCollection(OutputSet.class)
.build();
typeBuilder.build(); | }
public InputSetImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Collection<DataInput> getDataInputs() {
return dataInputDataInputRefsCollection.getReferenceTargetElements(this);
}
public Collection<DataInput> getOptionalInputs() {
return optionalInputRefsCollection.getReferenceTargetElements(this);
}
public Collection<DataInput> getWhileExecutingInput() {
return whileExecutingInputRefsCollection.getReferenceTargetElements(this);
}
public Collection<OutputSet> getOutputSets() {
return outputSetOutputSetRefsCollection.getReferenceTargetElements(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\InputSetImpl.java | 1 |
请完成以下Java代码 | public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public long getTotalPage() {
return totalPage;
}
public void setTotalPage(long totalPage) {
this.totalPage = totalPage;
}
public long getTotalNumber() {
return totalNumber;
}
public void setTotalNumber(long totalNumber) {
this.totalNumber = totalNumber;
}
public List<E> getList() {
return list;
} | public void setList(List<E> list) {
this.list = list;
}
@Override
public String toString() {
return "Page{" +
"currentPage=" + currentPage +
", totalPage=" + totalPage +
", totalNumber=" + totalNumber +
", list=" + list +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-mybatis-xml\src\main\java\com\neo\result\Page.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void startProcess(Article article) {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("author", article.getAuthor());
variables.put("url", article.getUrl());
runtimeService.startProcessInstanceByKey("articleReview", variables);
}
@Transactional
public List<Article> getTasks(String assignee) {
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateGroup(assignee)
.list();
List<Article> articles = tasks.stream()
.map(task -> { | Map<String, Object> variables = taskService.getVariables(task.getId());
return new Article(
task.getId(), (String) variables.get("author"), (String) variables.get("url"));
})
.collect(Collectors.toList());
return articles;
}
@Transactional
public void submitReview(Approval approval) {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("approved", approval.isStatus());
taskService.complete(approval.getId(), variables);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-flowable\src\main\java\com\baeldung\service\ArticleWorkflowService.java | 2 |
请完成以下Java代码 | public class DateTimePeriodDetails {
@XmlElement(name = "FrDtTm", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar frDtTm;
@XmlElement(name = "ToDtTm", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar toDtTm;
/**
* Gets the value of the frDtTm property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFrDtTm() {
return frDtTm;
}
/**
* Sets the value of the frDtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFrDtTm(XMLGregorianCalendar value) {
this.frDtTm = value;
}
/**
* Gets the value of the toDtTm property.
*
* @return | * possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getToDtTm() {
return toDtTm;
}
/**
* Sets the value of the toDtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setToDtTm(XMLGregorianCalendar value) {
this.toDtTm = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DateTimePeriodDetails.java | 1 |
请完成以下Java代码 | public void windowActivated(final WindowEvent e)
{
windowGainedFocus(e);
}
@Override
public void windowDeactivated(final WindowEvent e)
{
// nothing
}
@Override
public void windowGainedFocus(final WindowEvent e)
{
EventQueue.invokeLater(() -> {
if (modalFrame == null || !modalFrame.isVisible() || !modalFrame.isShowing())
{
return;
}
modalFrame.toFront();
modalFrame.repaint();
});
}
@Override
public void windowLostFocus(final WindowEvent e)
{
// nothing
}
}); | if (modalFrame instanceof CFrame)
{
addToWindowManager(modalFrame);
}
showCenterWindow(parentFrame, modalFrame);
}
/**
* Create a {@link FormFrame} for the given {@link I_AD_Form}.
*
* @return formFrame which was created or null
*/
public static FormFrame createForm(final I_AD_Form form)
{
final FormFrame formFrame = new FormFrame();
if (formFrame.openForm(form))
{
formFrame.pack();
return formFrame;
}
else
{
formFrame.dispose();
return null;
}
}
} // AEnv | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AEnv.java | 1 |
请完成以下Java代码 | public void setR_RequestProcessor_ID (int R_RequestProcessor_ID)
{
if (R_RequestProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_ID, Integer.valueOf(R_RequestProcessor_ID));
}
/** Get Request Processor.
@return Processor for Requests
*/
public int getR_RequestProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request Processor Log.
@param R_RequestProcessorLog_ID
Result of the execution of the Request Processor
*/
public void setR_RequestProcessorLog_ID (int R_RequestProcessorLog_ID)
{
if (R_RequestProcessorLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestProcessorLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestProcessorLog_ID, Integer.valueOf(R_RequestProcessorLog_ID));
}
/** Get Request Processor Log.
@return Result of the execution of the Request Processor
*/
public int getR_RequestProcessorLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessorLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
public void setSummary (String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
} | /** Get Summary.
@return Textual summary of this request
*/
public String getSummary ()
{
return (String)get_Value(COLUMNNAME_Summary);
}
/** 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_R_RequestProcessorLog.java | 1 |
请完成以下Java代码 | public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
String stringRepresentation = this.stringRepresentation;
if (stringRepresentation == null)
{
stringRepresentation = this.stringRepresentation = applicationId.getAsString() + SEPARATOR + idPart;
}
return stringRepresentation;
}
@Nullable
public static String getAsStringOrNull(@Nullable final WFProcessId id)
{
return id != null ? id.getAsString() : null;
}
@NonNull
public <ID extends RepoIdAware> ID getRepoId(@NonNull final Function<Integer, ID> idMapper)
{
try
{
final int repoIdInt = Integer.parseInt(idPart);
return idMapper.apply(repoIdInt);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting " + this + " to ID", ex);
} | }
@NonNull
public <ID extends RepoIdAware> ID getRepoIdAssumingApplicationId(@NonNull MobileApplicationId expectedApplicationId, @NonNull final Function<Integer, ID> idMapper)
{
assertApplicationId(expectedApplicationId);
return getRepoId(idMapper);
}
public void assertApplicationId(@NonNull final MobileApplicationId expectedApplicationId)
{
if (!Objects.equals(this.applicationId, expectedApplicationId))
{
throw new AdempiereException("Expected applicationId `" + expectedApplicationId + "` but was `" + this.applicationId + "`");
}
}
public static boolean equals(@Nullable final WFProcessId id1, @Nullable final WFProcessId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcessId.java | 1 |
请完成以下Java代码 | public void setRetourenMenge(int value) {
this.retourenMenge = value;
}
/**
* Gets the value of the retouregrund property.
*
* @return
* possible object is
* {@link RetoureGrund }
*
*/
public RetoureGrund getRetouregrund() {
return retouregrund;
}
/**
* Sets the value of the retouregrund property.
*
* @param value
* allowed object is
* {@link RetoureGrund }
*
*/
public void setRetouregrund(RetoureGrund value) {
this.retouregrund = value;
}
/**
* Gets the value of the charge property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCharge() {
return charge;
}
/**
* Sets the value of the charge property.
*
* @param value
* allowed object is | * {@link String }
*
*/
public void setCharge(String value) {
this.charge = value;
}
/**
* Gets the value of the verfalldatum property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getVerfalldatum() {
return verfalldatum;
}
/**
* Sets the value of the verfalldatum property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setVerfalldatum(XMLGregorianCalendar value) {
this.verfalldatum = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourePositionType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class AiModelDataValidator extends DataValidator<AiModel> {
private final TenantService tenantService;
private final AiModelDao aiModelDao;
@Override
protected AiModel validateUpdate(TenantId tenantId, AiModel model) {
Optional<AiModel> existing = aiModelDao.findByTenantIdAndId(tenantId, model.getId());
if (existing.isEmpty()) {
throw new DataValidationException("Cannot update non-existent AI model!");
}
return existing.get();
}
@Override
protected void validateDataImpl(TenantId tenantId, AiModel model) {
// ID validation
if (model.getId() != null) {
if (model.getUuidId() == null) {
throw new DataValidationException("AI model UUID should be specified!");
} | if (model.getId().isNullUid()) {
throw new DataValidationException("AI model UUID must not be the reserved null value!");
}
}
// tenant ID validation
if (model.getTenantId() == null || model.getTenantId().getId() == null) {
throw new DataValidationException("AI model should be assigned to tenant!");
}
if (model.getTenantId().isSysTenantId()) {
throw new DataValidationException("AI model cannot be assigned to the system tenant!");
}
if (!tenantService.tenantExists(tenantId)) {
throw new DataValidationException("AI model reference a non-existent tenant!");
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\AiModelDataValidator.java | 2 |
请完成以下Java代码 | final public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final I_M_Inventory inventory = context.getSelectedModel(I_M_Inventory.class);
if (inventory.isProcessed())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("inventory is processed");
}
return ProcessPreconditionsResolution.accept();
}
@Override
final protected String doIt() | {
final Inventory inventory = inventoryService.getById(InventoryId.ofRepoId(getRecord_ID()));
final DraftInventoryLinesCreateResponse response = inventoryService.createDraftLines(
DraftInventoryLinesCreateRequest.builder()
.inventory(inventory)
.strategy(createStrategy(inventory))
.build()
);
return "@Created@/@Updated@ #" + response.getCountInventoryLines();
}
protected abstract HUsForInventoryStrategy createStrategy(Inventory inventory);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\process\DraftInventoryBase.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReferenceType getSupplierOrderReference() {
return supplierOrderReference;
}
/**
* Sets the value of the supplierOrderReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setSupplierOrderReference(ReferenceType value) {
this.supplierOrderReference = value;
}
/**
* Reference to the consignment.
*
* @return
* possible object is
* {@link String }
* | */
public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = 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\DESADVExtensionType.java | 2 |
请完成以下Java代码 | public boolean isProtoEnabled() {
return protoEnabled;
}
public void setProtoEnabled(boolean protoEnabled) {
this.protoEnabled = protoEnabled;
}
public boolean isPrefixEnabled() {
return prefixEnabled;
}
public void setPrefixEnabled(boolean prefixEnabled) {
this.prefixEnabled = prefixEnabled;
}
public boolean isForAppend() {
return forAppend;
}
public void setForAppend(boolean forAppend) {
this.forAppend = forAppend;
}
public boolean isHostAppend() {
return hostAppend;
}
public void setHostAppend(boolean hostAppend) {
this.hostAppend = hostAppend;
} | public boolean isPortAppend() {
return portAppend;
}
public void setPortAppend(boolean portAppend) {
this.portAppend = portAppend;
}
public boolean isProtoAppend() {
return protoAppend;
}
public void setProtoAppend(boolean protoAppend) {
this.protoAppend = protoAppend;
}
public boolean isPrefixAppend() {
return prefixAppend;
}
public void setPrefixAppend(boolean prefixAppend) {
this.prefixAppend = prefixAppend;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\XForwardedRequestHeadersFilterProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean resetPassword(String userIds) {
User user = new User();
user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
user.setUpdateTime(DateUtil.now());
return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
}
@Override
public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
User user = getById(userId);
if (!newPassword.equals(newPassword1)) {
throw new ServiceException("请输入正确的确认密码!");
}
if (!user.getPassword().equals(DigestUtil.encrypt(oldPassword))) {
throw new ServiceException("原密码不正确!");
}
return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.encrypt(newPassword)).eq(User::getId, userId));
}
@Override
public List<String> getRoleName(String roleIds) {
return baseMapper.getRoleName(Func.toStrArray(roleIds));
}
@Override
public List<String> getDeptName(String deptIds) {
return baseMapper.getDeptName(Func.toStrArray(deptIds));
}
@Override
public void importUser(List<UserExcel> data) {
data.forEach(userExcel -> {
User user = Objects.requireNonNull(BeanUtil.copyProperties(userExcel, User.class));
// 设置部门ID
user.setDeptId(sysClient.getDeptIds(userExcel.getTenantId(), userExcel.getDeptName()));
// 设置岗位ID
user.setPostId(sysClient.getPostIds(userExcel.getTenantId(), userExcel.getPostName()));
// 设置角色ID
user.setRoleId(sysClient.getRoleIds(userExcel.getTenantId(), userExcel.getRoleName()));
// 设置默认密码
user.setPassword(CommonConstant.DEFAULT_PASSWORD);
this.submit(user);
});
} | @Override
public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
userList.forEach(user -> {
user.setRoleName(StringUtil.join(sysClient.getRoleNames(user.getRoleId())));
user.setDeptName(StringUtil.join(sysClient.getDeptNames(user.getDeptId())));
user.setPostName(StringUtil.join(sysClient.getPostNames(user.getPostId())));
});
return userList;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean registerGuest(User user, Long oauthId) {
R<Tenant> result = sysClient.getTenant(user.getTenantId());
Tenant tenant = result.getData();
if (!result.isSuccess() || tenant == null || tenant.getId() == null) {
throw new ServiceException("租户信息错误!");
}
UserOauth userOauth = userOauthService.getById(oauthId);
if (userOauth == null || userOauth.getId() == null) {
throw new ServiceException("第三方登陆信息错误!");
}
user.setRealName(user.getName());
user.setAvatar(userOauth.getAvatar());
user.setRoleId(MINUS_ONE);
user.setDeptId(MINUS_ONE);
user.setPostId(MINUS_ONE);
boolean userTemp = this.submit(user);
userOauth.setUserId(user.getId());
userOauth.setTenantId(user.getTenantId());
boolean oauthTemp = userOauthService.updateById(userOauth);
return (userTemp && oauthTemp);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\UserServiceImpl.java | 2 |
请完成以下Java代码 | private Iterator<HUEditorRow> getNextPageIterator()
{
// the result; part of it will be taken from cache, the, rest will be loaded
final HUEditorRow[] rows = new HUEditorRow[bufferSize];
// HUEditorRowIds that we don't have in the cache and that therefore need to be loaded
final Map<HUEditorRowId, Integer> rowIdToLoad2index = new HashMap<>();
// Get from cache as much as possible
{
int idx = 0;
while (rowIds.hasNext() && idx < bufferSize)
{
final HUEditorRowId rowId = rowIds.next();
final HUEditorRowId topLevelRowId = rowId.toTopLevelRowId();
final HUEditorRow topLevelRow = cache.get(topLevelRowId.toDocumentId());
if (topLevelRow == null)
{
// to be loaded
rowIdToLoad2index.put(rowId, idx);
}
else
{
if (rowId.equals(topLevelRowId))
{
rows[idx] = topLevelRow;
}
else
{
rows[idx] = topLevelRow.getIncludedRowById(rowId.toDocumentId()).orElse(null);
}
}
idx++;
}
}
//
// Load missing rows (which were not found in cache)
if (!rowIdToLoad2index.isEmpty())
{
final ListMultimap<HUEditorRowId, HUEditorRowId> topLevelRowId2rowIds = rowIdToLoad2index.keySet()
.stream()
.map(rowId -> GuavaCollectors.entry(rowId.toTopLevelRowId(), rowId))
.collect(GuavaCollectors.toImmutableListMultimap());
final Set<HuId> topLevelHUIds = topLevelRowId2rowIds
.keys() | .stream()
.map(HUEditorRowId::getTopLevelHUId)
.collect(ImmutableSet.toImmutableSet());
huEditorRepo.retrieveHUEditorRows(topLevelHUIds, filter)
.forEach(topLevelRow -> {
final HUEditorRowId topLevelRowId = topLevelRow.getHURowId();
for (final HUEditorRowId includedRowId : topLevelRowId2rowIds.get(topLevelRowId))
{
final Integer idx = rowIdToLoad2index.remove(includedRowId);
if (idx == null)
{
// wtf?! shall not happen
continue;
}
if (topLevelRowId.equals(includedRowId))
{
rows[idx] = topLevelRow;
cache.put(topLevelRow.getId(), topLevelRow);
}
else
{
rows[idx] = topLevelRow.getIncludedRowById(includedRowId.toDocumentId()).orElse(null);
}
}
});
}
return Stream.of(rows)
.filter(Objects::nonNull) // IMPORTANT: just to make sure we won't stream some empty gaps (e.g. missing rows because HU was not a top level one)
.filter(filterPredicate)
.iterator();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowsPagedLoadingIterator.java | 1 |
请完成以下Java代码 | public I_CM_WebProject getCM_WebProject() throws RuntimeException
{
return (I_CM_WebProject)MTable.get(getCtx(), I_CM_WebProject.Table_Name)
.getPO(getCM_WebProject_ID(), get_TrxName()); }
/** Set Web Project.
@param CM_WebProject_ID
A web project is the main data container for Containers, URLs, Ads, Media etc.
*/
public void setCM_WebProject_ID (int CM_WebProject_ID)
{
if (CM_WebProject_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_WebProject_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_WebProject_ID, Integer.valueOf(CM_WebProject_ID));
}
/** Get Web Project.
@return A web project is the main data container for Containers, URLs, Ads, Media etc.
*/
public int getCM_WebProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_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 Fully Qualified Domain Name.
@param FQDN
Fully Qualified Domain Name i.e. www.comdivision.com
*/
public void setFQDN (String FQDN)
{
set_Value (COLUMNNAME_FQDN, FQDN);
}
/** Get Fully Qualified Domain Name.
@return Fully Qualified Domain Name i.e. www.comdivision.com
*/
public String getFQDN ()
{
return (String)get_Value(COLUMNNAME_FQDN);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
} | /** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject_Domain.java | 1 |
请完成以下Java代码 | public void setPIName (final @Nullable java.lang.String PIName)
{
set_ValueNoCheck (COLUMNNAME_PIName, PIName);
}
@Override
public java.lang.String getPIName()
{
return get_ValueAsString(COLUMNNAME_PIName);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value); | }
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_ValueNoCheck (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Instance_Properties_v.java | 1 |
请完成以下Java代码 | public void notify(DmnDecisionTableEvaluationEvent evaluationEvent) {
// the wrapper listen for decision evaluation events
}
@Override
public void notify(DmnDecisionEvaluationEvent evaluationEvent) {
notifyCollector(evaluationEvent.getDecisionResult());
for (DmnDecisionLogicEvaluationEvent event : evaluationEvent.getRequiredDecisionResults()) {
notifyCollector(event);
}
}
protected void notifyCollector(DmnDecisionLogicEvaluationEvent evaluationEvent) {
if (evaluationEvent instanceof DmnDecisionTableEvaluationEvent) {
collector.notify((DmnDecisionTableEvaluationEvent) evaluationEvent);
}
// ignore other evaluation events since the collector is implemented as decision table evaluation listener
} | @Override
public long getExecutedDecisionInstances() {
return collector.getExecutedDecisionInstances();
}
@Override
public long getExecutedDecisionElements() {
return collector.getExecutedDecisionElements();
}
@Override
public long clearExecutedDecisionInstances() {
return collector.clearExecutedDecisionInstances();
}
@Override
public long clearExecutedDecisionElements() {
return collector.clearExecutedDecisionElements();
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\metrics\DmnEngineMetricCollectorWrapper.java | 1 |
请完成以下Java代码 | protected long getLockDuration() {
return lockDuration;
}
protected boolean isAutoFetchingEnabled() {
return isAutoFetchingEnabled;
}
protected BackoffStrategy getBackoffStrategy() {
return backoffStrategy;
}
public String getDefaultSerializationFormat() {
return defaultSerializationFormat;
}
public String getDateFormat() {
return dateFormat;
} | public ObjectMapper getObjectMapper() {
return objectMapper;
}
public ValueMappers getValueMappers() {
return valueMappers;
}
public TypedValues getTypedValues() {
return typedValues;
}
public EngineClient getEngineClient() {
return engineClient;
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_K_Synonym[")
.append(get_ID()).append("]");
return sb.toString();
}
/** AD_Language AD_Reference_ID=106 */
public static final int AD_LANGUAGE_AD_Reference_ID=106;
/** Set Language.
@param AD_Language
Language for this entity
*/
public void setAD_Language (String AD_Language)
{
set_Value (COLUMNNAME_AD_Language, AD_Language);
}
/** Get Language.
@return Language for this entity
*/
public String getAD_Language ()
{
return (String)get_Value(COLUMNNAME_AD_Language);
}
/** Set Knowledge Synonym.
@param K_Synonym_ID
Knowlege Keyword Synonym
*/
public void setK_Synonym_ID (int K_Synonym_ID)
{
if (K_Synonym_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Synonym_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Synonym_ID, Integer.valueOf(K_Synonym_ID));
}
/** Get Knowledge Synonym.
@return Knowlege Keyword Synonym
*/
public int getK_Synonym_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Synonym_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/ | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Synonym Name.
@param SynonymName
The synonym for the name
*/
public void setSynonymName (String SynonymName)
{
set_Value (COLUMNNAME_SynonymName, SynonymName);
}
/** Get Synonym Name.
@return The synonym for the name
*/
public String getSynonymName ()
{
return (String)get_Value(COLUMNNAME_SynonymName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Synonym.java | 1 |
请完成以下Java代码 | public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
} | public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@ManyToOne
@JoinColumn(name = "customer_id")
private User customer;
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\Product.java | 1 |
请完成以下Java代码 | public void setPharmaRestApiBaseURL (java.lang.String PharmaRestApiBaseURL)
{
set_Value (COLUMNNAME_PharmaRestApiBaseURL, PharmaRestApiBaseURL);
}
/** Get Pharma REST API URL.
@return Pharma REST API URL */
@Override
public java.lang.String getPharmaRestApiBaseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_PharmaRestApiBaseURL);
}
/** Set Support Benutzer.
@param Support_User_ID
Benutzer für Benachrichtigungen
*/
@Override
public void setSupport_User_ID (int Support_User_ID)
{
if (Support_User_ID < 1)
set_Value (COLUMNNAME_Support_User_ID, null);
else
set_Value (COLUMNNAME_Support_User_ID, Integer.valueOf(Support_User_ID));
}
/** Get Support Benutzer.
@return Benutzer für Benachrichtigungen
*/
@Override
public int getSupport_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Support_User_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set TAN Passwort.
@param TanPassword
TAN Passwort benutzt für Authentifizierung
*/
@Override
public void setTanPassword (java.lang.String TanPassword)
{
set_Value (COLUMNNAME_TanPassword, TanPassword);
}
/** Get TAN Passwort.
@return TAN Passwort benutzt für Authentifizierung
*/
@Override
public java.lang.String getTanPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_TanPassword);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Config.java | 1 |
请完成以下Java代码 | public static double logsumexp(double x, double y, boolean flg)
{
if (flg)
{
return y;
}
double vmin = Math.min(x, y);
double vmax = Math.max(x, y);
if (vmax > vmin + MINUS_LOG_EPSILON)
{
return vmax;
}
else
{
return vmax + Math.log(Math.exp(vmin - vmax) + 1.0);
}
}
public void calcAlpha()
{
alpha = 0.0;
for (Path p : lpath)
{
alpha = logsumexp(alpha, p.cost + p.lnode.alpha, p == lpath.get(0));
}
alpha += cost;
}
public void calcBeta()
{
beta = 0.0;
for (Path p : rpath)
{
beta = logsumexp(beta, p.cost + p.rnode.beta, p == rpath.get(0));
}
beta += cost; | }
/**
* 计算节点期望
*
* @param expected 输出期望
* @param Z 规范化因子
* @param size 标签个数
*/
public void calcExpectation(double[] expected, double Z, int size)
{
double c = Math.exp(alpha + beta - cost - Z);
for (int i = 0; fVector.get(i) != -1; i++)
{
int idx = fVector.get(i) + y;
expected[idx] += c;
}
for (Path p : lpath)
{
p.calcExpectation(expected, Z, size);
}
}
public void clear()
{
x = y = 0;
alpha = beta = cost = 0;
prev = null;
fVector = null;
lpath.clear();
rpath.clear();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Node.java | 1 |
请完成以下Java代码 | public void setPayPal_PaymentApprovedCallbackUrl (final @Nullable java.lang.String PayPal_PaymentApprovedCallbackUrl)
{
set_Value (COLUMNNAME_PayPal_PaymentApprovedCallbackUrl, PayPal_PaymentApprovedCallbackUrl);
}
@Override
public java.lang.String getPayPal_PaymentApprovedCallbackUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_PaymentApprovedCallbackUrl);
}
@Override
public void setPayPal_Sandbox (final boolean PayPal_Sandbox)
{
set_Value (COLUMNNAME_PayPal_Sandbox, PayPal_Sandbox);
}
@Override | public boolean isPayPal_Sandbox()
{
return get_ValueAsBoolean(COLUMNNAME_PayPal_Sandbox);
}
@Override
public void setPayPal_WebUrl (final @Nullable java.lang.String PayPal_WebUrl)
{
set_Value (COLUMNNAME_PayPal_WebUrl, PayPal_WebUrl);
}
@Override
public java.lang.String getPayPal_WebUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_WebUrl);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setExternalId (final @Nullable java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternalUrl (final @Nullable java.lang.String ExternalUrl)
{
set_Value (COLUMNNAME_ExternalUrl, ExternalUrl);
}
@Override
public java.lang.String getExternalUrl()
{
return get_ValueAsString(COLUMNNAME_ExternalUrl);
}
@Override
public void setMilestone_DueDate (final @Nullable java.sql.Timestamp Milestone_DueDate)
{
set_Value (COLUMNNAME_Milestone_DueDate, Milestone_DueDate);
}
@Override
public java.sql.Timestamp getMilestone_DueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_Milestone_DueDate);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override | public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setS_Milestone_ID (final int S_Milestone_ID)
{
if (S_Milestone_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, S_Milestone_ID);
}
@Override
public int getS_Milestone_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Milestone_ID);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Milestone.java | 2 |
请完成以下Java代码 | public void setC_PurchaseCandidate_Alloc_ID (final int C_PurchaseCandidate_Alloc_ID)
{
if (C_PurchaseCandidate_Alloc_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_Alloc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_Alloc_ID, C_PurchaseCandidate_Alloc_ID);
}
@Override
public int getC_PurchaseCandidate_Alloc_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_Alloc_ID);
}
@Override
public de.metas.purchasecandidate.model.I_C_PurchaseCandidate getC_PurchaseCandidate()
{
return get_ValueAsPO(COLUMNNAME_C_PurchaseCandidate_ID, de.metas.purchasecandidate.model.I_C_PurchaseCandidate.class);
}
@Override
public void setC_PurchaseCandidate(final de.metas.purchasecandidate.model.I_C_PurchaseCandidate C_PurchaseCandidate)
{
set_ValueFromPO(COLUMNNAME_C_PurchaseCandidate_ID, de.metas.purchasecandidate.model.I_C_PurchaseCandidate.class, C_PurchaseCandidate);
}
@Override
public void setC_PurchaseCandidate_ID (final int C_PurchaseCandidate_ID)
{
if (C_PurchaseCandidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_ID, C_PurchaseCandidate_ID);
}
@Override
public int getC_PurchaseCandidate_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_ID);
}
@Override
public void setDateOrdered (final @Nullable java.sql.Timestamp DateOrdered)
{
set_Value (COLUMNNAME_DateOrdered, DateOrdered);
}
@Override
public java.sql.Timestamp getDateOrdered()
{
return get_ValueAsTimestamp(COLUMNNAME_DateOrdered);
}
@Override
public void setDatePromised (final @Nullable java.sql.Timestamp DatePromised)
{
set_Value (COLUMNNAME_DatePromised, DatePromised);
}
@Override
public java.sql.Timestamp getDatePromised()
{
return get_ValueAsTimestamp(COLUMNNAME_DatePromised); | }
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRemotePurchaseOrderId (final @Nullable java.lang.String RemotePurchaseOrderId)
{
set_Value (COLUMNNAME_RemotePurchaseOrderId, RemotePurchaseOrderId);
}
@Override
public java.lang.String getRemotePurchaseOrderId()
{
return get_ValueAsString(COLUMNNAME_RemotePurchaseOrderId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate_Alloc.java | 1 |
请完成以下Java代码 | public I_M_HU_PI getLuPI()
{
return luPIItem.getM_HU_PI_Version().getM_HU_PI();
}
@Override
public ProductId getCuProductId()
{
return cuProductId;
}
@Override
public I_C_UOM getCuUOM()
{
return cuUOM;
}
@Override
public BigDecimal getCuPerTU()
{ | return cuPerTU;
}
@Override
public BigDecimal getTuPerLU()
{
return tuPerLU;
}
@Override
public BigDecimal getMaxLUToAllocate()
{
return maxLUToAllocate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUSplitDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected static class ConnectionEndpointListBuilder {
protected static @NonNull ConnectionEndpointList from(@NonNull Pool pool) {
ConnectionEndpointList list = new ConnectionEndpointList();
if (pool != null) {
Set<InetSocketAddress> poolSocketAddresses = new HashSet<>();
collect(poolSocketAddresses, pool.getLocators());
collect(poolSocketAddresses, pool.getOnlineLocators());
collect(poolSocketAddresses, pool.getServers());
poolSocketAddresses.stream()
.map(ConnectionEndpoint::from)
.map(PoolConnectionEndpoint::from)
.map(it -> it.with(pool))
.forEach(list::add);
}
return list;
}
private static <T extends Collection<InetSocketAddress>> T collect(@NonNull T collection,
@NonNull Collection<InetSocketAddress> socketAddressesToCollect) {
CollectionUtils.nullSafeCollection(socketAddressesToCollect).stream()
.filter(Objects::nonNull)
.forEach(collection::add);
return collection;
}
}
protected static class PoolConnectionEndpoint extends ConnectionEndpoint {
protected static PoolConnectionEndpoint from(@NonNull ConnectionEndpoint connectionEndpoint) {
return new PoolConnectionEndpoint(connectionEndpoint.getHost(), connectionEndpoint.getPort());
}
private Pool pool;
PoolConnectionEndpoint(@NonNull String host, int port) {
super(host, port);
}
public Optional<Pool> getPool() {
return Optional.ofNullable(this.pool);
}
public @NonNull PoolConnectionEndpoint with(@Nullable Pool pool) {
this.pool = pool;
return this;
}
/**
* @inheritDoc
*/
@Override
public boolean equals(Object obj) { | if (obj == this) {
return true;
}
if (!(obj instanceof PoolConnectionEndpoint)) {
return false;
}
PoolConnectionEndpoint that = (PoolConnectionEndpoint) obj;
return super.equals(that)
&& this.getPool().equals(that.getPool());
}
/**
* @inheritDoc
*/
@Override
public int hashCode() {
int hashValue = super.hashCode();
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPool());
return hashValue;
}
/**
* @inheritDoc
*/
@Override
public String toString() {
return String.format("ConnectionEndpoint [%1$s] from Pool [%2$s]",
super.toString(), getPool().map(Pool::getName).orElse(""));
}
}
@SuppressWarnings("unused")
protected static class SocketCreationException extends RuntimeException {
protected SocketCreationException() { }
protected SocketCreationException(String message) {
super(message);
}
protected SocketCreationException(Throwable cause) {
super(cause);
}
protected SocketCreationException(String message, Throwable cause) {
super(message, cause);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAwareConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class LoggableWithThrowableUtil
{
private static final Logger logger = LogManager.getLogger(LoggableWithThrowableUtil.class);
public FormattedMsgWithAdIssueId extractMsgAndAdIssue(@NonNull final String msg, final Object... msgParameters)
{
final IErrorManager errorManager = Services.get(IErrorManager.class);
final Throwable exception = LoggableWithThrowableUtil.extractThrowable(msgParameters);
Object[] msgParametersEffective = msgParameters;
AdIssueId adIssueId = null;
if (exception != null)
{
try
{
adIssueId = errorManager.createIssue(exception);
msgParametersEffective = LoggableWithThrowableUtil.removeLastElement(msgParameters);
}
catch (final Exception createIssueException)
{
createIssueException.addSuppressed(exception);
logger.warn("Failed creating AD_Issue for exception: Skip creating the AD_Issue.", createIssueException);
}
}
//
String messageFormatted;
try
{
messageFormatted = StringUtils.formatMessage(msg, msgParametersEffective);
}
catch (final Exception formatMessageException)
{
logger.warn("Failed creating log entry for msg={} and msgParametes={}. Creating a fallback one instead",
msg, msgParametersEffective, formatMessageException);
messageFormatted = (msg != null ? msg : "")
+ (msgParameters != null && msgParameters.length > 0 ? " -- parameters: " + Arrays.asList(msgParameters) : "");
}
return new FormattedMsgWithAdIssueId(messageFormatted, Optional.ofNullable(adIssueId));
}
private Throwable extractThrowable(final Object[] msgParameters)
{ | if (msgParameters == null || msgParameters.length == 0)
{
return null;
}
final Object lastEntry = msgParameters[msgParameters.length - 1];
return lastEntry instanceof Throwable
? (Throwable)lastEntry
: null;
}
private Object[] removeLastElement(final Object[] msgParameters)
{
if (msgParameters == null || msgParameters.length == 0)
{
return msgParameters;
}
final int newLen = msgParameters.length - 1;
final Object[] msgParametersNew = new Object[newLen];
System.arraycopy(msgParameters, 0, msgParametersNew, 0, newLen);
return msgParametersNew;
}
@Value
public static class FormattedMsgWithAdIssueId
{
String formattedMessage;
Optional<AdIssueId> adIsueId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\LoggableWithThrowableUtil.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public de.metas.elasticsearch.model.I_ES_FTS_Config getES_FTS_Config()
{
return get_ValueAsPO(COLUMNNAME_ES_FTS_Config_ID, de.metas.elasticsearch.model.I_ES_FTS_Config.class);
}
@Override
public void setES_FTS_Config(final de.metas.elasticsearch.model.I_ES_FTS_Config ES_FTS_Config)
{
set_ValueFromPO(COLUMNNAME_ES_FTS_Config_ID, de.metas.elasticsearch.model.I_ES_FTS_Config.class, ES_FTS_Config);
} | @Override
public void setES_FTS_Config_ID (final int ES_FTS_Config_ID)
{
if (ES_FTS_Config_ID < 1)
set_Value (COLUMNNAME_ES_FTS_Config_ID, null);
else
set_Value (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID);
}
@Override
public int getES_FTS_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID);
}
@Override
public void setES_FTS_Filter_ID (final int ES_FTS_Filter_ID)
{
if (ES_FTS_Filter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, ES_FTS_Filter_ID);
}
@Override
public int getES_FTS_Filter_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Filter.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_K_EntryCategory[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_K_Category getK_Category() throws RuntimeException
{
return (I_K_Category)MTable.get(getCtx(), I_K_Category.Table_Name)
.getPO(getK_Category_ID(), get_TrxName()); }
/** Set Knowledge Category.
@param K_Category_ID
Knowledge Category
*/
public void setK_Category_ID (int K_Category_ID)
{
if (K_Category_ID < 1)
set_Value (COLUMNNAME_K_Category_ID, null);
else
set_Value (COLUMNNAME_K_Category_ID, Integer.valueOf(K_Category_ID));
}
/** Get Knowledge Category.
@return Knowledge Category
*/
public int getK_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_K_CategoryValue getK_CategoryValue() throws RuntimeException
{
return (I_K_CategoryValue)MTable.get(getCtx(), I_K_CategoryValue.Table_Name)
.getPO(getK_CategoryValue_ID(), get_TrxName()); }
/** Set Category Value.
@param K_CategoryValue_ID
The value of the category
*/
public void setK_CategoryValue_ID (int K_CategoryValue_ID)
{
if (K_CategoryValue_ID < 1)
set_Value (COLUMNNAME_K_CategoryValue_ID, null); | else
set_Value (COLUMNNAME_K_CategoryValue_ID, Integer.valueOf(K_CategoryValue_ID));
}
/** Get Category Value.
@return The value of the category
*/
public int getK_CategoryValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_CategoryValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_CategoryValue_ID()));
}
public I_K_Entry getK_Entry() throws RuntimeException
{
return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name)
.getPO(getK_Entry_ID(), get_TrxName()); }
/** Set Entry.
@param K_Entry_ID
Knowledge Entry
*/
public void setK_Entry_ID (int K_Entry_ID)
{
if (K_Entry_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID));
}
/** Get Entry.
@return Knowledge Entry
*/
public int getK_Entry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_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_K_EntryCategory.java | 1 |
请完成以下Java代码 | public PaymentCard4 getCard() {
return card;
}
/**
* Sets the value of the card property.
*
* @param value
* allowed object is
* {@link PaymentCard4 }
*
*/
public void setCard(PaymentCard4 value) {
this.card = value;
}
/**
* Gets the value of the poi property.
*
* @return
* possible object is
* {@link PointOfInteraction1 }
*
*/
public PointOfInteraction1 getPOI() {
return poi;
}
/**
* Sets the value of the poi property.
*
* @param value | * allowed object is
* {@link PointOfInteraction1 }
*
*/
public void setPOI(PointOfInteraction1 value) {
this.poi = value;
}
/**
* Gets the value of the aggtdNtry property.
*
* @return
* possible object is
* {@link CardAggregated1 }
*
*/
public CardAggregated1 getAggtdNtry() {
return aggtdNtry;
}
/**
* Sets the value of the aggtdNtry property.
*
* @param value
* allowed object is
* {@link CardAggregated1 }
*
*/
public void setAggtdNtry(CardAggregated1 value) {
this.aggtdNtry = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardEntry1.java | 1 |
请完成以下Java代码 | public static class FacetsCollection implements Iterable<Facet>
{
private static final FacetsCollection EMPTY = new FacetsCollection(ImmutableSet.of());
private final ImmutableSet<Facet> set;
private FacetsCollection(@NonNull final ImmutableSet<Facet> set)
{
this.set = set;
}
public static FacetsCollection ofCollection(final Collection<Facet> collection)
{
return !collection.isEmpty() ? new FacetsCollection(ImmutableSet.copyOf(collection)) : EMPTY;
}
@Override
@NonNull
public Iterator<Facet> iterator() {return set.iterator();}
public boolean isEmpty() {return set.isEmpty();}
public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds)
{
if (isEmpty())
{
return WorkflowLaunchersFacetGroupList.EMPTY;
}
final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>(); | for (final ManufacturingJobFacets.Facet manufacturingFacet : set)
{
final WorkflowLaunchersFacet facet = manufacturingFacet.toWorkflowLaunchersFacet(activeFacetIds);
groupBuilders.computeIfAbsent(facet.getGroupId(), k -> manufacturingFacet.newWorkflowLaunchersFacetGroupBuilder())
.facet(facet);
}
final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values()
.stream()
.map(WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder::build)
.collect(ImmutableList.toImmutableList());
return WorkflowLaunchersFacetGroupList.ofList(groups);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobFacets.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigInteger getEDICctop120VID() {
return ediCctop120VID;
}
/**
* Sets the value of the ediCctop120VID property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setEDICctop120VID(BigInteger value) {
this.ediCctop120VID = value;
}
/**
* Gets the value of the isoCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getISOCode() {
return isoCode;
}
/**
* Sets the value of the isoCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setISOCode(String value) {
this.isoCode = value;
}
/**
* Gets the value of the netdate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getNetdate() {
return netdate;
}
/**
* Sets the value of the netdate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setNetdate(XMLGregorianCalendar value) {
this.netdate = value;
}
/**
* Gets the value of the netDays property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNetDays() {
return netDays;
}
/**
* Sets the value of the netDays property.
* | * @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNetDays(BigInteger value) {
this.netDays = value;
}
/**
* Gets the value of the singlevat property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getSinglevat() {
return singlevat;
}
/**
* Sets the value of the singlevat property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSinglevat(BigDecimal value) {
this.singlevat = value;
}
/**
* Gets the value of the taxfree property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxfree() {
return taxfree;
}
/**
* Sets the value of the taxfree property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxfree(String value) {
this.taxfree = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop120VType.java | 2 |
请完成以下Java代码 | public boolean createXML (StreamResult result)
{
try
{
DOMSource source = new DOMSource(getDocument());
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.transform (source, result);
}
catch (Exception e)
{
log.error("(StreamResult)", e);
return false;
}
return true;
} // createXML
/**
* Create XML representation to File
* @param fileName file name
* @return true if success
*/
public boolean createXML (String fileName)
{
try
{
File file = new File(fileName);
file.createNewFile();
StreamResult result = new StreamResult(file);
createXML (result);
}
catch (Exception e)
{
log.error("(file)", e);
return false;
}
return true;
} // createXMLFile | /**************************************************************************
* Create PrintData from XML
* @param ctx context
* @param input InputSource
* @return PrintData
*/
public static PrintData parseXML (Properties ctx, File input)
{
log.info(input.toString());
PrintData pd = null;
try
{
PrintDataHandler handler = new PrintDataHandler(ctx);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(input, handler);
pd = handler.getPrintData();
}
catch (Exception e)
{
log.error("", e);
}
return pd;
} // parseXML
} // PrintData | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintData.java | 1 |
请完成以下Java代码 | default <ChildType> IQueryBuilder<ChildType> andCollectChildren(final ModelColumn<ChildType, ?> linkColumnInChildTable)
{
final String linkColumnNameInChildTable = linkColumnInChildTable.getColumnName();
final Class<ChildType> childType = linkColumnInChildTable.getModelClass();
return andCollectChildren(linkColumnNameInChildTable, childType);
}
/**
* Sets the join mode of this instance's internal composite filter.
*
* @return this
* @see ICompositeQueryFilter#setJoinOr()
*/
IQueryBuilder<T> setJoinOr();
/**
* Sets the join mode of this instance's internal composite filter.
*
* @return this | * @see ICompositeQueryFilter#setJoinAnd()
*/
IQueryBuilder<T> setJoinAnd();
/**
* Will only return records that are referenced by a <code>T_Selection</code> records which has the given selection ID.
*/
IQueryBuilder<T> setOnlySelection(PInstanceId pinstanceId);
/**
* Start an aggregation of different columns, everything grouped by given <code>column</code>
*
* @return aggregation builder
*/
<TargetModelType> IQueryAggregateBuilder<T, TargetModelType> aggregateOnColumn(ModelColumn<T, TargetModelType> column);
<TargetModelType> IQueryAggregateBuilder<T, TargetModelType> aggregateOnColumn(String collectOnColumnName, Class<TargetModelType> targetModelType);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\IQueryBuilder.java | 1 |
请完成以下Java代码 | public class AlternativePickFromKeys implements Iterable<AlternativePickFromKey>
{
public static final AlternativePickFromKeys EMPTY = new AlternativePickFromKeys(ImmutableSet.of());
private final ImmutableSet<AlternativePickFromKey> keys;
private AlternativePickFromKeys(@NonNull final Set<AlternativePickFromKey> keys)
{
this.keys = ImmutableSet.copyOf(keys);
}
public static AlternativePickFromKeys ofSet(final Set<AlternativePickFromKey> keys)
{
return !keys.isEmpty() ? new AlternativePickFromKeys(keys) : EMPTY;
}
public static Collector<AlternativePickFromKey, ?, AlternativePickFromKeys> collect()
{
return GuavaCollectors.collectUsingHashSetAccumulator(AlternativePickFromKeys::ofSet);
} | public boolean isEmpty() {return keys.isEmpty();}
public AlternativePickFromKeys filter(@NonNull final Predicate<AlternativePickFromKey> predicate)
{
final ImmutableSet<AlternativePickFromKey> keysNew = keys.stream().filter(predicate).collect(ImmutableSet.toImmutableSet());
return keys.size() != keysNew.size() ? ofSet(keysNew) : this;
}
@Override
public UnmodifiableIterator<AlternativePickFromKey> iterator() {return keys.iterator();}
public Stream<AlternativePickFromKey> stream() {return keys.stream();}
public ImmutableSet<HuId> getHuIds() {return keys.stream().map(AlternativePickFromKey::getHuId).collect(ImmutableSet.toImmutableSet());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\AlternativePickFromKeys.java | 1 |
请完成以下Java代码 | public class FileIOUtil {
private static final Logger LOG = LoggerFactory.getLogger(FileIOUtil.class);
public static String readFileFromResource(String filePath) {
try (InputStream inputStream = FileIOUtil.class.getResourceAsStream(filePath)) {
String result = null;
if (inputStream != null) {
result = new BufferedReader(new InputStreamReader(inputStream))
.lines()
.collect(Collectors.joining("\n"));
}
return result;
} catch (IOException e) {
LOG.error("Error reading file:", e); | return null;
}
}
public static String readFileFromFileSystem(String filePath) {
try (InputStream inputStream = Files.newInputStream(Paths.get(filePath))) {
return new BufferedReader(new InputStreamReader(inputStream))
.lines()
.collect(Collectors.joining("\n"));
} catch (IOException e) {
LOG.error("Error reading file:", e);
return null;
}
}
} | repos\tutorials-master\core-java-modules\core-java-io-6\src\main\java\com\baeldung\filereadmethods\FileIOUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void cleanCache() {
try {
cleanPdfCache();
cleanImgCache();
cleanPdfImgCache();
cleanMediaConvertCache();
} catch (IOException | RocksDBException e) {
LOGGER.error("Clean Cache Exception" + e);
}
}
@Override
public void addQueueTask(String url) {
blockingQueue.add(url);
}
@Override
public String takeQueueTask() throws InterruptedException {
return blockingQueue.take();
}
@SuppressWarnings("unchecked")
private Map<String, Integer> getPdfImageCaches() {
Map<String, Integer> map = new HashMap<>();
try {
map = (Map<String, Integer>) toObject(db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()));
} catch (RocksDBException | IOException | ClassNotFoundException e) {
LOGGER.error("Get from RocksDB Exception" + e);
}
return map;
}
private byte[] toByteArray(Object obj) throws IOException {
byte[] bytes;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush(); | bytes = bos.toByteArray();
oos.close();
bos.close();
return bytes;
}
private Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
return obj;
}
private void cleanPdfCache() throws IOException, RocksDBException {
Map<String, String> initPDFCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
}
private void cleanImgCache() throws IOException, RocksDBException {
Map<String, List<String>> initIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
}
private void cleanPdfImgCache() throws IOException, RocksDBException {
Map<String, Integer> initPDFIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
}
private void cleanMediaConvertCache() throws IOException, RocksDBException {
Map<String, String> initMediaConvertCache = new HashMap<>();
db.put(FILE_PREVIEW_MEDIA_CONVERT_KEY.getBytes(), toByteArray(initMediaConvertCache));
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRocksDBImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static PickAttributes ofHUQRCode(@NonNull final IHUQRCode pickFromHUQRCode, @Nullable final UomId catchWeightUomId)
{
final PickAttributesBuilder builder = builder();
final BigDecimal catchWeightBD = pickFromHUQRCode.getWeightInKg().orElse(null);
if (catchWeightBD != null && catchWeightUomId != null)
{
builder.catchWeight(Quantitys.of(catchWeightBD, catchWeightUomId));
}
pickFromHUQRCode.getBestBeforeDate().ifPresent(bestBeforeDate -> builder.isSetBestBeforeDate(true).bestBeforeDate(bestBeforeDate));
pickFromHUQRCode.getProductionDate().ifPresent(productionDate -> builder.isSetProductionDate(true).productionDate(productionDate));
pickFromHUQRCode.getLotNumber().ifPresent(lotNo -> builder.isSetLotNo(true).lotNo(lotNo));
return builder.build();
}
public PickAttributes fallbackTo(@NonNull final PickAttributes fallback)
{
final PickAttributesBuilder builder = toBuilder();
boolean changed = false;
if (catchWeight == null && fallback.catchWeight != null)
{ | builder.catchWeight(fallback.catchWeight);
changed = true;
}
if (!isSetBestBeforeDate && fallback.isSetBestBeforeDate)
{
builder.isSetBestBeforeDate(true).bestBeforeDate(fallback.bestBeforeDate);
changed = true;
}
if (!isSetProductionDate && fallback.isSetProductionDate)
{
builder.isSetProductionDate(true).productionDate(fallback.productionDate);
changed = true;
}
if (!isSetLotNo && fallback.isSetLotNo)
{
builder.isSetLotNo(true).lotNo(fallback.lotNo);
changed = true;
}
return changed ? builder.build() : this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\pick\PickAttributes.java | 2 |
请完成以下Java代码 | public String getUserLastnameAttribute() {
return userLastnameAttribute;
}
public void setUserLastnameAttribute(String userLastnameAttribute) {
this.userLastnameAttribute = userLastnameAttribute;
}
public String getUserEmailAttribute() {
return userEmailAttribute;
}
public void setUserEmailAttribute(String userEmailAttribute) {
this.userEmailAttribute = userEmailAttribute;
}
public String getUserPasswordAttribute() {
return userPasswordAttribute;
}
public void setUserPasswordAttribute(String userPasswordAttribute) {
this.userPasswordAttribute = userPasswordAttribute;
}
public boolean isSortControlSupported() {
return sortControlSupported;
}
public void setSortControlSupported(boolean sortControlSupported) {
this.sortControlSupported = sortControlSupported;
}
public String getGroupIdAttribute() {
return groupIdAttribute;
}
public void setGroupIdAttribute(String groupIdAttribute) {
this.groupIdAttribute = groupIdAttribute;
}
public String getGroupMemberAttribute() {
return groupMemberAttribute;
}
public void setGroupMemberAttribute(String groupMemberAttribute) {
this.groupMemberAttribute = groupMemberAttribute;
}
public boolean isUseSsl() {
return useSsl;
}
public void setUseSsl(boolean useSsl) {
this.useSsl = useSsl;
}
public boolean isUsePosixGroups() {
return usePosixGroups;
} | public void setUsePosixGroups(boolean usePosixGroups) {
this.usePosixGroups = usePosixGroups;
}
public SearchControls getSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
return searchControls;
}
public String getGroupTypeAttribute() {
return groupTypeAttribute;
}
public void setGroupTypeAttribute(String groupTypeAttribute) {
this.groupTypeAttribute = groupTypeAttribute;
}
public boolean isAllowAnonymousLogin() {
return allowAnonymousLogin;
}
public void setAllowAnonymousLogin(boolean allowAnonymousLogin) {
this.allowAnonymousLogin = allowAnonymousLogin;
}
public boolean isAuthorizationCheckEnabled() {
return authorizationCheckEnabled;
}
public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) {
this.authorizationCheckEnabled = authorizationCheckEnabled;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public boolean isPasswordCheckCatchAuthenticationException() {
return passwordCheckCatchAuthenticationException;
}
public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) {
this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException;
}
} | repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
#spring.jpa.properties.hibernate.format_sql= true
spring.jpa.open-in-view=false
spring.datasource.initialization-mode=always
spring.datasource.platform=mysql
# always avoid this setting
spring.jpa.properties.hibernate.enable_l | azy_load_no_trans=true
logging.level.ROOT=INFO
logging.level.org.hibernate.engine.transaction.internal.TransactionImpl=DEBUG
logging.level.org.springframework.orm.jpa=DEBUG
logging.level.org.springframework.transaction=DEBUG | repos\Hibernate-SpringBoot-master\HibernateSpringBootEnableLazyLoadNoTrans\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | static class JavaClientConfiguration {
@Bean
@ConditionalOnMissingBean(value = ElasticsearchOperations.class, name = "elasticsearchTemplate")
@ConditionalOnBean(ElasticsearchClient.class)
ElasticsearchTemplate elasticsearchTemplate(ElasticsearchClient client, ElasticsearchConverter converter) {
return new ElasticsearchTemplate(client, converter);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ElasticsearchTransport.class)
@ConditionalOnClass({ ReactiveElasticsearchClient.class, ElasticsearchTransport.class, Mono.class })
static class ReactiveRestClientConfiguration { | @Bean
@ConditionalOnMissingBean
ReactiveElasticsearchClient reactiveElasticsearchClient(ElasticsearchTransport transport) {
return new ReactiveElasticsearchClient(transport);
}
@Bean
@ConditionalOnMissingBean(value = ReactiveElasticsearchOperations.class, name = "reactiveElasticsearchTemplate")
ReactiveElasticsearchTemplate reactiveElasticsearchTemplate(ReactiveElasticsearchClient client,
ElasticsearchConverter converter) {
return new ReactiveElasticsearchTemplate(client, converter);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-elasticsearch\src\main\java\org\springframework\boot\data\elasticsearch\autoconfigure\DataElasticsearchConfiguration.java | 2 |
请完成以下Java代码 | private PPOrderQuantities getPPOrderQuantities()
{
return orderBOMBL.getQuantities(ppOrder);
}
@Override
protected BigDecimal retrieveQtyInitial()
{
checkStaled();
final PPOrderQuantities ppOrderQtys = getPPOrderQuantities();
final Quantity qtyToReceive = ppOrderQtys.getQtyRemainingToProduce();
return qtyToReceive.toBigDecimal();
}
@Override
protected void beforeMarkingStalled() | {
staled = true;
}
private void checkStaled()
{
if (!staled)
{
return;
}
InterfaceWrapperHelper.refresh(ppOrder);
staled = false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderProductStorage.java | 1 |
请完成以下Java代码 | public class FileToHashMap {
enum DupKeyOption {
OVERWRITE, DISCARD
}
public static Map<String, String> byBufferedReader(String filePath, DupKeyOption dupKeyOption) {
HashMap<String, String> map = new HashMap<>();
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
while ((line = reader.readLine()) != null) {
String[] keyValuePair = line.split(":", 2);
if (keyValuePair.length > 1) {
String key = keyValuePair[0];
String value = keyValuePair[1];
if (DupKeyOption.OVERWRITE == dupKeyOption) {
map.put(key, value);
} else if (DupKeyOption.DISCARD == dupKeyOption) {
map.putIfAbsent(key, value);
}
} else {
System.out.println("No Key:Value found in line, ignoring: " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
public static Map<String, String> byStream(String filePath, DupKeyOption dupKeyOption) {
Map<String, String> map = new HashMap<>();
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.filter(line -> line.contains(":"))
.forEach(line -> {
String[] keyValuePair = line.split(":", 2);
String key = keyValuePair[0];
String value = keyValuePair[1];
if (DupKeyOption.OVERWRITE == dupKeyOption) {
map.put(key, value);
} else if (DupKeyOption.DISCARD == dupKeyOption) {
map.putIfAbsent(key, value);
} | });
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
public static Map<String, List<String>> aggregateByKeys(String filePath) {
Map<String, List<String>> map = new HashMap<>();
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.filter(line -> line.contains(":"))
.forEach(line -> {
String[] keyValuePair = line.split(":", 2);
String key = keyValuePair[0];
String value = keyValuePair[1];
if (map.containsKey(key)) {
map.get(key).add(value);
} else {
map.put(key, Stream.of(value).collect(Collectors.toList()));
}
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
} | repos\tutorials-master\core-java-modules\core-java-io-4\src\main\java\com\baeldung\filetomap\FileToHashMap.java | 1 |
请完成以下Java代码 | public CompositeHUTrxListener copy()
{
final CompositeHUTrxListener copy = new CompositeHUTrxListener();
copy.listeners.addAll(listeners);
return copy;
}
@Override
public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine)
{
for (final IHUTrxListener listener : listeners)
{
listener.trxLineProcessed(huContext, trxLine);
}
}
@Override
public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld)
{
for (final IHUTrxListener listener : listeners)
{
listener.huParentChanged(hu, parentHUItemOld);
}
}
@Override
public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines)
{
for (final IHUTrxListener listener : listeners)
{
listener.afterTrxProcessed(trxHdrRef, trxLines);
}
}
@Override
public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults)
{
for (final IHUTrxListener listener : listeners)
{
listener.afterLoad(huContext, loadResults);
}
}
@Override
public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{ | for (final IHUTrxListener listener : listeners)
{
listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx);
}
}
@Override
public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
for (final IHUTrxListener listener : listeners)
{
listener.onSplitTransaction(huContext, unloadTrx, loadTrx);
}
}
@Override
public String toString()
{
return "CompositeHUTrxListener [listeners=" + listeners + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class Offer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
private Artist artist;
Offer(String name, Artist artist) {
this.name = name;
this.artist = artist;
}
@Override
public boolean equals(Object o) { | if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Offer offer = (Offer) o;
return id != null ? id.equals(offer.id) : offer.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
protected Offer() {
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\multiplebagfetchexception\Offer.java | 2 |
请完成以下Java代码 | public java.sql.Timestamp getEventTime()
{
return get_ValueAsTimestamp(COLUMNNAME_EventTime);
}
@Override
public void setEventTopicName (final @Nullable java.lang.String EventTopicName)
{
set_Value (COLUMNNAME_EventTopicName, EventTopicName);
}
@Override
public java.lang.String getEventTopicName()
{
return get_ValueAsString(COLUMNNAME_EventTopicName);
}
/**
* EventTypeName AD_Reference_ID=540802
* Reference name: EventTypeName
*/
public static final int EVENTTYPENAME_AD_Reference_ID=540802;
/** LOCAL = LOCAL */
public static final String EVENTTYPENAME_LOCAL = "LOCAL";
/** DISTRIBUTED = DISTRIBUTED */
public static final String EVENTTYPENAME_DISTRIBUTED = "DISTRIBUTED";
@Override
public void setEventTypeName (final @Nullable java.lang.String EventTypeName)
{
set_Value (COLUMNNAME_EventTypeName, EventTypeName);
}
@Override
public java.lang.String getEventTypeName()
{
return get_ValueAsString(COLUMNNAME_EventTypeName);
}
@Override
public void setEvent_UUID (final java.lang.String Event_UUID)
{
set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID);
}
@Override
public java.lang.String getEvent_UUID()
{
return get_ValueAsString(COLUMNNAME_Event_UUID);
} | @Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setIsErrorAcknowledged (final boolean IsErrorAcknowledged)
{
set_Value (COLUMNNAME_IsErrorAcknowledged, IsErrorAcknowledged);
}
@Override
public boolean isErrorAcknowledged()
{
return get_ValueAsBoolean(COLUMNNAME_IsErrorAcknowledged);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExampleServiceImpl extends ExampleServiceImplBase {
private boolean InjectError() {
// We create ~5% error.
return ThreadLocalRandom.current().nextInt(0, 99) >= 95;
}
@Override
public void unaryRpc(UnaryRequest request,
StreamObserver<UnaryResponse> responseObserver) {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onNext(UnaryResponse.newBuilder().setMessage(request.getMessage()).build());
responseObserver.onCompleted();
}
}
@Override
public StreamObserver<ClientStreamingRequest> clientStreamingRpc(
StreamObserver<ClientStreamingResponse> responseObserver) {
return new StreamObserver<>() {
@Override
public void onNext(ClientStreamingRequest value) {
responseObserver.onNext(
ClientStreamingResponse.newBuilder().setMessage(value.getMessage()).build());
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onCompleted();
}
}
}; | }
@Override
public void serverStreamingRpc(ServerStreamingRequest request,
StreamObserver<ServerStreamingResponse> responseObserver) {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onNext(
ServerStreamingResponse.newBuilder().setMessage(request.getMessage()).build());
responseObserver.onCompleted();
}
}
@Override
public StreamObserver<BidiStreamingRequest> bidiStreamingRpc(
StreamObserver<BidiStreamingResponse> responseObserver) {
return new StreamObserver<>() {
@Override
public void onNext(BidiStreamingRequest value) {
responseObserver.onNext(
BidiStreamingResponse.newBuilder().setMessage(value.getMessage()).build());
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onCompleted();
}
}
};
}
} | repos\grpc-spring-master\examples\grpc-observability\backend\src\main\java\net\devh\boot\grpc\examples\observability\backend\ExampleServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultDeploymentConfiguration extends AbstractCamundaConfiguration implements CamundaDeploymentConfiguration {
private final Logger logger = LoggerFactory.getLogger(DefaultDeploymentConfiguration.class);
@Override
public void preInit(SpringProcessEngineConfiguration configuration) {
if (camundaBpmProperties.isAutoDeploymentEnabled()) {
final Set<Resource> resources = getDeploymentResources();
configuration.setDeploymentResources(resources.toArray(new Resource[resources.size()]));
LOG.autoDeployResources(resources);
}
}
@Override
public Set<Resource> getDeploymentResources() {
final ResourceArrayPropertyEditor resolver = new ResourceArrayPropertyEditor();
try {
final String[] resourcePattern = camundaBpmProperties.getDeploymentResourcePattern();
logger.debug("resolving deployment resources for pattern {}", (Object[]) resourcePattern);
resolver.setValue(resourcePattern);
return Arrays.stream((Resource[])resolver.getValue())
.peek(resource -> logger.debug("processing deployment resource {}", resource))
.filter(this::isFile)
.peek(resource -> logger.debug("added deployment resource {}", resource))
.collect(Collectors.toSet());
} catch (final RuntimeException e) {
logger.error("unable to resolve resources", e);
}
return EMPTY_SET;
}
private boolean isFile(Resource resource) {
if (resource.isReadable()) { | if (resource instanceof UrlResource || resource instanceof ClassPathResource) {
try {
URL url = resource.getURL();
return !url.toString().endsWith("/");
} catch (IOException e) {
logger.debug("unable to handle " + resource + " as URL", e);
}
} else {
try {
return !resource.getFile().isDirectory();
} catch (IOException e) {
logger.debug("unable to handle " + resource + " as file", e);
}
}
}
logger.warn("unable to determine if resource {} is a deployable resource", resource);
return false;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\DefaultDeploymentConfiguration.java | 2 |
请完成以下Java代码 | public void setAD_Table(org.compiere.model.I_AD_Table AD_Table)
{
set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table);
}
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
@Override
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausschluß.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
@Override
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Ausschluß.
@return Exclude access to the data - if not selected Include access to the data
*/
@Override | public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column_Access.java | 1 |
请完成以下Java代码 | private String getHeaderName(final int col)
{
return m_tab.getField(col).getHeader();
}
@Override
public int getRowCount()
{
return m_tab.getRowCount();
}
private CellValue getValueAt(final int row, final int col)
{
final GridField f = m_tab.getField(col);
final Object key = m_tab.getValue(row, f.getColumnName());
Object value = key;
Lookup lookup = f.getLookup();
if (lookup != null)
{
// nothing to do
}
else if (f.getDisplayType() == DisplayType.Button)
{
lookup = getButtonLookup(f);
}
if (lookup != null)
{
value = lookup.getDisplay(key);
}
final int displayType = f.getDisplayType();
return CellValues.toCellValue(value, displayType);
}
@Override
public boolean isColumnPrinted(final int col)
{
final GridField f = m_tab.getField(col);
// Hide not displayed fields
if (!f.isDisplayed(GridTabLayoutMode.Grid))
{
return false;
}
// Hide encrypted fields
if (f.isEncrypted())
{
return false;
}
// Hide simple button fields without a value
if (f.getDisplayType() == DisplayType.Button && f.getAD_Reference_Value_ID() == null)
{
return false;
}
// Hide included tab fields (those are only placeholders for included tabs, always empty)
if (f.getIncluded_Tab_ID() > 0)
{
return false;
}
//
return true;
}
@Override
public boolean isFunctionRow(final int row)
{
return false;
}
@Override
public boolean isPageBreak(final int row, final int col)
{
return false;
}
private final HashMap<String, MLookup> m_buttonLookups = new HashMap<>();
private MLookup getButtonLookup(final GridField mField)
{
MLookup lookup = m_buttonLookups.get(mField.getColumnName());
if (lookup != null)
{
return lookup; | }
// TODO: refactor with org.compiere.grid.ed.VButton.setField(GridField)
if (mField.getColumnName().endsWith("_ID") && !IColumnBL.isRecordIdColumnName(mField.getColumnName()))
{
lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.Search);
}
else if (mField.getAD_Reference_Value_ID() != null)
{
// Assuming List
lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.List);
}
//
m_buttonLookups.put(mField.getColumnName(), lookup);
return lookup;
}
@Override
protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\impexp\spreadsheet\excel\GridTabExcelExporter.java | 1 |
请完成以下Java代码 | public class ChangeEDI_ExportStatus_EDI_Desadv_SingleView
extends JavaProcess
implements IProcessPrecondition, IProcessDefaultParametersProvider
{
private final IDesadvDAO desadvDAO = Services.get(IDesadvDAO.class);
protected static final String PARAM_TargetExportStatus = I_EDI_Desadv.COLUMNNAME_EDI_ExportStatus;
@Param(parameterName = PARAM_TargetExportStatus)
private String p_TargetExportStatus;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final I_EDI_Desadv desadv = desadvDAO.retrieveById(EDIDesadvId.ofRepoId(context.getSingleSelectedRecordId()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofNullableCode(desadv.getEDI_ExportStatus());
if (fromExportStatus == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Cannot change ExportStatus from the current one for: " + desadv);
}
if (ChangeEDI_ExportStatusHelper.getAvailableTargetExportStatuses(fromExportStatus).isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Cannot change ExportStatus from the current one: " + fromExportStatus);
}
return ProcessPreconditionsResolution.accept();
}
@ProcessParamLookupValuesProvider(parameterName = PARAM_TargetExportStatus, numericKey = false, lookupSource = LookupSource.list)
private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final I_EDI_Desadv desadv = desadvDAO.retrieveById(EDIDesadvId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(desadv.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus);
}
@Override | @Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final I_EDI_Desadv desadv = desadvDAO.retrieveById(EDIDesadvId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(desadv.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
{
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
final boolean isProcessed = ChangeEDI_ExportStatusHelper.computeIsProcessedByTargetExportStatus(targetExportStatus);
ChangeEDI_ExportStatusHelper.EDI_DesadvDoIt(EDIDesadvId.ofRepoId(getRecord_ID()),
targetExportStatus,
isProcessed);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_EDI_Desadv_SingleView.java | 1 |
请完成以下Java代码 | public JSONZoomInto getRowFieldZoomInto(
@PathVariable("windowId") final String windowIdStr,
@PathVariable(PARAM_ViewId) final String viewIdStr,
@PathVariable("rowId") final String rowIdStr,
@PathVariable("fieldName") final String fieldName)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.ofViewIdString(viewIdStr, WindowId.fromJson(windowIdStr));
final IView view = viewsRepo.getView(viewId);
if (view instanceof IViewZoomIntoFieldSupport)
{
final IViewZoomIntoFieldSupport zoomIntoSupport = (IViewZoomIntoFieldSupport)view;
final DocumentId rowId = DocumentId.of(rowIdStr);
final DocumentZoomIntoInfo zoomIntoInfo = zoomIntoSupport.getZoomIntoInfo(rowId, fieldName);
final DocumentPath zoomIntoDocumentPath = documentZoomIntoService.getDocumentPath(zoomIntoInfo);
return JSONZoomInto.builder()
.documentPath(JSONDocumentPath.ofWindowDocumentPath(zoomIntoDocumentPath))
.source(JSONDocumentPath.builder().viewId(viewId).rowId(rowId).fieldName(fieldName).build())
.build();
}
// Fallback to windowRestController, hoping the document existing and has the same ID as view's row ID.
return windowRestController.getDocumentFieldZoomInto(windowIdStr, rowIdStr, fieldName);
}
@GetMapping("/{viewId}/export/excel")
public ResponseEntity<Resource> exportToExcel(
@PathVariable("windowId") final String windowIdStr,
@PathVariable(PARAM_ViewId) final String viewIdStr,
@RequestParam(name = "selectedIds", required = false) @Parameter(description = "comma separated IDs") final String selectedIdsListStr)
throws Exception
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.ofViewIdString(viewIdStr, WindowId.fromJson(windowIdStr));
final ExcelFormat excelFormat = ExcelFormats.getDefaultFormat();
final File tmpFile = File.createTempFile("exportToExcel", "." + excelFormat.getFileExtension());
try (final FileOutputStream out = new FileOutputStream(tmpFile)) | {
ViewExcelExporter.builder()
.excelFormat(excelFormat)
.view(viewsRepo.getView(viewId))
.rowIds(DocumentIdsSelection.ofCommaSeparatedString(selectedIdsListStr))
.layout(viewsRepo.getViewLayout(viewId.getWindowId(), JSONViewDataType.grid, ViewProfileId.NULL, userSession.getUserRolePermissionsKey()))
.language(userSession.getLanguage())
.zoneId(userSession.getTimeZone())
.build()
.export(out);
}
final String filename = "report." + excelFormat.getFileExtension(); // TODO: use a better name
final String contentType = MimeType.getMimeType(filename);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(contentType));
headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<>(new InputStreamResource(Files.newInputStream(tmpFile.toPath())), headers, HttpStatus.OK);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class AddToResultGroupRequest
{
WarehouseId warehouseId;
ProductId productId;
BPartnerClassifier bpartner;
AttributesKey storageAttributesKey;
BigDecimal qty;
Instant date;
int seqNo; // needed to disambiguated requests with the same date
@Builder
public AddToResultGroupRequest(
@NonNull final WarehouseId warehouseId,
@NonNull final ProductId productId,
@NonNull final AttributesKey storageAttributesKey,
@NonNull final BPartnerClassifier bpartner,
@NonNull final BigDecimal qty,
@NonNull final Instant date,
final int seqNo)
{
this.warehouseId = warehouseId;
this.productId = productId;
this.bpartner = bpartner;
this.storageAttributesKey = storageAttributesKey; | this.qty = qty;
this.date = date;
this.seqNo = Check.assumeGreaterThanZero(seqNo, "seqNo");
}
public ArrayKey computeKey()
{
return ArrayKey.of(warehouseId, productId, storageAttributesKey);
}
public DateAndSeqNo getDateAndSeqNo()
{
return DateAndSeqNo.builder()
.date(date)
.seqNo(seqNo)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AddToResultGroupRequest.java | 2 |
请完成以下Java代码 | protected void validateIncomingSequenceFlows(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions,
MigrationInstructionValidationReportImpl report) {
ActivityImpl sourceActivity = instruction.getSourceActivity();
ActivityImpl targetActivity = instruction.getTargetActivity();
int numSourceIncomingFlows = sourceActivity.getIncomingTransitions().size();
int numTargetIncomingFlows = targetActivity.getIncomingTransitions().size();
if (numSourceIncomingFlows > numTargetIncomingFlows) {
report.addFailure("The target gateway must have at least the same number "
+ "of incoming sequence flows that the source gateway has");
}
}
protected void validateParentScopeMigrates(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions,
MigrationInstructionValidationReportImpl report) {
ActivityImpl sourceActivity = instruction.getSourceActivity();
ScopeImpl flowScope = sourceActivity.getFlowScope();
if (flowScope != flowScope.getProcessDefinition()) {
if (instructions.getInstructionsBySourceScope(flowScope).isEmpty()) {
report.addFailure("The gateway's flow scope '" + flowScope.getId() + "' must be mapped");
}
}
}
protected void validateSingleInstruction(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions,
MigrationInstructionValidationReportImpl report) { | ActivityImpl targetActivity = instruction.getTargetActivity();
List<ValidatingMigrationInstruction> instructionsToTargetGateway =
instructions.getInstructionsByTargetScope(targetActivity);
if (instructionsToTargetGateway.size() > 1) {
report.addFailure("Only one gateway can be mapped to gateway '" + targetActivity.getId() + "'");
}
}
protected boolean isWaitStateGateway(ActivityImpl activity) {
ActivityBehavior behavior = activity.getActivityBehavior();
return behavior instanceof ParallelGatewayActivityBehavior
|| behavior instanceof InclusiveGatewayActivityBehavior;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\GatewayMappingValidator.java | 1 |
请完成以下Java代码 | public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
//
// Determine what we will filter
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int offset = evalCtx.getOffset(0);
final int limit = evalCtx.getLimit(filter.isMatchAll() ? Integer.MAX_VALUE : 100);
//
// Get, filter, return
return getAllCountriesById()
.getValues()
.stream()
.filter(filter)
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
private LookupValuesList getAllCountriesById()
{
final Object cacheKey = "ALL";
return allCountriesCache.getOrLoad(cacheKey, this::retriveAllCountriesById);
}
private LookupValuesList retriveAllCountriesById()
{
return Services.get(ICountryDAO.class) | .getCountries(Env.getCtx())
.stream()
.map(this::createLookupValue)
.collect(LookupValuesList.collect());
}
private IntegerLookupValue createLookupValue(final I_C_Country countryRecord)
{
final int countryId = countryRecord.getC_Country_ID();
final IModelTranslationMap modelTranslationMap = InterfaceWrapperHelper.getModelTranslationMap(countryRecord);
final ITranslatableString countryName = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Name, countryRecord.getName());
final ITranslatableString countryDescription = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Description, countryRecord.getName());
return IntegerLookupValue.of(countryId, countryName, countryDescription);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressCountryLookupDescriptor.java | 1 |
请完成以下Java代码 | public void setServices(ServicesType value) {
this.services = value;
}
/**
* Gets the value of the documents property.
*
* @return
* possible object is
* {@link DocumentsType }
*
*/
public DocumentsType getDocuments() {
return documents;
}
/**
* Sets the value of the documents property.
*
* @param value
* allowed object is
* {@link DocumentsType }
*
*/
public void setDocuments(DocumentsType value) {
this.documents = value;
}
/**
* Gets the value of the roleTitle property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRoleTitle() {
return roleTitle;
}
/**
* Sets the value of the roleTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRoleTitle(String value) {
this.roleTitle = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/** | * Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the place property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlace() {
return place;
}
/**
* Sets the value of the place property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlace(String value) {
this.place = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BodyType.java | 1 |
请完成以下Java代码 | public AdProcessId toAdProcessId()
{
final AdProcessId adProcessId = toAdProcessIdOrNull();
if (adProcessId == null)
{
throw new AdempiereException("Cannot convert " + this + " to " + AdProcessId.class.getSimpleName() + " because the processHanderType=" + processHandlerType + " is not supported");
}
return adProcessId;
}
/**
* Convenience method to get the {@link AdProcessId} for this instance if its {@code processIdAsInt} member is set and/or if {@link #getProcessHandlerType()} is {@link #PROCESSHANDLERTYPE_AD_Process}.
* {@code null} otherwise.
*/
public AdProcessId toAdProcessIdOrNull()
{
if (this.processIdAsInt > 0) // was set by the creator of this instance
{ | return AdProcessId.ofRepoId(this.processIdAsInt);
}
else if (this.processHandlerType.isADProcess())
{
return AdProcessId.ofRepoId(getProcessIdAsInt());
}
else // nothing we can do here
{
return null;
}
}
public DocumentId toDocumentId()
{
return DocumentId.ofString(toJson());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private double generateValueForType(String type) {
switch (type) {
case "CPU_USAGE":
return Math.round(random.nextDouble() * 10000.0) / 100.0; // 0.00 - 100.00 percent
case "MEMORY_USAGE":
return Math.round((random.nextDouble() * 32_000) * 100.0) / 100.0; // MB, up to ~32GB
case "APPLICATION_AVAILABILITY":
return random.nextBoolean() ? 1.0 : 0.0; // 1 = up, 0 = down
case "DISK_IO":
return Math.round((random.nextDouble() * 5000) * 100.0) / 100.0; // IOPS-ish
case "NETWORK_THROUGHPUT":
return Math.round((random.nextDouble() * 1000) * 100.0) / 100.0; // Mbps
default:
return random.nextDouble() * 100.0;
}
}
/**
* Build a MonitoringEvent instance using direct setters on the MonitoringEvent POJO.
*/
private MonitoringEvent buildMonitoringEvent(String id, String device, String type, double value, long timestamp) {
try {
MonitoringEvent evt = new MonitoringEvent();
// Map generated values to the MonitoringEvent fields
evt.setEventId(random.nextInt(10_000));
evt.setDeviceId(device);
evt.setEventType(type);
// Use a human-friendly event name | String name = type + "-" + id.substring(0, 8);
evt.setEventName(name);
// creationDate as ISO-8601 string
evt.setCreationDate(Instant.ofEpochMilli(timestamp).toString());
// status: for availability events, use UP/DOWN; otherwise store numeric value as string
if ("APPLICATION_AVAILABILITY".equals(type)) {
evt.setStatus(value == 1.0 ? "UP" : "DOWN");
} else {
evt.setStatus(String.format("%.2f", value));
}
return evt;
} catch (Exception e) {
// In case of unexpected error, return null (caller will skip)
return null;
}
}
} | repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\service\MonitoringDataService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public BigDecimal getInterest() {
return interest;
}
public void setInterest(BigDecimal interest) {
this.interest = interest;
}
public Boolean getDeposit() { | return deposit;
}
public void setDeposit(Boolean deposit) {
this.deposit = deposit;
}
public Boolean getCapitalization() {
return capitalization;
}
public void setCapitalization(Boolean capitalization) {
this.capitalization = capitalization;
}
} | repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\domain\Saving.java | 2 |
请完成以下Java代码 | protected void doHealthCheck(Health.Builder builder) {
if (getApplicationContext().isPresent()) {
Map<String, Index> indexes = getApplicationContext()
.map(it -> it.getBeansOfType(Index.class))
.orElseGet(Collections::emptyMap);
builder.withDetail("geode.index.count", indexes.size());
indexes.values().stream()
.filter(Objects::nonNull)
.forEach(index -> {
String indexName = index.getName();
builder.withDetail(indexKey(indexName, "from-clause"), index.getFromClause())
.withDetail(indexKey(indexName, "indexed-expression"), index.getIndexedExpression())
.withDetail(indexKey(indexName, "projection-attributes"), index.getProjectionAttributes())
.withDetail(indexKey(indexName, "region"), toRegionPath(index.getRegion()))
.withDetail(indexKey(indexName, "type"), String.valueOf(index.getType()));
IndexStatistics indexStatistics = index.getStatistics();
if (indexStatistics != null) {
builder.withDetail(indexStatisticsKey(indexName, "number-of-bucket-indexes"), indexStatistics.getNumberOfBucketIndexes())
.withDetail(indexStatisticsKey(indexName, "number-of-keys"), indexStatistics.getNumberOfKeys())
.withDetail(indexStatisticsKey(indexName, "number-of-map-index-keys"), indexStatistics.getNumberOfMapIndexKeys())
.withDetail(indexStatisticsKey(indexName, "number-of-values"), indexStatistics.getNumberOfValues())
.withDetail(indexStatisticsKey(indexName, "number-of-updates"), indexStatistics.getNumUpdates())
.withDetail(indexStatisticsKey(indexName, "read-lock-count"), indexStatistics.getReadLockCount())
.withDetail(indexStatisticsKey(indexName, "total-update-time"), indexStatistics.getTotalUpdateTime())
.withDetail(indexStatisticsKey(indexName, "total-uses"), indexStatistics.getTotalUses());
}
});
builder.up();
return;
} | builder.unknown();
}
private String emptyIfUnset(String value) {
return StringUtils.hasText(value) ? value : "";
}
private String indexKey(String indexName, String suffix) {
return String.format("geode.index.%1$s.%2$s", indexName, suffix);
}
private String indexStatisticsKey(String indexName, String suffix) {
return String.format("geode.index.%1$s.statistics.%2$s", indexName, suffix);
}
@SuppressWarnings("rawtypes")
private String toRegionPath(Region region) {
String regionPath = region != null ? region.getFullPath() : null;
return emptyIfUnset(regionPath);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeIndexesHealthIndicator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getLINESAMOUNT() {
return linesamount;
}
/**
* Sets the value of the linesamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLINESAMOUNT(String value) {
this.linesamount = value;
}
/**
* Gets the value of the chargesamount property.
*
* @return
* possible object is
* {@link String }
* | */
public String getCHARGESAMOUNT() {
return chargesamount;
}
/**
* Sets the value of the chargesamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCHARGESAMOUNT(String value) {
this.chargesamount = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\TTAXI1.java | 2 |
请完成以下Java代码 | private static ImmutableList<ColumnDDL> retrieveAppDictColumns(@Nullable final String tableName, @Nullable AdColumnId adColumnId)
{
final StringBuilder sqlWhereClause = new StringBuilder();
final ArrayList<Object> sqlWhereClauseParams = new ArrayList<>();
if (!Check.isBlank(tableName))
{
if (sqlWhereClause.length() > 0)
{
sqlWhereClause.append(" AND ");
}
sqlWhereClause.append("t.TableName=?");
sqlWhereClauseParams.add(tableName);
}
if (adColumnId != null)
{
if (sqlWhereClause.length() > 0)
{
sqlWhereClause.append(" AND ");
}
sqlWhereClause.append("c.AD_Column_ID=?");
sqlWhereClauseParams.add(adColumnId);
}
if (sqlWhereClause.length() <= 0)
{
throw new AdempiereException("Retrieving all columns from database is not allowed. Possible development mistake.");
}
final String sql = "SELECT"
+ " t." + I_AD_Table.COLUMNNAME_TableName
+ ", c." + I_AD_Column.COLUMNNAME_ColumnName
+ ", c." + I_AD_Column.COLUMNNAME_AD_Reference_ID | + ", c." + I_AD_Column.COLUMNNAME_DefaultValue
+ ", c." + I_AD_Column.COLUMNNAME_IsMandatory
+ ", c." + I_AD_Column.COLUMNNAME_FieldLength
+ ", c." + I_AD_Column.COLUMNNAME_IsKey
+ ", c." + I_AD_Column.COLUMNNAME_IsParent
+ ", c." + I_AD_Column.COLUMNNAME_DDL_NoForeignKey
+ " FROM " + I_AD_Column.Table_Name + " c "
+ " INNER JOIN " + I_AD_Table.Table_Name + " t ON t.AD_Table_ID=c.AD_Table_ID"
+ " WHERE t.IsActive='Y' AND t.IsView='N'"
+ " AND c.IsActive='Y'"
+ " AND (c." + I_AD_Column.COLUMNNAME_ColumnSQL + " is null or length(TRIM(c.ColumnSQL)) = 0)" // no virtual columns
+ " AND (" + sqlWhereClause + ")"
+ " ORDER BY t.TableName, c.ColumnName";
return DB.retrieveRows(sql, sqlWhereClauseParams, TableDDLSyncService::retrieveAppDictColumn);
}
private static ColumnDDL retrieveAppDictColumn(final ResultSet rs) throws SQLException
{
return ColumnDDL.builder()
.tableName(rs.getString(I_AD_Table.COLUMNNAME_TableName))
.columnName(rs.getString(I_AD_Column.COLUMNNAME_ColumnName))
.referenceId(ReferenceId.ofRepoId(rs.getInt(I_AD_Column.COLUMNNAME_AD_Reference_ID)))
.defaultValue(rs.getString(I_AD_Column.COLUMNNAME_DefaultValue))
.mandatory(StringUtils.toBoolean(rs.getString(I_AD_Column.COLUMNNAME_IsMandatory)))
.fieldLength(rs.getInt(I_AD_Column.COLUMNNAME_FieldLength))
.isPrimaryKey(StringUtils.toBoolean(rs.getString(I_AD_Column.COLUMNNAME_IsKey)))
.isParentLink(StringUtils.toBoolean(rs.getString(I_AD_Column.COLUMNNAME_IsParent)))
.noForeignKey(StringUtils.toBoolean(rs.getString(I_AD_Column.COLUMNNAME_DDL_NoForeignKey)))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\ddl\TableDDLSyncService.java | 1 |
请完成以下Java代码 | public AsyncInlineCachingRegionConfigurer<T, ID> withQueueMaxMemory(int maximumMemory) {
this.maximumQueueMemory = maximumMemory;
return this;
}
/**
* Builder method used to configure the {@link AsyncEventQueue} order of processing for cache events when the AEQ
* is serial and the AEQ is using multiple dispatcher threads.
*
* @param orderPolicy {@link GatewaySender} {@link OrderPolicy} used to determine the order of processing
* for cache events when the AEQ is serial and uses multiple dispatcher threads.
* @return this {@link AsyncInlineCachingRegionConfigurer}.
* @see org.apache.geode.cache.wan.GatewaySender.OrderPolicy
*/
public AsyncInlineCachingRegionConfigurer<T, ID> withQueueOrderPolicy(
@Nullable GatewaySender.OrderPolicy orderPolicy) {
this.orderPolicy = orderPolicy;
return this; | }
/**
* Builder method used to enable a single {@link AsyncEventQueue AEQ} attached to a {@link Region Region}
* (possibly) hosted and distributed across the cache cluster to process cache events.
*
* Default is {@literal false}, or {@literal serial}.
*
* @return this {@link AsyncInlineCachingRegionConfigurer}.
* @see #withParallelQueue()
*/
public AsyncInlineCachingRegionConfigurer<T, ID> withSerialQueue() {
this.parallel = false;
return this;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\AsyncInlineCachingRegionConfigurer.java | 1 |
请完成以下Java代码 | public void customizeButtonPressed(final ActionEvent e)
{
}
public void historyButtonPressed(final ActionEvent e)
{
}
public void zoomButtonPressed(final ActionEvent e)
{
}
public void processButtonPressed(final ActionEvent e)
{
}
public void printButtonPressed(final ActionEvent e)
{
}
public void exportButtonPressed(final ActionEvent e)
{ | }
public void helpButtonPressed(final ActionEvent e)
{
}
public void deleteButtonPressed(final ActionEvent e)
{
}
public void pAttributeButtonPressed(final ActionEvent e)
{
}
public void newButtonPressed(final ActionEvent e)
{
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ConfirmPanelListener.java | 1 |
请完成以下Java代码 | public class JsonHUQRCodeTargetConverters
{
@Nullable
public static JsonHUQRCodeTarget fromNullable(
@Nullable final ReceivingTarget receivingTarget,
@NonNull final HUQRCodesService huQRCodeService)
{
return receivingTarget != null
? from(receivingTarget, huQRCodeService)
: null;
}
public static JsonHUQRCodeTarget from(
@NonNull final ReceivingTarget receivingTarget,
@NonNull final HUQRCodesService huQRCodeService)
{
return JsonHUQRCodeTarget.builder() | .huQRCode(toJsonRenderedHUQRCode(
CoalesceUtil.coalesceNotNull(
receivingTarget.getLuId(),
receivingTarget.getTuId()),
huQRCodeService))
.tuPIItemProductId(receivingTarget.getTuPIItemProductId())
.build();
}
private static JsonDisplayableQRCode toJsonRenderedHUQRCode(
@NonNull final HuId huId,
@NonNull final HUQRCodesService huQRCodeService)
{
return huQRCodeService.getQRCodeByHuId(huId).toRenderedJson();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\receive\json\JsonHUQRCodeTargetConverters.java | 1 |
请完成以下Java代码 | private BodyBuilder headers(BodyBuilder builder) {
proxy();
for (String name : filterHeaderKeys(headers)) {
java.util.List<String> headerValues = headers.get(name);
if (headerValues != null) {
builder.header(name, headerValues.toArray(new String[0]));
}
}
return builder;
}
private void proxy() {
URI uri = exchange.getRequest().getURI();
appendForwarded(uri);
appendXForwarded(uri);
}
private void appendXForwarded(URI uri) {
// Append the legacy headers if they were already added upstream
String host = headers.getFirst("x-forwarded-host");
if (host == null) {
return;
}
host = host + "," + uri.getHost();
headers.set("x-forwarded-host", host);
String proto = headers.getFirst("x-forwarded-proto");
if (proto == null) {
return;
}
proto = proto + "," + uri.getScheme();
headers.set("x-forwarded-proto", proto);
}
private void appendForwarded(URI uri) {
String forwarded = headers.getFirst("forwarded");
if (forwarded != null) {
forwarded = forwarded + ",";
}
else {
forwarded = "";
}
forwarded = forwarded + forwarded(uri, exchange.getRequest().getHeaders().getFirst("host"));
headers.set("forwarded", forwarded);
}
private String forwarded(URI uri, @Nullable String hostHeader) {
if (StringUtils.hasText(hostHeader)) {
return "host=" + hostHeader;
}
if ("http".equals(uri.getScheme())) {
return "host=" + uri.getHost();
}
return String.format("host=%s;proto=%s", uri.getHost(), uri.getScheme());
}
private @Nullable Publisher<?> body() {
Publisher<?> body = this.body;
if (body != null) {
return body;
} | body = getRequestBody();
hasBody = true; // even if it's null
return body;
}
/**
* Search for the request body if it was already deserialized using
* <code>@RequestBody</code>. If it is not found then deserialize it in the same way
* that it would have been for a <code>@RequestBody</code>.
* @return the request body
*/
private @Nullable Mono<Object> getRequestBody() {
for (String key : bindingContext.getModel().asMap().keySet()) {
if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key);
Object target = result.getTarget();
if (target != null) {
return Mono.just(target);
}
}
}
return null;
}
protected static class BodyGrabber {
public Publisher<Object> body(@RequestBody Publisher<Object> body) {
return body;
}
}
protected static class BodySender {
@ResponseBody
public @Nullable Publisher<Object> body() {
return null;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java | 1 |
请完成以下Java代码 | public void onModelChange(final Object model, final ModelChangeType changeType)
{
if (changeType != ModelChangeType.BEFORE_NEW && changeType != ModelChangeType.BEFORE_CHANGE)
{
return;
}
// Skip updating the ASI if automatic ASI updating is disabled (08091)
if (IModelAttributeSetInstanceListener.DYNATTR_DisableASIUpdateOnModelChange.getValue(model, false))
{
return;
}
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
for (final IModelAttributeSetInstanceListener listener : listenersBySourceTableName.get(tableName))
{
if (changeType.isNew() || isValueChanged(model, listener.getSourceColumnNames()))
{
listener.modelChanged(model);
}
}
}
/**
* @return true if at least one of the given column names were changed.
*/
private static boolean isValueChanged(final Object model, final List<String> columnNames)
{ | if (columnNames == IModelAttributeSetInstanceListener.ANY_SOURCE_COLUMN)
{
return true;
}
if (columnNames == null || columnNames.isEmpty())
{
return false;
}
for (final String columnName : columnNames)
{
if (InterfaceWrapperHelper.isValueChanged(model, columnName))
{
return true;
}
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\interceptor\ModelAttributeSetInstanceListenerInterceptor.java | 1 |
请完成以下Spring Boot application配置 | # Thymeleaf
spring.thymeleaf.cache: false
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:8889/netgloo_blog
db.username: root
db.password: root
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5D | ialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: netgloo | repos\spring-boot-samples-master\spring-boot-mysql-hibernate\src\main\resources\application.properties | 2 |
请完成以下Spring Boot application配置 | server:
port: 9002
spring:
application:
name: server-consumer
cloud:
consul:
host: 192.168.140.215
port: 8500
| discovery:
service-name: ${spring.application.name} | repos\SpringAll-master\55.Spring-Cloud-Consul\server-consumer\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public static void addDevice(@NonNull final DummyDeviceAddRequest request)
{
final DeviceConfig device = DeviceConfig.builder(request.getDeviceName())
.setAssignedAttributeCodes(request.getAssignedAttributeCodes())
.setDeviceClassname(DummyDevice.class.getName())
.setParameterValueSupplier(DummyDeviceConfigPool::getDeviceParamValue)
.setRequestClassnamesSupplier(DummyDeviceConfigPool::getDeviceRequestClassnames)
.setAssignedWarehouseIds(request.getOnlyWarehouseIds())
.build();
staticState.addDevice(device);
logger.info("Added device: {}", device);
}
public static void removeDeviceByName(@NonNull final String deviceName)
{
staticState.removeDeviceByName(deviceName);
}
private static String getDeviceParamValue(final String deviceName, final String parameterName, final String defaultValue)
{
return defaultValue;
}
private static Set<String> getDeviceRequestClassnames(final String deviceName, final AttributeCode attributeCode)
{
return DummyDevice.getDeviceRequestClassnames();
}
public static DummyDeviceResponse generateRandomResponse()
{
final BigDecimal value = NumberUtils.randomBigDecimal(responseMinValue, responseMaxValue, 3);
return new DummyDeviceResponse(value);
}
//
//
//
//
//
private static class StaticStateHolder
{
private final HashMap<String, DeviceConfig> devicesByName = new HashMap<>();
private final ArrayListMultimap<AttributeCode, DeviceConfig> devicesByAttributeCode = ArrayListMultimap.create(); | public synchronized void addDevice(final DeviceConfig device)
{
final String deviceName = device.getDeviceName();
final DeviceConfig existingDevice = removeDeviceByName(deviceName);
devicesByName.put(deviceName, device);
device.getAssignedAttributeCodes()
.forEach(attributeCode -> devicesByAttributeCode.put(attributeCode, device));
logger.info("addDevice: {} -> {}", existingDevice, device);
}
public synchronized @Nullable DeviceConfig removeDeviceByName(@NonNull final String deviceName)
{
final DeviceConfig existingDevice = devicesByName.remove(deviceName);
if (existingDevice != null)
{
existingDevice.getAssignedAttributeCodes()
.forEach(attributeCode -> devicesByAttributeCode.remove(attributeCode, existingDevice));
}
return existingDevice;
}
public synchronized ImmutableList<DeviceConfig> getAllDevices()
{
return ImmutableList.copyOf(devicesByName.values());
}
public synchronized ImmutableList<DeviceConfig> getDeviceConfigsForAttributeCode(@NonNull final AttributeCode attributeCode)
{
return ImmutableList.copyOf(devicesByAttributeCode.get(attributeCode));
}
public ImmutableSet<AttributeCode> getAllAttributeCodes()
{
return ImmutableSet.copyOf(devicesByAttributeCode.keySet());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDeviceConfigPool.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!sysConfigBL.getBooleanValue(EDIWorkpackageProcessor.SYS_CONFIG_OneDesadvPerShipment, false))
{
return ProcessPreconditionsResolution.reject();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final Properties ctx = getCtx();
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(ctx, EDIWorkpackageProcessor.class);
trxItemProcessorExecutorService
.<I_EDI_Desadv, Void>createExecutor()
.setContext(getCtx(), ITrx.TRXNAME_None)
.setExceptionHandler(FailTrxItemExceptionHandler.instance)
.setProcessor(new TrxItemProcessorAdapter<I_EDI_Desadv, Void>()
{
@Override
public void process(@NonNull final I_EDI_Desadv desadv)
{
enqueueShipmentsForDesadv(queue, desadv);
}
})
.process(createIterator());
return MSG_OK;
}
private void enqueueShipmentsForDesadv(
final @NonNull IWorkPackageQueue queue,
final @NonNull I_EDI_Desadv desadv)
{
final List<I_M_InOut> shipments = desadvDAO.retrieveShipmentsWithStatus(desadv, ImmutableSet.of(EDIExportStatus.Pending, EDIExportStatus.Error));
final String trxName = InterfaceWrapperHelper.getTrxName(desadv);
for (final I_M_InOut shipment : shipments)
{
queue.newWorkPackage()
.setAD_PInstance_ID(getPinstanceId())
.bindToTrxName(trxName)
.addElement(shipment)
.buildAndEnqueue(); | shipment.setEDI_ExportStatus(I_M_InOut.EDI_EXPORTSTATUS_Enqueued);
InterfaceWrapperHelper.save(shipment);
addLog("Enqueued M_InOut_ID={} for EDI_Desadv_ID={}", shipment.getM_InOut_ID(), desadv.getEDI_Desadv_ID());
}
if(shipments.isEmpty())
{
addLog("Found no M_InOuts to enqueue for EDI_Desadv_ID={}", desadv.getEDI_Desadv_ID());
}
else
{
desadv.setEDI_ExportStatus(I_M_InOut.EDI_EXPORTSTATUS_Enqueued);
InterfaceWrapperHelper.save(desadv);
}
}
@NonNull
private Iterator<I_EDI_Desadv> createIterator()
{
final IQueryBuilder<I_EDI_Desadv> queryBuilder = queryBL.createQueryBuilder(I_EDI_Desadv.class, getCtx(), get_TrxName())
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse());
queryBuilder.orderBy()
.addColumn(I_EDI_Desadv.COLUMNNAME_POReference)
.addColumn(I_EDI_Desadv.COLUMNNAME_EDI_Desadv_ID);
final Iterator<I_EDI_Desadv> iterator = queryBuilder
.create()
.iterate(I_EDI_Desadv.class);
if(!iterator.hasNext())
{
addLog("Found no EDI_Desadvs to enqueue within the current selection");
}
return iterator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_InOut_EnqueueForExport.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.