instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public String getLanguageISO ()
{
return (String)get_Value(COLUMNNAME_LanguageISO);
}
/** 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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Time Pattern.
@param TimePattern
Java Time Pattern
*/
public void setTimePattern (String TimePattern)
{
set_Value (COLUMNNAME_TimePattern, TimePattern);
}
/** Get Time Pattern.
@return Java Time Pattern
*/
public String getTimePattern ()
{
return (String)get_Value(COLUMNNAME_TimePattern);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Language.java
| 1
|
请完成以下Java代码
|
public BOMCostElementPrice getCostElementPriceOrNull(@NonNull final CostElementId costElementId)
{
return pricesByElementId.get(costElementId);
}
public void clearOwnCostPrice(@NonNull final CostElementId costElementId)
{
final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId);
if (elementCostPrice != null)
{
elementCostPrice.clearOwnCostPrice();
}
}
public void setComponentsCostPrice(
@NonNull final CostAmount costPrice,
@NonNull final CostElementId costElementId)
{
pricesByElementId.computeIfAbsent(costElementId, k -> BOMCostElementPrice.zero(costElementId, costPrice.getCurrencyId(), uomId))
.setComponentsCostPrice(costPrice);
}
public void clearComponentsCostPrice(@NonNull final CostElementId costElementId)
|
{
final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId);
if (elementCostPrice != null)
{
elementCostPrice.clearComponentsCostPrice();
}
}
ImmutableList<BOMCostElementPrice> getElementPrices()
{
return ImmutableList.copyOf(pricesByElementId.values());
}
<T extends RepoIdAware> Stream<T> streamIds(@NonNull final Class<T> idType)
{
return getElementPrices()
.stream()
.map(elementCostPrice -> elementCostPrice.getId(idType))
.filter(Objects::nonNull);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMCostPrice.java
| 1
|
请完成以下Java代码
|
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public String getExecutorShardingParam() {
return executorShardingParam;
}
public void setExecutorShardingParam(String executorShardingParam) {
this.executorShardingParam = executorShardingParam;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public Date getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime;
}
public int getTriggerCode() {
return triggerCode;
}
public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode;
}
public String getTriggerMsg() {
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
}
public Date getHandleTime() {
return handleTime;
}
public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
|
}
public int getHandleCode() {
return handleCode;
}
public void setHandleCode(int handleCode) {
this.handleCode = handleCode;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
public int getAlarmStatus() {
return alarmStatus;
}
public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GreeterAutoConfiguration {
@Autowired
private GreeterProperties greeterProperties;
@Bean
@ConditionalOnMissingBean
public GreetingConfig greeterConfig() {
String userName = greeterProperties.getUserName() == null ? System.getProperty("user.name") : greeterProperties.getUserName();
String morningMessage = greeterProperties.getMorningMessage() == null ? "Good Morning" : greeterProperties.getMorningMessage();
String afternoonMessage = greeterProperties.getAfternoonMessage() == null ? "Good Afternoon" : greeterProperties.getAfternoonMessage();
String eveningMessage = greeterProperties.getEveningMessage() == null ? "Good Evening" : greeterProperties.getEveningMessage();
String nightMessage = greeterProperties.getNightMessage() == null ? "Good Night" : greeterProperties.getNightMessage();
GreetingConfig greetingConfig = new GreetingConfig();
|
greetingConfig.put(USER_NAME, userName);
greetingConfig.put(MORNING_MESSAGE, morningMessage);
greetingConfig.put(AFTERNOON_MESSAGE, afternoonMessage);
greetingConfig.put(EVENING_MESSAGE, eveningMessage);
greetingConfig.put(NIGHT_MESSAGE, nightMessage);
return greetingConfig;
}
@Bean
@ConditionalOnMissingBean
public Greeter greeter(GreetingConfig greetingConfig) {
return new Greeter(greetingConfig);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-custom-starter\greeter-spring-boot-autoconfigure\src\main\java\com\baeldung\greeter\autoconfigure\GreeterAutoConfiguration.java
| 2
|
请完成以下Java代码
|
private void updateColumnFromSuggestion(@NonNull final I_AD_Column column, @NonNull final ColumnTypeAndLengthStats suggestion)
{
column.setAD_Reference_ID(suggestion.getDisplayType().getRepoId());
column.setAD_Reference_Value_ID(ReferenceId.toRepoId(suggestion.getReferenceValueId()));
column.setFieldLength(suggestion.getFieldLength());
}
private String computeDefaultValue_Line(final I_AD_Table table, final I_AD_Column column)
{
if (table.isView()) {return null;}
if (!Check.isBlank(column.getColumnSQL())) {return null;}
final String columnName = column.getColumnName();
final String tableName = table.getTableName();
final ImmutableSet<String> parentColumnNames = adTableDAO.retrieveColumnsForTable(table)
.stream()
.filter(c -> c.getAD_Column_ID() != column.getAD_Column_ID())
.filter(I_AD_Column::isParent)
.map(I_AD_Column::getColumnName)
.collect(ImmutableSet.toImmutableSet());
|
if (parentColumnNames.isEmpty()) {return null;}
final StringBuilder sqlWhereClause = new StringBuilder();
parentColumnNames.forEach(parentColumnName -> {
if (sqlWhereClause.length() > 0)
{
sqlWhereClause.append(" AND ");
}
sqlWhereClause.append("t.").append(parentColumnName).append("=@").append(parentColumnName).append("@");
});
return "@SQL="
+ "SELECT CEILING(COALESCE(MAX(t." + columnName + "), 0) / 10) * 10 + 10"
+ " FROM " + tableName + " t"
+ " WHERE " + sqlWhereClause;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\callout\AD_Column.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setES_FieldName (final java.lang.String ES_FieldName)
{
set_Value (COLUMNNAME_ES_FieldName, ES_FieldName);
}
@Override
public java.lang.String getES_FieldName()
{
return get_ValueAsString(COLUMNNAME_ES_FieldName);
}
@Override
public void setES_FTS_Config_Field_ID (final int ES_FTS_Config_Field_ID)
{
if (ES_FTS_Config_Field_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_Field_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_Field_ID, ES_FTS_Config_Field_ID);
}
@Override
public int getES_FTS_Config_Field_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_Field_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_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID);
}
@Override
public int getES_FTS_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config_Field.java
| 1
|
请完成以下Java代码
|
public T get()
{
// A 2-field variant of Double Checked Locking.
if (!initialized)
{
synchronized (this)
{
if (!initialized)
{
final T t = delegate.get();
value = t;
initialized = true;
return t;
}
}
}
return value;
}
@NonNull
public T getNotNull() {return Check.assumeNotNull(get(), "Supplier is expected to return non null value");}
/**
* @return memorized value or <code>null</code> if not initialized
*/
@Nullable
public T peek()
{
synchronized (this)
{
return value;
}
}
/**
* Forget memorized value
*
* @return current value if any
*/
@Nullable
public T forget()
{
// https://github.com/metasfresh/metasfresh-webui-api/issues/787 - similar to the code of get();
// if the instance known to not be initialized
// then don't attempt to acquire lock (and to other time consuming stuff..)
if (initialized)
{
synchronized (this)
{
if (initialized)
{
final T valueOld = this.value;
|
initialized = false;
value = null;
return valueOld;
}
}
}
return null;
}
/**
* @return true if this supplier has a value memorized
*/
public boolean isInitialized()
{
return initialized;
}
@Override
public String toString()
{
return "ExtendedMemorizingSupplier[" + delegate + "]";
}
private static final long serialVersionUID = 0;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\ExtendedMemorizingSupplier.java
| 1
|
请完成以下Java代码
|
public String getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
/**
* Gets the value of the nb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNb() {
return nb;
}
/**
* Sets the value of the nb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
|
public void setNb(String value) {
this.nb = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = 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\CorporateAction1.java
| 1
|
请完成以下Java代码
|
public final I_C_UOM getC_UOM()
{
final int uomId = huPIAttribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{
// fallback to M_Attribute's UOM
return super.getC_UOM();
}
}
@Override
public final boolean isReadonlyUI()
{
return huPIAttribute.isReadOnly();
}
@Override
public final boolean isDisplayedUI()
{
return huPIAttribute.isDisplayed();
}
@Override
public final boolean isMandatory()
{
return huPIAttribute.isMandatory();
}
@Override
public final int getDisplaySeqNo()
|
{
final int seqNo = huPIAttribute.getSeqNo();
if (seqNo > 0)
{
return seqNo;
}
// Fallback: if SeqNo was not set, return max int (i.e. show them last)
return Integer.MAX_VALUE;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return huPIAttribute.isOnlyIfInProductAttributeSet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractHUAttributeValue.java
| 1
|
请完成以下Java代码
|
public Color getSeparatorColor()
{
return separatorColor;
}
/**
*
* @param separatorColor
*/
public void setSeparatorColor(final Color separatorColor)
{
this.separatorColor = separatorColor;
}
/**
* get title foreground color
*
* @return color
*/
public Color getTitleForegroundColor()
{
return titleForegroundColor;
}
/**
* Set title foreground color
*
* @param titleForegroundColor
*/
public void setTitleForegroundColor(final Color titleForegroundColor)
{
this.titleForegroundColor = titleForegroundColor;
}
/**
*
* @return title background color
*/
public Color getTitleBackgroundColor()
{
return titleBackgroundColor;
}
/**
* Set background color of title
*
* @param titleBackgroundColor
*/
public void setTitleBackgroundColor(final Color titleBackgroundColor)
{
this.titleBackgroundColor = titleBackgroundColor;
}
/**
* Set title of the section
*
* @param title
*/
public void setTitle(final String title)
{
if (link != null)
{
link.setText(title);
}
}
/**
*
* @return collapsible pane
*/
public JXCollapsiblePane getCollapsiblePane()
{
return collapsible;
}
public JComponent getContentPane()
{
return (JComponent)getCollapsiblePane().getContentPane();
}
public void setContentPane(JComponent contentPanel)
{
getCollapsiblePane().setContentPane(contentPanel);
}
/**
* The border between the stack components. It separates each component with a fine line border.
*/
class SeparatorBorder implements Border
{
boolean isFirst(final Component c)
{
return c.getParent() == null || c.getParent().getComponent(0) == c;
}
@Override
public Insets getBorderInsets(final Component c)
{
|
// if the collapsible is collapsed, we do not want its border to be
// painted.
if (c instanceof JXCollapsiblePane)
{
if (((JXCollapsiblePane)c).isCollapsed())
{
return new Insets(0, 0, 0, 0);
}
}
return new Insets(4, 0, 1, 0);
}
@Override
public boolean isBorderOpaque()
{
return true;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height)
{
// if the collapsible is collapsed, we do not want its border to be painted.
if (c instanceof JXCollapsiblePane)
{
if (((JXCollapsiblePane)c).isCollapsed())
{
return;
}
}
g.setColor(getSeparatorColor());
if (isFirst(c))
{
g.drawLine(x, y + 2, x + width, y + 2);
}
g.drawLine(x, y + height - 1, x + width, y + height - 1);
}
}
@Override
public final Component add(final Component comp)
{
return collapsible.add(comp);
}
public final void setCollapsed(final boolean collapsed)
{
collapsible.setCollapsed(collapsed);
}
public final void setCollapsible(final boolean collapsible)
{
this.toggleAction.setEnabled(collapsible);
if (!collapsible)
{
this.collapsible.setCollapsed(false);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CollapsiblePanel.java
| 1
|
请完成以下Java代码
|
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getResultVariable() {
return resultVariable;
}
public void setResultVariable(String resultVariable) {
this.resultVariable = resultVariable;
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public boolean isAutoStoreVariables() {
return autoStoreVariables;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
}
public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
if (inParameters == null) {
inParameters = new ArrayList<>();
|
}
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public ScriptTask clone() {
ScriptTask clone = new ScriptTask();
clone.setValues(this);
return clone;
}
public void setValues(ScriptTask otherElement) {
super.setValues(otherElement);
setScriptFormat(otherElement.getScriptFormat());
setScript(otherElement.getScript());
setResultVariable(otherElement.getResultVariable());
setSkipExpression(otherElement.getSkipExpression());
setAutoStoreVariables(otherElement.isAutoStoreVariables());
setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables());
inParameters = null;
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
inParameters = new ArrayList<>();
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java
| 1
|
请完成以下Java代码
|
public class SysLoginModel {
@Schema(description = "账号")
private String username;
@Schema(description = "密码")
private String password;
@Schema(description = "登录部门")
private String loginOrgCode;
@Schema(description = "验证码")
private String captcha;
@Schema(description = "验证码key")
private String checkKey;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
|
public String getCheckKey() {
return checkKey;
}
public void setCheckKey(String checkKey) {
this.checkKey = checkKey;
}
public String getLoginOrgCode() {
return loginOrgCode;
}
public void setLoginOrgCode(String loginOrgCode) {
this.loginOrgCode = loginOrgCode;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysLoginModel.java
| 1
|
请完成以下Java代码
|
private Money withValue(@NonNull final BigDecimal newValue)
{
return value.compareTo(newValue) != 0 ? of(newValue, currencyId) : this;
}
public static int countNonZero(final Money... array)
{
if (array == null || array.length == 0)
{
return 0;
}
int count = 0;
for (final Money money : array)
{
if (money != null && money.signum() != 0)
|
{
count++;
}
}
return count;
}
public static boolean equals(@Nullable Money money1, @Nullable Money money2) {return Objects.equals(money1, money2);}
public Percent percentageOf(@NonNull final Money whole)
{
assertCurrencyIdMatching(whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\Money.java
| 1
|
请完成以下Java代码
|
protected final void grantAccessToRecord()
{
userGroupRecordAccessService.grantAccess(RecordAccessGrantRequest.builder()
.recordRef(getRecordRef())
.principal(getPrincipal())
.permissions(getPermissionsToGrant())
.issuer(PermissionIssuer.MANUAL)
.requestedBy(getUserId())
.build());
}
protected final void revokeAccessFromRecord()
{
final boolean revokeAllPermissions;
final List<Access> permissionsToRevoke;
final Access permission = getPermissionOrNull();
if (permission == null)
{
revokeAllPermissions = true;
permissionsToRevoke = ImmutableList.of();
}
else
{
revokeAllPermissions = false;
permissionsToRevoke = ImmutableList.of(permission);
}
userGroupRecordAccessService.revokeAccess(RecordAccessRevokeRequest.builder()
.recordRef(getRecordRef())
.principal(getPrincipal())
.revokeAllPermissions(revokeAllPermissions)
.permissions(permissionsToRevoke)
.issuer(PermissionIssuer.MANUAL)
.requestedBy(getUserId())
.build());
}
private Principal getPrincipal()
{
final PrincipalType principalType = PrincipalType.ofCode(principalTypeCode);
if (PrincipalType.USER.equals(principalType))
{
return Principal.userId(userId);
}
else if (PrincipalType.USER_GROUP.equals(principalType))
{
return Principal.userGroupId(userGroupId);
}
else
{
throw new AdempiereException("@Unknown@ @PrincipalType@: " + principalType);
}
|
}
private Set<Access> getPermissionsToGrant()
{
final Access permission = getPermissionOrNull();
if (permission == null)
{
throw new FillMandatoryException(PARAM_PermissionCode);
}
if (Access.WRITE.equals(permission))
{
return ImmutableSet.of(Access.READ, Access.WRITE);
}
else
{
return ImmutableSet.of(permission);
}
}
private Access getPermissionOrNull()
{
if (Check.isEmpty(permissionCode))
{
return null;
}
else
{
return Access.ofCode(permissionCode);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\process\UserGroupRecordAccess_Base.java
| 1
|
请完成以下Java代码
|
public boolean isUseTranslantionLanguage()
{
return adLanguage == null && Boolean.FALSE.equals(useBaseLanguage);
}
public boolean isUseSpecificLanguage()
{
return adLanguage != null;
}
public String getAD_Language()
{
Check.assumeNotNull(adLanguage, "Parameter adLanguage is not null");
return adLanguage;
}
public String extractString(final TranslatableParameterizedString trlString)
{
if (trlString == null)
{
return null;
}
else if (isUseBaseLanguage())
|
{
return trlString.getStringBaseLanguage();
}
else if (isUseTranslantionLanguage())
{
return trlString.getStringTrlPattern();
}
else if (isUseSpecificLanguage())
{
return trlString.translate(getAD_Language());
}
else
{
// internal error: shall never happen
throw new IllegalStateException("Cannot extract string from " + trlString + " using " + this);
}
}
}
} // MLookupFactory
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookupFactory.java
| 1
|
请完成以下Java代码
|
public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) {
return DFY_MD_HMS.format(localDateTime);
}
/**
* 日期格式化 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public String localDateTimeFormatyMd(LocalDateTime localDateTime) {
return DFY_MD.format(localDateTime);
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
|
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) {
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) {
return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime));
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\DateUtil.java
| 1
|
请完成以下Java代码
|
public Builder uri(URI uri) {
return new StrictFirewallBuilder(this.delegate.uri(uri));
}
@Override
public Builder path(String path) {
return new StrictFirewallBuilder(this.delegate.path(path));
}
@Override
public Builder contextPath(String contextPath) {
return new StrictFirewallBuilder(this.delegate.contextPath(contextPath));
}
@Override
public Builder header(String headerName, String... headerValues) {
return new StrictFirewallBuilder(this.delegate.header(headerName, headerValues));
}
@Override
public Builder headers(Consumer<HttpHeaders> headersConsumer) {
return new StrictFirewallBuilder(this.delegate.headers(headersConsumer));
}
@Override
|
public Builder sslInfo(SslInfo sslInfo) {
return new StrictFirewallBuilder(this.delegate.sslInfo(sslInfo));
}
@Override
public Builder remoteAddress(InetSocketAddress remoteAddress) {
return new StrictFirewallBuilder(this.delegate.remoteAddress(remoteAddress));
}
@Override
public Builder localAddress(InetSocketAddress localAddress) {
return new StrictFirewallBuilder(this.delegate.localAddress(localAddress));
}
@Override
public ServerHttpRequest build() {
return new StrictFirewallHttpRequest(this.delegate.build());
}
}
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\firewall\StrictServerWebExchangeFirewall.java
| 1
|
请完成以下Java代码
|
private Quantity getQtyFromHU()
{
final I_M_HU pickFromHU = handlingUnitsDAO.getById(pickFrom.getHuId());
final ProductId productId = getProductId();
final IHUProductStorage productStorage = huContextFactory
.createMutableHUContext()
.getHUStorageFactory()
.getStorage(pickFromHU)
.getProductStorageOrNull(productId);
// Allow empty storage. That's the case when we are adding a newly created HU
if (productStorage == null)
{
final I_C_UOM uom = getShipmentScheduleUOM();
return Quantity.zero(uom);
}
return productStorage.getQty();
}
private I_M_ShipmentSchedule getShipmentSchedule()
{
if (_shipmentSchedule == null)
{
_shipmentSchedule = shipmentSchedulesRepo.getById(shipmentScheduleId, I_M_ShipmentSchedule.class);
}
return _shipmentSchedule;
}
|
private I_C_UOM getShipmentScheduleUOM()
{
return shipmentScheduleBL.getUomOfProduct(getShipmentSchedule());
}
private void allocatePickingSlotIfPossible()
{
if (pickingSlotId == null)
{
return;
}
final I_M_ShipmentSchedule shipmentSchedule = getShipmentSchedule();
final BPartnerLocationId bpartnerAndLocationId = shipmentScheduleEffectiveBL.getBPartnerLocationId(shipmentSchedule);
huPickingSlotBL.allocatePickingSlotIfPossible(PickingSlotAllocateRequest.builder()
.pickingSlotId(pickingSlotId)
.bpartnerAndLocationId(bpartnerAndLocationId)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PickHUCommand.java
| 1
|
请完成以下Java代码
|
private void refresh(int M_Product_ID, int M_PriceList_Version_ID)
{
String sql = m_sqlRelated;
log.trace(sql);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
pstmt.setInt(2, M_PriceList_Version_ID);
rs = pstmt.executeQuery();
relatedTbl.loadTable(rs);
rs.close();
}
catch (Exception e)
{
log.warn(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
|
pstmt = null;
}
}
public java.awt.Component getComponent()
{
return (java.awt.Component)relatedTbl;
}
@Override
public void refresh(int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID)
{
refresh( M_Product_ID, M_PriceList_Version_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductRelated.java
| 1
|
请完成以下Java代码
|
public class GoogleMapsGeocodingProviderImpl implements GeocodingProvider
{
private static final Logger logger = LogManager.getLogger(GoogleMapsGeocodingProviderImpl.class);
private final CCache<GeoCoordinatesRequest, ImmutableList<GeographicalCoordinates>> coordinatesCache;
private final GeoApiContext context;
public GoogleMapsGeocodingProviderImpl(final GeoApiContext context, final int cacheCapacity)
{
logger.info("context={}; cacheCapacity={}", context, cacheCapacity);
this.context = context;
coordinatesCache = CCache.<GeoCoordinatesRequest, ImmutableList<GeographicalCoordinates>>builder()
.cacheMapType(CCache.CacheMapType.LRU)
.initialCapacity(cacheCapacity)
.build();
}
@Override
public Optional<GeographicalCoordinates> findBestCoordinates(final GeoCoordinatesRequest request)
{
final List<GeographicalCoordinates> coords = findAllCoordinates(request);
if (coords.isEmpty())
{
return Optional.empty();
}
return Optional.of(coords.get(0));
}
@NonNull
private ImmutableList<GeographicalCoordinates> findAllCoordinates(final @NonNull GeoCoordinatesRequest request)
{
final ImmutableList<GeographicalCoordinates> response = coordinatesCache.get(request);
if (response != null)
{
return response;
}
return coordinatesCache.getOrLoad(request, this::queryAllCoordinates);
}
@NonNull
private ImmutableList<GeographicalCoordinates> queryAllCoordinates(@NonNull final GeoCoordinatesRequest request)
{
final String formattedAddress = String.format("%s, %s %s, %s",
CoalesceUtil.coalesce(request.getAddress(), ""),
CoalesceUtil.coalesce(request.getPostal(), ""),
CoalesceUtil.coalesce(request.getCity(), ""),
CoalesceUtil.coalesce(request.getCountryCode2(), ""));
logger.trace("Formatted address: {}", formattedAddress);
|
final GeocodingResult[] results = GeocodingApi
.geocode(context, formattedAddress)
.awaitIgnoreError();
//noinspection ConfusingArgumentToVarargsMethod
logger.trace("Geocoding response from google: {}", results);
if (results == null)
{
return ImmutableList.of();
}
return Arrays.stream(results)
.map(GoogleMapsGeocodingProviderImpl::toGeographicalCoordinates)
.collect(GuavaCollectors.toImmutableList());
}
private static GeographicalCoordinates toGeographicalCoordinates(@NonNull final GeocodingResult result)
{
final LatLng ll = result.geometry.location;
return GeographicalCoordinates.builder()
.latitude(BigDecimal.valueOf(ll.lat))
.longitude(BigDecimal.valueOf(ll.lng))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\googlemaps\GoogleMapsGeocodingProviderImpl.java
| 1
|
请完成以下Java代码
|
void addAll(ExitCodeGenerator... generators) {
Assert.notNull(generators, "'generators' must not be null");
addAll(Arrays.asList(generators));
}
void addAll(Iterable<? extends ExitCodeGenerator> generators) {
Assert.notNull(generators, "'generators' must not be null");
for (ExitCodeGenerator generator : generators) {
add(generator);
}
}
void add(ExitCodeGenerator generator) {
Assert.notNull(generator, "'generator' must not be null");
this.generators.add(generator);
AnnotationAwareOrderComparator.sort(this.generators);
}
@Override
public Iterator<ExitCodeGenerator> iterator() {
return this.generators.iterator();
}
/**
* Get the final exit code that should be returned. The final exit code is the first
* non-zero exit code that is {@link ExitCodeGenerator#getExitCode generated}.
* @return the final exit code.
*/
int getExitCode() {
int exitCode = 0;
for (ExitCodeGenerator generator : this.generators) {
try {
int value = generator.getExitCode();
if (value != 0) {
exitCode = value;
break;
}
}
catch (Exception ex) {
exitCode = 1;
ex.printStackTrace();
}
}
return exitCode;
}
|
/**
* Adapts an {@link ExitCodeExceptionMapper} to an {@link ExitCodeGenerator}.
*/
private static class MappedExitCodeGenerator implements ExitCodeGenerator {
private final Throwable exception;
private final ExitCodeExceptionMapper mapper;
MappedExitCodeGenerator(Throwable exception, ExitCodeExceptionMapper mapper) {
this.exception = exception;
this.mapper = mapper;
}
@Override
public int getExitCode() {
return this.mapper.getExitCode(this.exception);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ExitCodeGenerators.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\n\nPESSIMISTIC_WRITE and UPDATE ...");
|
System.out.println("-----------------------------------------------------------------");
bookstoreService.pessimisticWriteUpdate();
System.out.println("\n\nPESSIMISTIC_WRITE and INSERT ...");
System.out.println("\n-------------------------REPEATABLE_READ---------------------");
bookstoreService.pessimisticWriteInsert(TransactionDefinition.ISOLATION_REPEATABLE_READ);
System.out.println("\n-------------------------READ_COMMITTED----------------------");
bookstoreService.pessimisticWriteInsert(TransactionDefinition.ISOLATION_READ_COMMITTED);
System.out.println("\n\nPESSIMISTIC_WRITE and DELETE ...");
System.out.println("-----------------------------------------------------------------");
bookstoreService.pessimisticWriteDelete();
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootPessimisticLocksDelInsUpd\src\main\java\com\bookstore\MainApplication.java
| 2
|
请完成以下Java代码
|
public class RabbitMQConsumer {
public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接
Connection connection = RabbitMQProducer.getConnection();
// 创建信道
final Channel channel = connection.createChannel();
channel.basicQos(64); // 设置客户端最多接收未被 ack 的消息数量为 64 。
// 创建消费者
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
// 打印日志
System.out.println(String.format("[线程:%s][路由键:%s][消息内容:%s]",
Thread.currentThread(), envelope.getRoutingKey(), new String(body)));
|
// ack 消息已经消费
channel.basicAck(envelope.getDeliveryTag(), false);
}
};
// 订阅消费 QUEUE_NAME 队列
channel.basicConsume(RabbitMQProducer.QUEUE_NAME, consumer);
// 关闭
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException ignore) {
}
channel.close();
connection.close();
}
}
|
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-native\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\RabbitMQConsumer.java
| 1
|
请完成以下Java代码
|
public CommonResult bindExceptionHandler(HttpServletRequest req, BindException ex) {
logger.debug("[bindExceptionHandler]", ex);
// 拼接错误
StringBuilder detailMessage = new StringBuilder();
for (ObjectError objectError : ex.getAllErrors()) {
// 使用 ; 分隔多个错误
if (detailMessage.length() > 0) {
detailMessage.append(";");
}
// 拼接内容到其中
detailMessage.append(objectError.getDefaultMessage());
}
// 包装 CommonResult 结果
return CommonResult.error(ServiceExceptionEnum.INVALID_REQUEST_PARAM_ERROR.getCode(),
ServiceExceptionEnum.INVALID_REQUEST_PARAM_ERROR.getMessage() + ":" + detailMessage.toString());
}
|
/**
* 处理其它 Exception 异常
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(HttpServletRequest req, Exception e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 返回 ERROR CommonResult
return CommonResult.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
ServiceExceptionEnum.SYS_ERROR.getMessage());
}
}
|
repos\SpringBoot-Labs-master\lab-22\lab-22-validation-01\src\main\java\cn\iocoder\springboot\lab22\validation\core\web\GlobalExceptionHandler.java
| 1
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getEngineVersion() {
return engineVersion;
}
public String getAuthorizationUserId() {
return authorizationUserId;
}
public String getProcDefId() {
return procDefId;
}
public String getEventSubscriptionName() {
return eventSubscriptionName;
}
|
public String getEventSubscriptionType() {
return eventSubscriptionType;
}
public boolean isIncludeAuthorization() {
return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty());
}
public List<List<String>> getSafeAuthorizationGroups() {
return safeAuthorizationGroups;
}
public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) {
this.safeAuthorizationGroups = safeAuthorizationGroups;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessDefinitionQueryImpl.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Schema(description = "Device Profile Name", example = "Temperature Sensor")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Schema(description = "Label that may be used in widgets", example = "Room 234 Sensor")
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "JSON object with Device Profile Id.")
public DeviceProfileId getDeviceProfileId() {
return deviceProfileId;
}
public void setDeviceProfileId(DeviceProfileId deviceProfileId) {
this.deviceProfileId = deviceProfileId;
}
@Schema(description = "JSON object with content specific to type of transport in the device profile.")
public DeviceData getDeviceData() {
if (deviceData != null) {
return deviceData;
} else {
if (deviceDataBytes != null) {
try {
deviceData = mapper.readValue(new ByteArrayInputStream(deviceDataBytes), DeviceData.class);
} catch (IOException e) {
log.warn("Can't deserialize device data: ", e);
return null;
}
return deviceData;
} else {
return null;
}
|
}
}
public void setDeviceData(DeviceData data) {
this.deviceData = data;
try {
this.deviceDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize device data: ", e);
}
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getFirmwareId() {
return firmwareId;
}
public void setFirmwareId(OtaPackageId firmwareId) {
this.firmwareId = firmwareId;
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getSoftwareId() {
return softwareId;
}
public void setSoftwareId(OtaPackageId softwareId) {
this.softwareId = softwareId;
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Device.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static List<JsonCustomerLocation> toJsonCustomerLocations(@NonNull final List<JsonResponseLocation> locations)
{
final Optional<JsonMetasfreshId> mainAddressId = ExportLocationHelper.getBPartnerMainLocation(locations)
.map(JsonResponseLocation::getMetasfreshId);
final Function<JsonResponseLocation,Boolean> isMainAddress = (location) -> mainAddressId
.map(addressId -> addressId.equals(location.getMetasfreshId())).orElse(false);
return locations.stream()
.map(location -> JsonCustomerLocation.builder()
.metasfreshId(location.getMetasfreshId())
.name(location.getName())
.address1(location.getAddress1())
.address2(location.getAddress2())
.address3(location.getAddress3())
.address4(location.getAddress4())
.postal(location.getPostal())
.city(location.getCity())
.countryCode(location.getCountryCode())
.gln(location.getGln())
.inactive(location.isActive() ? 0 : 1)
.shipTo(location.isShipTo())
.billTo(location.isBillTo())
.mainAddress(isMainAddress.apply(location) ? 1 : 0)
.build())
.collect(ImmutableList.toImmutableList());
}
|
@Nullable
private static List<String> toBPartnerProductExternalReferences(@Nullable final JsonExternalReferenceLookupResponse jsonExternalReferenceLookupResponse)
{
if (jsonExternalReferenceLookupResponse == null || Check.isEmpty(jsonExternalReferenceLookupResponse.getItems()))
{
return null;
}
return jsonExternalReferenceLookupResponse
.getItems()
.stream()
.map(JsonExternalReferenceItem::getExternalReference)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\ExportCustomerProcessor.java
| 2
|
请完成以下Java代码
|
public class CompleteStagePlanItemInstanceCmd extends AbstractNeedsPlanItemInstanceCmd {
protected boolean force;
public CompleteStagePlanItemInstanceCmd(String planItemInstanceId) {
super(planItemInstanceId);
}
public CompleteStagePlanItemInstanceCmd(String planItemInstanceId, boolean force) {
super(planItemInstanceId);
this.force = force;
}
public CompleteStagePlanItemInstanceCmd(String planItemInstanceId, Map<String, Object> variables,
Map<String, Object> formVariables, String formOutcome, FormInfo formInfo,
Map<String, Object> localVariables, Map<String, Object> transientVariables, boolean force) {
super(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables);
|
this.force = force;
}
@Override
protected void internalExecute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
if (!PlanItemDefinitionType.STAGE.equals(planItemInstanceEntity.getPlanItemDefinitionType())) {
throw new FlowableIllegalArgumentException("Can only complete plan item instances of type stage. Type is " + planItemInstanceEntity.getPlanItemDefinitionType());
}
if (!force && !planItemInstanceEntity.isCompletable()) { // if force is true, ignore the completable flag
throw new FlowableIllegalArgumentException("Can only complete a stage plan item instance that is marked as completable (there might still be active plan item instance).");
}
CommandContextUtil.getAgenda(commandContext).planCompletePlanItemInstanceOperation(planItemInstanceEntity);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\CompleteStagePlanItemInstanceCmd.java
| 1
|
请完成以下Java代码
|
public boolean accept(I_C_Year pojo)
{
if (!pojo.isActive())
{
return false;
}
if (pojo.getC_Calendar_ID() != calendar.getC_Calendar_ID())
{
return false;
}
if (pojo.getAD_Client_ID() != 0 && pojo.getAD_Client_ID() != Env.getAD_Client_ID(ctx))
{
return false;
}
return true;
}
});
Collections.sort(years, new AccessorComparator<I_C_Year, Integer>(
new ComparableComparator<Integer>(),
new TypedAccessor<Integer>()
{
@Override
public Integer getValue(Object o)
{
return ((I_C_Year)o).getC_Year_ID();
}
}));
return years;
}
@Override
public I_C_Period retrieveFirstPeriodOfTheYear(I_C_Year year)
{
final List<I_C_Period> periods = getPeriodsOfYear(year);
return periods.get(0);
}
@Override
public I_C_Period retrieveLastPeriodOfTheYear(I_C_Year year)
{
final List<I_C_Period> periods = getPeriodsOfYear(year);
return periods.get(periods.size() - 1);
}
private List<I_C_Period> getPeriodsOfYear(final I_C_Year year)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(year);
List<I_C_Period> periods = db.getRecords(I_C_Period.class, new IQueryFilter<I_C_Period>()
{
@Override
public boolean accept(I_C_Period pojo)
{
if (!pojo.getC_Year().equals(year))
{
return false;
}
|
if (!pojo.isActive())
{
return false;
}
if (pojo.getAD_Client_ID() != 0 && pojo.getAD_Client_ID() != Env.getAD_Client_ID(ctx))
{
return false;
}
return true;
}
});
Collections.sort(periods, new AccessorComparator<I_C_Period, Timestamp>(
new ComparableComparator<Timestamp>(),
new TypedAccessor<Timestamp>()
{
@Override
public Timestamp getValue(Object o)
{
return ((I_C_Period)o).getStartDate();
}
}));
return periods;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\PlainCalendarDAO.java
| 1
|
请完成以下Java代码
|
private Optional<PaymentTermId> extractPaymentTermIdFromLines(@NonNull final InvoiceHeaderImpl invoiceHeader)
{
final List<IInvoiceCandAggregate> lines = invoiceHeader.getLines();
if (lines == null || lines.isEmpty())
{
return Optional.empty();
}
final ImmutableMap<Optional<PaymentTermId>, IInvoiceLineRW> uniquePaymentTermLines = mapUniqueIInvoiceLineRWPerPaymentTerm(lines);
// extract payment term if all lines have same C_PaymentTerm_ID
if (uniquePaymentTermLines.size() == 1)
{
final ImmutableSet<Optional<PaymentTermId>> ids = uniquePaymentTermLines.keySet();
return ids.iterator().next();
}
return Optional.empty();
}
private ImmutableMap<Optional<PaymentTermId>, IInvoiceLineRW> mapUniqueIInvoiceLineRWPerPaymentTerm(@NonNull final List<IInvoiceCandAggregate> lines)
{
final List<IInvoiceLineRW> invoiceLinesRW = new ArrayList<>();
lines.forEach(lineAgg -> invoiceLinesRW.addAll(lineAgg.getAllLines()));
return invoiceLinesRW.stream()
.collect(GuavaCollectors.toImmutableMapByKey(line -> PaymentTermId.optionalOfRepoId(line.getC_PaymentTerm_ID())));
}
private void setDocTypeInvoiceId(@NonNull final InvoiceHeaderImpl invoiceHeader)
{
final boolean invoiceIsSOTrx = invoiceHeader.isSOTrx();
final boolean isTakeDocTypeFromPool = invoiceHeader.isTakeDocTypeFromPool();
final DocTypeId docTypeIdToBeUsed;
final Optional<DocTypeId> docTypeInvoiceId = invoiceHeader.getDocTypeInvoiceId();
if (docTypeInvoiceId.isPresent() && !isTakeDocTypeFromPool)
{
docTypeIdToBeUsed = docTypeInvoiceId.get();
}
else if (invoiceHeader.getDocTypeInvoicingPoolId().isPresent())
{
|
final DocTypeInvoicingPool docTypeInvoicingPool = docTypeInvoicingPoolService.getById(invoiceHeader.getDocTypeInvoicingPoolId().get());
final Money totalAmt = invoiceHeader.calculateTotalNetAmtFromLines();
docTypeIdToBeUsed = docTypeInvoicingPool.getDocTypeId(totalAmt);
final I_C_DocType docTypeToBeUsedRecord = docTypeBL.getById(docTypeIdToBeUsed);
Check.assume(invoiceIsSOTrx == docTypeToBeUsedRecord.isSOTrx(), "InvoiceHeader's IsSOTrx={} shall match document type {}", invoiceIsSOTrx, docTypeToBeUsedRecord);
}
else
{
docTypeIdToBeUsed = null;
}
invoiceHeader.setDocTypeInvoiceId(docTypeIdToBeUsed);
}
private Optional<DocTypeInvoicingPool> getDocTypeInvoicingPool(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType docTypeInvoice = docTypeBL.getByIdInTrx(docTypeId);
return Optional.ofNullable(DocTypeInvoicingPoolId.ofRepoIdOrNull(docTypeInvoice.getC_DocType_Invoicing_Pool_ID()))
.map(docTypeInvoicingPoolService::getById);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationEngine.java
| 1
|
请完成以下Java代码
|
static ExternalTaskClientBuilder create() {
return new ExternalTaskClientBuilderImpl();
}
/**
* Creates a fluent builder to create and configure a topic subscription
*
* @param topicName the client subscribes to
* @return builder to apply configurations on
*/
TopicSubscriptionBuilder subscribe(String topicName);
/**
* Stops continuous fetching and locking of tasks
*/
|
void stop();
/**
* Starts continuous fetching and locking of tasks
*/
void start();
/**
* @return <ul>
* <li> {@code true} if the client is actively fetching for tasks
* <li> {@code false} if the client is not actively fetching for tasks
* </ul>
*/
boolean isActive();
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\ExternalTaskClient.java
| 1
|
请完成以下Java代码
|
public class DateOrDateTimePeriodChoice {
@XmlElement(name = "Dt")
protected DatePeriodDetails dt;
@XmlElement(name = "DtTm")
protected DateTimePeriodDetails dtTm;
/**
* Gets the value of the dt property.
*
* @return
* possible object is
* {@link DatePeriodDetails }
*
*/
public DatePeriodDetails getDt() {
return dt;
}
/**
* Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link DatePeriodDetails }
*
*/
public void setDt(DatePeriodDetails value) {
this.dt = value;
}
|
/**
* Gets the value of the dtTm property.
*
* @return
* possible object is
* {@link DateTimePeriodDetails }
*
*/
public DateTimePeriodDetails getDtTm() {
return dtTm;
}
/**
* Sets the value of the dtTm property.
*
* @param value
* allowed object is
* {@link DateTimePeriodDetails }
*
*/
public void setDtTm(DateTimePeriodDetails value) {
this.dtTm = 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\DateOrDateTimePeriodChoice.java
| 1
|
请完成以下Java代码
|
protected List<EventSubscriptionEntity> collectActivityInstanceEventSubscriptions(MigratingActivityInstance migratingInstance) {
if (migratingInstance.getSourceScope().isScope()) {
return migratingInstance.resolveRepresentativeExecution().getEventSubscriptions();
}
else {
return Collections.emptyList();
}
}
protected List<JobEntity> collectActivityInstanceJobs(MigratingActivityInstance migratingInstance) {
if (migratingInstance.getSourceScope().isScope()) {
return migratingInstance.resolveRepresentativeExecution().getJobs();
}
else {
return Collections.emptyList();
|
}
}
public static List<VariableInstanceEntity> getConcurrentLocalVariables(ExecutionEntity execution) {
List<VariableInstanceEntity> variables = new ArrayList<VariableInstanceEntity>();
for (VariableInstanceEntity variable : execution.getVariablesInternal()) {
if (variable.isConcurrentLocal()) {
variables.add(variable);
}
}
return variables;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\ActivityInstanceHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<Long> deleteFlowRule(Long id) {
if (id == null) {
return Result.ofFail(-1, "id can't be null");
}
GatewayFlowRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
} catch (Throwable throwable) {
logger.error("delete gateway flow rule error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
logger.warn("publish gateway flow rules fail after delete");
}
|
return Result.ofSuccess(id);
}
private boolean publishRules(String app, String ip, Integer port) {
List<GatewayFlowRuleEntity> rules = repository.findAllByApp(app);
try {
rulePublisher.publish(app, rules);
//延迟加载
delayTime();
return true;
} catch (Exception e) {
logger.error("publish rules error!");
e.printStackTrace();
return false;
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\gateway\GatewayFlowRuleController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class HistoryCleanupRestServiceImpl implements HistoryCleanupRestService {
protected ObjectMapper objectMapper;
protected ProcessEngine processEngine;
public HistoryCleanupRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) {
this.objectMapper = objectMapper;
this.processEngine = processEngine;
}
public JobDto cleanupAsync(boolean immediatelyDue) {
Job job = processEngine.getHistoryService().cleanUpHistoryAsync(immediatelyDue);
return JobDto.fromJob(job);
}
public JobDto findCleanupJob() {
Job job = processEngine.getHistoryService().findHistoryCleanupJob();
if (job == null) {
throw new RestException(Status.NOT_FOUND, "History cleanup job does not exist");
}
return JobDto.fromJob(job);
}
public List<JobDto> findCleanupJobs() {
List<Job> jobs = processEngine.getHistoryService().findHistoryCleanupJobs();
if (jobs == null || jobs.isEmpty()) {
throw new RestException(Status.NOT_FOUND, "History cleanup jobs are empty");
}
List<JobDto> dtos = new ArrayList<JobDto>();
for (Job job : jobs) {
|
JobDto dto = JobDto.fromJob(job);
dtos.add(dto);
}
return dtos;
}
public HistoryCleanupConfigurationDto getHistoryCleanupConfiguration() {
ProcessEngineConfigurationImpl engineConfiguration =
(ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
HistoryCleanupConfigurationDto configurationDto = new HistoryCleanupConfigurationDto();
configurationDto.setEnabled(engineConfiguration.isHistoryCleanupEnabled());
BatchWindow batchWindow = engineConfiguration.getBatchWindowManager()
.getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), engineConfiguration);
if (batchWindow != null) {
configurationDto.setBatchWindowStartTime(batchWindow.getStart());
configurationDto.setBatchWindowEndTime(batchWindow.getEnd());
}
return configurationDto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoryCleanupRestServiceImpl.java
| 2
|
请完成以下Java代码
|
private boolean hasNoModels()
{
return isCreateOneWorkpackagePerAsyncBatch() ? batchId2Models.isEmpty() : models.isEmpty();
}
}
private static final class ModelsScheduler<ModelType> extends WorkpackagesOnCommitSchedulerTemplate<ModelType>
{
private final Class<ModelType> modelType;
private final boolean collectModels;
public ModelsScheduler(final Class<? extends IWorkpackageProcessor> workpackageProcessorClass, final Class<ModelType> modelType, final boolean collectModels)
{
super(workpackageProcessorClass);
this.modelType = modelType;
this.collectModels = collectModels;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("collectModels", collectModels)
.add("workpackageProcessorClass", getWorkpackageProcessorClass())
.add("modelType", modelType)
.toString();
}
@Override
protected Properties extractCtxFromItem(final ModelType item)
|
{
return InterfaceWrapperHelper.getCtx(item);
}
@Override
protected String extractTrxNameFromItem(final ModelType item)
{
return InterfaceWrapperHelper.getTrxName(item);
}
@Nullable
@Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final ModelType item)
{
return collectModels ? item : null;
}
@Override
protected boolean isEnqueueWorkpackageWhenNoModelsEnqueued()
{
return !collectModels;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackagesOnCommitSchedulerTemplate.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver
spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.username = sa
spring.datasource.password =
spring.jpa.hibernate.ddl-auto = create
# Enabling H2 Console
spring.h2.console.enabled=true
hibernate.globally_quoted_identifiers=true
#spring.datasource.hikari.connecti
|
onTimeout=30000
#spring.datasource.hikari.idleTimeout=600000
#spring.datasource.hikari.maxLifetime=1800000
#spring.datasource.hikari.registerMbeans=true
|
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
private static ITranslatableString computeCaption(@NonNull final Plan plan)
{
return TranslatableStrings.builder()
.appendADElement(plan.getAction().getColumnName()).append(": ").append(plan.getAmountToDiscountOrWriteOff())
.build();
}
@Override
protected String doIt()
{
final Plan plan = creatPlan().orElseThrow();
final I_C_Invoice invoice = invoiceBL.getById(plan.getInvoiceId());
final InvoiceAmtMultiplier amtMultiplier = plan.getAmtMultiplier();
final Money amountToDiscountOrWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToDiscountOrWriteOff())
.toMoney(moneyService::getCurrencyIdByCurrencyCode);
allocationBL.invoiceDiscountAndWriteOff(
IAllocationBL.InvoiceDiscountAndWriteOffRequest.builder()
.invoice(invoice)
.dateTrx(TimeUtil.asInstant(p_DateTrx))
.discountAmt(plan.getAction() == PlanAction.Discount ? amountToDiscountOrWriteOff : null)
.writeOffAmt(plan.getAction() == PlanAction.WriteOff ? amountToDiscountOrWriteOff : null)
.build());
return MSG_OK;
}
//
//
//
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<InvoiceRow> invoiceRows, final PlanAction action)
{
if (invoiceRows.size() != 1)
{
return ExplainedOptional.emptyBecause("Only one invoice row can be selected");
}
final InvoiceRow invoiceRow = CollectionUtils.singleElement(invoiceRows);
if (invoiceRow.getDocBaseType().isCreditMemo())
{
return ExplainedOptional.emptyBecause("Credit Memos are not eligible");
}
final Amount openAmt = invoiceRow.getOpenAmt();
if (openAmt.signum() == 0)
{
return ExplainedOptional.emptyBecause("Zero open amount");
}
|
return ExplainedOptional.of(
Plan.builder()
.invoiceId(invoiceRow.getInvoiceId())
.action(action)
.amtMultiplier(invoiceRow.getInvoiceAmtMultiplier())
.amountToDiscountOrWriteOff(openAmt)
.build());
}
@AllArgsConstructor
enum PlanAction
{
Discount("DiscountAmt"),
WriteOff("WriteOffAmt"),
;
// used mainly to build the action caption
@Getter
private final String columnName;
}
@Value
@Builder
private static class Plan
{
@NonNull InvoiceId invoiceId;
@NonNull PlanAction action;
@NonNull InvoiceAmtMultiplier amtMultiplier;
@NonNull Amount amountToDiscountOrWriteOff;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_InvoiceDiscountOrWriteOff.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Long organizationId) {
this.organizationId = organizationId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
|
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Department [id=" + id + ", organizationId=" + organizationId + ", name=" + name + "]";
}
}
|
repos\sample-spring-microservices-new-master\department-service\src\main\java\pl\piomin\services\department\model\Department.java
| 2
|
请完成以下Java代码
|
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
if (!this.explicitSecurityContextProvided) {
this.delegateSecurityContext = securityContextHolderStrategy.getContext();
}
}
@Override
public String toString() {
return this.delegate.toString();
}
/**
* Creates a {@link DelegatingSecurityContextCallable} and with the given
* {@link Callable} and {@link SecurityContext}, but if the securityContext is null
* will defaults to the current {@link SecurityContext} on the
* {@link SecurityContextHolder}
* @param delegate the delegate {@link DelegatingSecurityContextCallable} to run with
* the specified {@link SecurityContext}. Cannot be null.
* @param securityContext the {@link SecurityContext} to establish for the delegate
* {@link Callable}. If null, defaults to {@link SecurityContextHolder#getContext()}
* @return
*/
public static <V> Callable<V> create(Callable<V> delegate, SecurityContext securityContext) {
return (securityContext != null) ? new DelegatingSecurityContextCallable<>(delegate, securityContext)
|
: new DelegatingSecurityContextCallable<>(delegate);
}
static <V> Callable<V> create(Callable<V> delegate, @Nullable SecurityContext securityContext,
SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(delegate, "delegate cannot be null");
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
DelegatingSecurityContextCallable<V> callable = (securityContext != null)
? new DelegatingSecurityContextCallable<>(delegate, securityContext)
: new DelegatingSecurityContextCallable<>(delegate);
callable.setSecurityContextHolderStrategy(securityContextHolderStrategy);
return callable;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\concurrent\DelegatingSecurityContextCallable.java
| 1
|
请完成以下Java代码
|
public NodeList getAllTutorials() {
NodeList nodeList = null;
try {
DocumentBuilderFactory builderFactory = newSecureDocumentBuilderFactory();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new NamespaceContext() {
@Override
public Iterator getPrefixes(String arg0) {
return null;
}
@Override
public String getPrefix(String arg0) {
return null;
}
@Override
public String getNamespaceURI(String arg0) {
if ("bdn".equals(arg0)) {
return "http://www.baeldung.com/full_archive";
}
return null;
}
});
String expression = "/bdn:tutorials/bdn:tutorial";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
|
}
return nodeList;
}
private void clean(Node node) {
NodeList childNodes = node.getChildNodes();
for (int n = childNodes.getLength() - 1; n >= 0; n--) {
Node child = childNodes.item(n);
short nodeType = child.getNodeType();
if (nodeType == Node.ELEMENT_NODE)
clean(child);
else if (nodeType == Node.TEXT_NODE) {
String trimmedNodeVal = child.getNodeValue().trim();
if (trimmedNodeVal.length() == 0)
node.removeChild(child);
else
child.setNodeValue(trimmedNodeVal);
} else if (nodeType == Node.COMMENT_NODE)
node.removeChild(child);
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
|
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\DefaultParser.java
| 1
|
请完成以下Java代码
|
public void setId(String id) {
this.id = id;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
|
return false;
}
StoreItem storeItem = (StoreItem) o;
return Objects.equals(name, storeItem.name) && Objects.equals(price, storeItem.price);
}
@Override
public int hashCode() {
return Objects.hash(name, price);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
repos\tutorials-master\quarkus-modules\quarkus-elasticsearch\src\main\java\com\baeldung\quarkus\elasticsearch\model\StoreItem.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8888
spring:
application:
name: gateway-application
cloud:
# Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway:
# 路由配置项,对应 RouteDefinition 数组
routes:
- id: yudaoyuanma # 路由的编号
uri: http://www.iocoder.cn # 路由到的目标地址
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
- Path=/blog
filters:
- StripPrefix=1
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 1 # 令牌桶的每秒放的数量
redis-rate-limiter.burstCapacity: 2 # 令牌桶的最大令牌数
key-resolver: "#{@ipKeyResolver}" # 获取限流 KEY 的 Bean 的名字
- id: oschi
|
na # 路由的编号
uri: https://www.oschina.net # 路由的目标地址
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
- Path=/oschina
filters: # 过滤器,对请求进行拦截,实现自定义的功能,对应 FilterDefinition 数组
- StripPrefix=1
# Redis 配置项
redis:
host: 127.0.0.1
port: 6379
|
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo06-rate-limiter\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public void afterPropertiesSet() throws Exception {
// 通过 ApplicationContext 获得所有 MessageHandler Bean
applicationContext.getBeansOfType(MessageHandler.class).values() // 获得所有 MessageHandler Bean
.forEach(messageHandler -> HANDLERS.put(messageHandler.getType(), messageHandler)); // 添加到 handlers 中
logger.info("[afterPropertiesSet][消息处理器数量:{}]", HANDLERS.size());
}
private Class<? extends Message> getMessageClass(MessageHandler handler) {
// 获得 Bean 对应的 Class 类名。因为有可能被 AOP 代理过。
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(handler);
// 获得接口的 Type 数组
Type[] interfaces = targetClass.getGenericInterfaces();
Class<?> superclass = targetClass.getSuperclass();
while ((Objects.isNull(interfaces) || 0 == interfaces.length) && Objects.nonNull(superclass)) { // 此处,是以父类的接口为准
interfaces = superclass.getGenericInterfaces();
superclass = targetClass.getSuperclass();
}
if (Objects.nonNull(interfaces)) {
// 遍历 interfaces 数组
for (Type type : interfaces) {
// 要求 type 是泛型参数
if (type instanceof ParameterizedType) {
|
ParameterizedType parameterizedType = (ParameterizedType) type;
// 要求是 MessageHandler 接口
if (Objects.equals(parameterizedType.getRawType(), MessageHandler.class)) {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// 取首个元素
if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
return (Class<Message>) actualTypeArguments[0];
} else {
throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler));
}
}
}
}
}
throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler));
}
}
|
repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\websocket\WebsocketServerEndpoint.java
| 1
|
请完成以下Java代码
|
public class FilterDto {
protected String id;
protected String resourceType;
protected String name;
protected String owner;
protected AbstractQueryDto<?> query;
protected Map<String, Object> properties;
protected Long itemCount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public AbstractQueryDto<?> getQuery() {
return query;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "resourceType", defaultImpl=TaskQueryDto.class)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = TaskQueryDto.class, name = EntityTypes.TASK)})
public void setQuery(AbstractQueryDto<?> query) {
this.query = query;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@JsonInclude(Include.NON_NULL)
public Long getItemCount() {
|
return itemCount;
}
public void setItemCount(Long itemCount) {
this.itemCount = itemCount;
}
public static FilterDto fromFilter(Filter filter) {
FilterDto dto = new FilterDto();
dto.id = filter.getId();
dto.resourceType = filter.getResourceType();
dto.name = filter.getName();
dto.owner = filter.getOwner();
if (EntityTypes.TASK.equals(filter.getResourceType())) {
dto.query = TaskQueryDto.fromQuery(filter.getQuery());
}
dto.properties = filter.getProperties();
return dto;
}
public void updateFilter(Filter filter, ProcessEngine engine) {
if (getResourceType() != null && !getResourceType().equals(filter.getResourceType())) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to update filter from resource type '" + filter.getResourceType() + "' to '" + getResourceType() + "'");
}
filter.setName(getName());
filter.setOwner(getOwner());
filter.setQuery(query.toQuery(engine));
filter.setProperties(getProperties());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterDto.java
| 1
|
请完成以下Java代码
|
public void setAD_AttachmentEntry(final org.compiere.model.I_AD_AttachmentEntry AD_AttachmentEntry)
{
set_ValueFromPO(COLUMNNAME_AD_AttachmentEntry_ID, org.compiere.model.I_AD_AttachmentEntry.class, AD_AttachmentEntry);
}
@Override
public void setAD_AttachmentEntry_ID (final int AD_AttachmentEntry_ID)
{
if (AD_AttachmentEntry_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, AD_AttachmentEntry_ID);
}
@Override
public int getAD_AttachmentEntry_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_AttachmentEntry_ID);
}
@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 void setFileName_Override (final @Nullable java.lang.String FileName_Override)
{
set_Value (COLUMNNAME_FileName_Override, FileName_Override);
|
}
@Override
public java.lang.String getFileName_Override()
{
return get_ValueAsString(COLUMNNAME_FileName_Override);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_MultiRef.java
| 1
|
请完成以下Java代码
|
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimeZone (final @Nullable java.lang.String TimeZone)
{
set_Value (COLUMNNAME_TimeZone, TimeZone);
}
@Override
public java.lang.String getTimeZone()
{
return get_ValueAsString(COLUMNNAME_TimeZone);
}
@Override
public void setTransferBank_ID (final int TransferBank_ID)
{
if (TransferBank_ID < 1)
set_Value (COLUMNNAME_TransferBank_ID, null);
else
set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID);
}
@Override
public int getTransferBank_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferBank_ID);
}
|
@Override
public org.compiere.model.I_C_CashBook getTransferCashBook()
{
return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class);
}
@Override
public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook)
{
set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook);
}
@Override
public void setTransferCashBook_ID (final int TransferCashBook_ID)
{
if (TransferCashBook_ID < 1)
set_Value (COLUMNNAME_TransferCashBook_ID, null);
else
set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID);
}
@Override
public int getTransferCashBook_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java
| 1
|
请完成以下Java代码
|
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
|
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getAuthorizedGrantTypes() {
return authorizedGrantTypes;
}
public void setAuthorizedGrantTypes(String authorizedGrantTypes) {
this.authorizedGrantTypes = authorizedGrantTypes;
}
}
|
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\model\Client.java
| 1
|
请完成以下Java代码
|
public @NonNull ITranslatableString getName() {return node.getName();}
@NonNull
public ITranslatableString getDescription() {return node.getDescription();}
@NonNull
public ITranslatableString getHelp() {return node.getHelp();}
public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();}
public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();}
public void setXPosition(final int x) { this.xPosition = x; }
public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();}
public void setYPosition(final int y) { this.yPosition = y; }
|
public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId)
{
return node.getTransitions(clientId)
.stream()
.map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition))
.collect(ImmutableList.toImmutableList());
}
public void saveEx()
{
workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder()
.nodeId(getId())
.xPosition(getXPosition())
.yPosition(getYPosition())
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java
| 1
|
请完成以下Java代码
|
public class BatchMonitorJobHandler implements JobHandler<BatchMonitorJobConfiguration> {
public static final String TYPE = "batch-monitor-job";
public String getType() {
return TYPE;
}
public void execute(BatchMonitorJobConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) {
String batchId = configuration.getBatchId();
BatchEntity batch = commandContext.getBatchManager().findBatchById(configuration.getBatchId());
ensureNotNull("Batch with id '" + batchId + "' cannot be found", "batch", batch);
boolean completed = batch.isCompleted();
if (!completed) {
batch.createMonitorJob(true);
}
else {
batch.delete(false, false);
}
}
@Override
public BatchMonitorJobConfiguration newConfiguration(String canonicalString) {
return new BatchMonitorJobConfiguration(canonicalString);
}
public static class BatchMonitorJobConfiguration implements JobHandlerConfiguration {
protected String batchId;
|
public BatchMonitorJobConfiguration(String batchId) {
this.batchId = batchId;
}
public String getBatchId() {
return batchId;
}
@Override
public String toCanonicalString() {
return batchId;
}
}
public void onDelete(BatchMonitorJobConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchMonitorJobHandler.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true&useLegacyDatetimeCode=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dial
|
ect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public String getSummaryTranslated(final Properties ctx)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final int countWorkpackages = getWorkpackageEnqueuedCount();
final int countUnprocessedWorkPackages = getWorkpackageQueueSizeBeforeEnqueueing();
return msgBL.getMsg(ctx, MSG_INVOICE_CANDIDATE_ENQUEUE, new Object[] { countWorkpackages, countUnprocessedWorkPackages });
}
@Override
public int getInvoiceCandidateEnqueuedCount()
{
return invoiceCandidateEnqueuedCount;
}
@Override
public int getWorkpackageEnqueuedCount()
{
return workpackageEnqueuedCount;
}
@Override
|
public int getWorkpackageQueueSizeBeforeEnqueueing()
{
return workpackageQueueSizeBeforeEnqueueing;
}
@Override
public BigDecimal getTotalNetAmtToInvoiceChecksum()
{
return totalNetAmtToInvoiceChecksum;
}
@Override
public ILock getLock()
{
return lock;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateEnqueueResult.java
| 1
|
请完成以下Java代码
|
protected void initializeVariableOnPart(CamundaVariableOnPart variableOnPart, CmmnSentryDeclaration sentryDeclaration, CmmnHandlerContext context) {
VariableTransition variableTransition;
try {
variableTransition = variableOnPart.getVariableEvent();
} catch(IllegalArgumentException illegalArgumentexception) {
throw LOG.nonMatchingVariableEvents(sentryDeclaration.getId());
} catch(NullPointerException nullPointerException) {
throw LOG.nonMatchingVariableEvents(sentryDeclaration.getId());
}
String variableName = variableOnPart.getVariableName();
String variableEventName = variableTransition.name();
if (variableName != null) {
if (!sentryDeclaration.hasVariableOnPart(variableEventName, variableName)) {
CmmnVariableOnPartDeclaration variableOnPartDeclaration = new CmmnVariableOnPartDeclaration();
variableOnPartDeclaration.setVariableEvent(variableEventName);
variableOnPartDeclaration.setVariableName(variableName);
sentryDeclaration.addVariableOnParts(variableOnPartDeclaration);
}
|
} else {
throw LOG.emptyVariableName(sentryDeclaration.getId());
}
}
protected <V extends ModelElementInstance> List<V> queryExtensionElementsByClass(CmmnElement element, Class<V> cls) {
ExtensionElements extensionElements = element.getExtensionElements();
if (extensionElements != null) {
Query<ModelElementInstance> query = extensionElements.getElementsQuery();
return query.filterByType(cls).list();
} else {
return new ArrayList<V>();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\SentryHandler.java
| 1
|
请完成以下Java代码
|
public class TransitionImpl extends ProcessElementImpl implements PvmTransition {
private static final long serialVersionUID = 1L;
protected ActivityImpl source;
protected ActivityImpl destination;
protected List<ExecutionListener> executionListeners;
protected Expression skipExpression;
/**
* Graphical information: a list of waypoints: x1, y1, x2, y2, x3, y3, ..
*/
protected List<Integer> waypoints = new ArrayList<>();
public TransitionImpl(String id, Expression skipExpression, ProcessDefinitionImpl processDefinition) {
super(id, processDefinition);
this.skipExpression = skipExpression;
}
@Override
public ActivityImpl getSource() {
return source;
}
public void setDestination(ActivityImpl destination) {
this.destination = destination;
destination.getIncomingTransitions().add(this);
}
public void addExecutionListener(ExecutionListener executionListener) {
if (executionListeners == null) {
executionListeners = new ArrayList<>();
}
executionListeners.add(executionListener);
}
@Override
public String toString() {
return "(" + source.getId() + ")--" + (id != null ? id + "-->(" : ">(") + destination.getId() + ")";
}
@SuppressWarnings("unchecked")
public List<ExecutionListener> getExecutionListeners() {
if (executionListeners == null) {
return Collections.EMPTY_LIST;
}
return executionListeners;
}
// getters and setters //////////////////////////////////////////////////////
protected void setSource(ActivityImpl source) {
|
this.source = source;
}
@Override
public ActivityImpl getDestination() {
return destination;
}
public void setExecutionListeners(List<ExecutionListener> executionListeners) {
this.executionListeners = executionListeners;
}
public List<Integer> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<Integer> waypoints) {
this.waypoints = waypoints;
}
@Override
public Expression getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(Expression skipExpression) {
this.skipExpression = skipExpression;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\TransitionImpl.java
| 1
|
请完成以下Java代码
|
public int getLine() {
return line;
}
@Override
public int getColumn() {
return column;
}
@Override
public String getMainElementId() {
return mainElementId;
}
@Override
public List<String> getElementIds() {
|
return elementIds;
}
public String toString() {
StringBuilder string = new StringBuilder();
if (line > 0) {
string.append(" | line " + line);
}
if (column > 0) {
string.append(" | column " + column);
}
return string.toString();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\xml\ProblemImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
@Nullable public static <T extends I_M_ProductPrice> T iterateAllPriceListVersionsAndFindProductPrice(
@Nullable final I_M_PriceList_Version startPriceListVersion,
@NonNull final Function<I_M_PriceList_Version, T> productPriceMapper,
@NonNull final ZonedDateTime priceDate)
{
if (startPriceListVersion == null)
{
return null;
}
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
final Set<Integer> checkedPriceListVersionIds = new HashSet<>();
I_M_PriceList_Version currentPriceListVersion = startPriceListVersion;
while (currentPriceListVersion != null)
{
// Stop here if the price list version was already considered
if (!checkedPriceListVersionIds.add(currentPriceListVersion.getM_PriceList_Version_ID()))
{
return null;
}
final T productPrice = productPriceMapper.apply(currentPriceListVersion);
if (productPrice != null)
{
return productPrice;
}
currentPriceListVersion = priceListsRepo.getBasePriceListVersionForPricingCalculationOrNull(currentPriceListVersion, priceDate);
}
return null;
}
/**
* @deprecated Please use {@link IPriceListDAO#addProductPrice(AddProductPriceRequest)}. If doesn't fit, extend it ;)
*/
|
@Deprecated
public static I_M_ProductPrice createProductPriceOrUpdateExistentOne(@NonNull final ProductPriceCreateRequest ppRequest, @NonNull final I_M_PriceList_Version plv)
{
final IProductDAO productDAO = Services.get(IProductDAO.class);
final BigDecimal price = ppRequest.getPrice().setScale(2);
I_M_ProductPrice pp = ProductPrices.retrieveMainProductPriceOrNull(plv, ProductId.ofRepoId(ppRequest.getProductId()));
if (pp == null)
{
pp = newInstance(I_M_ProductPrice.class, plv);
}
// do not update the price with value 0; 0 means that no price was changed
else if (pp != null && price.signum() == 0)
{
return pp;
}
pp.setM_PriceList_Version_ID(plv.getM_PriceList_Version_ID());
pp.setM_Product_ID(ppRequest.getProductId());
pp.setSeqNo(ppRequest.getSeqNo());
pp.setPriceLimit(price);
pp.setPriceList(price);
pp.setPriceStd(price);
final org.compiere.model.I_M_Product product = productDAO.getById(ppRequest.getProductId());
pp.setC_UOM_ID(product.getC_UOM_ID());
pp.setC_TaxCategory_ID(ppRequest.getTaxCategoryId());
save(pp);
return pp;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\ProductPrices.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String employeeNumber;
private String title;
private String name;
public Employee() {
}
public Employee(String name, String employeeNumber) {
this.name = name;
this.employeeNumber = employeeNumber;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmployeeNumber() {
return employeeNumber;
}
|
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\logging\Employee.java
| 2
|
请完成以下Java代码
|
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
RouteDefinition that = (RouteDefinition) o;
return this.order == that.order && Objects.equals(this.id, that.id)
&& Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters)
&& Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata)
&& Objects.equals(this.enabled, that.enabled);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order, this.enabled);
}
@Override
public String toString() {
return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters
+ ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + ", enabled=" + enabled + '}';
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RouteDefinition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteAuthorsAndBooksViaDeleteAllInBatch() {
authorRepository.deleteAllInBatch();
}
// deleting the authors will delete the books as well
@Transactional
public void deleteAuthorsAndBooksViaDeleteInBatch() {
List<Author> authors = authorRepository.fetchAuthorsAndBooks(60);
authorRepository.deleteInBatch(authors);
}
// good if you need to delete in a classical batch approach
// the authors will be deleted in batches; the books will be deleted as well
@Transactional
|
public void deleteAuthorsAndBooksViaDeleteAll() {
List<Author> authors = authorRepository.fetchAuthorsAndBooks(60);
authorRepository.deleteAll(authors); // for deleting all Author use deleteAll()
}
// good if you need to delete in a classical batch approach
// the authors will be deleted in batches; the books will be deleted as well
@Transactional
public void deleteAuthorsAndBooksViaDelete() {
List<Author> authors = authorRepository.fetchAuthorsAndBooks(60);
authors.forEach(authorRepository::delete);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteCascadeDelete\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public void setLineStroke (BigDecimal LineStroke)
{
set_Value (COLUMNNAME_LineStroke, LineStroke);
}
/** Get Line Stroke.
@return Width of the Line Stroke
*/
public BigDecimal getLineStroke ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineStroke);
if (bd == null)
return Env.ZERO;
return bd;
}
/** LineStrokeType AD_Reference_ID=312 */
public static final int LINESTROKETYPE_AD_Reference_ID=312;
/** Solid Line = S */
public static final String LINESTROKETYPE_SolidLine = "S";
/** Dashed Line = D */
public static final String LINESTROKETYPE_DashedLine = "D";
/** Dotted Line = d */
public static final String LINESTROKETYPE_DottedLine = "d";
/** Dash-Dotted Line = 2 */
public static final String LINESTROKETYPE_Dash_DottedLine = "2";
/** Set Line Stroke Type.
@param LineStrokeType
Type of the Line Stroke
*/
public void setLineStrokeType (String LineStrokeType)
{
set_Value (COLUMNNAME_LineStrokeType, LineStrokeType);
}
/** Get Line Stroke Type.
@return Type of the Line Stroke
*/
public String getLineStrokeType ()
{
|
return (String)get_Value(COLUMNNAME_LineStrokeType);
}
/** 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_AD_PrintTableFormat.java
| 1
|
请完成以下Java代码
|
private static String toString(@NonNull final Message message)
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(message);
}
catch (final JsonProcessingException e)
{
return message.toString();
}
}
//
//
//
//
@RequiredArgsConstructor
private static class LoggableAsGraphLoggerAdapter implements ILogger
{
@NonNull private final ILoggable loggable;
@NonNull @Getter @Setter private LoggerLevel loggingLevel = LoggerLevel.DEBUG;
@Override
public void logDebug(@NonNull final String message)
{
loggable.addLog(message);
}
@Override
public void logError(@NonNull final String message, @Nullable final Throwable throwable)
{
final StringBuilder finalMessage = new StringBuilder("ERROR: ").append(message);
if (throwable != null)
{
finalMessage.append("\n").append(Util.dumpStackTraceToString(throwable));
}
loggable.addLog(finalMessage.toString());
}
}
@RequiredArgsConstructor
private static class SLF4JAsGraphLoggerAdapter implements ILogger
{
@NonNull private final Logger logger;
@Override
public void setLoggingLevel(@NonNull final LoggerLevel level)
{
switch (level)
{
case ERROR:
|
LogManager.setLoggerLevel(logger, Level.WARN);
break;
case DEBUG:
default:
LogManager.setLoggerLevel(logger, Level.DEBUG);
break;
}
}
@Override
public @NonNull LoggerLevel getLoggingLevel()
{
final Level level = LogManager.getLoggerLevel(logger);
if (level == null)
{
return LoggerLevel.DEBUG;
}
else if (Level.ERROR.equals(level) || Level.WARN.equals(level))
{
return LoggerLevel.ERROR;
}
else
{
return LoggerLevel.DEBUG;
}
}
@Override
public void logDebug(@NonNull final String message)
{
logger.debug(message);
}
@Override
public void logError(@NonNull final String message, @Nullable final Throwable throwable)
{
logger.warn(message, throwable);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\sender\MicrosoftGraphMailSender.java
| 1
|
请完成以下Java代码
|
public List<Role> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Role> authorities) {
this.authorities = authorities;
}
/**
* 用户账号是否过期
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
/**
* 用户账号是否被锁定
*/
@Override
public boolean isAccountNonLocked() {
return true;
}
|
/**
* 用户密码是否过期
*/
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* 用户是否可用
*/
@Override
public boolean isEnabled() {
return true;
}
}
|
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\entity\User.java
| 1
|
请完成以下Java代码
|
public void setAssetMarketValueAmt (BigDecimal AssetMarketValueAmt)
{
set_Value (COLUMNNAME_AssetMarketValueAmt, AssetMarketValueAmt);
}
/** Get Market value Amount.
@return Market value of the asset
*/
public BigDecimal getAssetMarketValueAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetMarketValueAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Asset value.
@param AssetValueAmt
Book Value of the asset
*/
public void setAssetValueAmt (BigDecimal AssetValueAmt)
{
set_Value (COLUMNNAME_AssetValueAmt, AssetValueAmt);
}
/** Get Asset value.
@return Book Value of the asset
*/
public BigDecimal getAssetValueAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetValueAmt);
if (bd == null)
return Env.ZERO;
|
return bd;
}
public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException
{
return (I_C_InvoiceLine)MTable.get(getCtx(), I_C_InvoiceLine.Table_Name)
.getPO(getC_InvoiceLine_ID(), get_TrxName()); }
/** Set Invoice Line.
@param C_InvoiceLine_ID
Invoice Detail Line
*/
public void setC_InvoiceLine_ID (int C_InvoiceLine_ID)
{
if (C_InvoiceLine_ID < 1)
set_Value (COLUMNNAME_C_InvoiceLine_ID, null);
else
set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID));
}
/** Get Invoice Line.
@return Invoice Detail Line
*/
public int getC_InvoiceLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_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_A_Asset_Retirement.java
| 1
|
请完成以下Java代码
|
private boolean isResolvable(Object base) {
return base == null;
}
private boolean resolve(ELContext context, Object base, Object property) {
context.setPropertyResolved(isResolvable(base) && property instanceof String);
return context.isPropertyResolved();
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return isResolvable(context) ? String.class : null;
}
@Override
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
return null;
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? Object.class : null;
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (resolve(context, base, property)) {
if (!isProperty((String) property)) {
throw new PropertyNotFoundException("Cannot find property " + property);
}
return getProperty((String) property);
}
return null;
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? readOnly : false;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value)
throws PropertyNotWritableException {
if (resolve(context, base, property)) {
if (readOnly) {
throw new PropertyNotWritableException("Resolver is read only!");
}
setProperty((String) property, value);
}
}
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (resolve(context, base, method)) {
throw new NullPointerException("Cannot invoke method " + method + " on null");
}
|
return null;
}
/**
* Get property value
*
* @param property
* property name
* @return value associated with the given property
*/
public Object getProperty(String property) {
return map.get(property);
}
/**
* Set property value
*
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value);
}
/**
* Test property
*
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java
| 1
|
请完成以下Java代码
|
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** 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());
}
|
/** Type AD_Reference_ID=101 */
public static final int TYPE_AD_Reference_ID=101;
/** SQL = S */
public static final String TYPE_SQL = "S";
/** Java = J */
public static final String TYPE_Java = "J";
/** Java-Script = E */
public static final String TYPE_Java_Script = "E";
/** Composite = C */
public static final String TYPE_Composite = "C";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule.java
| 1
|
请完成以下Java代码
|
public final String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public final List<Object> getSqlParams(final Properties ctx)
{
return getSqlParams();
}
public final List<Object> getSqlParams()
{
buildSql();
return sqlParams;
}
private void buildSql()
{
if (sqlBuilt)
{
return;
}
final ArrayList<Object> sqlParams = new ArrayList<>();
final StringBuilder sql = new StringBuilder();
sql.append(columnName).append(" IS NOT NULL");
if (range.hasLowerBound())
{
final String operator;
final BoundType boundType = range.lowerBoundType();
switch (boundType)
{
case OPEN:
operator = ">";
break;
case CLOSED:
operator = ">=";
break;
default:
throw new AdempiereException("Unknown bound: " + boundType);
}
sql.append(" AND ").append(columnName).append(operator).append("?");
|
sqlParams.add(range.lowerEndpoint());
}
if (range.hasUpperBound())
{
final String operator;
final BoundType boundType = range.upperBoundType();
switch (boundType)
{
case OPEN:
operator = "<";
break;
case CLOSED:
operator = "<=";
break;
default:
throw new AdempiereException("Unknown bound: " + boundType);
}
sql.append(" AND ").append(columnName).append(operator).append("?");
sqlParams.add(range.upperEndpoint());
}
//
this.sqlWhereClause = sql.toString();
this.sqlParams = !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of();
this.sqlBuilt = true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InstantRangeQueryFilter.java
| 1
|
请完成以下Java代码
|
public void onError(Throwable t) {
CallClientStreamingRpc();
}
@Override
public void onCompleted() {
CallClientStreamingRpc();
}
});
requestStreamObserver.onNext(request);
requestStreamObserver.onCompleted();
}
private void CallServerStreamingRpc() {
byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(10240, 20480)];
ThreadLocalRandom.current().nextBytes(bytes);
ServerStreamingRequest request = ServerStreamingRequest.newBuilder()
.setMessage(new String(bytes)).build();
stub.serverStreamingRpc(request, new StreamObserver<>() {
@Override
public void onNext(ServerStreamingResponse value) {}
@Override
public void onError(Throwable t) {
CallServerStreamingRpc();
}
@Override
public void onCompleted() {
CallServerStreamingRpc();
}
});
}
private void CallBidStreamingRpc() {
byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(10240, 20480)];
ThreadLocalRandom.current().nextBytes(bytes);
BidiStreamingRequest request = BidiStreamingRequest.newBuilder()
.setMessage(new String(bytes)).build();
|
StreamObserver<BidiStreamingRequest> requestStreamObserver = stub.bidiStreamingRpc(
new StreamObserver<>() {
@Override
public void onNext(BidiStreamingResponse value) {}
@Override
public void onError(Throwable t) {
CallBidStreamingRpc();
}
@Override
public void onCompleted() {
CallBidStreamingRpc();
}
});
requestStreamObserver.onNext(request);
requestStreamObserver.onCompleted();
}
@Override
public void run(String... args) {
CallUnaryRpc();
CallServerStreamingRpc();
CallClientStreamingRpc();
CallBidStreamingRpc();
}
}
|
repos\grpc-spring-master\examples\grpc-observability\frontend\src\main\java\net\devh\boot\grpc\examples\observability\frontend\FrontendApplication.java
| 1
|
请完成以下Java代码
|
public void setMatchStatement (java.lang.String MatchStatement)
{
set_Value (COLUMNNAME_MatchStatement, MatchStatement);
}
@Override
public java.lang.String getMatchStatement()
{
return (java.lang.String)get_Value(COLUMNNAME_MatchStatement);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public void setPosted (boolean Posted)
{
set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
@Override
public boolean isPosted()
{
return get_ValueAsBoolean(COLUMNNAME_Posted);
}
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
|
@Override
public void setStatementDate (java.sql.Timestamp StatementDate)
{
set_Value (COLUMNNAME_StatementDate, StatementDate);
}
@Override
public java.sql.Timestamp getStatementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementDate);
}
@Override
public void setStatementDifference (java.math.BigDecimal StatementDifference)
{
set_Value (COLUMNNAME_StatementDifference, StatementDifference);
}
@Override
public java.math.BigDecimal getStatementDifference()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StatementDifference);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BankStatement.java
| 1
|
请完成以下Java代码
|
public java.sql.Timestamp getDK_DesiredDeliveryTime_From ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_From);
}
/** Set Gewünschte Lieferuhrzeit bis.
@param DK_DesiredDeliveryTime_To Gewünschte Lieferuhrzeit bis */
@Override
public void setDK_DesiredDeliveryTime_To (java.sql.Timestamp DK_DesiredDeliveryTime_To)
{
set_Value (COLUMNNAME_DK_DesiredDeliveryTime_To, DK_DesiredDeliveryTime_To);
}
/** Get Gewünschte Lieferuhrzeit bis.
@return Gewünschte Lieferuhrzeit bis */
@Override
public java.sql.Timestamp getDK_DesiredDeliveryTime_To ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_To);
}
/** Set EMail Empfänger.
@param EMail_To
EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public void setEMail_To (java.lang.String EMail_To)
{
set_Value (COLUMNNAME_EMail_To, EMail_To);
}
/** Get EMail Empfänger.
@return EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public java.lang.String getEMail_To ()
{
return (java.lang.String)get_Value(COLUMNNAME_EMail_To);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
|
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_Shipper_Config.java
| 1
|
请完成以下Java代码
|
public IHUDocumentHandler createHandler(final String tableName)
{
Check.assumeNotEmpty(tableName, "Table name not empty");
final Class<? extends IHUDocumentHandler> producerClass = producerClasses.get(tableName);
if (null != producerClass)
{
try
{
return producerClass.newInstance();
}
catch (final Exception e)
{
throw new AdempiereException("Cannot instantiate producer class " + producerClass, e);
}
}
return null;
}
@Override
public void registerHandler(final String tableName, final Class<? extends IHUDocumentHandler> producerClass)
|
{
Check.assumeNotEmpty(tableName, "Table name not empty");
Check.assumeNotNull(producerClass, "Class not null");
if (producerClasses.containsKey(tableName))
{
// No composite implemented. Assume only one handler per table.
throw new AdempiereException("HU document handler already implemented for " + tableName);
}
producerClasses.put(tableName, producerClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUDocumentHandlerFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class OidcBackChannelLogoutAuthentication extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = 9095810699956350287L;
private final OidcLogoutToken logoutToken;
private final ClientRegistration clientRegistration;
/**
* Construct an {@link OidcBackChannelLogoutAuthentication}
* @param logoutToken a deserialized, verified OIDC Logout Token
*/
OidcBackChannelLogoutAuthentication(OidcLogoutToken logoutToken, ClientRegistration clientRegistration) {
super(Collections.emptyList());
this.logoutToken = logoutToken;
this.clientRegistration = clientRegistration;
setAuthenticated(true);
}
/**
* {@inheritDoc}
*/
@Override
|
public OidcLogoutToken getPrincipal() {
return this.logoutToken;
}
/**
* {@inheritDoc}
*/
@Override
public OidcLogoutToken getCredentials() {
return this.logoutToken;
}
ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcBackChannelLogoutAuthentication.java
| 2
|
请完成以下Java代码
|
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set UOM Code.
@param X12DE355
|
UOM EDI X12 Code
*/
public void setX12DE355 (String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
/** Get UOM Code.
@return UOM EDI X12 Code
*/
public String getX12DE355 ()
{
return (String)get_Value(COLUMNNAME_X12DE355);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java
| 1
|
请完成以下Java代码
|
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
@Override
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getLimitApp() {
|
return limitApp;
}
public void setLimitApp(String limitApp) {
this.limitApp = limitApp;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Rule toRule() {
ParamFlowRule rule = new ParamFlowRule();
return rule;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private SimpleConfigurationMetadataRepository create(RawConfigurationMetadata metadata) {
SimpleConfigurationMetadataRepository repository = new SimpleConfigurationMetadataRepository();
repository.add(metadata.getSources());
for (ConfigurationMetadataItem item : metadata.getItems()) {
ConfigurationMetadataSource source = metadata.getSource(item);
repository.add(item, source);
}
Map<String, ConfigurationMetadataProperty> allProperties = repository.getAllProperties();
for (ConfigurationMetadataHint hint : metadata.getHints()) {
ConfigurationMetadataProperty property = allProperties.get(hint.getId());
if (property != null) {
addValueHints(property, hint);
}
else {
String id = hint.resolveId();
property = allProperties.get(id);
if (property != null) {
if (hint.isMapKeyHints()) {
addMapHints(property, hint);
}
else {
addValueHints(property, hint);
}
}
}
}
return repository;
}
private void addValueHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) {
property.getHints().getValueHints().addAll(hint.getValueHints());
property.getHints().getValueProviders().addAll(hint.getValueProviders());
}
private void addMapHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) {
property.getHints().getKeyHints().addAll(hint.getValueHints());
property.getHints().getKeyProviders().addAll(hint.getValueProviders());
}
|
/**
* Create a new builder instance using {@link StandardCharsets#UTF_8} as the default
* charset and the specified JSON resource.
* @param inputStreams the source input streams
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
* @throws IOException on error
*/
public static ConfigurationMetadataRepositoryJsonBuilder create(InputStream... inputStreams) throws IOException {
ConfigurationMetadataRepositoryJsonBuilder builder = create();
for (InputStream inputStream : inputStreams) {
builder = builder.withJsonResource(inputStream);
}
return builder;
}
/**
* Create a new builder instance using {@link StandardCharsets#UTF_8} as the default
* charset.
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
*/
public static ConfigurationMetadataRepositoryJsonBuilder create() {
return create(StandardCharsets.UTF_8);
}
/**
* Create a new builder instance using the specified default {@link Charset}.
* @param defaultCharset the default charset to use
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
*/
public static ConfigurationMetadataRepositoryJsonBuilder create(Charset defaultCharset) {
return new ConfigurationMetadataRepositoryJsonBuilder(defaultCharset);
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataRepositoryJsonBuilder.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return value;
}
@Override
public String translate(final String adLanguage)
{
return value;
}
@Override
public String getDefaultValue()
{
return value;
}
|
@Override
public Set<String> getAD_Languages()
{
return ImmutableSet.of();
}
@Override
public boolean isTranslatedTo(final String adLanguage)
{
return anyLanguage;
}
@JsonIgnore // needed for snapshot testing
public boolean isEmpty() {return value.isEmpty();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ConstantTranslatableString.java
| 1
|
请完成以下Java代码
|
public static GroupTemplateCompensationLineType ofCode(@NonNull final String code)
{
final GroupTemplateCompensationLineType type = ofNullableCode(code);
if (type == null)
{
throw new AdempiereException("Invalid code: `" + code + "`");
}
return type;
}
@Nullable
public static GroupTemplateCompensationLineType ofNullableCode(@Nullable final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
return codeNorm != null
? typesByCode.computeIfAbsent(code, GroupTemplateCompensationLineType::new)
: null;
}
|
private final String code;
private GroupTemplateCompensationLineType(@NonNull final String code) {this.code = code;}
@Override
@Deprecated
public String toString()
{
return getCode();
}
@JsonValue
public String getCode()
{
return code;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupTemplateCompensationLineType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void lock(String lockKey) {
Lock lock = obtainLock(lockKey);
lock.lock();
}
public boolean tryLock(String lockKey) {
Lock lock = obtainLock(lockKey);
return lock.tryLock();
}
public boolean tryLock(String lockKey, long seconds) {
Lock lock = obtainLock(lockKey);
try {
return lock.tryLock(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return false;
}
}
|
public void unlock(String lockKey) {
try {
Lock lock = obtainLock(lockKey);
lock.unlock();
redisLockRegistry.expireUnusedOlderThan(DEFAULT_EXPIRE_UNUSED);
} catch (Exception e) {
logger.error("分布式锁 [{}] 释放异常", lockKey, e);
}
}
private Lock obtainLock(String lockKey) {
return redisLockRegistry.obtain(lockKey);
}
}
|
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisLockService.java
| 2
|
请完成以下Java代码
|
public final class RfQResponsePublisherRequest
{
public static final RfQResponsePublisherRequest of(final I_C_RfQResponse rfqResponse, final PublishingType publishingType)
{
return new RfQResponsePublisherRequest(rfqResponse, publishingType);
}
public static enum PublishingType
{
Invitation, Close,
};
private final I_C_RfQResponse rfqResponse;
private final PublishingType publishingType;
private RfQResponsePublisherRequest(final I_C_RfQResponse rfqResponse, final PublishingType publishingType)
{
super();
Check.assumeNotNull(rfqResponse, "rfqResponse not null");
this.rfqResponse = rfqResponse;
Check.assumeNotNull(publishingType, "publishingType not null");
this.publishingType = publishingType;
}
|
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("rfqResponse", rfqResponse)
.add("publishingType", publishingType)
.toString();
}
public String getSummary()
{
return Services.get(IRfqBL.class).getSummary(rfqResponse)
+ "/" + publishingType;
}
public I_C_RfQResponse getC_RfQResponse()
{
return rfqResponse;
}
public PublishingType getPublishingType()
{
return publishingType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\RfQResponsePublisherRequest.java
| 1
|
请完成以下Java代码
|
static public String getFunctionSymbol (char function)
{
for (int i = 0; i < FUNCTIONS.length; i++)
{
if (FUNCTIONS[i] == function)
return FUNCTION_SYMBOLS[i];
}
return "UnknownFunction=" + function;
} // getFunctionSymbol
/**
* Get Function Name of function
* @param function function
* @return function name
*/
static public String getFunctionName (char function)
{
for (int i = 0; i < FUNCTIONS.length; i++)
{
if (FUNCTIONS[i] == function)
return FUNCTION_NAMES[i];
}
return "UnknownFunction=" + function;
} // getFunctionName
|
/**
* Get DisplayType of function
* @param function function
* @param displayType columns display type
* @return function name
*/
static public int getFunctionDisplayType (char function, int displayType)
{
if (function == F_SUM || function == F_MIN || function == F_MAX)
return displayType;
if (function == F_COUNT)
return DisplayType.Integer;
// Mean, Variance, Std. Deviation
return DisplayType.Number;
}
} // PrintDataFunction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataFunction.java
| 1
|
请完成以下Java代码
|
public String getStatusLine()
{
return statusLine.getText().trim();
} // setStatusLine
/**
* Set ToolTip of StatusLine
*
* @param tip tip
*/
public void setStatusToolTip(final String tip)
{
statusLine.setToolTipText(tip);
} // setStatusToolTip
/**
* Set Status DB Info
*
* @param text text
* @param dse data status event
*/
@Override
public void setStatusDB(final String text, final DataStatusEvent dse)
{
// log.info( "StatusBar.setStatusDB - " + text + " - " + created + "/" + createdBy);
if (text == null || text.length() == 0)
{
statusDB.setText("");
statusDB.setVisible(false);
}
else
{
final StringBuilder sb = new StringBuilder(" ");
sb.append(text).append(" ");
statusDB.setText(sb.toString());
if (!statusDB.isVisible())
{
statusDB.setVisible(true);
}
}
// Save
// m_text = text;
m_dse = dse;
} // setStatusDB
/**
* Set Status DB Info
*
* @param text text
*/
@Override
public void setStatusDB(final String text)
{
setStatusDB(text, null);
} // setStatusDB
/**
* Set Status DB Info
*
* @param no no
*/
public void setStatusDB(final int no)
{
setStatusDB(String.valueOf(no), null);
} // setStatusDB
/**
|
* Set Info Line
*
* @param text text
*/
@Override
public void setInfo(final String text)
{
infoLine.setVisible(true);
infoLine.setText(text);
} // setInfo
/**
* Show {@link RecordInfo} dialog
*/
private void showRecordInfo()
{
if (m_dse == null)
{
return;
}
final int adTableId = m_dse.getAdTableId();
final ComposedRecordId recordId = m_dse.getRecordId();
if (adTableId <= 0 || recordId == null)
{
return;
}
if (!Env.getUserRolePermissions().isShowPreference())
{
return;
}
//
final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId);
AEnv.showCenterScreen(info);
}
public void removeBorders()
{
statusLine.setBorder(BorderFactory.createEmptyBorder());
statusDB.setBorder(BorderFactory.createEmptyBorder());
infoLine.setBorder(BorderFactory.createEmptyBorder());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java
| 1
|
请完成以下Java代码
|
private static Object extractValueAndResolve(
@NonNull final IAttributeStorage attributesStorage,
@NonNull final IAttributeValue attributeValue)
{
final Object value = attributeValue.getValue();
if (!attributeValue.isList())
{
return value;
}
final IAttributeValuesProvider valuesProvider = attributeValue.getAttributeValuesProvider();
final Evaluatee evalCtx = valuesProvider.prepareContext(attributesStorage);
final NamePair valueNP = valuesProvider.getAttributeValueOrNull(evalCtx, value);
final TooltipType tooltipType = Services.get(IADTableDAO.class).getTooltipTypeByTableName(I_M_Attribute.Table_Name);
return LookupValue.fromNamePair(valueNP, null, tooltipType);
}
public static DocumentFieldWidgetType extractWidgetType(final IAttributeValue attributeValue)
{
if (attributeValue.isList())
{
final I_M_Attribute attribute = attributeValue.getM_Attribute();
if (attribute.isHighVolume())
{
return DocumentFieldWidgetType.Lookup;
}
else
{
return DocumentFieldWidgetType.List;
}
}
else if (attributeValue.isStringValue())
{
return DocumentFieldWidgetType.Text;
}
else if (attributeValue.isNumericValue())
{
return DocumentFieldWidgetType.Number;
}
else if (attributeValue.isDateValue())
{
return DocumentFieldWidgetType.LocalDate;
}
else
{
throw new IllegalArgumentException("Cannot extract widgetType from " + attributeValue);
}
}
@NonNull
private static Optional<DocumentLayoutElementDescriptor> getClearanceNoteLayoutElement(@NonNull final I_M_HU hu)
{
if (Check.isBlank(hu.getClearanceNote()))
|
{
return Optional.empty();
}
final boolean isDisplayedClearanceStatus = Services.get(ISysConfigBL.class).getBooleanValue(SYS_CONFIG_CLEARANCE, true);
if (!isDisplayedClearanceStatus)
{
return Optional.empty();
}
return Optional.of(createClearanceNoteLayoutElement());
}
@NonNull
private static DocumentLayoutElementDescriptor createClearanceNoteLayoutElement()
{
final ITranslatableString caption = Services.get(IMsgBL.class).translatable(I_M_HU.COLUMNNAME_ClearanceNote);
return DocumentLayoutElementDescriptor.builder()
.setCaption(caption)
.setWidgetType(DocumentFieldWidgetType.Text)
.addField(DocumentLayoutElementFieldDescriptor
.builder(I_M_HU.COLUMNNAME_ClearanceNote)
.setPublicField(true))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesHelper.java
| 1
|
请完成以下Java代码
|
public final void setValue(Bindings bindings, ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", getStructuralId(bindings)));
}
public final MethodInfo getMethodInfo(
Bindings bindings,
ELContext context,
Class<?> returnType,
Class<?>[] paramTypes
) {
return null;
}
public final Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
|
Class<?>[] paramTypes,
Object[] paramValues
) {
throw new ELException(LocalMessages.get("error.method.invalid", getStructuralId(bindings)));
}
public final boolean isLeftValue() {
return false;
}
public boolean isMethodInvocation() {
return false;
}
public final ValueReference getValueReference(Bindings bindings, ELContext context) {
return null;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstRightValue.java
| 1
|
请完成以下Java代码
|
public FromToAmountRange getFrToAmt() {
return frToAmt;
}
/**
* Sets the value of the frToAmt property.
*
* @param value
* allowed object is
* {@link FromToAmountRange }
*
*/
public void setFrToAmt(FromToAmountRange value) {
this.frToAmt = value;
}
/**
* Gets the value of the eqAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getEQAmt() {
return eqAmt;
}
/**
* Sets the value of the eqAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setEQAmt(BigDecimal value) {
|
this.eqAmt = value;
}
/**
* Gets the value of the neqAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getNEQAmt() {
return neqAmt;
}
/**
* Sets the value of the neqAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setNEQAmt(BigDecimal value) {
this.neqAmt = 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\ImpliedCurrencyAmountRangeChoice.java
| 1
|
请完成以下Java代码
|
public UserEventListenerInstanceQuery asc() {
innerQuery.asc();
return this;
}
@Override
public UserEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
}
@Override
public UserEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this;
}
@Override
public UserEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return innerQuery.count();
}
@Override
|
public UserEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return UserEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<UserEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<UserEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<UserEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(UserEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\UserEventListenerInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public final class RegisteredClientOAuth2ClientRegistrationConverter
implements Converter<RegisteredClient, OAuth2ClientRegistration> {
@Override
public OAuth2ClientRegistration convert(RegisteredClient registeredClient) {
// @formatter:off
OAuth2ClientRegistration.Builder builder = OAuth2ClientRegistration.builder()
.clientId(registeredClient.getClientId())
.clientIdIssuedAt(registeredClient.getClientIdIssuedAt())
.clientName(registeredClient.getClientName());
builder
.tokenEndpointAuthenticationMethod(registeredClient.getClientAuthenticationMethods().iterator().next().getValue());
if (registeredClient.getClientSecret() != null) {
builder.clientSecret(registeredClient.getClientSecret());
}
if (registeredClient.getClientSecretExpiresAt() != null) {
builder.clientSecretExpiresAt(registeredClient.getClientSecretExpiresAt());
}
if (!CollectionUtils.isEmpty(registeredClient.getRedirectUris())) {
builder.redirectUris((redirectUris) ->
redirectUris.addAll(registeredClient.getRedirectUris()));
}
builder.grantTypes((grantTypes) ->
registeredClient.getAuthorizationGrantTypes().forEach((authorizationGrantType) ->
grantTypes.add(authorizationGrantType.getValue())));
|
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) {
builder.responseType(OAuth2AuthorizationResponseType.CODE.getValue());
}
if (!CollectionUtils.isEmpty(registeredClient.getScopes())) {
builder.scopes((scopes) ->
scopes.addAll(registeredClient.getScopes()));
}
ClientSettings clientSettings = registeredClient.getClientSettings();
if (clientSettings.getJwkSetUrl() != null) {
builder.jwkSetUrl(clientSettings.getJwkSetUrl());
}
return builder.build();
// @formatter:on
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\converter\RegisteredClientOAuth2ClientRegistrationConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static MaterialDescriptor toMaterialDescriptor(@NonNull final I_MD_Candidate candidate)
{
return toMaterialDescriptorBuilder(candidate)
.quantity(candidate.getQty())
.build();
}
@NonNull
private static MaterialDescriptor.MaterialDescriptorBuilder toMaterialDescriptorBuilder(@NonNull final I_MD_Candidate candidate)
{
final ProductDescriptor productDescriptor = ProductDescriptor.forProductAndAttributes(candidate.getM_Product_ID(),
AttributesKey.ofString(candidate.getStorageAttributesKey()));
return MaterialDescriptor.builder()
.date(TimeUtil.asInstant(candidate.getDateProjected()))
.productDescriptor(productDescriptor)
.warehouseId(WarehouseId.ofRepoId(candidate.getM_Warehouse_ID()));
}
@NonNull
private static CandidatesQuery buildCandidateStockQueryForReplacingOld(@NonNull final I_MD_Candidate candidateRecord)
{
return CandidatesQuery.builder()
.materialDescriptorQuery(buildMaterialDescriptorQueryForReplacingOld(candidateRecord))
.type(CandidateType.STOCK)
.matchExactStorageAttributesKey(true)
.build();
}
@NonNull
private static MaterialDescriptorQuery buildMaterialDescriptorQueryForReplacingOld(@NonNull final I_MD_Candidate oldCandidateRecord)
{
final Instant endOfTheDay = oldCandidateRecord.getDateProjected()
.toInstant()
.plus(1, ChronoUnit.DAYS)
.truncatedTo(ChronoUnit.DAYS);
return MaterialDescriptorQuery
.builder()
.warehouseId(WarehouseId.ofRepoId(oldCandidateRecord.getM_Warehouse_ID()))
.productId(oldCandidateRecord.getM_Product_ID())
.storageAttributesKey(AttributesKey.ofString(oldCandidateRecord.getStorageAttributesKey()))
.customer(BPartnerClassifier.specificOrAny(BPartnerId.ofRepoIdOrNull(oldCandidateRecord.getC_BPartner_Customer_ID())))
.customerIdOperator(MaterialDescriptorQuery.CustomerIdOperator.GIVEN_ID_ONLY)
|
.timeRangeEnd(DateAndSeqNo.builder()
.date(endOfTheDay)
.operator(DateAndSeqNo.Operator.EXCLUSIVE)
.build())
.build();
}
private static boolean isMaterialDescriptorChanged(
@NonNull final I_MD_Candidate oldCandidateRecord,
@NonNull final I_MD_Candidate candidateRecord)
{
return !candidateRecord.getDateProjected().equals(oldCandidateRecord.getDateProjected())
|| !candidateRecord.getStorageAttributesKey().equals(oldCandidateRecord.getStorageAttributesKey())
|| oldCandidateRecord.getM_Warehouse_ID() != candidateRecord.getM_Warehouse_ID()
|| oldCandidateRecord.getM_Product_ID() != candidateRecord.getM_Product_ID();
}
private static boolean isUpdateOldStockRequired(
@NonNull final ModelChangeType timingType,
@NonNull final I_MD_Candidate oldCandidateRecord,
@NonNull final I_MD_Candidate candidate)
{
return timingType.isDelete() || (timingType.isChange() && isMaterialDescriptorChanged(oldCandidateRecord, candidate));
}
private static boolean isUpdateCurrentStockRequired(@NonNull final ModelChangeType timingType)
{
return !timingType.isDelete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\interceptor\MD_Candidate.java
| 2
|
请完成以下Java代码
|
public I_M_ShipmentSchedule getSched()
{
return shipmentSchedule;
}
public ShipmentScheduleId getShipmentScheduleId()
{
return ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
}
/**
* @return shipment schedule's QtyToDeliver_Override or <code>null</code>
*/
public BigDecimal getQtyOverride()
{
return InterfaceWrapperHelper.getValueOrNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
}
public BigDecimal getInitialSchedQtyDelivered()
{
return initialSchedQtyDelivered;
}
public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt)
{
|
shipmentSchedule.setLineNetAmt(lineNetAmt);
}
@Nullable
public String getSalesOrderPORef()
{
return salesOrder.map(I_C_Order::getPOReference).orElse(null);
}
@Nullable
public InputDataSourceId getSalesOrderADInputDatasourceID()
{
if(!salesOrder.isPresent())
{
return null;
}
final I_C_Order orderRecord = salesOrder.get();
return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java
| 1
|
请完成以下Java代码
|
public class PatternPerformanceComparison {
private static final String PATTERN = "\\d*[02468]";
private static List<String> values;
private static Matcher matcherFromPreCompiledPattern;
private static Pattern preCompiledPattern;
public static void main(String[] args) throws IOException, RunnerException {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
public void matcherFromPreCompiledPatternResetMatches(Blackhole bh) {
//With pre-compiled pattern and reusing the matcher
// 1 Pattern object created
// 1 Matcher objects created
for (String value : values) {
bh.consume(matcherFromPreCompiledPattern.reset(value).matches());
}
}
@Benchmark
public void preCompiledPatternMatcherMatches(Blackhole bh) {
// With pre-compiled pattern
// 1 Pattern object created
// 5_000_000 Matcher objects created
for (String value : values) {
bh.consume(preCompiledPattern.matcher(value).matches());
}
}
@Benchmark
public void patternCompileMatcherMatches(Blackhole bh) {
// Above approach "Pattern.matches(PATTERN, value)" makes this internally
// 5_000_000 Pattern objects created
// 5_000_000 Matcher objects created
for (String value : values) {
bh.consume(Pattern.compile(PATTERN).matcher(value).matches());
}
}
@Benchmark
public void patternMatches(Blackhole bh) {
// Above approach "value.matches(PATTERN)" makes this internally
|
// 5_000_000 Pattern objects created
// 5_000_000 Matcher objects created
for (String value : values) {
bh.consume(Pattern.matches(PATTERN, value));
}
}
@Benchmark
public void stringMatchs(Blackhole bh) {
// 5_000_000 Pattern objects created
// 5_000_000 Matcher objects created
Instant start = Instant.now();
for (String value : values) {
bh.consume(value.matches(PATTERN));
}
}
@Setup()
public void setUp() {
preCompiledPattern = Pattern.compile(PATTERN);
matcherFromPreCompiledPattern = preCompiledPattern.matcher("");
values = new ArrayList<>();
for (int x = 1; x <= 5_000_000; x++) {
values.add(String.valueOf(x));
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-regex-3\src\main\java\com\baeldung\patternreuse\PatternPerformanceComparison.java
| 1
|
请完成以下Java代码
|
public boolean isSubscribed()
{
return isActive() && getOptOutDate() == null;
} // isSubscribed
/**
* String representation
* @return info
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer ("MContactInterest[")
.append("R_InterestArea_ID=").append(getR_InterestArea_ID())
.append(",AD_User_ID=").append(getAD_User_ID())
.append(",Subscribed=").append(isSubscribed())
.append ("]");
return sb.toString ();
} // toString
/**************************************************************************
|
* @param args ignored
*/
public static void main (String[] args)
{
org.compiere.Adempiere.startup(true);
int R_InterestArea_ID = 1000002;
int AD_User_ID = 1000002;
MContactInterest ci = MContactInterest.get(Env.getCtx(), R_InterestArea_ID, AD_User_ID, false, null);
ci.subscribe();
ci.save();
//
ci = MContactInterest.get(Env.getCtx(), R_InterestArea_ID, AD_User_ID, false, null);
} // main
} // MContactInterest
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContactInterest.java
| 1
|
请完成以下Java代码
|
private void reverseCostCollectorsGeneratedOnClose(final PPOrderId ppOrderId)
{
final ArrayList<I_PP_Cost_Collector> costCollectors = new ArrayList<>(ppCostCollectorDAO.getByOrderId(ppOrderId));
// Sort the cost collectors in reverse order of their creation,
// just to make sure we are reversing the effect from last one to first one.
costCollectors.sort(ModelByIdComparator.getInstance().reversed());
for (final I_PP_Cost_Collector cc : costCollectors)
{
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(cc.getDocStatus());
if (docStatus.isReversedOrVoided())
{
continue;
}
|
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
if (costCollectorType == CostCollectorType.UsageVariance)
{
if (docStatus.isClosed())
{
cc.setDocStatus(DocStatus.Completed.getCode());
ppCostCollectorDAO.save(cc);
}
docActionBL.processEx(cc, IDocument.ACTION_Reverse_Correct, DocStatus.Reversed.getCode());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_UnClose.java
| 1
|
请完成以下Java代码
|
public FacetCategory build()
{
return new FacetCategory(this);
}
public Builder setDisplayName(final String displayName)
{
this.displayName = displayName;
return this;
}
public Builder setDisplayNameAndTranslate(final String displayName)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final Properties ctx = Env.getCtx();
this.displayName = msgBL.translate(ctx, displayName);
return this;
}
|
public Builder setCollapsed(final boolean collapsed)
{
this.collapsed = collapsed;
return this;
}
public Builder setEagerRefresh()
{
this.eagerRefresh = true;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCategory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MyBatisArticleRepository implements ArticleRepository {
private ArticleMapper articleMapper;
public MyBatisArticleRepository(ArticleMapper articleMapper) {
this.articleMapper = articleMapper;
}
@Override
@Transactional
public void save(Article article) {
if (articleMapper.findById(article.getId()) == null) {
createNew(article);
} else {
articleMapper.update(article);
}
}
private void createNew(Article article) {
for (Tag tag : article.getTags()) {
Tag targetTag =
Optional.ofNullable(articleMapper.findTag(tag.getName()))
.orElseGet(
() -> {
articleMapper.insertTag(tag);
return tag;
});
|
articleMapper.insertArticleTagRelation(article.getId(), targetTag.getId());
}
articleMapper.insert(article);
}
@Override
public Optional<Article> findById(String id) {
return Optional.ofNullable(articleMapper.findById(id));
}
@Override
public Optional<Article> findBySlug(String slug) {
return Optional.ofNullable(articleMapper.findBySlug(slug));
}
@Override
public void remove(Article article) {
articleMapper.delete(article.getId());
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\infrastructure\repository\MyBatisArticleRepository.java
| 2
|
请完成以下Java代码
|
private CostAmount getPOCost(final AcctSchema as)
{
// Uses PO Date
String sql = "SELECT currencyConvert(ol.PriceActual, o.C_Currency_ID, ?, o.DateOrdered, o.C_ConversionType_ID, ?, ?) "
+ "FROM C_OrderLine ol"
+ " INNER JOIN M_InOutLine iol ON (iol.C_OrderLine_ID=ol.C_OrderLine_ID)"
+ " INNER JOIN C_Order o ON (o.C_Order_ID=ol.C_Order_ID) "
+ "WHERE iol.M_InOutLine_ID=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
pstmt.setInt(1, as.getCurrencyId().getRepoId());
pstmt.setInt(2, getClientId().getRepoId());
pstmt.setInt(3, getOrgId().getRepoId());
pstmt.setInt(4, m_issue.getM_InOutLine_ID());
rs = pstmt.executeQuery();
final BigDecimal costs;
if (rs.next())
{
costs = rs.getBigDecimal(1);
logger.debug("POCost = {}", costs);
}
else
{
logger.warn("Not found for M_InOutLine_ID={}", m_issue.getM_InOutLine_ID());
costs = BigDecimal.ZERO;
}
return CostAmount.of(costs, as.getCurrencyId());
}
catch (Exception e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
pstmt = null;
rs = null;
}
} // getPOCost();
/**
* Get Labor Cost from Expense Report
*
* @param as Account Schema
* @return Unit Labor Cost
*/
private CostAmount getLaborCost(final AcctSchema as)
{
|
String sql = "SELECT ConvertedAmt, Qty" +
" FROM " + I_S_TimeExpenseLine.Table_Name +
" WHERE S_TimeExpenseLine.S_TimeExpenseLine_ID = ?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
pstmt.setInt(1, m_issue.getS_TimeExpenseLine_ID());
rs = pstmt.executeQuery();
BigDecimal costs;
if (rs.next())
{
costs = rs.getBigDecimal(1);
final BigDecimal qty = rs.getBigDecimal(2);
costs = costs.multiply(qty);
logger.debug("ExpLineCost = {}", costs);
}
else
{
logger.warn("Not found for S_TimeExpenseLine_ID={}", m_issue.getS_TimeExpenseLine_ID());
costs = BigDecimal.ZERO;
}
return CostAmount.of(costs, as.getCurrencyId());
}
catch (Exception e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
pstmt = null;
rs = null;
}
} // getLaborCost
@NonNull
private Account getProjectAccount(final ProjectAccountType acctType, final AcctSchema as)
{
final ProjectId projectId = getC_Project_ID();
if (projectId == null)
{
throw new AdempiereException("Project not set");
}
return getAccountProvider().getProjectAccount(as.getId(), projectId, acctType);
}
} // DocProjectIssue
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_ProjectIssue.java
| 1
|
请完成以下Java代码
|
public static void findOneAndUpdate() {
Document sort = new Document("roll_no", 1);
Document projection = new Document("_id", 0).append("student_id", 1)
.append("address", 1);
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
.sort(sort)
.projection(projection)
.returnDocument(ReturnDocument.AFTER));
System.out.println("resultDocument:- " + resultDocument);
}
public static void setup() {
if (mongoClient == null) {
mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student");
}
}
public static void main(String[] args) {
//
// Connect to cluster (default is localhost:27017)
//
setup();
//
// Update a document using updateOne method
//
updateOne();
//
// Update documents using updateMany method
//
updateMany();
|
//
// replace a document using replaceOne method
//
replaceOne();
//
// replace a document using findOneAndReplace method
//
findOneAndReplace();
//
// Update a document using findOneAndUpdate method
//
findOneAndUpdate();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\update\UpdateFields.java
| 1
|
请完成以下Java代码
|
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getMinAge() {
return minAge;
}
public void setMinAge(Integer minAge) {
this.minAge = minAge;
}
public Integer getMaxAge() {
return maxAge;
}
public void setMaxAge(Integer maxAge) {
this.maxAge = maxAge;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getIntroduction() {
|
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\param\UserDetailParam.java
| 1
|
请完成以下Java代码
|
public class SysPermissionDataRuleModel {
/**
* id
*/
private String id;
/**
* 对应的菜单id
*/
private String permissionId;
/**
* 规则名称
*/
private String ruleName;
/**
* 字段
*/
private String ruleColumn;
/**
* 条件
*/
private String ruleConditions;
/**
* 规则值
*/
private String ruleValue;
/**
* 创建时间
*/
private Date createTime;
/**
* 创建人
*/
private String createBy;
/**
* 修改时间
*/
private Date updateTime;
/**
* 修改人
*/
private String updateBy;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPermissionId() {
return permissionId;
}
public void setPermissionId(String permissionId) {
this.permissionId = permissionId;
}
public String getRuleName() {
return ruleName;
|
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public String getRuleColumn() {
return ruleColumn;
}
public void setRuleColumn(String ruleColumn) {
this.ruleColumn = ruleColumn;
}
public String getRuleConditions() {
return ruleConditions;
}
public void setRuleConditions(String ruleConditions) {
this.ruleConditions = ruleConditions;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysPermissionDataRuleModel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HistoricTaskLogEntryQuery subScopeId(String subScopeId) {
this.subScopeId = subScopeId;
return this;
}
@Override
public HistoricTaskLogEntryQuery scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public HistoricTaskLogEntryQuery from(Date fromDate) {
this.fromDate = fromDate;
return this;
}
@Override
public HistoricTaskLogEntryQuery to(Date toDate) {
this.toDate = toDate;
return this;
}
@Override
public HistoricTaskLogEntryQuery tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public HistoricTaskLogEntryQuery fromLogNumber(long fromLogNumber) {
this.fromLogNumber = fromLogNumber;
return this;
}
@Override
public HistoricTaskLogEntryQuery toLogNumber(long toLogNumber) {
this.toLogNumber = toLogNumber;
return this;
}
public String getTaskId() {
return taskId;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public String getSubScopeId() {
|
return subScopeId;
}
public String getScopeType() {
return scopeType;
}
public Date getFromDate() {
return fromDate;
}
public Date getToDate() {
return toDate;
}
public String getTenantId() {
return tenantId;
}
public long getFromLogNumber() {
return fromLogNumber;
}
public long getToLogNumber() {
return toLogNumber;
}
@Override
public long executeCount(CommandContext commandContext) {
return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesCountByQueryCriteria(this);
}
@Override
public List<HistoricTaskLogEntry> executeList(CommandContext commandContext) {
return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesByQueryCriteria(this);
}
@Override
public HistoricTaskLogEntryQuery orderByLogNumber() {
orderBy(HistoricTaskLogEntryQueryProperty.LOG_NUMBER);
return this;
}
@Override
public HistoricTaskLogEntryQuery orderByTimeStamp() {
orderBy(HistoricTaskLogEntryQueryProperty.TIME_STAMP);
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskLogEntryQueryImpl.java
| 2
|
请完成以下Java代码
|
private DocumentsRepository getDocumentsRepository()
{
return entityDescriptor.getDataBinding().getDocumentsRepository();
}
public Builder setRecordId(@Nullable final DocumentId documentId)
{
recordIds = documentId != null
? ImmutableSet.of(documentId)
: ImmutableSet.of();
return this;
}
public Builder setRecordIds(@Nullable final Collection<DocumentId> documentIds)
{
recordIds = documentIds != null
? ImmutableSet.copyOf(documentIds)
: ImmutableSet.of();
return this;
}
public Builder setParentDocument(final Document parentDocument)
{
this.parentDocument = parentDocument;
return this;
}
public Builder noSorting()
{
_noSorting = true;
_orderBys = null;
return this;
}
public boolean isNoSorting()
{
return _noSorting;
}
public Builder addOrderBy(@NonNull final DocumentQueryOrderBy orderBy)
{
Check.assume(!_noSorting, "sorting not disabled for {}", this);
if (_orderBys == null)
{
_orderBys = new ArrayList<>();
}
_orderBys.add(orderBy);
|
return this;
}
public Builder setOrderBys(final DocumentQueryOrderByList orderBys)
{
if (orderBys == null || orderBys.isEmpty())
{
_orderBys = null;
}
else
{
_orderBys = new ArrayList<>(orderBys.toList());
}
return this;
}
private DocumentQueryOrderByList getOrderBysEffective()
{
return _noSorting
? DocumentQueryOrderByList.EMPTY
: DocumentQueryOrderByList.ofList(_orderBys);
}
public Builder setFirstRow(final int firstRow)
{
this.firstRow = firstRow;
return this;
}
public Builder setPageLength(final int pageLength)
{
this.pageLength = pageLength;
return this;
}
public Builder setExistingDocumentsSupplier(final Function<DocumentId, Document> existingDocumentsSupplier)
{
this.existingDocumentsSupplier = existingDocumentsSupplier;
return this;
}
public Builder setChangesCollector(IDocumentChangesCollector changesCollector)
{
this.changesCollector = changesCollector;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQuery.java
| 1
|
请完成以下Java代码
|
public SqlViewRowsWhereClause buildSqlWhereClause(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds)
{
return SqlViewSelectionQueryBuilder.prepareSqlWhereClause()
.sqlTableAlias(I_M_HU.Table_Name)
.keyColumnNamesMap(SqlViewKeyColumnNamesMap.ofIntKeyField(I_M_HU.COLUMNNAME_M_HU_ID))
.selectionId(selection.getSelectionId())
.rowIds(rowIds)
.rowIdsConverter(getRowIdsConverter())
.build();
}
@Override
public void warmUp(@NonNull final Set<HuId> huIds)
{
InterfaceWrapperHelper.loadByRepoIdAwares(huIds, I_M_HU.class); // caches the given HUs with one SQL query
huReservationService.warmup(huIds);
}
|
@Nullable
private JSONLookupValue getHUClearanceStatusLookupValue(@NonNull final I_M_HU hu)
{
final ClearanceStatus huClearanceStatus = ClearanceStatus.ofNullableCode(hu.getClearanceStatus());
if (huClearanceStatus == null)
{
return null;
}
final ITranslatableString huClearanceStatusCaption = handlingUnitsBL.getClearanceStatusCaption(huClearanceStatus);
return JSONLookupValue.of(huClearanceStatus.getCode(), huClearanceStatusCaption.translate(Env.getAD_Language()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\SqlHUEditorViewRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object updateFirst() {
// 创建条件对象
Criteria criteria = Criteria.where("name").is("zhangsan");
// 创建查询对象,然后将条件对象添加到其中,并设置排序
Query query = new Query(criteria).with(Sort.by("age").ascending());
// 创建更新对象,并设置更新的内容
Update update = new Update().set("age", 30).set("name", "zhangsansan");
// 执行更新
UpdateResult result = mongoTemplate.updateFirst(query, update, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
log.info("更新结果:{}", resultInfo);
return resultInfo;
}
/**
* 更新【匹配查询】到的【文档数据集合】中的【所有数据】
*
|
* @return 执行更新的结果
*/
public Object updateMany() {
// 创建条件对象
Criteria criteria = Criteria.where("age").gt(28);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 设置更新字段和更新的内容
Update update = new Update().set("age", 29).set("salary", "1999");
// 执行更新
UpdateResult result = mongoTemplate.updateMulti(query, update, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "总共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
log.info("更新结果:{}", resultInfo);
return resultInfo;
}
}
|
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\UpdateService.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.