instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private static void buildDisabled(StringBuilder sb, @Nullable Object[] elements) {
for (Object element : elements) {
if (!(element instanceof AnsiElement) && element != null) {
sb.append(element);
}
}
}
private static boolean isEnabled() {
if (enabled == Enabled.DETECT) {
if (ansiCapable == null) {
ansiCapable = detectIfAnsiCapable();
}
return ansiCapable;
}
return enabled == Enabled.ALWAYS;
}
private static boolean detectIfAnsiCapable() {
try {
if (Boolean.FALSE.equals(consoleAvailable)) {
return false;
}
if (consoleAvailable == null) {
Console console = System.console();
if (console == null) {
return false;
}
Method isTerminalMethod = ClassUtils.getMethodIfAvailable(Console.class, "isTerminal");
if (isTerminalMethod != null) {
Boolean isTerminal = (Boolean) isTerminalMethod.invoke(console);
if (Boolean.FALSE.equals(isTerminal)) {
return false;
}
}
}
return !(OPERATING_SYSTEM_NAME.contains("win"));
}
catch (Throwable ex) {
return false;
}
}
/**
* Possible values to pass to {@link AnsiOutput#setEnabled}. Determines when to output
* ANSI escape sequences for coloring application output.
*/ | public enum Enabled {
/**
* Try to detect whether ANSI coloring capabilities are available. The default
* value for {@link AnsiOutput}.
*/
DETECT,
/**
* Enable ANSI-colored output.
*/
ALWAYS,
/**
* Disable ANSI-colored output.
*/
NEVER
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiOutput.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BrandInsertReq extends AbsReq {
/** 主键 */
private String id;
/** 产品品牌名称 */
private String brand;
/** 品牌logo url*/
private String brandLogoUrl;
/** 品牌所属企业 */
private String companyEntityId;
/** 品牌排序(权值越高,排名越前) */
private int sort;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getBrandLogoUrl() {
return brandLogoUrl;
}
public void setBrandLogoUrl(String brandLogoUrl) {
this.brandLogoUrl = brandLogoUrl;
}
public String getCompanyEntityId() {
return companyEntityId; | }
public void setCompanyEntityId(String companyEntityId) {
this.companyEntityId = companyEntityId;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
@Override
public String toString() {
return "BrandInsertReq{" +
"id='" + id + '\'' +
", brand='" + brand + '\'' +
", brandLogoUrl='" + brandLogoUrl + '\'' +
", companyEntityId='" + companyEntityId + '\'' +
", sort=" + sort +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\BrandInsertReq.java | 2 |
请完成以下Java代码 | protected void addHeader(Headers headers, String headerName, Class<?> clazz) {
if (this.classIdMapping.containsKey(clazz)) {
headers.add(new RecordHeader(headerName, this.classIdMapping.get(clazz)));
}
else {
headers.add(new RecordHeader(headerName, clazz.getName().getBytes(StandardCharsets.UTF_8)));
}
}
protected String retrieveHeader(Headers headers, String headerName) {
String classId = retrieveHeaderAsString(headers, headerName);
if (classId == null) {
throw new MessageConversionException(
"failed to convert Message content. Could not resolve " + headerName + " in header");
}
return classId;
}
protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) {
Header header = headers.lastHeader(headerName);
if (header != null) {
String classId = null;
if (header.value() != null) {
classId = new String(header.value(), StandardCharsets.UTF_8);
}
return classId;
}
return null;
}
private void createReverseMap() {
this.classIdMapping.clear();
for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) {
String id = entry.getKey();
Class<?> clazz = entry.getValue();
this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8));
}
} | public Map<String, Class<?>> getIdClassMapping() {
return Collections.unmodifiableMap(this.idClassMapping);
}
/**
* Configure the TypeMapper to use default key type class.
* @param isKey Use key type headers if true
* @since 2.1.3
*/
public void setUseForKey(boolean isKey) {
if (isKey) {
setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME);
setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME);
setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java | 1 |
请完成以下Java代码 | public java.lang.String getJSONPathMetasfreshID()
{
return get_ValueAsString(COLUMNNAME_JSONPathMetasfreshID);
}
@Override
public void setJSONPathSalesRepID (final @Nullable java.lang.String JSONPathSalesRepID)
{
set_Value (COLUMNNAME_JSONPathSalesRepID, JSONPathSalesRepID);
}
@Override
public java.lang.String getJSONPathSalesRepID()
{
return get_ValueAsString(COLUMNNAME_JSONPathSalesRepID);
}
@Override
public void setJSONPathShopwareID (final @Nullable java.lang.String JSONPathShopwareID)
{
set_Value (COLUMNNAME_JSONPathShopwareID, JSONPathShopwareID);
}
@Override
public java.lang.String getJSONPathShopwareID()
{
return get_ValueAsString(COLUMNNAME_JSONPathShopwareID);
}
@Override
public void setM_FreightCost_NormalVAT_Product_ID (final int M_FreightCost_NormalVAT_Product_ID)
{
if (M_FreightCost_NormalVAT_Product_ID < 1)
set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, null);
else
set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, M_FreightCost_NormalVAT_Product_ID);
}
@Override
public int getM_FreightCost_NormalVAT_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCost_NormalVAT_Product_ID);
}
@Override
public void setM_FreightCost_ReducedVAT_Product_ID (final int M_FreightCost_ReducedVAT_Product_ID)
{
if (M_FreightCost_ReducedVAT_Product_ID < 1)
set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, null);
else
set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, M_FreightCost_ReducedVAT_Product_ID);
}
@Override
public int getM_FreightCost_ReducedVAT_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else | set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
/**
* ProductLookup AD_Reference_ID=541499
* Reference name: _ProductLookup
*/
public static final int PRODUCTLOOKUP_AD_Reference_ID=541499;
/** Product Id = ProductId */
public static final String PRODUCTLOOKUP_ProductId = "ProductId";
/** Product Number = ProductNumber */
public static final String PRODUCTLOOKUP_ProductNumber = "ProductNumber";
@Override
public void setProductLookup (final java.lang.String ProductLookup)
{
set_Value (COLUMNNAME_ProductLookup, ProductLookup);
}
@Override
public java.lang.String getProductLookup()
{
return get_ValueAsString(COLUMNNAME_ProductLookup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TodoService {
private static final List<Todo> todos = new ArrayList<>();
private static int todosCount = 0;
static {
todos.add(new Todo(++todosCount, "in28minutes","Get AWS Certified 1",
LocalDate.now().plusYears(1), false ));
todos.add(new Todo(++todosCount, "in28minutes","Learn DevOps 1",
LocalDate.now().plusYears(2), false ));
todos.add(new Todo(++todosCount, "in28minutes","Learn Full Stack Development 1",
LocalDate.now().plusYears(3), false ));
}
public List<Todo> findByUsername(String username){
Predicate<? super Todo> predicate =
todo -> todo.getUsername().equalsIgnoreCase(username);
return todos.stream().filter(predicate).toList();
}
public void addTodo(String username, String description, LocalDate targetDate, boolean done) {
Todo todo = new Todo(++todosCount,username,description,targetDate,done);
todos.add(todo);
}
public void deleteById(int id) {
//todo.getId() == id | // todo -> todo.getId() == id
Predicate<? super Todo> predicate = todo -> todo.getId() == id;
todos.removeIf(predicate);
}
public Todo findById(int id) {
Predicate<? super Todo> predicate = todo -> todo.getId() == id;
Todo todo = todos.stream().filter(predicate).findFirst().get();
return todo;
}
public void updateTodo(@Valid Todo todo) {
deleteById(todo.getId());
todos.add(todo);
}
} | repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\TodoService.java | 2 |
请完成以下Java代码 | public int getM_QualityNote_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityNote_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* PerformanceType AD_Reference_ID=540689
* Reference name: R_Request.PerformanceType
*/
public static final int PERFORMANCETYPE_AD_Reference_ID=540689;
/** Liefer Performance = LP */
public static final String PERFORMANCETYPE_LieferPerformance = "LP";
/** Quality Performance = QP */
public static final String PERFORMANCETYPE_QualityPerformance = "QP";
/** Set PerformanceType.
@param PerformanceType PerformanceType */
@Override
public void setPerformanceType (java.lang.String PerformanceType)
{
set_Value (COLUMNNAME_PerformanceType, PerformanceType);
}
/** Get PerformanceType.
@return PerformanceType */ | @Override
public java.lang.String getPerformanceType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PerformanceType);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_QualityNote.java | 1 |
请完成以下Java代码 | public void setProductValue (final java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setProjectValue (final @Nullable java.lang.String ProjectValue)
{
set_Value (COLUMNNAME_ProjectValue, ProjectValue);
}
@Override
public java.lang.String getProjectValue()
{
return get_ValueAsString(COLUMNNAME_ProjectValue);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated); | }
@Override
public BigDecimal getQtyCalculated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM()
{
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setWarehouseValue (final java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return get_ValueAsString(COLUMNNAME_WarehouseValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java | 1 |
请完成以下Java代码 | protected void checkInstallationIdLockExists(CommandContext commandContext) {
PropertyEntity installationIdProperty = commandContext.getPropertyManager().findPropertyById("installationId.lock");
if (installationIdProperty == null) {
LOG.noInstallationIdLockPropertyFound();
}
}
protected void updateTelemetryData(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.getProcessEngineConfiguration();
String installationId = processEngineConfiguration.getInstallationId();
TelemetryDataImpl telemetryData = processEngineConfiguration.getTelemetryData();
// set installationId in the telemetry data
telemetryData.setInstallation(installationId); | // set the persisted license key in the telemetry data and registry
ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineConfiguration.getManagementService();
String licenseKey = managementService.getLicenseKey();
if (licenseKey != null) {
LicenseKeyDataImpl licenseKeyData = LicenseKeyDataImpl.fromRawString(licenseKey);
managementService.setLicenseKeyForDiagnostics(licenseKeyData);
telemetryData.getProduct().getInternals().setLicenseKey(licenseKeyData);
}
}
protected void acquireExclusiveInstallationIdLock(CommandContext commandContext) {
PropertyManager propertyManager = commandContext.getPropertyManager();
//exclusive lock
propertyManager.acquireExclusiveLockForInstallationId();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\BootstrapEngineCommand.java | 1 |
请完成以下Java代码 | public String getProductBrand() {
return productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSn() {
return productSn;
}
public void setProductSn(String productSn) {
this.productSn = productSn;
}
public String getProductAttr() {
return productAttr;
}
public void setProductAttr(String productAttr) {
this.productAttr = productAttr;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode()); | sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", productSkuId=").append(productSkuId);
sb.append(", memberId=").append(memberId);
sb.append(", quantity=").append(quantity);
sb.append(", price=").append(price);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productSubTitle=").append(productSubTitle);
sb.append(", productSkuCode=").append(productSkuCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", createDate=").append(createDate);
sb.append(", modifyDate=").append(modifyDate);
sb.append(", deleteStatus=").append(deleteStatus);
sb.append(", productCategoryId=").append(productCategoryId);
sb.append(", productBrand=").append(productBrand);
sb.append(", productSn=").append(productSn);
sb.append(", productAttr=").append(productAttr);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItem.java | 1 |
请完成以下Java代码 | public class BaseReadTsKvQuery extends BaseTsKvQuery implements ReadTsKvQuery {
private final AggregationParams aggParameters;
private final int limit;
private final String order;
public BaseReadTsKvQuery(String key, long startTs, long endTs, long interval, int limit, Aggregation aggregation) {
this(key, startTs, endTs, interval, limit, aggregation, "DESC");
}
public BaseReadTsKvQuery(String key, long startTs, long endTs, long interval, int limit, Aggregation aggregation, String descOrder) {
this(key, startTs, endTs, AggregationParams.of(aggregation, IntervalType.MILLISECONDS, ZoneId.systemDefault(), interval), limit, descOrder);
}
public BaseReadTsKvQuery(String key, long startTs, long endTs, AggregationParams parameters, int limit) {
this(key, startTs, endTs, parameters, limit, "DESC");
}
public BaseReadTsKvQuery(String key, long startTs, long endTs, AggregationParams parameters, int limit, String order) {
super(key, startTs, endTs); | this.aggParameters = parameters;
this.limit = limit;
this.order = order;
}
public BaseReadTsKvQuery(String key, long startTs, long endTs) {
this(key, startTs, endTs, AggregationParams.milliseconds(Aggregation.AVG, endTs - startTs), 1, "DESC");
}
public BaseReadTsKvQuery(String key, long startTs, long endTs, int limit, String order) {
this(key, startTs, endTs, AggregationParams.none(), limit, order);
}
public BaseReadTsKvQuery(ReadTsKvQuery query, long startTs, long endTs) {
super(query.getId(), query.getKey(), startTs, endTs);
this.aggParameters = query.getAggParameters();
this.limit = query.getLimit();
this.order = query.getOrder();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BaseReadTsKvQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void log(
final String queueName,
final String direction,
final Object message,
final String eventId,
final String relatedEventId)
{
try
{
final RabbitMQAuditEntry entry = new RabbitMQAuditEntry();
entry.setQueue(queueName);
entry.setDirection(direction);
entry.setContent(Ascii.truncate(convertToString(message), RabbitMQAuditEntry.CONTENT_LENGTH, "..."));
entry.setEventId(eventId);
entry.setRelatedEventId(relatedEventId);
repository.save(entry);
}
catch (Exception ex)
{
logger.warn("Failed saving audit entry for queueName={}, direction={}, message=`{}`.", queueName, direction, message, ex); | }
}
private String convertToString(@NonNull final Object message)
{
try
{
return Constants.PROCUREMENT_WEBUI_OBJECT_MAPPER.writeValueAsString(message);
}
catch (final Exception ex)
{
logger.warn("Failed converting message to JSON: {}. Returning toString().", message, ex);
return message.toString();
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\RabbitMQAuditService.java | 2 |
请完成以下Java代码 | public class PasswordPolicyAwareContextSource extends DefaultSpringSecurityContextSource {
public PasswordPolicyAwareContextSource(String providerUrl) {
super(providerUrl);
}
@Override
public DirContext getContext(String principal, String credentials) throws PasswordPolicyException {
if (principal.equals(getUserDn())) {
return super.getContext(principal, credentials);
}
this.logger.trace(LogMessage.format("Binding as %s, prior to reconnect as user %s", getUserDn(), principal));
// First bind as manager user before rebinding as the specific principal.
LdapContext ctx = (LdapContext) super.getContext(getUserDn(), getPassword());
Control[] rctls = { new PasswordPolicyControl(false) };
try {
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
ctx.reconnect(rctls);
}
catch (javax.naming.NamingException ex) {
PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(ctx);
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Failed to bind with %s", ctrl), ex);
} | LdapUtils.closeContext(ctx);
if (ctrl != null && ctrl.isLocked()) {
throw new PasswordPolicyException(ctrl.getErrorStatus());
}
throw LdapUtils.convertLdapException(ex);
}
this.logger.debug(LogMessage.of(() -> "Bound with " + PasswordPolicyControlExtractor.extractControl(ctx)));
return ctx;
}
@Override
@SuppressWarnings("unchecked")
protected Hashtable getAuthenticatedEnv(String principal, String credentials) {
Hashtable<String, Object> env = super.getAuthenticatedEnv(principal, credentials);
env.put(LdapContext.CONTROL_FACTORIES, PasswordPolicyControlFactory.class.getName());
return env;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\ppolicy\PasswordPolicyAwareContextSource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DateTimeType {
@XmlElement(required = true)
protected String date;
@XmlElement(required = true)
protected String time;
/**
* Gets the value of the date property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDate() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDate(String value) {
this.date = value;
}
/**
* Gets the value of the time property.
*
* @return
* possible object is
* {@link String }
* | */
public String getTime() {
return time;
}
/**
* Sets the value of the time property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTime(String value) {
this.time = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\DateTimeType.java | 2 |
请完成以下Java代码 | public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* InvoicableQtyBasedOn AD_Reference_ID=541023
* Reference name: InvoicableQtyBasedOn
*/
public static final int INVOICABLEQTYBASEDON_AD_Reference_ID=541023;
/** Nominal = Nominal */
public static final String INVOICABLEQTYBASEDON_Nominal = "Nominal";
/** CatchWeight = CatchWeight */
public static final String INVOICABLEQTYBASEDON_CatchWeight = "CatchWeight";
@Override
public void setInvoicableQtyBasedOn (final java.lang.String InvoicableQtyBasedOn)
{
set_Value (COLUMNNAME_InvoicableQtyBasedOn, InvoicableQtyBasedOn);
}
@Override
public java.lang.String getInvoicableQtyBasedOn()
{
return get_ValueAsString(COLUMNNAME_InvoicableQtyBasedOn);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPriceList (final @Nullable BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList); | }
@Override
public BigDecimal getPriceList()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceStd (final BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
@Override
public BigDecimal getPriceStd()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign_Price.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JpaOrdersConfig {
@Resource(name = "hibernateVendorProperties")
private Map<String, Object> hibernateVendorProperties;
/**
* 创建 orders 数据源
*/
@Bean(name = "ordersDataSource")
@ConfigurationProperties(prefix = "spring.datasource.orders")
@Primary // 需要特殊添加,否则初始化会有问题
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
/**
* 创建 LocalContainerEntityManagerFactoryBean
*/
@Bean(name = DBConstants.ENTITY_MANAGER_FACTORY_ORDERS)
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder | .dataSource(this.dataSource()) // 数据源
.properties(hibernateVendorProperties) // 获取并注入 Hibernate Vendor 相关配置
.packages("cn.iocoder.springboot.lab17.dynamicdatasource.dataobject") // 数据库实体 entity 所在包
.persistenceUnit("ordersPersistenceUnit") // 设置持久单元的名字,需要唯一
.build();
}
/**
* 创建 PlatformTransactionManager
*/
@Bean(name = DBConstants.TX_MANAGER_ORDERS)
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactory(builder).getObject());
}
} | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-springdatajpa\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\config\JpaOrdersConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HierarchyConfigId implements RepoIdAware
{
int repoId;
@JsonCreator
public static HierarchyConfigId ofRepoId(final int repoId)
{
return new HierarchyConfigId(repoId);
}
public static HierarchyConfigId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new HierarchyConfigId(repoId) : null;
}
public static int toRepoId(final HierarchyConfigId productId) | {
return productId != null ? productId.getRepoId() : -1;
}
private HierarchyConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "hierarchyConfigIdId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\algorithms\hierarchy\HierarchyConfigId.java | 2 |
请完成以下Java代码 | public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenznummer.
@param ReferenceNo
Ihre Kunden- oder Lieferantennummer beim Geschäftspartner
*/
@Override
public void setReferenceNo (java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
/** Get Referenznummer.
@return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner
*/
@Override
public java.lang.String getReferenceNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo);
}
/** Set Bewegungs-Betrag.
@param TrxAmt
Betrag einer Transaktion
*/
@Override | public void setTrxAmt (java.math.BigDecimal TrxAmt)
{
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
/** Get Bewegungs-Betrag.
@return Betrag einer Transaktion
*/
@Override
public java.math.BigDecimal getTrxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TrxAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_BankStatementLine_Ref.java | 1 |
请完成以下Java代码 | public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Authentication Token.
@param AuthToken Authentication Token */
@Override
public void setAuthToken (java.lang.String AuthToken)
{
set_Value (COLUMNNAME_AuthToken, AuthToken);
}
/** Get Authentication Token.
@return Authentication Token */
@Override
public java.lang.String getAuthToken ()
{
return (java.lang.String)get_Value(COLUMNNAME_AuthToken);
}
/** Set Beschreibung. | @param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_AuthToken.java | 1 |
请完成以下Java代码 | public void setQtyRequiered (java.math.BigDecimal QtyRequiered)
{
set_Value (COLUMNNAME_QtyRequiered, QtyRequiered);
}
/** Get Qty Requiered.
@return Qty Requiered */
@Override
public java.math.BigDecimal getQtyRequiered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyRequiered);
if (bd == null)
return Env.ZERO;
return bd;
}
@Override
public org.compiere.model.I_S_Resource getS_Resource() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
/** Set Ressource.
@param S_Resource_ID
Resource
*/
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Ressource.
@return Resource
*/
@Override
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* TypeMRP AD_Reference_ID=53230
* Reference name: _MRP Type
*/
public static final int TYPEMRP_AD_Reference_ID=53230;
/** Demand = D */
public static final String TYPEMRP_Demand = "D";
/** Supply = S */
public static final String TYPEMRP_Supply = "S";
/** Set TypeMRP.
@param TypeMRP TypeMRP */
@Override
public void setTypeMRP (java.lang.String TypeMRP)
{
set_Value (COLUMNNAME_TypeMRP, TypeMRP);
}
/** Get TypeMRP.
@return TypeMRP */
@Override | public java.lang.String getTypeMRP ()
{
return (java.lang.String)get_Value(COLUMNNAME_TypeMRP);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.math.BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.math.BigDecimal getVersion ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java | 1 |
请完成以下Java代码 | public abstract class AbstractPlanItemInstanceOperation extends CmmnOperation {
protected PlanItemInstanceEntity planItemInstanceEntity;
public AbstractPlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
super(commandContext);
this.planItemInstanceEntity = planItemInstanceEntity;
}
public PlanItemInstanceEntity getPlanItemInstanceEntity() {
return planItemInstanceEntity;
}
public void setPlanItemInstanceEntity(PlanItemInstanceEntity planItemInstanceEntity) {
this.planItemInstanceEntity = planItemInstanceEntity; | }
@Override
public String getCaseInstanceId() {
return planItemInstanceEntity.getCaseInstanceId();
}
protected void removeSentryRelatedData() {
CommandContextUtil.getPlanItemInstanceEntityManager(commandContext).deleteSentryRelatedData(planItemInstanceEntity.getId());
}
protected Date getCurrentTime(CommandContext commandContext) {
return CommandContextUtil.getCmmnEngineConfiguration(commandContext).getClock().getCurrentTime();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\AbstractPlanItemInstanceOperation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ApiResponse<User> get(@PathVariable Integer id) {
log.info("单个参数用 @ApiImplicitParam");
return ApiResponse.<User>builder().code(200).message("操作成功").data(new User(id, "u1", "p1")).build();
}
@DeleteMapping("/{id}")
@ApiOperation(value = "删除用户(DONE)", notes = "备注")
@ApiImplicitParam(name = "id", value = "用户编号", dataType = DataType.INT, paramType = ParamType.PATH)
public void delete(@PathVariable Integer id) {
log.info("单个参数用 ApiImplicitParam");
}
@PostMapping
@ApiOperation(value = "添加用户(DONE)")
public User post(@RequestBody User user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PostMapping("/multipar")
@ApiOperation(value = "添加用户(DONE)")
public List<User> multipar(@RequestBody List<User> user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user; | }
@PostMapping("/array")
@ApiOperation(value = "添加用户(DONE)")
public User[] array(@RequestBody User[] user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PutMapping("/{id}")
@ApiOperation(value = "修改用户(DONE)")
public void put(@PathVariable Long id, @RequestBody User user) {
log.info("如果你不想写 @ApiImplicitParam 那么 swagger 也会使用默认的参数名作为描述信息 ");
}
@PostMapping("/{id}/file")
@ApiOperation(value = "文件上传(DONE)")
public String file(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
log.info(file.getContentType());
log.info(file.getName());
log.info(file.getOriginalFilename());
return file.getOriginalFilename();
}
} | repos\spring-boot-demo-master\demo-swagger\src\main\java\com\xkcoding\swagger\controller\UserController.java | 2 |
请完成以下Java代码 | public String getName()
{
return "Refresh";
}
@Override
public String getIcon()
{
return "Refresh16";
}
@Override
public boolean isAvailable()
{
final IRefreshableEditor editor = getRefreshableEditor();
if (editor == null)
{
return false;
}
return true;
}
public IRefreshableEditor getRefreshableEditor()
{
final VEditor editor = getEditor();
if (editor instanceof IRefreshableEditor)
{
return (IRefreshableEditor)editor;
}
else
{ | return null;
}
}
@Override
public boolean isRunnable()
{
return true;
}
@Override
public void run()
{
final IRefreshableEditor editor = (IRefreshableEditor)getEditor();
editor.refreshValue();
}
@Override
public boolean isLongOperation()
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\RefreshContextEditorAction.java | 1 |
请完成以下Java代码 | public void pick(@NonNull final Quantity qtyPicked)
{
assertDraft();
this.qtyPicked = qtyPicked;
pickStatus = computePickOrPackStatus(this.packToSpec);
approvalStatus = computeApprovalStatus(this.qtyPicked, this.qtyReview, this.pickStatus);
}
public void rejectPicking(@NonNull final Quantity qtyRejected)
{
assertDraft();
assertNotApproved();
qtyPicked = qtyRejected;
pickStatus = PickingCandidatePickStatus.WILL_NOT_BE_PICKED;
}
public void rejectPickingPartially(@NonNull final QtyRejectedWithReason qtyRejected)
{
assertDraft();
// assertNotApproved();
Quantity.assertSameUOM(qtyPicked, qtyRejected.toQuantity());
this.qtyRejected = qtyRejected;
}
public void packTo(@Nullable final PackToSpec packToSpec)
{
assertDraft();
if (!pickStatus.isEligibleForPacking())
{
throw new AdempiereException("Invalid status when changing packing instructions: " + pickStatus);
}
this.packToSpec = packToSpec;
pickStatus = computePickOrPackStatus(this.packToSpec);
}
public void reviewPicking(final BigDecimal qtyReview)
{
assertDraft();
if (!pickStatus.isEligibleForReview())
{
throw new AdempiereException("Picking candidate cannot be approved because it's not picked or packed yet: " + this);
}
this.qtyReview = qtyReview;
approvalStatus = computeApprovalStatus(qtyPicked, this.qtyReview, pickStatus);
}
public void reviewPicking()
{
reviewPicking(qtyPicked.toBigDecimal());
}
private static PickingCandidateApprovalStatus computeApprovalStatus(final Quantity qtyPicked, final BigDecimal qtyReview, final PickingCandidatePickStatus pickStatus)
{
if (qtyReview == null)
{
return PickingCandidateApprovalStatus.TO_BE_APPROVED;
} | //
final BigDecimal qtyReviewToMatch;
if (pickStatus.isPickRejected())
{
qtyReviewToMatch = BigDecimal.ZERO;
}
else
{
qtyReviewToMatch = qtyPicked.toBigDecimal();
}
//
if (qtyReview.compareTo(qtyReviewToMatch) == 0)
{
return PickingCandidateApprovalStatus.APPROVED;
}
else
{
return PickingCandidateApprovalStatus.REJECTED;
}
}
private static PickingCandidatePickStatus computePickOrPackStatus(@Nullable final PackToSpec packToSpec)
{
return packToSpec != null ? PickingCandidatePickStatus.PACKED : PickingCandidatePickStatus.PICKED;
}
public boolean isPickFromPickingOrder()
{
return getPickFrom().isPickFromPickingOrder();
}
public void issueToPickingOrder(@Nullable final List<PickingCandidateIssueToBOMLine> issuesToPickingOrder)
{
this.issuesToPickingOrder = issuesToPickingOrder != null
? ImmutableList.copyOf(issuesToPickingOrder)
: ImmutableList.of();
}
public PickingCandidateSnapshot snapshot()
{
return PickingCandidateSnapshot.builder()
.id(getId())
.qtyReview(getQtyReview())
.pickStatus(getPickStatus())
.approvalStatus(getApprovalStatus())
.processingStatus(getProcessingStatus())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidate.java | 1 |
请完成以下Java代码 | public int getC_PaymentTerm_Break_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_Break_ID);
}
@Override
public void setC_PaymentTerm_ID (final int C_PaymentTerm_ID)
{
if (C_PaymentTerm_ID < 1)
set_Value (COLUMNNAME_C_PaymentTerm_ID, null);
else
set_Value (COLUMNNAME_C_PaymentTerm_ID, C_PaymentTerm_ID);
}
@Override
public int getC_PaymentTerm_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_ID);
}
@Override
public void setDueAmt (final BigDecimal DueAmt)
{
set_Value (COLUMNNAME_DueAmt, DueAmt);
}
@Override
public BigDecimal getDueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDueDate (final java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setOffsetDays (final int OffsetDays)
{
set_Value (COLUMNNAME_OffsetDays, OffsetDays);
}
@Override
public int getOffsetDays()
{
return get_ValueAsInt(COLUMNNAME_OffsetDays);
}
@Override
public void setPercent (final int Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public int getPercent()
{
return get_ValueAsInt(COLUMNNAME_Percent);
}
/**
* ReferenceDateType AD_Reference_ID=541989
* Reference name: ReferenceDateType
*/
public static final int REFERENCEDATETYPE_AD_Reference_ID=541989;
/** InvoiceDate = IV */
public static final String REFERENCEDATETYPE_InvoiceDate = "IV";
/** BLDate = BL */
public static final String REFERENCEDATETYPE_BLDate = "BL";
/** OrderDate = OD */
public static final String REFERENCEDATETYPE_OrderDate = "OD";
/** LCDate = LC */
public static final String REFERENCEDATETYPE_LCDate = "LC";
/** ETADate = ET */
public static final String REFERENCEDATETYPE_ETADate = "ET";
@Override
public void setReferenceDateType (final java.lang.String ReferenceDateType)
{
set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType);
}
@Override | public java.lang.String getReferenceDateType()
{
return get_ValueAsString(COLUMNNAME_ReferenceDateType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Status AD_Reference_ID=541993
* Reference name: C_OrderPaySchedule_Status
*/
public static final int STATUS_AD_Reference_ID=541993;
/** Pending_Ref = PR */
public static final String STATUS_Pending_Ref = "PR";
/** Awaiting_Pay = WP */
public static final String STATUS_Awaiting_Pay = "WP";
/** Paid = P */
public static final String STATUS_Paid = "P";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderPaySchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomActuatorMetricService implements MetricService {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Autowired
private MeterRegistry registry;
private final List<List<Integer>> statusMetricsByMinute;
private final List<String> statusList;
public CustomActuatorMetricService() {
statusMetricsByMinute = new ArrayList<>();
statusList = new ArrayList<>();
}
public void increaseCount(int status) {
String counterName = "counter.status." + status;
registry.counter(counterName).increment();
if (!statusList.contains(counterName)) {
statusList.add(counterName);
}
}
@Override
public Object[][] getGraphData() {
final Date current = new Date();
final int colCount = statusList.size() + 1;
final int rowCount = statusMetricsByMinute.size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
int j = 1;
for (final String status : statusList) {
result[0][j] = status;
j++;
}
for (int i = 1; i < rowCount; i++) {
result[i][0] = DATE_FORMAT.format(new Date(current.getTime() - (60000L * (rowCount - i))));
}
List<Integer> minuteOfStatuses;
for (int i = 1; i < rowCount; i++) {
minuteOfStatuses = statusMetricsByMinute.get(i - 1);
for (j = 1; j <= minuteOfStatuses.size(); j++) { | result[i][j] = minuteOfStatuses.get(j - 1);
}
while (j < colCount) {
result[i][j] = 0;
j++;
}
}
return result;
}
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds:60000}")
private void exportMetrics() {
List<Integer> statusCount = new ArrayList<>();
for (final String status : statusList) {
Search search = registry.find(status);
Counter counter = search.counter();
if (counter == null) {
statusCount.add(0);
} else {
statusCount.add((int) counter.count());
registry.remove(counter);
}
}
statusMetricsByMinute.add(statusCount);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\java\com\baeldung\metrics\service\CustomActuatorMetricService.java | 2 |
请完成以下Java代码 | public class Author {
private final String name;
private final String surname;
public Author(String name, String surname) {
this.name = name;
this.surname = surname;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
@Override
public boolean equals(Object o) { | if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Author author = (Author) o;
return Objects.equals(name, author.name) && Objects.equals(surname, author.surname);
}
@Override
public int hashCode() {
return Objects.hash(name, surname);
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\microstream\Author.java | 1 |
请完成以下Java代码 | public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
} | public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityImpl.java | 1 |
请完成以下Java代码 | protected static void applyFieldExtension(FieldExtension fieldExtension, Object target, boolean throwExceptionOnMissingField) {
Object value = null;
if (fieldExtension.getExpression() != null) {
ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
value = expressionManager.createExpression(fieldExtension.getExpression());
} else {
value = new FixedValue(fieldExtension.getStringValue());
}
ReflectUtil.invokeSetterOrField(target, fieldExtension.getFieldName(), value, throwExceptionOnMissingField);
}
@Override
public String getSourceState() {
return sourceState;
}
public void setSourceState(String sourceState) {
this.sourceState = sourceState;
}
@Override
public String getTargetState() {
return targetState;
}
public void setTargetState(String targetState) {
this.targetState = targetState;
}
public String getClassName() {
return className; | }
public void setClassName(String className) {
this.className = className;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public CmmnActivityBehavior getActivityBehaviorInstance() {
return activityBehaviorInstance;
}
public void setActivityBehaviorInstance(CmmnActivityBehavior activityBehaviorInstance) {
this.activityBehaviorInstance = activityBehaviorInstance;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\CmmnClassDelegate.java | 1 |
请完成以下Java代码 | public class UOMUtil
{
public static boolean isMinute(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.MINUTE.equals(x12de355);
}
public static boolean isHour(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.HOUR.equals(x12de355);
}
public static boolean isDay(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.DAY.equals(x12de355);
}
public static boolean isWorkDay(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.DAY_WORK.equals(x12de355);
}
public static boolean isWeek(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.WEEK.equals(x12de355);
}
public static boolean isMonth(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.MONTH.equals(x12de355);
}
public static boolean isWorkMonth(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.MONTH_WORK.equals(x12de355); | }
public static boolean isYear(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355());
return X12DE355.YEAR.equals(x12de355);
}
/**
* @return true if is time UOM
*/
public static boolean isTime(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355());
return x12de355.isTemporalUnit();
}
@NonNull
public static TemporalUnit toTemporalUnit(final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355());
return x12de355.getTemporalUnit();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\uom\UOMUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
// 使用内存中的 InMemoryUserDetailsManager
inMemoryAuthentication()
// 不使用 PasswordEncoder 密码编码器
.passwordEncoder(passwordEncoder())
// 配置 yunai 用户
.withUser("yunai").password("1024").roles("USER");
} | // @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests()
// // 对所有 URL 都进行认证
// .anyRequest()
// .authenticated();
// }
// @Override
// public void configure(HttpSecurity http) throws Exception {
// http.csrf()
// .disable()
// .authorizeRequests()
// .antMatchers("/oauth/**", "/login/**", "/logout/**").permitAll()
// .anyRequest().authenticated()
// .and().formLogin().permitAll();
// }
} | repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo01-authorization-code-server\src\main\java\cn\iocoder\springboot\lab68\resourceserverdemo\config\SecurityConfig.java | 2 |
请完成以下Java代码 | protected boolean canMigrate(MigratingProcessElementInstance instance) {
return instance instanceof MigratingActivityInstance
|| instance instanceof MigratingTransitionInstance;
}
protected void instantiateScopes(
MigratingScopeInstance ancestorScopeInstance,
MigratingScopeInstanceBranch executionBranch,
List<ScopeImpl> scopesToInstantiate) {
if (scopesToInstantiate.isEmpty()) {
return;
}
// must always be an activity instance | MigratingActivityInstance ancestorActivityInstance = (MigratingActivityInstance) ancestorScopeInstance;
ExecutionEntity newParentExecution = ancestorActivityInstance.createAttachableExecution();
Map<PvmActivity, PvmExecutionImpl> createdExecutions =
newParentExecution.instantiateScopes((List) scopesToInstantiate, skipCustomListeners, skipIoMappings);
for (ScopeImpl scope : scopesToInstantiate) {
ExecutionEntity createdExecution = (ExecutionEntity) createdExecutions.get(scope);
createdExecution.setActivity(null);
createdExecution.setActive(false);
executionBranch.visited(new MigratingActivityInstance(scope, createdExecution));
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingActivityInstanceVisitor.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Tab_Callout[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set AD_Tab_Callout.
@param AD_Tab_Callout_ID AD_Tab_Callout */
public void setAD_Tab_Callout_ID (int AD_Tab_Callout_ID)
{
if (AD_Tab_Callout_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Tab_Callout_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Tab_Callout_ID, Integer.valueOf(AD_Tab_Callout_ID));
}
/** Get AD_Tab_Callout.
@return AD_Tab_Callout */
public int getAD_Tab_Callout_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_Callout_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Tab getAD_Tab() throws RuntimeException
{
return (org.compiere.model.I_AD_Tab)MTable.get(getCtx(), org.compiere.model.I_AD_Tab.Table_Name)
.getPO(getAD_Tab_ID(), get_TrxName()); }
/** Set Register.
@param AD_Tab_ID
Register auf einem Fenster
*/
public void setAD_Tab_ID (int AD_Tab_ID)
{
if (AD_Tab_ID < 1)
set_Value (COLUMNNAME_AD_Tab_ID, null);
else
set_Value (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID));
}
/** Get Register.
@return Register auf einem Fenster
*/
public int getAD_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
} | /** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (String SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public String getSeqNo ()
{
return (String)get_Value(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_AD_Tab_Callout.java | 1 |
请完成以下Java代码 | public boolean isParentLinkColumn(final String columnName)
{
final POInfoColumn column = getColumn(columnName);
return column != null && column.isParent();
}
@NonNull
public ImmutableList<POInfoColumn> getColumns() {return m_columns;}
@NonNull
public Stream<POInfoColumn> streamColumns(@NonNull final Predicate<POInfoColumn> poInfoColumnPredicate)
{
return m_columns.stream()
.filter(poInfoColumnPredicate);
}
public Optional<String> getTableIdColumnName(@NonNull final String recordIdColumnName)
{
return tableAndRecordColumnNames.stream()
.filter(tableAndRecordColumnName -> tableAndRecordColumnName.equalsByColumnName(recordIdColumnName))
.map(TableAndColumnName::getTableNameAsString)
.findFirst();
}
@Value
@Builder
private static class POInfoHeader
{
@NonNull String tableName;
@NonNull AdTableId adTableId;
@NonNull TableAccessLevel accessLevel;
boolean isView;
boolean isChangeLog;
int webuiViewPageLength;
@NonNull TableCloningEnabled cloningEnabled;
@NonNull TableWhenChildCloningStrategy whenChildCloningStrategy;
@NonNull TableDownlineCloningStrategy downlineCloningStrategy;
}
public static class POInfoMap
{
private final ImmutableMap<AdTableId, POInfo> byTableId;
private final ImmutableMap<String, POInfo> byTableNameUC;
public POInfoMap(@NonNull final List<POInfo> poInfos)
{
byTableId = Maps.uniqueIndex(poInfos, POInfo::getAdTableId);
byTableNameUC = Maps.uniqueIndex(poInfos, POInfo::getTableNameUC);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("size", byTableId.size())
.toString();
} | @Nullable
public POInfo getByTableIdOrNull(@NonNull final AdTableId tableId)
{
return byTableId.get(tableId);
}
@NonNull
public POInfo getByTableId(@NonNull final AdTableId tableId)
{
final POInfo poInfo = getByTableIdOrNull(tableId);
if (poInfo == null)
{
throw new AdempiereException("No POInfo found for " + tableId);
}
return poInfo;
}
@Nullable
public POInfo getByTableNameOrNull(@NonNull final String tableName)
{
return byTableNameUC.get(tableName.toUpperCase());
}
@NonNull
public POInfo getByTableName(@NonNull final String tableName)
{
final POInfo poInfo = getByTableNameOrNull(tableName);
if (poInfo == null)
{
throw new AdempiereException("No POInfo found for " + tableName);
}
return poInfo;
}
public Stream<POInfo> stream() {return byTableId.values().stream();}
public int size() {return byTableId.size();}
public ImmutableCollection<POInfo> toCollection() {return byTableId.values();}
}
} // POInfo | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfo.java | 1 |
请完成以下Java代码 | public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) {
this.useAnnotationTemplate = templateDefaults != null;
this.scanner = SecurityAnnotationScanners.requireUnique(AuthenticationPrincipal.class, templateDefaults);
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private @Nullable AuthenticationPrincipal findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) {
return this.scanner.scan(parameter.getParameter());
} | AuthenticationPrincipal annotation = parameter.getParameterAnnotation(this.annotationType);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType);
if (annotation != null) {
return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize();
}
}
return null;
}
} | repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\AuthenticationPrincipalArgumentResolver.java | 1 |
请完成以下Java代码 | public SimpleElement getName() {
return this.name;
}
public SimpleElement getDescription() {
return this.description;
}
public SimpleElement getPackageName() {
return this.packageName;
}
/**
* A simple element from the properties.
*/
public static final class SimpleElement {
/**
* Element title.
*/
private String title;
/**
* Element description.
*/
private String description;
/**
* Element default value.
*/
private String value;
/**
* Create a new instance with the given value.
* @param value the value
*/
public SimpleElement(String value) {
this.value = value;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
} | public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public void apply(TextCapability capability) {
if (StringUtils.hasText(this.title)) {
capability.setTitle(this.title);
}
if (StringUtils.hasText(this.description)) {
capability.setDescription(this.description);
}
if (StringUtils.hasText(this.value)) {
capability.setContent(this.value);
}
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrProperties.java | 1 |
请完成以下Java代码 | public synchronized void clear()
{
map.clear();
}
public synchronized <T> void registerJUnitBean(@NonNull final T beanImpl)
{
assertJUnitMode();
@SuppressWarnings("unchecked") final Class<T> beanType = (Class<T>)beanImpl.getClass();
registerJUnitBean(beanType, beanImpl);
}
public synchronized <BT, T extends BT> void registerJUnitBean(
@NonNull final Class<BT> beanType,
@NonNull final T beanImpl)
{
assertJUnitMode();
final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>());
if (!beans.contains(beanImpl))
{
beans.add(beanImpl);
logger.info("JUnit testing: Registered bean {}={}", beanType, beanImpl);
}
else
{
logger.info("JUnit testing: Skip registering bean because already registered {}={}", beanType, beanImpl);
}
}
public synchronized <BT, T extends BT> void registerJUnitBeans(
@NonNull final Class<BT> beanType,
@NonNull final List<T> beansToAdd)
{
assertJUnitMode();
final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>());
beans.addAll(beansToAdd);
logger.info("JUnit testing: Registered beans {}={}", beanType, beansToAdd);
}
public synchronized <T> T getBeanOrNull(@NonNull final Class<T> beanType)
{
assertJUnitMode();
final ArrayList<Object> beans = map.get(ClassReference.of(beanType));
if (beans == null || beans.isEmpty())
{
return null;
}
if (beans.size() > 1) | {
logger.warn("Found more than one bean for {} but returning the first one: {}", beanType, beans);
}
final T beanImpl = castBean(beans.get(0), beanType);
logger.debug("JUnit testing Returning manually registered bean: {}", beanImpl);
return beanImpl;
}
private static <T> T castBean(final Object beanImpl, final Class<T> ignoredBeanType)
{
@SuppressWarnings("unchecked") final T beanImplCasted = (T)beanImpl;
return beanImplCasted;
}
public synchronized <T> ImmutableList<T> getBeansOfTypeOrNull(@NonNull final Class<T> beanType)
{
assertJUnitMode();
List<Object> beanObjs = map.get(ClassReference.of(beanType));
if (beanObjs == null)
{
final List<Object> assignableBeans = map.values()
.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(impl -> beanType.isAssignableFrom(impl.getClass()))
.collect(Collectors.toList());
if (assignableBeans.isEmpty())
{
return null;
}
beanObjs = assignableBeans;
}
return beanObjs
.stream()
.map(beanObj -> castBean(beanObj, beanType))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\JUnitBeansMap.java | 1 |
请完成以下Java代码 | public style addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public style addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element. | @param hashcode the name of the element to be removed.
*/
public style removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\style.java | 1 |
请完成以下Java代码 | public void setIsSOTrx()
{
final boolean isSOTrx = Services.get(IDocTypeBL.class).isSOTrx(getDocBaseType());
setIsSOTrx(isSOTrx);
} // setIsSOTrx
/**
* String Representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("MDocType[");
sb.append(get_ID()).append("-").append(getName())
.append(",DocNoSequence_ID=").append(getDocNoSequence_ID())
.append("]");
return sb.toString();
} // toString
/**
* Get Print Name
* @param AD_Language language
* @return print Name if available translated
*/
public String getPrintName (String AD_Language)
{
if (AD_Language == null || AD_Language.length() == 0)
{
return super.getPrintName();
}
return get_Translation (COLUMNNAME_PrintName, AD_Language);
} // getPrintName
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord && success)
{
// Add doctype/docaction access to all roles of client
String sqlDocAction = "INSERT INTO AD_Document_Action_Access " | + "(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,"
+ "C_DocType_ID , AD_Ref_List_ID, AD_Role_ID) "
+ "(SELECT "
+ getAD_Client_ID() + ",0,'Y', now(),"
+ getUpdatedBy() + ", now()," + getUpdatedBy()
+ ", doctype.C_DocType_ID, action.AD_Ref_List_ID, rol.AD_Role_ID "
+ "FROM AD_Client client "
+ "INNER JOIN C_DocType doctype ON (doctype.AD_Client_ID=client.AD_Client_ID) "
+ "INNER JOIN AD_Ref_List action ON (action.AD_Reference_ID=135) "
+ "INNER JOIN AD_Role rol ON (rol.AD_Client_ID=client.AD_Client_ID) "
+ "WHERE client.AD_Client_ID=" + getAD_Client_ID()
+ " AND doctype.C_DocType_ID=" + get_ID()
+ " AND rol.IsManual='N'"
+ ")";
int docact = DB.executeUpdateAndSaveErrorOnFail(sqlDocAction, get_TrxName());
log.debug("AD_Document_Action_Access=" + docact);
}
return success;
} // afterSave
/**
* Executed after Delete operation.
* @param success true if record deleted
* @return true if delete is a success
*/
@Override
protected boolean afterDelete (boolean success)
{
if(success) {
//delete access records
int docactDel = DB.executeUpdateAndSaveErrorOnFail("DELETE FROM AD_Document_Action_Access WHERE C_DocType_ID=" + get_IDOld(), get_TrxName());
log.debug("Deleting AD_Document_Action_Access=" + docactDel + " for C_DocType_ID: " + get_IDOld());
}
return success;
} // afterDelete
} // MDocType | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDocType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DetailDataRequestHandler
{
public void handleInsertDetailRequest(@NonNull final InsertDetailRequest insertDetailRequest)
{
final I_MD_Cockpit_DocumentDetail documentDetailRecord = newInstance(I_MD_Cockpit_DocumentDetail.class);
final DetailDataRecordIdentifier detailDataRecordIdentifier = insertDetailRequest
.getDetailDataRecordIdentifier();
final int cockpitId = retrieveDataId(detailDataRecordIdentifier
.getMainDataRecordIdentifier());
documentDetailRecord.setMD_Cockpit_ID(cockpitId);
documentDetailRecord.setM_ShipmentSchedule_ID(detailDataRecordIdentifier.getShipmentScheduleId());
documentDetailRecord.setM_ReceiptSchedule_ID(detailDataRecordIdentifier.getReceiptScheduleId());
documentDetailRecord.setC_BPartner_ID(insertDetailRequest.getBPartnerId());
documentDetailRecord.setQtyOrdered(stripTrailingDecimalZeros(insertDetailRequest.getQtyOrdered()));
documentDetailRecord.setQtyReserved(stripTrailingDecimalZeros(insertDetailRequest.getQtyReserved()));
documentDetailRecord.setC_Order_ID(insertDetailRequest.getOrderId());
documentDetailRecord.setC_OrderLine_ID(insertDetailRequest.getOrderLineId());
documentDetailRecord.setC_Flatrate_Term_ID(insertDetailRequest.getSubscriptionId());
documentDetailRecord.setC_SubscriptionProgress_ID(insertDetailRequest.getSubscriptionLineId());
if (insertDetailRequest.getDocTypeId() > 0)
{ // don't set it to 0, because C_DocType_ID = 0 won't end up as "none" but as "new"
documentDetailRecord.setC_DocType_ID(insertDetailRequest.getDocTypeId());
}
save(documentDetailRecord);
}
private int retrieveDataId(@NonNull final MainDataRecordIdentifier identifier)
{
final int result = identifier
.createQueryBuilder()
.create()
.firstIdOnly();
Check.errorIf(result <= 0, "Found no I_MD_Cockpit record for identifier={}", identifier);
return result;
} | public int handleUpdateDetailRequest(@NonNull final UpdateDetailRequest updateDetailRequest)
{
final ICompositeQueryUpdater<I_MD_Cockpit_DocumentDetail> updater = Services.get(IQueryBL.class)
.createCompositeQueryUpdater(I_MD_Cockpit_DocumentDetail.class)
.addSetColumnValue(
I_MD_Cockpit_DocumentDetail.COLUMNNAME_QtyOrdered,
stripTrailingDecimalZeros(updateDetailRequest.getQtyOrdered()))
.addSetColumnValue(
I_MD_Cockpit_DocumentDetail.COLUMNNAME_QtyReserved,
stripTrailingDecimalZeros(updateDetailRequest.getQtyReserved()));
return updateDetailRequest.getDetailDataRecordIdentifier()
.createQuery()
.update(updater);
}
public int handleRemoveDetailRequest(@NonNull final RemoveDetailRequest removeDetailsRequest)
{
final int deletedCount = removeDetailsRequest
.getDetailDataRecordIdentifier()
.createQuery()
.delete();
return deletedCount;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\detailrecord\DetailDataRequestHandler.java | 2 |
请完成以下Java代码 | Optional<String> getBioToUpdate() {
return ofNullable(bioToUpdate);
}
private UserUpdateRequest(UserUpdateRequestBuilder builder) {
this.emailToUpdate = builder.emailToUpdate;
this.userNameToUpdate = builder.userNameToUpdate;
this.passwordToUpdate = builder.passwordToUpdate;
this.imageToUpdate = builder.imageToUpdate;
this.bioToUpdate = builder.bioToUpdate;
}
public static class UserUpdateRequestBuilder {
private Email emailToUpdate;
private UserName userNameToUpdate;
private String passwordToUpdate;
private Image imageToUpdate;
private String bioToUpdate;
public UserUpdateRequestBuilder emailToUpdate(Email emailToUpdate) {
this.emailToUpdate = emailToUpdate;
return this;
}
public UserUpdateRequestBuilder userNameToUpdate(UserName userNameToUpdate) {
this.userNameToUpdate = userNameToUpdate;
return this;
}
public UserUpdateRequestBuilder passwordToUpdate(String passwordToUpdate) {
this.passwordToUpdate = passwordToUpdate; | return this;
}
public UserUpdateRequestBuilder imageToUpdate(Image imageToUpdate) {
this.imageToUpdate = imageToUpdate;
return this;
}
public UserUpdateRequestBuilder bioToUpdate(String bioToUpdate) {
this.bioToUpdate = bioToUpdate;
return this;
}
public UserUpdateRequest build() {
return new UserUpdateRequest(this);
}
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\UserUpdateRequest.java | 1 |
请完成以下Java代码 | public void showCodeSnippetFormattingUsingPRETag() {
// do nothing
}
/**
* This is an example to show usage of HTML character entities while code snippet formatting in Javadocs
*
* <pre>
* public class Application(){
* List<Integer> nums = new ArrayList<>();
* }
*
* </pre>
*/
public void showCodeSnippetFormattingUsingCharacterEntities() {
// do nothing
}
/**
* This is an example to show usage of javadoc code tag while code snippet formatting in Javadocs
*
* <pre>
*
* public class Application(){
* {@code List<Integer> nums = new ArrayList<>(); }
* }
*
* </pre>
*/
public void showCodeSnippetFormattingUsingCodeTag() {
// do nothing
}
/**
* This is an example to show issue faced while using annotations in Javadocs
*
* <pre>
*
* public class Application(){
* @Getter
* {@code List<Integer> nums = new ArrayList<>(); }
* }
*
* </pre>
*/
public void showCodeSnippetFormattingIssueUsingCodeTag() {
// do nothing
}
/**
* This is an example to show usage of javadoc code tag for handling '@' character
*
* <pre>
*
* public class Application(){
* {@code @Getter}
* {@code List<Integer> nums = new ArrayList<>(); }
* }
*
* </pre>
*/
public void showCodeSnippetAnnotationFormattingUsingCodeTag() {
// do nothing
}
/**
* This is an example to show difference in javadoc literal and code tag
*
* <p>
*
* {@literal @Getter}
* {@literal List<Integer> nums = new ArrayList<>(); }
*
* <br />
* {@code @Getter}
* {@code List<Integer> nums = new ArrayList<>(); }
* </p> | */
public void showCodeSnippetCommentsFormattingUsingCodeAndLiteralTag() {
// do nothing
}
/**
* This is an example to illustrate a basic jQuery code snippet embedded in documentation comments
* <pre>
* {@code <script>}
* $document.ready(function(){
* console.log("Hello World!);
* })
* {@code </script>}
* </pre>
*/
public void showJSCodeSnippetUsingJavadoc() {
// do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>{@code
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>}
* </pre>
*
*/
public void showHTMLCodeSnippetUsingJavadoc() {
// do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>
* </pre>
*
*/
public void showHTMLCodeSnippetIssueUsingJavadoc() {
// do nothing
}
} | repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\CodeSnippetFormatting.java | 1 |
请完成以下Java代码 | public void setFullyChanged()
{
fullyChanged = true;
}
public boolean isHeaderPropertiesChanged()
{
return headerPropertiesChanged;
}
public void setHeaderPropertiesChanged()
{
this.headerPropertiesChanged = true;
}
public boolean isFullyChanged()
{
return fullyChanged;
}
public boolean hasChanges()
{
if (fullyChanged)
{
return true;
}
if (headerPropertiesChanged)
{
return true;
}
return changedRowIds != null && !changedRowIds.isEmpty();
}
public void addChangedRowIds(@Nullable final DocumentIdsSelection rowIds)
{
// Don't collect rowIds if this was already flagged as fully changed.
if (fullyChanged)
{
return;
}
if (rowIds == null || rowIds.isEmpty())
{
return;
}
else if (rowIds.isAll())
{
fullyChanged = true;
changedRowIds = null;
}
else
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds.toSet());
}
}
public void addChangedRowIds(final Collection<DocumentId> rowIds)
{
if (rowIds.isEmpty())
{
return;
} | if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds);
}
public void addChangedRowId(@NonNull final DocumentId rowId)
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.add(rowId);
}
public DocumentIdsSelection getChangedRowIds()
{
final boolean fullyChanged = this.fullyChanged;
final Set<DocumentId> changedRowIds = this.changedRowIds;
if (fullyChanged)
{
return DocumentIdsSelection.ALL;
}
else if (changedRowIds == null || changedRowIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
}
else
{
return DocumentIdsSelection.of(changedRowIds);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChanges.java | 1 |
请完成以下Java代码 | public void remove(S element) {
if (isEmpty()) {
return;
}
Node<S> previous = null;
Node<S> current = head;
while (current != null) {
if (Objects.equals(element, current.element)) {
Node<S> next = current.next;
if (isFistNode(current)) {
head = next;
} else if (isLastNode(current)) {
previous.next = null;
} else {
Node<S> next1 = current.next;
previous.next = next1;
}
--size;
break;
}
previous = current;
current = current.next;
}
}
public void removeLast() {
if (isEmpty()) {
return;
} else if (size() == 1) {
tail = null;
head = null;
} else {
Node<S> secondToLast = null;
Node<S> last = head;
while (last.next != null) {
secondToLast = last;
last = last.next;
}
secondToLast.next = null;
}
--size;
}
public boolean contains(S element) {
if (isEmpty()) {
return false;
}
Node<S> current = head;
while (current != null) {
if (Objects.equals(element, current.element))
return true; | current = current.next;
}
return false;
}
private boolean isLastNode(Node<S> node) {
return tail == node;
}
private boolean isFistNode(Node<S> node) {
return head == node;
}
public static class Node<T> {
private T element;
private Node<T> next;
public Node(T element) {
this.element = element;
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\linkedlistremove\SinglyLinkedList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "Product name is required.")
@Basic(optional = false)
private String name;
private Double price;
private String pictureUrl;
public Product(Long id, @NotNull(message = "Product name is required.") String name, Double price, String pictureUrl) {
this.id = id;
this.name = name;
this.price = price;
this.pictureUrl = pictureUrl;
}
public Product() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getPictureUrl() {
return pictureUrl;
}
public void setPictureUrl(String pictureUrl) {
this.pictureUrl = pictureUrl;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\Product.java | 2 |
请完成以下Java代码 | public String toString()
{
return "PrintPackageInfo [printService=" + printService + ", tray=" + tray + ", pageFrom=" + pageFrom + ", pageTo=" + pageTo + ", calX=" + calX + ", calY=" + calY + "]";
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + calX;
result = prime * result + calY;
result = prime * result + pageFrom;
result = prime * result + pageTo;
result = prime * result + ((printService == null) ? 0 : printService.hashCode());
result = prime * result + ((tray == null) ? 0 : tray.hashCode());
result = prime * result + trayNumber;
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) | return false;
PrintPackageInfo other = (PrintPackageInfo)obj;
if (calX != other.calX)
return false;
if (calY != other.calY)
return false;
if (pageFrom != other.pageFrom)
return false;
if (pageTo != other.pageTo)
return false;
if (printService == null)
{
if (other.printService != null)
return false;
}
else if (!printService.equals(other.printService))
return false;
if (tray == null)
{
if (other.tray != null)
return false;
}
else if (!tray.equals(other.tray))
return false;
if (trayNumber != other.trayNumber)
return false;
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackageInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected String getMybatisCfgPath() {
return IdmEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE;
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
if (idmEngineConfiguration == null) {
idmEngineConfiguration = new StandaloneIdmEngineConfiguration();
}
initialiseCommonProperties(engineConfiguration, idmEngineConfiguration);
initEngine();
initServiceConfigurations(engineConfiguration, idmEngineConfiguration);
}
@Override
protected IdmEngine buildEngine() {
return idmEngineConfiguration.buildEngine();
} | @Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
}
@Override
protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
}
public IdmEngineConfiguration getIdmEngineConfiguration() {
return idmEngineConfiguration;
}
public IdmEngineConfigurator setIdmEngineConfiguration(IdmEngineConfiguration idmEngineConfiguration) {
this.idmEngineConfiguration = idmEngineConfiguration;
return this;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine-configurator\src\main\java\org\flowable\idm\engine\configurator\IdmEngineConfigurator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class DataCouchbaseConfiguration {
@Bean
@ConditionalOnMissingBean
MappingCouchbaseConverter couchbaseMappingConverter(DataCouchbaseProperties properties,
CouchbaseMappingContext couchbaseMappingContext, CouchbaseCustomConversions couchbaseCustomConversions) {
MappingCouchbaseConverter converter = new MappingCouchbaseConverter(couchbaseMappingContext,
properties.getTypeKey());
converter.setCustomConversions(couchbaseCustomConversions);
return converter;
}
@Bean
@ConditionalOnMissingBean
TranslationService couchbaseTranslationService() {
return new JacksonTranslationService();
}
@Bean(name = BeanNames.COUCHBASE_MAPPING_CONTEXT)
@ConditionalOnMissingBean(name = BeanNames.COUCHBASE_MAPPING_CONTEXT)
CouchbaseMappingContext couchbaseMappingContext(DataCouchbaseProperties properties,
ApplicationContext applicationContext, CouchbaseCustomConversions couchbaseCustomConversions)
throws ClassNotFoundException {
CouchbaseMappingContext mappingContext = new CouchbaseMappingContext();
mappingContext.setInitialEntitySet(new EntityScanner(applicationContext).scan(Document.class)); | mappingContext.setSimpleTypeHolder(couchbaseCustomConversions.getSimpleTypeHolder());
Class<?> fieldNamingStrategy = properties.getFieldNamingStrategy();
if (fieldNamingStrategy != null) {
mappingContext
.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(fieldNamingStrategy));
}
mappingContext.setAutoIndexCreation(properties.isAutoIndex());
return mappingContext;
}
@Bean(name = BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
@ConditionalOnMissingBean(name = BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
CouchbaseCustomConversions couchbaseCustomConversions() {
return new CouchbaseCustomConversions(Collections.emptyList());
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-couchbase\src\main\java\org\springframework\boot\data\couchbase\autoconfigure\DataCouchbaseConfiguration.java | 2 |
请完成以下Java代码 | public static final class OAuth2 {
private final OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings;
private OAuth2(OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings) {
this.oAuth2Settings = oAuth2Settings;
}
public OAuth2 tokenEndpointUri(String uri) {
this.oAuth2Settings.tokenEndpointUri(uri);
return this;
}
public OAuth2 clientId(String clientId) {
this.oAuth2Settings.clientId(clientId);
return this;
}
public OAuth2 clientSecret(String clientSecret) {
this.oAuth2Settings.clientSecret(clientSecret);
return this;
}
public OAuth2 grantType(String grantType) {
this.oAuth2Settings.grantType(grantType);
return this;
}
public OAuth2 parameter(String name, String value) {
this.oAuth2Settings.parameter(name, value);
return this;
}
public OAuth2 shared(boolean shared) {
this.oAuth2Settings.shared(shared);
return this;
} | public OAuth2 sslContext(SSLContext sslContext) {
this.oAuth2Settings.tls().sslContext(sslContext);
return this;
}
}
public static final class Recovery {
private final ConnectionBuilder.RecoveryConfiguration recoveryConfiguration;
private Recovery(ConnectionBuilder.RecoveryConfiguration recoveryConfiguration) {
this.recoveryConfiguration = recoveryConfiguration;
}
public Recovery activated(boolean activated) {
this.recoveryConfiguration.activated(activated);
return this;
}
public Recovery backOffDelayPolicy(BackOffDelayPolicy backOffDelayPolicy) {
this.recoveryConfiguration.backOffDelayPolicy(backOffDelayPolicy);
return this;
}
public Recovery topology(boolean activated) {
this.recoveryConfiguration.topology(activated);
return this;
}
}
} | repos\spring-amqp-main\spring-rabbitmq-client\src\main\java\org\springframework\amqp\rabbitmq\client\SingleAmqpConnectionFactory.java | 1 |
请完成以下Java代码 | public Stream<StockDataItem> streamStockDataItems(@NonNull final StockDataMultiQuery multiQuery)
{
final IQuery<I_MD_Stock> query = multiQuery
.getStockDataQueries()
.stream()
.map(this::createStockDataItemQuery)
.reduce(IQuery.unionDistict())
.orElse(null);
if (query == null)
{
return Stream.empty();
}
return query
.iterateAndStream()
.map(this::recordToStockDataItem);
}
private IQuery<I_MD_Stock> createStockDataItemQuery(@NonNull final StockDataQuery query)
{
final IQueryBuilder<I_MD_Stock> queryBuilder = queryBL.createQueryBuilder(I_MD_Stock.class);
queryBuilder.addEqualsFilter(I_MD_Stock.COLUMNNAME_M_Product_ID, query.getProductId());
if (!query.getWarehouseIds().isEmpty()) | {
queryBuilder.addInArrayFilter(I_MD_Stock.COLUMNNAME_M_Warehouse_ID, query.getWarehouseIds());
}
//
// Storage Attributes Key
{
final AttributesKeyQueryHelper<I_MD_Stock> helper = AttributesKeyQueryHelper.createFor(I_MD_Stock.COLUMN_AttributesKey);
final IQueryFilter<I_MD_Stock> attributesKeysFilter = helper.createFilter(ImmutableList.of(AttributesKeyPatternsUtil.ofAttributeKey(query.getStorageAttributesKey())));
queryBuilder.filter(attributesKeysFilter);
}
return queryBuilder.create();
}
private StockDataItem recordToStockDataItem(@NonNull final I_MD_Stock record)
{
return StockDataItem.builder()
.productId(ProductId.ofRepoId(record.getM_Product_ID()))
.warehouseId(WarehouseId.ofRepoId(record.getM_Warehouse_ID()))
.storageAttributesKey(AttributesKey.ofString(record.getAttributesKey()))
.qtyOnHand(record.getQtyOnHand())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\StockRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Mono<Boolean> blockingSearch(@PathVariable("name") String fileName, @RequestParam String term) {
return fileContentSearchService.blockingSearch(fileName, term);
}
@GetMapping(value = "/{name}/workable-blocking-search")
Mono<Boolean> workableBlockingSearch(@PathVariable("name") String fileName, @RequestParam String term) {
return fileContentSearchService.workableBlockingSearch(fileName, term)
.doOnNext(aBoolean -> ThreadLogger.log("1. In Controller"))
.map(Function.identity())
.doOnNext(aBoolean -> ThreadLogger.log("2. In Controller"));
}
@GetMapping(value = "/{name}/incorrect-use-of-schedulers-search")
Mono<Boolean> incorrectUseOfSchedulersSearch(@PathVariable("name") String fileName, @RequestParam String term) {
return fileContentSearchService.incorrectUseOfSchedulersSearch(fileName, term)
.doOnNext(aBoolean -> ThreadLogger.log("1. In Controller"))
.map(Function.identity())
.doOnNext(aBoolean -> ThreadLogger.log("2. In Controller"));
}
@GetMapping(value = "/{name}/blocking-search-on-custom-thread-pool")
Mono<Boolean> blockingSearchOnCustomThreadPool(@PathVariable("name") String fileName, @RequestParam String term) {
return fileContentSearchService.blockingSearchOnCustomThreadPool(fileName, term)
.doOnNext(aBoolean -> ThreadLogger.log("1. In Controller")) | .map(Function.identity())
.doOnNext(aBoolean -> ThreadLogger.log("2. In Controller"));
}
@GetMapping(value = "/{name}/blocking-search-on-parallel-thread-pool")
Mono<Boolean> blockingSearchOnParallelThreadPool(@PathVariable("name") String fileName, @RequestParam String term) {
return fileContentSearchService.blockingSearchOnParallelThreadPool(fileName, term)
.doOnNext(aBoolean -> ThreadLogger.log("1. In Controller"))
.map(Function.identity())
.doOnNext(aBoolean -> ThreadLogger.log("2. In Controller"));
}
@GetMapping(value = "/{name}/non-blocking-search")
Mono<Boolean> nonBlockingSearch(@PathVariable("name") String fileName, @RequestParam String term) {
return fileContentSearchService.nonBlockingSearch(fileName, term)
.doOnNext(aBoolean -> ThreadLogger.log("1. In Controller"))
.map(Function.identity())
.doOnNext(aBoolean -> ThreadLogger.log("2. In Controller"));
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-4\src\main\java\com\baeldung\webflux\block\controller\FileController.java | 2 |
请完成以下Java代码 | public class ErrorEvent extends Event {
private static final long serialVersionUID = 960461434033192571L;
@Builder
private ErrorEvent(TenantId tenantId, UUID entityId, String serviceId, UUID id, long ts, String method, String error) {
super(tenantId, entityId, serviceId, id, ts);
this.method = method;
this.error = error;
}
@Getter
@Setter
private String method;
@Getter
@Setter
private String error; | @Override
public EventType getType() {
return EventType.ERROR;
}
@Override
public EventInfo toInfo(EntityType entityType) {
EventInfo eventInfo = super.toInfo(entityType);
var json = (ObjectNode) eventInfo.getBody();
json.put("method", method);
if (error != null) {
json.put("error", error);
}
return eventInfo;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\event\ErrorEvent.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public void setResources(Map<String, EngineResource> resources) {
this.resources = resources;
}
@Override
public Date getDeploymentTime() {
return deploymentTime; | }
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public String getDerivedFrom() {
return null;
}
@Override
public String getDerivedFromRoot() {
return null;
}
@Override
public String getEngineVersion() {
return null;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "AppDeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getCaseInstanceLastReactivatedBefore() {
return caseInstanceLastReactivatedBefore;
}
public void setCaseInstanceLastReactivatedBefore(Date caseInstanceLastReactivatedBefore) {
this.caseInstanceLastReactivatedBefore = caseInstanceLastReactivatedBefore;
}
public Date getCaseInstanceLastReactivatedAfter() {
return caseInstanceLastReactivatedAfter;
}
public void setCaseInstanceLastReactivatedAfter(Date caseInstanceLastReactivatedAfter) {
this.caseInstanceLastReactivatedAfter = caseInstanceLastReactivatedAfter;
}
public Boolean getIncludeCaseVariables() {
return includeCaseVariables;
}
public void setIncludeCaseVariables(Boolean includeCaseVariables) {
this.includeCaseVariables = includeCaseVariables;
}
public Collection<String> getIncludeCaseVariablesNames() {
return includeCaseVariablesNames;
}
public void setIncludeCaseVariablesNames(Collection<String> includeCaseVariablesNames) {
this.includeCaseVariablesNames = includeCaseVariablesNames;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class)
public List<QueryVariable> getVariables() {
return variables;
}
public void setVariables(List<QueryVariable> variables) {
this.variables = variables;
}
public String getActivePlanItemDefinitionId() {
return activePlanItemDefinitionId;
}
public void setActivePlanItemDefinitionId(String activePlanItemDefinitionId) {
this.activePlanItemDefinitionId = activePlanItemDefinitionId;
}
public Set<String> getActivePlanItemDefinitionIds() {
return activePlanItemDefinitionIds;
}
public void setActivePlanItemDefinitionIds(Set<String> activePlanItemDefinitionIds) {
this.activePlanItemDefinitionIds = activePlanItemDefinitionIds;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
} | public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public String getTenantIdLikeIgnoreCase() {
return tenantIdLikeIgnoreCase;
}
public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) {
this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase;
}
public Set<String> getCaseInstanceCallbackIds() {
return caseInstanceCallbackIds;
}
public void setCaseInstanceCallbackIds(Set<String> caseInstanceCallbackIds) {
this.caseInstanceCallbackIds = caseInstanceCallbackIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public TypedValue getRootObject() {
return delegate.getRootObject();
}
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return delegate.getPropertyAccessors();
}
@Override
public List<ConstructorResolver> getConstructorResolvers() {
return delegate.getConstructorResolvers();
}
@Override
public List<MethodResolver> getMethodResolvers() {
return delegate.getMethodResolvers();
}
@Override
@Nullable
public BeanResolver getBeanResolver() {
return this.beanFactoryResolver;
}
@Override
public TypeLocator getTypeLocator() {
return delegate.getTypeLocator();
}
@Override
public TypeConverter getTypeConverter() {
return delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return delegate.getOperatorOverloader(); | }
@Override
public void setVariable(String name, Object value) {
delegate.setVariable(name, value);
}
@Override
@Nullable
public Object lookupVariable(String name) {
return delegate.lookupVariable(name);
}
@Override
public List<IndexAccessor> getIndexAccessors() {
return delegate.getIndexAccessors();
}
@Override
public TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
return delegate.assignVariable(name, valueSupplier);
}
@Override
public boolean isAssignmentEnabled() {
return delegate.isAssignmentEnabled();
}
}
class RestrictivePropertyAccessor extends ReflectivePropertyAccessor {
@Override
public boolean canRead(EvaluationContext context, Object target, String name) {
return false;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ShortcutConfigurable.java | 1 |
请完成以下Java代码 | public final class LocatorScannedCodeResolverResult
{
@Nullable LocatorQRCode locatorQRCode;
@NonNull @Getter ImmutableList<LocatorNotResolvedReason> notResolvedReasons;
private LocatorScannedCodeResolverResult(@NonNull LocatorQRCode locatorQRCode)
{
this.locatorQRCode = locatorQRCode;
this.notResolvedReasons = ImmutableList.of();
}
private LocatorScannedCodeResolverResult(@NonNull final List<LocatorNotResolvedReason> notResolvedReasons)
{
this.locatorQRCode = null;
this.notResolvedReasons = ImmutableList.copyOf(notResolvedReasons);
}
public static LocatorScannedCodeResolverResult notFound(@NonNull final LocatorGlobalQRCodeResolverKey resolver, @NonNull final String reason)
{
return new LocatorScannedCodeResolverResult(ImmutableList.of(LocatorNotResolvedReason.of(resolver, reason)));
}
public static LocatorScannedCodeResolverResult notFound(@NonNull final List<LocatorNotResolvedReason> notFoundReasons)
{
return new LocatorScannedCodeResolverResult(notFoundReasons);
}
public static LocatorScannedCodeResolverResult found(@NonNull final LocatorQRCode locatorQRCode)
{
return new LocatorScannedCodeResolverResult(locatorQRCode);
} | public boolean isFound() {return locatorQRCode != null;}
@NonNull
public LocatorId getLocatorId()
{
return getLocatorQRCode().getLocatorId();
}
@NonNull
public LocatorQRCode getLocatorQRCode()
{
if (locatorQRCode == null)
{
throw AdempiereException.notFound()
.setParameter("notResolvedReasons", notResolvedReasons);
}
return locatorQRCode;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\resolver\LocatorScannedCodeResolverResult.java | 1 |
请完成以下Java代码 | public Builder setAD_Tab_ID(final int adTabId)
{
this.adTabId = adTabId;
return this;
}
private int getAD_Tab_ID()
{
Check.assumeNotNull(adTabId, "adTabId not null");
return adTabId;
}
public Builder setAD_Table_ID(final int adTableId)
{
this.adTableId = adTableId;
return this;
}
private int getAD_Table_ID()
{
Check.assumeNotNull(adTableId, "adTableId not null");
Check.assume(adTableId > 0, "adTableId > 0");
return adTableId;
}
public Builder setAD_User_ID(final int adUserId)
{
this.adUserId = adUserId;
return this;
}
public Builder setAD_User_ID_Any()
{
this.adUserId = -1;
return this;
} | private int getAD_User_ID()
{
Check.assumeNotNull(adUserId, "Parameter adUserId is not null");
return adUserId;
}
public Builder setColumnDisplayTypeProvider(@NonNull final ColumnDisplayTypeProvider columnDisplayTypeProvider)
{
this.columnDisplayTypeProvider = columnDisplayTypeProvider;
return this;
}
public ColumnDisplayTypeProvider getColumnDisplayTypeProvider()
{
return columnDisplayTypeProvider;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\UserQueryRepository.java | 1 |
请完成以下Java代码 | public class ComponentDescriptorEntity extends BaseSqlEntity<ComponentDescriptor> {
@Enumerated(EnumType.STRING)
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY)
private ComponentType type;
@Enumerated(EnumType.STRING)
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY)
private ComponentScope scope;
@Enumerated(EnumType.STRING)
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_CLUSTERING_MODE_PROPERTY)
private ComponentClusteringMode clusteringMode;
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_NAME_PROPERTY)
private String name;
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, unique = true)
private String clazz;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_CONFIGURATION_DESCRIPTOR_PROPERTY)
private JsonNode configurationDescriptor;
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_CONFIGURATION_VERSION_PROPERTY)
private int configurationVersion;
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_ACTIONS_PROPERTY)
private String actions;
@Column(name = ModelConstants.COMPONENT_DESCRIPTOR_HAS_QUEUE_NAME_PROPERTY)
private boolean hasQueueName;
public ComponentDescriptorEntity() {
}
public ComponentDescriptorEntity(ComponentDescriptor component) {
if (component.getId() != null) {
this.setUuid(component.getId().getId());
}
this.setCreatedTime(component.getCreatedTime());
this.actions = component.getActions();
this.type = component.getType();
this.scope = component.getScope();
this.clusteringMode = component.getClusteringMode();
this.name = component.getName(); | this.clazz = component.getClazz();
this.configurationDescriptor = component.getConfigurationDescriptor();
this.configurationVersion = component.getConfigurationVersion();
this.hasQueueName = component.isHasQueueName();
}
@Override
public ComponentDescriptor toData() {
ComponentDescriptor data = new ComponentDescriptor(new ComponentDescriptorId(this.getUuid()));
data.setCreatedTime(createdTime);
data.setType(type);
data.setScope(scope);
data.setClusteringMode(clusteringMode);
data.setName(this.getName());
data.setClazz(this.getClazz());
data.setActions(this.getActions());
data.setConfigurationDescriptor(configurationDescriptor);
data.setConfigurationVersion(configurationVersion);
data.setHasQueueName(hasQueueName);
return data;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\ComponentDescriptorEntity.java | 1 |
请完成以下Java代码 | public void invalidateAll() {}
@NonNull
Optional<ImmutableList<AttachmentLinksRequest>> createAttachmentLinksRequestList()
{
final ImmutableList<AttachmentLinksRequest> userChanges = aggregateRowsByAttachmentEntryId()
.stream()
.map(OrderAttachmentRow::toAttachmentLinksRequest)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
return !userChanges.isEmpty()
? Optional.of(userChanges)
: Optional.empty();
}
private void changeRow(
@NonNull final DocumentId rowId,
@NonNull final UnaryOperator<OrderAttachmentRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
}
rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{
throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
/**
* Aggregates the view rows by {@link OrderAttachmentRow#getAttachmentEntryId()}.
* The aggregation logic goes like this: | * 1. if there is at least one row marked by the user for attaching to the purchase order ({@link OrderAttachmentRow#getIsAttachToPurchaseOrder()})
* then, that row will be taken into account for the attachment entry in cause.
* 2. otherwise, take the first row of the group.
*
* @return an aggregated list of {@link OrderAttachmentRow} by {@link AttachmentEntryId}
*/
@NonNull
private List<OrderAttachmentRow> aggregateRowsByAttachmentEntryId()
{
final ArrayListMultimap<Integer, OrderAttachmentRow> rowsByAttachmentEntryId = rowsById.values()
.stream()
.collect(GuavaCollectors.toArrayListMultimapByKey(OrderAttachmentRow::getAttachmentEntryId));
final ImmutableList.Builder<OrderAttachmentRow> attachmentRowCollector = ImmutableList.builder();
for (final Integer attachmentEntryId : rowsByAttachmentEntryId.keySet())
{
final List<OrderAttachmentRow> attachmentRowsForEntryId = rowsByAttachmentEntryId.get(attachmentEntryId);
final OrderAttachmentRow firstRowAttach = attachmentRowsForEntryId.stream()
.filter(OrderAttachmentRow::getIsAttachToPurchaseOrder)
.findFirst()
.orElseGet(() -> attachmentRowsForEntryId.get(0));
attachmentRowCollector.add(firstRowAttach);
}
return attachmentRowCollector.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentRows.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Book> findAll() {
return new ArrayList<>(BOOK_DB.values());
}
@Override
public Book insertByBook(Book book) {
book.setId(BOOK_DB.size() + 1L);
BOOK_DB.put(book.getId().toString(), book);
return book;
}
@Override
public Book update(Book book) {
BOOK_DB.put(book.getId().toString(), book);
return book;
}
@Override
public Book delete(Long id) {
return BOOK_DB.remove(id.toString());
}
@Override
public Book findById(Long id) {
return BOOK_DB.get(id.toString());
}
@Override | public boolean exists(Book book) {
return findByName(book.getName()) != null;
}
@Override
public Book findByName(String name) {
for (Book book : books) {
if (book.getName().equals(name)) {
return book;
}
}
return null;
}
} | repos\springboot-learning-example-master\chapter-3-spring-boot-web\src\main\java\demo\springboot\service\impl\BookServiceImpl.java | 2 |
请完成以下Java代码 | public static String toGlobalQRCodeJsonString(final DeviceQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final DeviceQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
public static DeviceQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static DeviceQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType())) | {
throw new AdempiereException("Invalid QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
}
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\qrcode\DeviceQRCodeJsonConverter.java | 1 |
请完成以下Java代码 | public RedisCacheElement get(final RedisCacheKey cacheKey) {
Assert.notNull(cacheKey, "CacheKey must not be null!");
// 根据key获取缓存值
RedisCacheElement redisCacheElement = new RedisCacheElement(cacheKey, fromStoreValue(lookup(cacheKey)));
// 判断key是否存在
Boolean exists = (Boolean) redisOperations.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.exists(cacheKey.getKeyBytes());
}
});
if (!exists.booleanValue()) {
return null;
}
return redisCacheElement;
}
/**
* 刷新缓存数据
*/
private void refreshCache(Object key, String cacheKeyStr) {
Long ttl = this.redisOperations.getExpire(cacheKeyStr);
if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
// 尽量少的去开启线程,因为线程池是有限的
ThreadTaskUtils.run(new Runnable() {
@Override
public void run() {
// 加一个分布式锁,只放一个请求去刷新缓存
RedisLock redisLock = new RedisLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock");
try {
if (redisLock.lock()) {
// 获取锁之后再判断一下过期时间,看是否需要加载数据
Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr);
if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
// 通过获取代理方法信息重新加载缓存数据
CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), cacheKeyStr);
} | }
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock.unlock();
}
}
});
}
}
public long getExpirationSecondTime() {
return expirationSecondTime;
}
/**
* 获取RedisCacheKey
*
* @param key
* @return
*/
public RedisCacheKey getRedisCacheKey(Object key) {
return new RedisCacheKey(key).usePrefix(this.prefix)
.withKeySerializer(redisOperations.getKeySerializer());
}
/**
* 获取RedisCacheKey
*
* @param key
* @return
*/
public String getCacheKey(Object key) {
return new String(getRedisCacheKey(key).getKeyBytes());
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CustomizedRedisCache.java | 1 |
请完成以下Java代码 | public static void adjust(
@NonNull final IHUDeliveryQuantities target,
@Nullable final IHUDeliveryQuantities qtysToRemove,
@Nullable final IHUDeliveryQuantities qtysToAdd)
{
if (qtysToRemove != null)
{
removeFrom(target, qtysToRemove);
}
if (qtysToAdd != null)
{
addTo(target, qtysToAdd);
}
}
/**
* Copy HU quantities from <code>from</code> to <code>to</code>.
*
* @param to
* @param shipmentSchedule
*/
public static void copy(
@NonNull final IHUDeliveryQuantities to,
@NonNull final I_M_ShipmentSchedule shipmentSchedule)
{
final List<I_M_ShipmentSchedule_QtyPicked> shipmentScheduleQtyPickedList = //
Services.get(IQueryBL.class)
.createQueryBuilder(I_M_ShipmentSchedule_QtyPicked.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_M_ShipmentSchedule_ID, shipmentSchedule.getM_ShipmentSchedule_ID())
.create()
.list();
BigDecimal qtyDeliveredLU = BigDecimal.ZERO;
BigDecimal qtyDeliveredTU = BigDecimal.ZERO;
for (final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked : shipmentScheduleQtyPickedList)
{
qtyDeliveredLU = add(qtyDeliveredLU, shipmentScheduleQtyPicked.getQtyLU());
qtyDeliveredTU = add(qtyDeliveredTU, shipmentScheduleQtyPicked.getQtyTU());
}
to.setQtyOrdered_LU(shipmentSchedule.getQtyOrdered_LU());
to.setQtyDelivered_LU(qtyDeliveredLU);
to.setQtyOrdered_TU(shipmentSchedule.getQtyOrdered_TU());
to.setQtyDelivered_TU(qtyDeliveredTU);
}
/**
*
* @param bd1
* @param bd2
* @return bd1 + bd2
*/
private static final BigDecimal add(final BigDecimal bd1, final BigDecimal bd2) | {
BigDecimal result;
if (bd1 != null)
{
result = bd1;
}
else
{
result = BigDecimal.ZERO;
}
if (bd2 != null)
{
result = result.add(bd2);
}
return result;
}
/**
*
* @param bd1
* @param bd2
* @return bd1 - bd2
*/
private static final BigDecimal subtract(final BigDecimal bd1, final BigDecimal bd2)
{
BigDecimal result;
if (bd1 != null)
{
result = bd1;
}
else
{
result = BigDecimal.ZERO;
}
if (bd2 != null)
{
result = result.subtract(bd2);
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUDeliveryQuantitiesHelper.java | 1 |
请完成以下Java代码 | public boolean isStoreInvoicesInResult()
{
if (storeInvoicesInResult != null)
{
return storeInvoicesInResult;
}
else if (defaults != null)
{
return defaults.isStoreInvoicesInResult();
}
else
{
return false;
}
}
public PlainInvoicingParams setStoreInvoicesInResult(final boolean storeInvoicesInResult)
{
this.storeInvoicesInResult = storeInvoicesInResult;
return this;
}
@Override
public boolean isAssumeOneInvoice()
{
if (assumeOneInvoice != null)
{
return assumeOneInvoice;
}
else if (defaults != null)
{
return defaults.isAssumeOneInvoice();
}
else
{
return false;
}
}
public PlainInvoicingParams setAssumeOneInvoice(final boolean assumeOneInvoice) | {
this.assumeOneInvoice = assumeOneInvoice;
return this;
}
public boolean isUpdateLocationAndContactForInvoice()
{
return updateLocationAndContactForInvoice;
}
public void setUpdateLocationAndContactForInvoice(boolean updateLocationAndContactForInvoice)
{
this.updateLocationAndContactForInvoice = updateLocationAndContactForInvoice;
}
public PlainInvoicingParams setCompleteInvoices(final boolean completeInvoices)
{
this.completeInvoices = completeInvoices;
return this;
}
@Override
public boolean isCompleteInvoices()
{
return completeInvoices;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\PlainInvoicingParams.java | 1 |
请完成以下Java代码 | protected ScopeImpl getScope(InterpretableExecution execution) {
ActivityImpl activity = (ActivityImpl) execution.getActivity();
if (activity != null) {
return activity;
} else {
InterpretableExecution parent = (InterpretableExecution) execution.getParent();
if (parent != null) {
return getScope((InterpretableExecution) execution.getParent());
}
return execution.getProcessDefinition();
}
}
@Override
protected String getEventName() {
return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_END;
}
@Override
protected void eventNotificationsCompleted(InterpretableExecution execution) {
ActivityImpl activity = (ActivityImpl) execution.getActivity(); | if ((execution.isScope())
&& (activity != null)) {
execution.setActivity(activity.getParentActivity());
execution.performOperation(AtomicOperation.DELETE_CASCADE_FIRE_ACTIVITY_END);
} else {
if (execution.isScope()) {
execution.destroy();
}
execution.remove();
if (!execution.isDeleteRoot()) {
InterpretableExecution parent = (InterpretableExecution) execution.getParent();
if (parent != null) {
parent.performOperation(AtomicOperation.DELETE_CASCADE);
}
}
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationDeleteCascadeFireActivityEnd.java | 1 |
请完成以下Java代码 | public void setCM_NewsChannel_ID (int CM_NewsChannel_ID)
{
if (CM_NewsChannel_ID < 1)
set_Value (COLUMNNAME_CM_NewsChannel_ID, null);
else
set_Value (COLUMNNAME_CM_NewsChannel_ID, Integer.valueOf(CM_NewsChannel_ID));
}
/** Get News Channel.
@return News channel for rss feed
*/
public int getCM_NewsChannel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_NewsChannel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set News Item / Article.
@param CM_NewsItem_ID
News item or article defines base content
*/
public void setCM_NewsItem_ID (int CM_NewsItem_ID)
{
if (CM_NewsItem_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_NewsItem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_NewsItem_ID, Integer.valueOf(CM_NewsItem_ID));
}
/** Get News Item / Article.
@return News item or article defines base content
*/
public int getCM_NewsItem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_NewsItem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Content HTML.
@param ContentHTML
Contains the content itself
*/
public void setContentHTML (String ContentHTML)
{
set_Value (COLUMNNAME_ContentHTML, ContentHTML);
}
/** Get Content HTML.
@return Contains the content itself
*/
public String getContentHTML ()
{
return (String)get_Value(COLUMNNAME_ContentHTML);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set LinkURL.
@param LinkURL
Contains URL to a target
*/
public void setLinkURL (String LinkURL)
{
set_Value (COLUMNNAME_LinkURL, LinkURL); | }
/** Get LinkURL.
@return Contains URL to a target
*/
public String getLinkURL ()
{
return (String)get_Value(COLUMNNAME_LinkURL);
}
/** Set Publication Date.
@param PubDate
Date on which this article will / should get published
*/
public void setPubDate (Timestamp PubDate)
{
set_Value (COLUMNNAME_PubDate, PubDate);
}
/** Get Publication Date.
@return Date on which this article will / should get published
*/
public Timestamp getPubDate ()
{
return (Timestamp)get_Value(COLUMNNAME_PubDate);
}
/** Set Title.
@param Title
Name this entity is referred to as
*/
public void setTitle (String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Title.
@return Name this entity is referred to as
*/
public String getTitle ()
{
return (String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java | 1 |
请完成以下Java代码 | public Duration getMaxInactiveInterval() {
return this.cached.getMaxInactiveInterval();
}
@Override
public boolean isExpired() {
return this.cached.isExpired();
}
private boolean hasChangedSessionId() {
return !getId().equals(this.originalSessionId);
}
private Mono<Void> save() {
return Mono.defer(() -> saveChangeSessionId().then(saveDelta()).doOnSuccess((aVoid) -> this.isNew = false));
}
private Mono<Void> saveDelta() {
if (this.delta.isEmpty()) {
return Mono.empty();
}
String sessionKey = getSessionKey(getId());
Mono<Boolean> update = ReactiveRedisSessionRepository.this.sessionRedisOperations.opsForHash()
.putAll(sessionKey, new HashMap<>(this.delta));
Mono<Boolean> setTtl;
if (getMaxInactiveInterval().getSeconds() >= 0) {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.expire(sessionKey,
getMaxInactiveInterval());
}
else {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.persist(sessionKey);
}
Mono<Object> clearDelta = Mono.fromDirect((s) -> {
this.delta.clear();
s.onComplete();
});
return update.flatMap((unused) -> setTtl).flatMap((unused) -> clearDelta).then();
}
private Mono<Void> saveChangeSessionId() {
if (!hasChangedSessionId()) {
return Mono.empty();
}
String sessionId = getId();
Publisher<Void> replaceSessionId = (s) -> {
this.originalSessionId = sessionId;
s.onComplete();
}; | if (this.isNew) {
return Mono.from(replaceSessionId);
}
else {
String originalSessionKey = getSessionKey(this.originalSessionId);
String sessionKey = getSessionKey(sessionId);
return ReactiveRedisSessionRepository.this.sessionRedisOperations.rename(originalSessionKey, sessionKey)
.flatMap((unused) -> Mono.fromDirect(replaceSessionId))
.onErrorResume((ex) -> {
String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
return StringUtils.startsWithIgnoreCase(message, "ERR no such key");
}, (ex) -> Mono.empty());
}
}
}
private static final class RedisSessionMapperAdapter
implements BiFunction<String, Map<String, Object>, Mono<MapSession>> {
private final RedisSessionMapper mapper = new RedisSessionMapper();
@Override
public Mono<MapSession> apply(String sessionId, Map<String, Object> map) {
return Mono.fromSupplier(() -> this.mapper.apply(sessionId, map));
}
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionRepository.java | 1 |
请完成以下Java代码 | public abstract class AbstractModelInterceptor implements IModelInterceptor, IUserLoginListener
{
private int adClientId = -1;
@Override
public final void initialize(final IModelValidationEngine engine, final I_AD_Client client)
{
adClientId = client == null ? -1 : client.getAD_Client_ID();
onInit(engine, client);
}
/**
* Called when interceptor is registered and needs to be initialized
*/
protected abstract void onInit(final IModelValidationEngine engine, final I_AD_Client client);
@Override
public final int getAD_Client_ID()
{
return adClientId;
}
// NOTE: method signature shall be the same as org.adempiere.ad.security.IUserLoginListener.onUserLogin(int, int, int)
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing
}
@Override | public void beforeLogout(final MFSession session)
{
// nothing
}
@Override
public void afterLogout(final MFSession session)
{
// nothing
}
@Override
public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception
{
// nothing
}
@Override
public void onDocValidate(final Object model, final DocTimingType timing) throws Exception
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AbstractModelInterceptor.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public double getPrice() { | return price;
}
public void setPrice(final double price) {
this.price = price;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Product [name=")
.append(name)
.append(", id=")
.append(id)
.append("]");
return builder.toString();
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\multipledb\model\product\Product.java | 1 |
请完成以下Java代码 | public final DefaultPaymentBuilder tenderType(@NonNull final TenderType tenderType)
{
assertNotBuilt();
payment.setTenderType(tenderType.getCode());
return this;
}
/**
* Sets the following fields using the given <code>invoice</code>:
* <ul>
* <li>C_Invoice_ID
* <li>C_BPartner_ID
* <li>C_Currency_ID
* <li>IsReceipt: set from the invoice's <code>SOTrx</code> (negated if the invoice is a credit memo)
* </ul>
*/
private DefaultPaymentBuilder fromInvoice(@NonNull final I_C_Invoice invoice)
{
adOrgId(OrgId.ofRepoId(invoice.getAD_Org_ID()));
invoiceId(InvoiceId.ofRepoId(invoice.getC_Invoice_ID()));
bpartnerId(BPartnerId.ofRepoId(invoice.getC_BPartner_ID()));
currencyId(CurrencyId.ofRepoId(invoice.getC_Currency_ID()));
final SOTrx soTrx = SOTrx.ofBoolean(invoice.isSOTrx());
final boolean creditMemo = Services.get(IInvoiceBL.class).isCreditMemo(invoice);
direction(PaymentDirection.ofSOTrxAndCreditMemo(soTrx, creditMemo));
return this;
}
public final DefaultPaymentBuilder invoiceId(@Nullable final InvoiceId invoiceId)
{
assertNotBuilt();
payment.setC_Invoice_ID(InvoiceId.toRepoId(invoiceId));
return this;
}
public final DefaultPaymentBuilder description(final String description)
{
assertNotBuilt();
payment.setDescription(description);
return this;
}
public final DefaultPaymentBuilder externalId(@Nullable final ExternalId externalId)
{
assertNotBuilt();
if (externalId != null)
{
payment.setExternalId(externalId.getValue());
}
return this;
}
public final DefaultPaymentBuilder orderId(@Nullable final OrderId orderId)
{
assertNotBuilt();
if (orderId != null) | {
payment.setC_Order_ID(orderId.getRepoId());
}
return this;
}
public final DefaultPaymentBuilder orderExternalId(@Nullable final String orderExternalId)
{
assertNotBuilt();
if (Check.isNotBlank(orderExternalId))
{
payment.setExternalOrderId(orderExternalId);
}
return this;
}
public final DefaultPaymentBuilder isAutoAllocateAvailableAmt(final boolean isAutoAllocateAvailableAmt)
{
assertNotBuilt();
payment.setIsAutoAllocateAvailableAmt(isAutoAllocateAvailableAmt);
return this;
}
private DefaultPaymentBuilder fromOrder(@NonNull final I_C_Order order)
{
adOrgId(OrgId.ofRepoId(order.getAD_Org_ID()));
orderId(OrderId.ofRepoId(order.getC_Order_ID()));
bpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
currencyId(CurrencyId.ofRepoId(order.getC_Currency_ID()));
final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx());
direction(PaymentDirection.ofSOTrxAndCreditMemo(soTrx, false));
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\DefaultPaymentBuilder.java | 1 |
请完成以下Java代码 | public boolean isFullExclude(I_M_AttributeSetExclude attributeSetExclude)
{
if (null == attributeSetExclude)
{
return false;
}
final List<I_M_AttributeSetExcludeLine> list = attributeExcludeDAO.retrieveLines(attributeSetExclude);
if ((null != list) && (!list.isEmpty()))
{
final AttributeSetId attributeSetId = AttributeSetId.ofRepoId(attributeSetExclude.getM_AttributeSet_ID());
final List<Attribute> attributeList = attributeDAO.retrieveAttributes(attributeSetId, true);
Check.assumeNotNull(attributeList, "We shouldn't have attribute exclude lines on attribute sets without attributes; attributeSetExclude=" + attributeSetExclude);
if (list.size() == attributeList.size())
{
// Every attribute is marked to be excluded.
return true;
}
// Only some attributes are excluded. Not full exclude.
return false;
}
return true;
}
@Override
public boolean isExcludedAttribute(Attribute attribute, AttributeSetId attributeSetId, int columnId, SOTrx soTrx)
{
final I_M_AttributeSetExclude attributeSetExclude = attributeExcludeDAO.retrieveAttributeSetExclude(attributeSetId, columnId, soTrx);
if (null == attributeSetExclude)
{
return false; | }
final List<I_M_AttributeSetExcludeLine> list = attributeExcludeDAO.retrieveLines(attributeSetExclude);
if ((null == list) || (list.isEmpty()))
{
// Full exclude.
return true;
}
for (final I_M_AttributeSetExcludeLine line : list)
{
final AttributeId lineAttributeId = AttributeId.ofRepoIdOrNull(line.getM_Attribute_ID());
if (AttributeId.equals(lineAttributeId, attribute.getAttributeId()))
{
// We have a match. Attribute excluded.
return true;
}
}
return false;
}
@Override
public I_M_AttributeSetExclude getAttributeSetExclude(@NonNull final AttributeSetId attributeSetId, int columnId, @NonNull SOTrx soTrx)
{
return attributeExcludeDAO.retrieveAttributeSetExclude(attributeSetId, columnId, soTrx);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeExcludeBL.java | 1 |
请完成以下Java代码 | public String buildStorageInvoiceHistorySQL(final boolean showDetail, final int warehouseId, final int asiId)
{
final StringBuilder sql = new StringBuilder("SELECT ")
.append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOnHand).append(", ")
.append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyReserved).append(", ")
.append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOrdered).append(", ")
.append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_HUStorageASIKey).append(", ")
.append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_HUStorageASIKey).append(", ")
.append("w.").append(org.compiere.model.I_M_Warehouse.COLUMNNAME_Name).append(", ")
.append("l.").append(org.compiere.model.I_M_Locator.COLUMNNAME_Value).append(" ");
sql.append("FROM ").append(I_RV_M_HU_Storage_InvoiceHistory.Table_Name).append(" s")
.append(" LEFT JOIN ").append(org.compiere.model.I_M_Locator.Table_Name).append(" l ON (s.M_Locator_ID=l.M_Locator_ID)")
.append(" LEFT JOIN ").append(org.compiere.model.I_M_Warehouse.Table_Name).append(" w ON (l.M_Warehouse_ID=w.M_Warehouse_ID) ")
.append("WHERE M_Product_ID=?"); | if (warehouseId != 0)
{
sql.append(" AND (1=1 OR l.M_Warehouse_ID=?)"); // Note the 1=1; We're mocking the warehouse filter to preserve legacy code and not screw with the prepared statement
}
if (asiId > 0)
{
sql.append(" OR GenerateHUStorageASIKey(?)=s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_HUStorageASIKey); // ASI dummy (keep original query by ASI)
}
sql.append(" AND (s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOnHand).append("<>0")
.append(" OR s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyReserved).append("<>0")
.append(" OR s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOrdered).append("<>0)");
return sql.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\compiere\apps\search\dao\impl\HUInvoiceHistoryDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WarehouseAccountsRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<WarehouseId, ImmutableMap<AcctSchemaId, WarehouseAccounts>> cache = CCache.<WarehouseId, ImmutableMap<AcctSchemaId, WarehouseAccounts>>builder()
.tableName(I_M_Warehouse.Table_Name)
.cacheMapType(CCache.CacheMapType.LRU)
.initialCapacity(50)
.build();
public WarehouseAccounts getAccounts(@NonNull final WarehouseId warehouseId, @NonNull final AcctSchemaId acctSchemaId)
{
final ImmutableMap<AcctSchemaId, WarehouseAccounts> map = cache.getOrLoad(warehouseId, this::retrieveAccounts);
final WarehouseAccounts accounts = map.get(acctSchemaId);
if (accounts == null)
{
throw new AdempiereException("No Warehouse accounts defined for " + warehouseId + " and " + acctSchemaId);
}
return accounts;
}
private ImmutableMap<AcctSchemaId, WarehouseAccounts> retrieveAccounts(@NonNull final WarehouseId warehouseId) | {
return queryBL.createQueryBuilder(I_M_Warehouse_Acct.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Warehouse_Acct.COLUMNNAME_M_Warehouse_ID, warehouseId)
.create()
.stream()
.map(WarehouseAccountsRepository::fromRecord)
.collect(ImmutableMap.toImmutableMap(WarehouseAccounts::getAcctSchemaId, accounts -> accounts));
}
private static WarehouseAccounts fromRecord(@NonNull final I_M_Warehouse_Acct record)
{
return WarehouseAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.W_Differences_Acct(Account.of(AccountId.ofRepoId(record.getW_Differences_Acct()), WarehouseAccountType.W_Differences_Acct))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\WarehouseAccountsRepository.java | 2 |
请完成以下Java代码 | public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
return getResAccessUrl(storePath);
}
/**
* 将一段字符串生成一个文件上传
* @param content 文件内容
* @param fileExtension
* @return
*/
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
return getResAccessUrl(storePath);
}
// 封装图片完整URL地址
private String getResAccessUrl(StorePath storePath) {
String fileUrl = FastDFSConstants.HTTP_PRODOCOL + "://" + FastDFSConstants.RES_HOST + "/" + storePath.getFullPath();
return fileUrl;
}
/**
* 删除文件
* @param fileUrl 文件访问地址
* @return
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try { | StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
log.warn(e.getMessage());
}
}
// 除了FastDFSClientWrapper类中用到的api,客户端提供的api还有很多,可根据自身的业务需求,将其它接口也添加到工具类中即可。
// 上传文件,并添加文件元数据
//StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 获取文件元数据
//Set<MateData> getMetadata(String groupName, String path);
// 上传图片并同时生成一个缩略图
//StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 。。。
} | repos\springboot-demo-master\fastdfs\src\main\java\com\et\fastdfs\util\FastDFSClientWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InvoiceRejectionDetailId implements RepoIdAware
{
@JsonCreator
public static InvoiceRejectionDetailId ofRepoId(final int repoId)
{
return new InvoiceRejectionDetailId(repoId);
}
public static InvoiceRejectionDetailId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new InvoiceRejectionDetailId(repoId) : null;
}
int repoId;
private InvoiceRejectionDetailId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, I_C_Invoice_Rejection_Detail.COLUMNNAME_C_Invoice_Rejection_Detail_ID);
}
@JsonValue
@Override | public int getRepoId()
{
return repoId;
}
public static int toRepoId(final InvoiceRejectionDetailId invoiceId)
{
return toRepoIdOr(invoiceId, -1);
}
public static int toRepoIdOr(final InvoiceRejectionDetailId invoiceId, final int defaultValue)
{
return invoiceId != null ? invoiceId.getRepoId() : defaultValue;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\InvoiceRejectionDetailId.java | 2 |
请完成以下Java代码 | public AttachmentListenerConstants.ListenerWorkStatus afterRecordLinked(
@NonNull final AttachmentEntry attachmentEntry,
@NonNull final TableRecordReference tableRecordReference)
{
final BankStatementImportFileId bankStatementImportFileId = tableRecordReference
.getIdAssumingTableName(I_C_BankStatement_Import_File.Table_Name, BankStatementImportFileId::ofRepoId);
bankStatementImportFileService.save(bankStatementImportFileService.getById(bankStatementImportFileId)
.toBuilder()
.filename(attachmentEntry.getFilename())
.build());
return AttachmentListenerConstants.ListenerWorkStatus.SUCCESS;
}
@Override
@NonNull
public AttachmentListenerConstants.ListenerWorkStatus beforeRecordLinked(
@NonNull final AttachmentEntry attachmentEntry,
@NonNull final TableRecordReference tableRecordReference)
{ | Check.assume(tableRecordReference.getTableName().equals(I_C_BankStatement_Import_File.Table_Name), "This is only about C_BankStatement_Import_File!");
final boolean attachmentEntryMatch = attachmentEntryService.getByReferencedRecord(tableRecordReference)
.stream()
.map(AttachmentEntry::getId)
.allMatch(attachmentEntryId -> AttachmentEntryId.equals(attachmentEntryId, attachmentEntry.getId()));
if (!attachmentEntryMatch)
{
logger.debug("multiple attachments not allowed for tableRecord reference ={}; -> returning FAILURE", tableRecordReference.getTableName());
return AttachmentListenerConstants.ListenerWorkStatus.FAILURE;
}
return AttachmentListenerConstants.ListenerWorkStatus.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\listener\BankStatementImportFileAttachmentListener.java | 1 |
请完成以下Java代码 | public @Nullable String getValidationQuery() {
return this.validationQuery;
}
/**
* Find a {@link DatabaseDriver} for the given URL.
* @param url the JDBC URL
* @return the database driver or {@link #UNKNOWN} if not found
*/
public static DatabaseDriver fromJdbcUrl(@Nullable String url) {
if (StringUtils.hasLength(url)) {
Assert.isTrue(url.startsWith("jdbc"), "'url' must start with \"jdbc\"");
String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH);
for (DatabaseDriver driver : values()) {
for (String urlPrefix : driver.getUrlPrefixes()) {
String prefix = ":" + urlPrefix + ":";
if (driver != UNKNOWN && urlWithoutPrefix.startsWith(prefix)) {
return driver;
}
}
} | }
return UNKNOWN;
}
/**
* Find a {@link DatabaseDriver} for the given product name.
* @param productName product name
* @return the database driver or {@link #UNKNOWN} if not found
*/
public static DatabaseDriver fromProductName(@Nullable String productName) {
if (StringUtils.hasLength(productName)) {
for (DatabaseDriver candidate : values()) {
if (candidate.matchProductName(productName)) {
return candidate;
}
}
}
return UNKNOWN;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\DatabaseDriver.java | 1 |
请完成以下Java代码 | public Predicate<ServerWebExchange> apply(WeightConfig config) {
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
Map<String, String> weights = exchange.getAttributeOrDefault(WEIGHT_ATTR, Collections.emptyMap());
String routeId = exchange.getAttribute(GATEWAY_PREDICATE_ROUTE_ATTR);
if (routeId == null) {
return false;
}
// all calculations and comparison against random num happened in
// WeightCalculatorWebFilter
String group = config.getGroup();
if (weights.containsKey(group)) {
String chosenRoute = weights.get(group);
if (log.isTraceEnabled()) {
log.trace("in group weight: " + group + ", current route: " + routeId + ", chosen route: "
+ chosenRoute);
}
return routeId.equals(chosenRoute);
}
else if (log.isTraceEnabled()) {
log.trace("no weights found for group: " + group + ", current route: " + routeId);
} | return false;
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Weight: %s %s", config.getGroup(), config.getWeight());
}
};
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\WeightRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public void setW_Differences_Acct (int W_Differences_Acct)
{
set_Value (COLUMNNAME_W_Differences_Acct, Integer.valueOf(W_Differences_Acct));
}
/** Get Warehouse Differences.
@return Warehouse Differences Account
*/
public int getW_Differences_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Differences_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getW_InvActualAdjust_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getW_InvActualAdjust_Acct(), get_TrxName()); }
/** Set Inventory Adjustment.
@param W_InvActualAdjust_Acct
Account for Inventory value adjustments for Actual Costing
*/
public void setW_InvActualAdjust_Acct (int W_InvActualAdjust_Acct)
{
set_Value (COLUMNNAME_W_InvActualAdjust_Acct, Integer.valueOf(W_InvActualAdjust_Acct));
}
/** Get Inventory Adjustment.
@return Account for Inventory value adjustments for Actual Costing
*/
public int getW_InvActualAdjust_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_InvActualAdjust_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getW_Inventory_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getW_Inventory_Acct(), get_TrxName()); }
/** Set (Not Used).
@param W_Inventory_Acct
Warehouse Inventory Asset Account - Currently not used
*/
public void setW_Inventory_Acct (int W_Inventory_Acct)
{
set_Value (COLUMNNAME_W_Inventory_Acct, Integer.valueOf(W_Inventory_Acct));
}
/** Get (Not Used).
@return Warehouse Inventory Asset Account - Currently not used
*/
public int getW_Inventory_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Inventory_Acct); | if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getW_Revaluation_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getW_Revaluation_Acct(), get_TrxName()); }
/** Set Inventory Revaluation.
@param W_Revaluation_Acct
Account for Inventory Revaluation
*/
public void setW_Revaluation_Acct (int W_Revaluation_Acct)
{
set_Value (COLUMNNAME_W_Revaluation_Acct, Integer.valueOf(W_Revaluation_Acct));
}
/** Get Inventory Revaluation.
@return Account for Inventory Revaluation
*/
public int getW_Revaluation_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Revaluation_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public NClob createNClob() throws SQLException
{
return delegate.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException
{
return delegate.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException
{
return delegate.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException
{
delegate.setClientInfo(name, value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
delegate.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException
{
return delegate.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException
{
return delegate.getClientInfo();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException
{
return delegate.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
return delegate.createStruct(typeName, attributes);
}
@Override
public void setSchema(String schema) throws SQLException
{
delegate.setSchema(schema); | }
@Override
public String getSchema() throws SQLException
{
return delegate.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException
{
delegate.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
delegate.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException
{
return delegate.getNetworkTimeout();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperJdbcConnection.java | 2 |
请完成以下Java代码 | public int getTotalAmountToBeWithdrawn() {
return totalAmountToBeWithdrawn;
}
public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) {
this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn;
}
public int getNoOfHundredsDispensed() {
return noOfHundredsDispensed;
}
public void setNoOfHundredsDispensed(int noOfHundredsDispensed) {
this.noOfHundredsDispensed = noOfHundredsDispensed;
}
public int getNoOfFiftiesDispensed() {
return noOfFiftiesDispensed;
}
public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) { | this.noOfFiftiesDispensed = noOfFiftiesDispensed;
}
public int getNoOfTensDispensed() {
return noOfTensDispensed;
}
public void setNoOfTensDispensed(int noOfTensDispensed) {
this.noOfTensDispensed = noOfTensDispensed;
}
public int getAmountLeftToBeWithdrawn() {
return amountLeftToBeWithdrawn;
}
public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) {
this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn;
}
} | repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\chain\AtmRequestContext.java | 1 |
请完成以下Java代码 | public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Role Notification Group.
@param AD_Role_NotificationGroup_ID Role Notification Group */
@Override
public void setAD_Role_NotificationGroup_ID (int AD_Role_NotificationGroup_ID)
{
if (AD_Role_NotificationGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_NotificationGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_NotificationGroup_ID, Integer.valueOf(AD_Role_NotificationGroup_ID));
}
/** Get Role Notification Group.
@return Role Notification Group */
@Override
public int getAD_Role_NotificationGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_NotificationGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* NotificationType AD_Reference_ID=344
* Reference name: AD_User NotificationType
*/ | public static final int NOTIFICATIONTYPE_AD_Reference_ID=344;
/** EMail = E */
public static final String NOTIFICATIONTYPE_EMail = "E";
/** Notice = N */
public static final String NOTIFICATIONTYPE_Notice = "N";
/** None = X */
public static final String NOTIFICATIONTYPE_None = "X";
/** EMailPlusNotice = B */
public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B";
/** NotifyUserInCharge = O */
public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O";
/** Set Benachrichtigungs-Art.
@param NotificationType
Art der Benachrichtigung
*/
@Override
public void setNotificationType (java.lang.String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
/** Get Benachrichtigungs-Art.
@return Art der Benachrichtigung
*/
@Override
public java.lang.String getNotificationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_NotificationType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_NotificationGroup.java | 1 |
请完成以下Java代码 | public DmnParse name(String name) {
this.name = name;
return this;
}
public DmnParse sourceInputStream(InputStream inputStream) {
if (name == null) {
name("inputStream");
}
setStreamSource(new InputStreamSource(inputStream));
return this;
}
public DmnParse sourceUrl(URL url) {
if (name == null) {
name(url.toString());
}
setStreamSource(new UrlStreamSource(url));
return this;
}
public DmnParse sourceUrl(String url) {
try {
return sourceUrl(new URL(url));
} catch (MalformedURLException e) {
throw new FlowableException("malformed url: " + url, e);
}
}
public DmnParse sourceResource(String resource) {
if (name == null) {
name(resource);
}
setStreamSource(new ResourceStreamSource(resource));
return this;
}
public DmnParse sourceString(String string) {
if (name == null) {
name("string");
}
setStreamSource(new StringStreamSource(string));
return this;
}
protected void setStreamSource(StreamSource streamSource) {
if (this.streamSource != null) {
throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource);
}
this.streamSource = streamSource;
} | public String getSourceSystemId() {
return sourceSystemId;
}
public DmnParse setSourceSystemId(String sourceSystemId) {
this.sourceSystemId = sourceSystemId;
return this;
}
/*
* ------------------- GETTERS AND SETTERS -------------------
*/
public boolean isValidateSchema() {
return validateSchema;
}
public void setValidateSchema(boolean validateSchema) {
this.validateSchema = validateSchema;
}
public List<DecisionEntity> getDecisions() {
return decisions;
}
public String getTargetNamespace() {
return targetNamespace;
}
public DmnDeploymentEntity getDeployment() {
return deployment;
}
public void setDeployment(DmnDeploymentEntity deployment) {
this.deployment = deployment;
}
public DmnDefinition getDmnDefinition() {
return dmnDefinition;
}
public void setDmnDefinition(DmnDefinition dmnDefinition) {
this.dmnDefinition = dmnDefinition;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\parser\DmnParse.java | 1 |
请完成以下Java代码 | public static String getAppPath(Class cls) {
// 检查用户传入的参数是否为空
if (cls == null) {
throw new java.lang.IllegalArgumentException("参数不能为空!");
}
ClassLoader loader = cls.getClassLoader();
// 获得类的全名,包括包名
String clsName = cls.getName() + ".class";
// 获得传入参数所在的包
Package pack = cls.getPackage();
String path = "";
// 如果不是匿名包,将包名转化为路径
if (pack != null) {
String packName = pack.getName();
String javaSpot="java.";
String javaxSpot="javax.";
// 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
if (packName.startsWith(javaSpot) || packName.startsWith(javaxSpot)) {
throw new java.lang.IllegalArgumentException("不要传送系统类!");
}
// 在类的名称中,去掉包名的部分,获得类的文件名
clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
if (packName.indexOf(SymbolConstant.SPOT) < 0) {
path = packName + "/";
} else {
// 否则按照包名的组成部分,将包名转换为路径
int start = 0, end = 0;
end = packName.indexOf(".");
StringBuilder pathBuilder = new StringBuilder();
while (end != -1) {
pathBuilder.append(packName, start, end).append("/");
start = end + 1;
end = packName.indexOf(".", start);
}
if(oConvertUtils.isNotEmpty(pathBuilder.toString())){
path = pathBuilder.toString();
}
path = path + packName.substring(start) + "/";
} | }
// 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
java.net.URL url = loader.getResource(path + clsName);
// 从URL对象中获取路径信息
String realPath = url.getPath();
// 去掉路径信息中的协议名"file:"
int pos = realPath.indexOf("file:");
if (pos > -1) {
realPath = realPath.substring(pos + 5);
}
// 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1);
// 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
if (realPath.endsWith(SymbolConstant.EXCLAMATORY_MARK)) {
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
}
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try {
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
return realPath;
}// getAppPath定义结束
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\MyClassLoader.java | 1 |
请完成以下Java代码 | public class EventInfo extends BaseData<EventId> {
@Schema(description = "JSON object with Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY)
private TenantId tenantId;
@Schema(description = "Event type", example = "STATS")
private String type;
@Schema(description = "string", example = "784f394c-42b6-435a-983c-b7beff2784f9")
private String uid;
@Schema(description = "JSON object with Entity Id for which event is created.", accessMode = Schema.AccessMode.READ_ONLY)
private EntityId entityId;
@Schema(description = "Event body.",implementation = com.fasterxml.jackson.databind.JsonNode.class)
private transient JsonNode body;
public EventInfo() {
super();
} | public EventInfo(EventId id) {
super(id);
}
public EventInfo(EventInfo event) {
super(event);
}
@Schema(description = "Timestamp of the event creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\EventInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig {
@Bean
public AuthenticationManager authenticationManager(HttpSecurity httpSecurity, UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = httpSecurity.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
return authenticationManagerBuilder.build();
}
@Bean
public UserDetailsService userDetailsService(BCryptPasswordEncoder bCryptPasswordEncoder) {
return new CustomUserDetailService(bCryptPasswordEncoder);
}
@Bean
public AuthorizationManager<MethodInvocation> authorizationManager() {
return new CustomAuthorizationManager<>();
}
@Bean
@Role(ROLE_INFRASTRUCTURE)
public Advisor authorizationManagerBeforeMethodInterception(AuthorizationManager<MethodInvocation> authorizationManager) { | JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
pattern.setPattern("com.baeldung.enablemethodsecurity.services.*");
return new AuthorizationManagerBeforeMethodInterceptor(pattern, authorizationManager);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.anyRequest().authenticated())
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-4\src\main\java\com\baeldung\enablemethodsecurity\configuration\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Integer getMaxRequestsPerSecond() {
return this.maxRequestsPerSecond;
}
public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public @Nullable Duration getDrainInterval() {
return this.drainInterval;
}
public void setDrainInterval(@Nullable Duration drainInterval) {
this.drainInterval = drainInterval;
}
}
/**
* Name of the algorithm used to compress protocol frames.
*/
public enum Compression {
/**
* Requires 'net.jpountz.lz4:lz4'.
*/
LZ4,
/**
* Requires org.xerial.snappy:snappy-java.
*/
SNAPPY,
/**
* No compression.
*/
NONE
}
public enum ThrottlerType {
/**
* Limit the number of requests that can be executed in parallel.
*/
CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"), | /**
* Limits the request rate per second.
*/
RATE_LIMITING("RateLimitingRequestThrottler"),
/**
* No request throttling.
*/
NONE("PassThroughRequestThrottler");
private final String type;
ThrottlerType(String type) {
this.type = type;
}
public String type() {
return this.type;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java | 2 |
请完成以下Java代码 | public class ReadOnlyMapELResolver extends ELResolver {
protected Map<Object, Object> wrappedMap;
public ReadOnlyMapELResolver(Map<Object, Object> map) {
this.wrappedMap = map;
}
public Object getValue(ELContext context, Object base, Object property) {
if (base == null) {
if (wrappedMap.containsKey(property)) {
context.setPropertyResolved(true);
return wrappedMap.get(property);
}
}
return null;
}
public boolean isReadOnly(ELContext context, Object base, Object property) {
return true;
} | public void setValue(ELContext context, Object base, Object property, Object value) {
if (base == null) {
if (wrappedMap.containsKey(property)) {
throw new IllegalArgumentException("Cannot set value of '" + property + "', it's readonly!");
}
}
}
public Class<?> getCommonPropertyType(ELContext context, Object arg) {
return Object.class;
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object arg) {
return null;
}
public Class<?> getType(ELContext context, Object arg1, Object arg2) {
return Object.class;
}
} | repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ReadOnlyMapELResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
String path=saveFile(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
redirectAttributes.addFlashAttribute("path", "file path url '" + path + "'");
} catch (Exception e) {
logger.error("upload file failed",e);
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
/**
* @param multipartFile
* @return
* @throws IOException
*/
public String saveFile(MultipartFile multipartFile) throws IOException {
String[] fileAbsolutePath={};
String fileName=multipartFile.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
byte[] file_buff = null; | InputStream inputStream=multipartFile.getInputStream();
if(inputStream!=null){
int len1 = inputStream.available();
file_buff = new byte[len1];
inputStream.read(file_buff);
}
inputStream.close();
FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
try {
fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs
} catch (Exception e) {
logger.error("upload file Exception!",e);
}
if (fileAbsolutePath==null) {
logger.error("upload file failed,please upload again!");
}
String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
return path;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\controller\UploadController.java | 2 |
请完成以下Java代码 | public class PlanItemExpressionActivityBehavior extends CoreCmmnActivityBehavior {
protected String expression;
protected String resultVariable;
protected boolean storeResultVariableAsTransient;
public PlanItemExpressionActivityBehavior(String expression, String resultVariable, boolean storeResultVariableAsTransient) {
this.expression = expression;
this.resultVariable = resultVariable;
this.storeResultVariableAsTransient = storeResultVariableAsTransient;
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
Object value = null;
Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
value = expressionObject.getValue(planItemInstanceEntity);
if (value instanceof CompletableFuture) {
CommandContextUtil.getAgenda(commandContext)
.planFutureOperation((CompletableFuture<Object>) value, new FutureExpressionCompleteAction(planItemInstanceEntity));
} else {
complete(value, planItemInstanceEntity);
}
}
protected void complete(Object value, PlanItemInstanceEntity planItemInstanceEntity) {
if (resultVariable != null) {
if (storeResultVariableAsTransient) { | planItemInstanceEntity.setTransientVariable(resultVariable, value);
} else {
planItemInstanceEntity.setVariable(resultVariable, value);
}
}
CommandContextUtil.getAgenda().planCompletePlanItemInstanceOperation(planItemInstanceEntity);
}
protected class FutureExpressionCompleteAction implements BiConsumer<Object, Throwable> {
protected final PlanItemInstanceEntity planItemInstanceEntity;
public FutureExpressionCompleteAction(PlanItemInstanceEntity planItemInstanceEntity) {
this.planItemInstanceEntity = planItemInstanceEntity;
}
@Override
public void accept(Object value, Throwable throwable) {
if (throwable == null) {
complete(value, planItemInstanceEntity);
} else {
sneakyThrow(throwable);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\PlanItemExpressionActivityBehavior.java | 1 |
请完成以下Java代码 | public int getC_RfQResponseLineQty_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQResponseLineQty_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zugesagter Termin.
@param DatePromised
Zugesagter Termin für diesen Auftrag
*/
@Override
public void setDatePromised (java.sql.Timestamp DatePromised)
{
set_Value (COLUMNNAME_DatePromised, DatePromised);
}
/** Get Zugesagter Termin.
@return Zugesagter Termin für diesen Auftrag
*/
@Override
public java.sql.Timestamp getDatePromised ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DatePromised);
}
/** Set Rabatt %.
@param Discount
Discount in percent
*/
@Override
public void setDiscount (java.math.BigDecimal Discount)
{
set_Value (COLUMNNAME_Discount, Discount);
}
/** Get Rabatt %.
@return Discount in percent
*/
@Override
public java.math.BigDecimal getDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
} | /** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ranking.
@param Ranking
Relative Rank Number
*/
@Override
public void setRanking (int Ranking)
{
set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class MCPServerConfiguration {
// --- Unconditional tool registration at starup ---
// Uncomment the below bean to enable unconditional tool registration
/*
@Bean
ToolCallbackProvider authorTools() {
return MethodToolCallbackProvider
.builder()
.toolObjects(new AuthorRepository())
.build();
}
*/
// --- Runtime conditional tool registration ---
// Comment the below bean to disable conditional tool registration
@Bean
CommandLineRunner commandLineRunner(
McpSyncServer mcpSyncServer, | @Value("${com.baeldung.author-tools.enabled:false}") boolean authorToolsEnabled
) {
return args -> {
if (authorToolsEnabled) {
ToolCallback[] toolCallbacks = ToolCallbacks.from(new AuthorRepository());
List<SyncToolSpecification> tools = McpToolUtils.toSyncToolSpecifications(toolCallbacks);
tools.forEach(tool -> {
mcpSyncServer.addTool(tool);
mcpSyncServer.notifyToolsListChanged();
});
}
};
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-mcp\src\main\java\com\baeldung\springai\mcp\server\MCPServerConfiguration.java | 2 |
请完成以下Java代码 | protected EventSubscriptionEntityManager getEventSubscriptionManager() {
return (getSession(EventSubscriptionEntityManager.class));
}
protected VariableInstanceEntityManager getVariableInstanceManager() {
return getSession(VariableInstanceEntityManager.class);
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceManager() {
return getSession(HistoricProcessInstanceEntityManager.class);
}
protected HistoricDetailEntityManager getHistoricDetailManager() {
return getSession(HistoricDetailEntityManager.class);
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceManager() {
return getSession(HistoricActivityInstanceEntityManager.class);
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceManager() {
return getSession(HistoricVariableInstanceEntityManager.class);
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
} | protected AttachmentEntityManager getAttachmentManager() {
return getSession(AttachmentEntityManager.class);
}
protected HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return Context.getProcessEngineConfiguration();
}
@Override
public void close() {
}
@Override
public void flush() {
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public Builder setC_BPartner_ID(final int C_BPartner_ID)
{
this.C_BPartner_ID = C_BPartner_ID;
return this;
}
public Builder setM_Product_ID(final int M_Product_ID)
{
this.M_Product_ID = M_Product_ID;
return this;
}
public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID;
return this;
}
public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID)
{
this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID;
return this;
}
public Builder setC_Flatrate_DataEntry_ID(int C_Flatrate_DataEntry_ID)
{
this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID;
return this;
}
public Builder setDate(final Date date)
{
this.date = date;
return this;
} | public Builder setQtyPromised(final BigDecimal qtyPromised, final BigDecimal qtyPromised_TU)
{
this.qtyPromised = qtyPromised;
this.qtyPromised_TU = qtyPromised_TU;
return this;
}
public Builder setQtyOrdered(final BigDecimal qtyOrdered, final BigDecimal qtyOrdered_TU)
{
this.qtyOrdered = qtyOrdered;
this.qtyOrdered_TU = qtyOrdered_TU;
return this;
}
public Builder setQtyDelivered(BigDecimal qtyDelivered)
{
this.qtyDelivered = qtyDelivered;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceChangeEvent.java | 1 |
请完成以下Java代码 | public class PaymentRuleValidation extends AbstractJavaValidationRule
{
private static final ImmutableSet<String> PARAMETERS = ImmutableSet.of(
I_C_BPartner.COLUMNNAME_C_BPartner_ID);
private final CreditPassConfigRepository creditPassConfigRepository = Adempiere.getBean(CreditPassConfigRepository.class);
@Override public Set<String> getParameters(@Nullable final String contextTableName)
{
return PARAMETERS;
}
@Override public boolean accept(final IValidationContext evalCtx, final NamePair item)
{
boolean accept = false;
final int bPartnerId = evalCtx.get_ValueAsInt(I_C_BPartner.COLUMNNAME_C_BPartner_ID, -1); | if (bPartnerId > -1)
{
final CreditPassConfig config = creditPassConfigRepository.getConfigByBPartnerId(BPartnerId.ofRepoId(bPartnerId));
final boolean hasMatch = config.getCreditPassConfigPaymentRuleList().stream()
.map(CreditPassConfigPaymentRule::getPaymentRule)
.anyMatch(pr -> StringUtils.equals(pr, item.getID()));
if (hasMatch)
{
accept = true;
}
}
return accept;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\process\validation\PaymentRuleValidation.java | 1 |
请完成以下Java代码 | public void broadcastToChildren(TbActorId parent, TbActorMsg msg, boolean highPriority) {
broadcastToChildren(parent, id -> true, msg, highPriority);
}
@Override
public void broadcastToChildren(TbActorId parent, Predicate<TbActorId> childFilter, TbActorMsg msg) {
broadcastToChildren(parent, childFilter, msg, false);
}
private void broadcastToChildren(TbActorId parent, Predicate<TbActorId> childFilter, TbActorMsg msg, boolean highPriority) {
Set<TbActorId> children = parentChildMap.get(parent);
if (children != null) {
children.stream().filter(childFilter).forEach(id -> {
try {
tell(id, msg, highPriority);
} catch (TbActorNotRegisteredException e) {
log.warn("Actor is missing for {}", id);
}
});
}
}
@Override
public List<TbActorId> filterChildren(TbActorId parent, Predicate<TbActorId> childFilter) {
Set<TbActorId> children = parentChildMap.get(parent);
if (children != null) {
return children.stream().filter(childFilter).collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
@Override
public void stop(TbActorRef actorRef) {
stop(actorRef.getActorId());
}
@Override
public void stop(TbActorId actorId) {
Set<TbActorId> children = parentChildMap.remove(actorId); | if (children != null) {
for (TbActorId child : children) {
stop(child);
}
}
parentChildMap.values().forEach(parentChildren -> parentChildren.remove(actorId));
TbActorMailbox mailbox = actors.remove(actorId);
if (mailbox != null) {
mailbox.destroy(null);
}
}
@Override
public void stop() {
dispatchers.values().forEach(dispatcher -> {
dispatcher.getExecutor().shutdown();
try {
dispatcher.getExecutor().awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("[{}] Failed to stop dispatcher", dispatcher.getDispatcherId(), e);
}
});
if (scheduler != null) {
scheduler.shutdownNow();
}
actors.clear();
}
} | repos\thingsboard-master\common\actor\src\main\java\org\thingsboard\server\actors\DefaultTbActorSystem.java | 1 |
请完成以下Java代码 | public void setProperty(final String key, final String value)
{
if (props == null)
{
props = new Properties();
}
if (value == null)
{
props.setProperty(key, "");
}
else
{
props.setProperty(key, value);
}
}
/**
* Set Property
*
* @param key Key
* @param value Value
*/
public void setProperty(final String key, final Boolean value)
{
setProperty(key, DisplayType.toBooleanString(value));
}
/**
* Set Property
*
* @param key Key
* @param value Value
*/
public void setProperty(final String key, final int value)
{
setProperty(key, String.valueOf(value));
}
/**
* Get Property
*
* @param key Key | * @return Value
*/
public String getProperty(final String key)
{
if (key == null)
{
return "";
}
if (props == null)
{
return "";
}
final String value = props.getProperty(key, "");
if (Check.isEmpty(value))
{
return "";
}
return value;
}
/**
* Get Property as Boolean
*
* @param key Key
* @return Value
*/
public boolean isPropertyBool(final String key)
{
final String value = getProperty(key);
return DisplayType.toBooleanNonNull(value, false);
}
public void updateContext(final Properties ctx)
{
Env.setContext(ctx, "#ShowTrl", true);
Env.setContext(ctx, "#ShowAdvanced", true);
Env.setAutoCommit(ctx, isPropertyBool(P_AUTO_COMMIT));
Env.setAutoNew(ctx, isPropertyBool(P_AUTO_NEW));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserPreference.java | 1 |
请完成以下Java代码 | public void setUp() {
murmur3 = Hashing.murmur3_128().newHasher();
}
}
@Fork(value = 1, warmups = 1)
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
public void benchMurmur3_128(ExecutionPlan plan) {
for (int i = plan.iterations; i > 0; i--) {
plan.murmur3.putString(plan.password, Charset.defaultCharset());
}
plan.murmur3.hash();
}
@Benchmark
@Fork(value = 1, warmups = 1)
@BenchmarkMode(Mode.Throughput)
public void init() {
// Do nothing
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void doNothing() {
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS) | @BenchmarkMode(Mode.AverageTime)
public void objectCreation() {
new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public Object pillarsOfCreation() {
return new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void blackHole(Blackhole blackhole) {
blackhole.consume(new Object());
}
@Benchmark
public double foldedLog() {
int x = 8;
return Math.log(x);
}
@Benchmark
public double log(Log input) {
return Math.log(input.x);
}
} | repos\tutorials-master\jmh\src\main\java\com\baeldung\BenchMark.java | 1 |
请完成以下Java代码 | public Map<String, Object> getRuleResult(int ruleNumber) {
return ruleResults.get(ruleNumber);
}
public Map<Integer, Map<String, Object>> getRuleResults() {
return ruleResults;
}
public DecisionExecutionAuditContainer getAuditContainer() {
return auditContainer;
}
public void setAuditContainer(DecisionExecutionAuditContainer auditContainer) {
this.auditContainer = auditContainer;
}
public Map<String, List<Object>> getOutputValues() {
return outputValues;
}
public void addOutputValues(String outputName, List<Object> outputValues) {
this.outputValues.put(outputName, outputValues);
}
public BuiltinAggregator getAggregator() {
return aggregator;
}
public void setAggregator(BuiltinAggregator aggregator) {
this.aggregator = aggregator;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
} | public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java | 1 |
请完成以下Java代码 | public static void handleFailedJob(final JobEntity job, final Throwable exception, final CommandExecutor commandExecutor) {
commandExecutor.execute(new Command<Void>() {
@Override
public Void execute(CommandContext commandContext) {
CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew();
FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory();
Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), exception);
LOGGER.trace("Using FailedJobCommandFactory '{}' and command of type '{}'", failedJobCommandFactory.getClass(), cmd.getClass());
commandExecutor.execute(commandConfig, cmd);
// Dispatch an event, indicating job execution failed in a try-catch block, to prevent the original
// exception to be swallowed
if (commandContext.getEventDispatcher().isEnabled()) {
try {
commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityExceptionEvent(
FlowableEngineEventType.JOB_EXECUTION_FAILURE, job, exception), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
} catch (Throwable ignore) {
LOGGER.warn("Exception occurred while dispatching job failure event, ignoring.", ignore);
}
}
return null;
}
});
unlockJobIsNeeded(job, commandExecutor);
}
protected static void unlockJobIsNeeded(final JobEntity job, final CommandExecutor commandExecutor) {
try {
if (job.isExclusive()) { | commandExecutor.execute(new UnlockExclusiveJobCmd(job));
}
} catch (ActivitiOptimisticLockingException optimisticLockingException) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Optimistic locking exception while unlocking the job. If you have multiple async executors running against the same database, " +
"this exception means that this thread tried to acquire an exclusive job, which already was changed by another async executor thread." +
"This is expected behavior in a clustered environment. " +
"You can ignore this message if you indeed have multiple job executor acquisition threads running against the same database. " +
"Exception message: {}", optimisticLockingException.getMessage());
}
} catch (Throwable t) {
LOGGER.error("Error while unlocking exclusive job {}", job.getId(), t);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\AsyncJobUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PayPalLogRepository
{
private static final Logger logger = LogManager.getLogger(PayPalLogRepository.class);
private final ObjectMapper jsonObjectMapper;
public PayPalLogRepository(
@NonNull final Optional<ObjectMapper> jsonObjectMapper)
{
if (jsonObjectMapper.isPresent())
{
this.jsonObjectMapper = jsonObjectMapper.get();
}
else
{
this.jsonObjectMapper = new ObjectMapper();
logger.warn("Using internal JSON object mapper");
}
}
public void log(@NonNull final PayPalCreateLogRequest log)
{
final I_PayPal_Log record = newInstanceOutOfTrx(I_PayPal_Log.class);
record.setRequestPath(log.getRequestPath());
record.setRequestMethod(log.getRequestMethod());
record.setRequestHeaders(toJson(log.getRequestHeaders())); | record.setResponseCode(log.getResponseStatusCode());
record.setResponseHeaders(toJson(log.getResponseHeaders()));
record.setResponseBody(log.getResponseBodyAsJson());
record.setC_Order_ID(OrderId.toRepoId(log.getSalesOrderId()));
record.setC_Payment_Reservation_ID(PaymentReservationId.toRepoId(log.getPaymentReservationId()));
record.setPayPal_Order_ID(PayPalOrderId.toRepoId(log.getInternalPayPalOrderId()));
saveRecord(record);
}
private String toJson(final Object obj)
{
if (obj == null)
{
return "";
}
try
{
return jsonObjectMapper.writeValueAsString(obj);
}
catch (JsonProcessingException ex)
{
logger.warn("Failed converting object to JSON. Returning toString(): {}", obj, ex);
return obj.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\logs\PayPalLogRepository.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.