instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException
{
return (org.eevolution.model.I_PP_Product_BOM)MTable.get(getCtx(), org.eevolution.model.I_PP_Product_BOM.Table_Name)
.getPO(getPP_Product_BOM_ID(), get_TrxName()); }
/** Set BOM & Formula.
@param PP_Product_BOM_ID
BOM & Formula
*/
public void setPP_Product_BOM_ID (int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_Value (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_Value (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID));
}
/** Get BOM & Formula.
@return BOM & Formula
*/
public int getPP_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** Set Group.
@param R_Group_ID
Request Group
*/
public void setR_Group_ID (int R_Group_ID)
{
if (R_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID));
}
/** Get Group.
@return Request Group
*/
public int getR_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Group.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 9000
spring:
application:
name: Ribbon-Consumer
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
serviceUrl:
defa
|
ultZone: http://mrbird:123456@peer1:8080/eureka/,http://mrbird:123456@peer2:8081/eureka/
|
repos\SpringAll-master\32.Spring-Cloud-Hystrix-Dashboard-Turbine-RabbitMQ\Ribbon-Consumer\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProcessInstanceImpl that = (ProcessInstanceImpl) o;
return (
Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(processDefinitionId, that.processDefinitionId) &&
Objects.equals(processDefinitionKey, that.processDefinitionKey) &&
Objects.equals(initiator, that.initiator) &&
Objects.equals(startDate, that.startDate) &&
Objects.equals(completedDate, that.completedDate) &&
Objects.equals(businessKey, that.businessKey) &&
status == that.status &&
Objects.equals(parentId, that.parentId) &&
Objects.equals(processDefinitionVersion, that.processDefinitionVersion) &&
Objects.equals(processDefinitionName, that.processDefinitionName)
);
}
@Override
public int hashCode() {
return Objects.hash(
super.hashCode(),
id,
name,
processDefinitionId,
processDefinitionKey,
initiator,
startDate,
completedDate,
businessKey,
status,
parentId,
processDefinitionVersion,
processDefinitionName
);
}
@Override
public String toString() {
return (
|
"ProcessInstance{" +
"id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", processDefinitionId='" +
processDefinitionId +
'\'' +
", processDefinitionKey='" +
processDefinitionKey +
'\'' +
", parentId='" +
parentId +
'\'' +
", initiator='" +
initiator +
'\'' +
", startDate=" +
startDate +
", completedDate=" +
completedDate +
", businessKey='" +
businessKey +
'\'' +
", status=" +
status +
", processDefinitionVersion='" +
processDefinitionVersion +
'\'' +
", processDefinitionName='" +
processDefinitionName +
'\'' +
'}'
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessInstanceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer getRevision()
{
return revision;
}
public void setRevision(Integer revision)
{
this.revision = revision;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
AcceptPaymentDisputeRequest acceptPaymentDisputeRequest = (AcceptPaymentDisputeRequest)o;
return Objects.equals(this.returnAddress, acceptPaymentDisputeRequest.returnAddress) &&
Objects.equals(this.revision, acceptPaymentDisputeRequest.revision);
}
@Override
public int hashCode()
{
return Objects.hash(returnAddress, revision);
}
@Override
public String toString()
{
|
StringBuilder sb = new StringBuilder();
sb.append("class AcceptPaymentDisputeRequest {\n");
sb.append(" returnAddress: ").append(toIndentedString(returnAddress)).append("\n");
sb.append(" revision: ").append(toIndentedString(revision)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AcceptPaymentDisputeRequest.java
| 2
|
请完成以下Java代码
|
public class ZKGetChildren {
private static ZooKeeper zk;
private static ZooKeeperConnection conn;
// Method to check existence of znode and its status, if znode is available.
public static Stat znode_exists(String path) throws
KeeperException, InterruptedException {
return zk.exists(path, true);
}
public static void main(String[] args) throws InterruptedException, KeeperException {
String path = ZKConstants.ZK_FIRST_PATH; // Assign path to the znode
try {
conn = new ZooKeeperConnection();
zk = conn.connect(ZKConstants.ZK_HOST);
Stat stat = znode_exists(path); // Stat checks the path
|
if (stat != null) {
//“getChildren" method- get all the children of znode.It has two args, path and watch
List<String> children = zk.getChildren(path, false);
for (int i = 0; i < children.size(); i++)
System.out.println(children.get(i)); //Print children's
} else {
System.out.println("Node does not exists");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
repos\spring-boot-quick-master\quick-zookeeper\src\main\java\com\quick\zookeeper\client\ZKGetChildren.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static final class AuthnRequestContext {
private final HttpServletRequest request;
private final RelyingPartyRegistration registration;
private final AuthnRequest authnRequest;
public AuthnRequestContext(HttpServletRequest request, RelyingPartyRegistration registration,
AuthnRequest authnRequest) {
this.request = request;
this.registration = registration;
this.authnRequest = authnRequest;
}
|
public HttpServletRequest getRequest() {
return this.request;
}
public RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
public AuthnRequest getAuthnRequest() {
return this.authnRequest;
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolver.java
| 2
|
请完成以下Java代码
|
public boolean isSOTrx()
{
final I_M_InOut inout = getM_InOut();
return inout.isSOTrx();
}
@Override
public I_C_BPartner getC_BPartner()
{
final I_M_InOut inout = getM_InOut();
final I_C_BPartner partner = InterfaceWrapperHelper.load(inout.getC_BPartner_ID(), I_C_BPartner.class);
if (partner == null)
{
return null;
}
return partner;
}
|
private I_M_InOut getM_InOut()
{
final I_M_InOut inout = inoutLine.getM_InOut();
if (inout == null)
{
throw new AdempiereException("M_InOut_ID was not set in " + inoutLine);
}
return inout;
}
@Override
public String toString()
{
return String.format("InOutLineBPartnerAware [inoutLine=%s, isSOTrx()=%s, getC_BPartner()=%s, getM_InOut()=%s]", inoutLine, isSOTrx(), getC_BPartner(), getM_InOut());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\InOutLineBPartnerAware.java
| 1
|
请完成以下Java代码
|
public void setM_Picking_Job_ID (final int M_Picking_Job_ID)
{
if (M_Picking_Job_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID);
}
@Override
public int getM_Picking_Job_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getPickFrom_HU()
{
return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU)
{
set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU);
}
@Override
public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID)
{
if (PickFrom_Locator_ID < 1)
set_Value (COLUMNNAME_PickFrom_Locator_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID);
}
@Override
public int getPickFrom_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID);
|
}
@Override
public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID)
{
if (PickFrom_Warehouse_ID < 1)
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID);
}
@Override
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyAvailable (final BigDecimal QtyAvailable)
{
set_Value (COLUMNNAME_QtyAvailable, QtyAvailable);
}
@Override
public BigDecimal getQtyAvailable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_HUAlternative.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_Substitute[")
.append(get_ID()).append("]");
return sb.toString();
}
/** 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);
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
|
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
public I_M_Product getSubstitute() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getSubstitute_ID(), get_TrxName()); }
/** Set Substitute.
@param Substitute_ID
Entity which can be used in place of this entity
*/
public void setSubstitute_ID (int Substitute_ID)
{
if (Substitute_ID < 1)
set_ValueNoCheck (COLUMNNAME_Substitute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID));
}
/** Get Substitute.
@return Entity which can be used in place of this entity
*/
public int getSubstitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Substitute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private XADataSource createXaDataSourceInstance(String className) {
try {
Class<?> dataSourceClass = ClassUtils.forName(className, this.classLoader);
Object instance = BeanUtils.instantiateClass(dataSourceClass);
Assert.state(instance instanceof XADataSource,
() -> "DataSource class " + className + " is not an XADataSource");
return (XADataSource) instance;
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create XADataSource instance from '" + className + "'");
}
}
private void bindXaProperties(XADataSource target, DataSourceProperties dataSourceProperties,
JdbcConnectionDetails connectionDetails) {
Binder binder = new Binder(getBinderSource(dataSourceProperties, connectionDetails));
binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(target));
}
private ConfigurationPropertySource getBinderSource(DataSourceProperties dataSourceProperties,
JdbcConnectionDetails connectionDetails) {
|
Map<Object, Object> properties = new HashMap<>(dataSourceProperties.getXa().getProperties());
properties.computeIfAbsent("user", (key) -> connectionDetails.getUsername());
properties.computeIfAbsent("password", (key) -> connectionDetails.getPassword());
try {
properties.computeIfAbsent("url", (key) -> connectionDetails.getJdbcUrl());
}
catch (DataSourceBeanCreationException ex) {
// Continue as not all XA DataSource's require a URL
}
MapConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
aliases.addAliases("user", "username");
return source.withAliases(aliases);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\XADataSourceAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void fetchAuthorDtoReadOnlyMode() {
AuthorDto authorDto = authorRepository.findTopByGenre("Anthology");
System.out.println("Author DTO: " + authorDto.getName() + ", " + authorDto.getAge());
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
System.out.println("No of managed entities : " + persistenceContext.getNumberOfManagedEntities());
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
private void displayInformation(String phase, Author author) {
System.out.println("\n-------------------------------------");
System.out.println("Phase:" + phase);
|
System.out.println("Entity: " + author);
System.out.println("-------------------------------------");
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
System.out.println("Has only non read entities : " + persistenceContext.hasNonReadOnlyEntities());
EntityEntry entityEntry = persistenceContext.getEntry(author);
Object[] loadedState = entityEntry.getLoadedState();
Status status = entityEntry.getStatus();
System.out.println("Entity entry : " + entityEntry);
System.out.println("Status:" + status);
System.out.println("Loaded state: " + Arrays.toString(loadedState));
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalReadOnlyMeaning\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public Integer getPriviledgeBirthday() {
return priviledgeBirthday;
}
public void setPriviledgeBirthday(Integer priviledgeBirthday) {
this.priviledgeBirthday = priviledgeBirthday;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@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(", name=").append(name);
sb.append(", growthPoint=").append(growthPoint);
sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", freeFreightPoint=").append(freeFreightPoint);
sb.append(", commentGrowthPoint=").append(commentGrowthPoint);
sb.append(", priviledgeFreeFreight=").append(priviledgeFreeFreight);
sb.append(", priviledgeSignIn=").append(priviledgeSignIn);
sb.append(", priviledgeComment=").append(priviledgeComment);
sb.append(", priviledgePromotion=").append(priviledgePromotion);
sb.append(", priviledgeMemberPrice=").append(priviledgeMemberPrice);
sb.append(", priviledgeBirthday=").append(priviledgeBirthday);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLevel.java
| 1
|
请完成以下Java代码
|
public class Course implements Serializable, Cloneable {
private Integer courseId;
private String courseName;
public Course() {
}
public Course(Integer courseId, String courseName) {
this.courseId = courseId;
this.courseName = courseName;
}
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
@Override
public Course clone() {
|
try {
return (Course) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Course that = (Course) o;
return Objects.equals(courseId,that.courseId)
&& Objects.equals(courseName,that.courseName);
}
@Override
public int hashCode() {
return Objects.hash(courseId,courseName);
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\deepcopyarraylist\Course.java
| 1
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getName() {
|
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\logging\Employee.java
| 1
|
请完成以下Java代码
|
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((genre == null) ? 0 : genre.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Artist other = (Artist) obj;
if (country == null) {
if (other.country != null)
|
return false;
} else if (!country.equals(other.country))
return false;
if (genre == null) {
if (other.genre != null)
return false;
} else if (!genre.equals(other.genre))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\Artist.java
| 1
|
请完成以下Java代码
|
public Object setValue(Object value) {
TypedValue typedValue = Variables.untypedValue(value);
return underlyingEntry.setValue(typedValue);
}
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Entry e = (Entry) o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public final int hashCode() {
String key = getKey();
Object value = getValue();
return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
};
}
public void remove() {
iterator.remove();
}
};
}
public int size() {
return variables.size();
}
};
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{\n");
for (Entry<String, TypedValue> variable : variables.entrySet()) {
stringBuilder.append(" ");
stringBuilder.append(variable.getKey());
stringBuilder.append(" => ");
stringBuilder.append(variable.getValue());
stringBuilder.append("\n");
}
stringBuilder.append("}");
return stringBuilder.toString();
|
}
public boolean equals(Object obj) {
return asValueMap().equals(obj);
}
public int hashCode() {
return asValueMap().hashCode();
}
public Map<String, Object> asValueMap() {
return new HashMap<String, Object>(this);
}
public TypedValue resolve(String variableName) {
return getValueTyped(variableName);
}
public boolean containsVariable(String variableName) {
return containsKey(variableName);
}
public VariableContext asVariableContext() {
return this;
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\VariableMapImpl.java
| 1
|
请完成以下Java代码
|
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
|
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getGradYear() {
return gradYear;
}
public void setGradYear(int gradYear) {
this.gradYear = gradYear;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteriaquery\Student.java
| 1
|
请完成以下Java代码
|
public class IOSpecification {
protected List<Data> dataInputs;
protected List<Data> dataOutputs;
protected List<DataRef> dataInputRefs;
protected List<DataRef> dataOutputRefs;
public IOSpecification() {
this.dataInputs = new ArrayList<Data>();
this.dataOutputs = new ArrayList<Data>();
this.dataInputRefs = new ArrayList<DataRef>();
this.dataOutputRefs = new ArrayList<DataRef>();
}
public void initialize(DelegateExecution execution) {
for (Data data : this.dataInputs) {
execution.setVariable(data.getName(), data.getDefinition().createInstance());
}
for (Data data : this.dataOutputs) {
execution.setVariable(data.getName(), data.getDefinition().createInstance());
}
}
public List<Data> getDataInputs() {
return unmodifiableList(this.dataInputs);
}
public List<Data> getDataOutputs() {
return unmodifiableList(this.dataOutputs);
}
public void addInput(Data data) {
this.dataInputs.add(data);
}
|
public void addOutput(Data data) {
this.dataOutputs.add(data);
}
public void addInputRef(DataRef dataRef) {
this.dataInputRefs.add(dataRef);
}
public void addOutputRef(DataRef dataRef) {
this.dataOutputRefs.add(dataRef);
}
public String getFirstDataInputName() {
return this.dataInputs.get(0).getName();
}
public String getFirstDataOutputName() {
if (this.dataOutputs != null && !this.dataOutputs.isEmpty()) {
return this.dataOutputs.get(0).getName();
} else {
return null;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\data\IOSpecification.java
| 1
|
请完成以下Java代码
|
public @Nullable String getArtifact() {
return get("artifact");
}
/**
* Return the name of the project or {@code null}.
* @return the name
*/
public @Nullable String getName() {
return get("name");
}
/**
* Return the version of the project or {@code null}.
* @return the version
*/
public @Nullable String getVersion() {
return get("version");
}
/**
* Return the timestamp of the build or {@code null}.
* <p>
* If the original value could not be parsed properly, it is still available with the
* {@code time} key.
* @return the build time
* @see #get(String)
*/
public @Nullable Instant getTime() {
return getInstant("time");
}
private static Properties processEntries(Properties properties) {
coerceDate(properties, "time");
return properties;
}
private static void coerceDate(Properties properties, String key) {
String value = properties.getProperty(key);
if (value != null) {
try {
|
String updatedValue = String
.valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli());
properties.setProperty(key, updatedValue);
}
catch (DateTimeException ex) {
// Ignore and store the original value
}
}
}
static class BuildPropertiesRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("META-INF/build-info.properties");
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\BuildProperties.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteSuspendedJobsByExecutionId(String executionId) {
SuspendedJobEntityManager suspendedJobEntityManager = getSuspendedJobEntityManager();
Collection<SuspendedJobEntity> suspendedJobsForExecution = suspendedJobEntityManager.findJobsByExecutionId(executionId);
for (SuspendedJobEntity job : suspendedJobsForExecution) {
suspendedJobEntityManager.delete(job);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
FlowableEngineEventType.JOB_CANCELED, job), configuration.getEngineName());
}
}
}
@Override
public void deleteDeadLetterJobsByExecutionId(String executionId) {
DeadLetterJobEntityManager deadLetterJobEntityManager = getDeadLetterJobEntityManager();
Collection<DeadLetterJobEntity> deadLetterJobsForExecution = deadLetterJobEntityManager.findJobsByExecutionId(executionId);
for (DeadLetterJobEntity job : deadLetterJobsForExecution) {
|
deadLetterJobEntityManager.delete(job);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
FlowableEngineEventType.JOB_CANCELED, job), configuration.getEngineName());
}
}
}
protected void deleteByteArrayRef(ByteArrayRef jobByteArrayRef) {
if (jobByteArrayRef != null) {
jobByteArrayRef.delete(configuration.getEngineName());
}
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\JobServiceImpl.java
| 2
|
请完成以下Java代码
|
public static void retrieveValueUsingAggregation() {
ArrayList<Document> response = new ArrayList<>();
ArrayList<Bson> pipeline = new ArrayList<>(Arrays.asList(
project(fields(Projections.exclude("_id"), Projections.include("passengerId")))));
database = mongoClient.getDatabase(databaseName);
database.getCollection(testCollectionName)
.aggregate(pipeline)
.allowDiskUse(true)
.into(response);
System.out.println("response:- " + response);
}
public static void retrieveValueAggregationUsingDocument() {
ArrayList<Document> response = new ArrayList<>();
ArrayList<Document> pipeline = new ArrayList<>(Arrays.asList(new Document("$project", new Document("passengerId", 1L))));
database = mongoClient.getDatabase(databaseName);
database.getCollection(testCollectionName)
.aggregate(pipeline)
.allowDiskUse(true)
.into(response);
System.out.println("response:- " + response);
}
public static void main(String args[]) {
//
|
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Fetch the data using find query with projected fields
//
retrieveValueUsingFind();
//
// Fetch the data using aggregate pipeline query with projected fields
//
retrieveValueUsingAggregation();
//
// Fetch the data using aggregate pipeline document query with projected fields
//
retrieveValueAggregationUsingDocument();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\RetrieveValue.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractExternalInvocationBpmnParseHandler<T extends FlowNode> extends AbstractActivityBpmnParseHandler<T> {
public AbstractDataAssociation createDataInputAssociation(BpmnParse bpmnParse, DataAssociation dataAssociationElement) {
if (dataAssociationElement.getAssignments().isEmpty()) {
return new MessageImplicitDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
} else {
SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(
dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
for (org.flowable.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
if (StringUtils.isNotEmpty(assignmentElement.getFrom()) && StringUtils.isNotEmpty(assignmentElement.getTo())) {
Expression from = bpmnParse.getExpressionManager().createExpression(assignmentElement.getFrom());
Expression to = bpmnParse.getExpressionManager().createExpression(assignmentElement.getTo());
Assignment assignment = new Assignment(from, to);
dataAssociation.addAssignment(assignment);
}
|
}
return dataAssociation;
}
}
public AbstractDataAssociation createDataOutputAssociation(BpmnParse bpmnParse, DataAssociation dataAssociationElement) {
if (StringUtils.isNotEmpty(dataAssociationElement.getSourceRef())) {
return new MessageImplicitDataOutputAssociation(dataAssociationElement.getTargetRef(), dataAssociationElement.getSourceRef());
} else {
Expression transformation = bpmnParse.getExpressionManager().createExpression(dataAssociationElement.getTransformation());
AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(null, dataAssociationElement.getTargetRef(), transformation);
return dataOutputAssociation;
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\AbstractExternalInvocationBpmnParseHandler.java
| 1
|
请完成以下Java代码
|
public static <P> void mapVariable(String objectPath, Map<String, Object> variables, P file) {
String[] segments = PERIOD.split(objectPath);
if (segments.length < 2) {
throw new RuntimeException("object-path in map must have at least two segments");
} else if (!"variables".equals(segments[0])) {
throw new RuntimeException("can only map into variables");
}
Object currentLocation = variables;
for (int i = 1; i < segments.length; i++) {
String segmentName = segments[i];
MultipartVariableMapper.Mapper mapper = determineMapper(currentLocation, objectPath, segmentName);
if (i == segments.length - 1) {
if (null != mapper.set(currentLocation, segmentName, file)) {
throw new RuntimeException("expected null value when mapping " + objectPath);
}
} else {
currentLocation = mapper.recurse(currentLocation, segmentName);
if (null == currentLocation) {
throw new RuntimeException("found null intermediate value when trying to map " + objectPath);
}
}
}
}
private static MultipartVariableMapper.Mapper<?> determineMapper(Object currentLocation, String objectPath, String segmentName) {
if (currentLocation instanceof Map) {
|
return MAP_MAPPER;
} else if (currentLocation instanceof List) {
return LIST_MAPPER;
}
throw new RuntimeException("expected a map or list at " + segmentName + " when trying to map " + objectPath);
}
interface Mapper<T> {
<P> Object set(T location, String target, P value);
Object recurse(T location, String target);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphql\fileupload\MultipartVariableMapper.java
| 1
|
请完成以下Java代码
|
public ApiUsageState findTenantApiUsageState(UUID tenantId) {
return DaoUtil.getData(apiUsageStateRepository.findByTenantId(tenantId));
}
@Override
public ApiUsageState findApiUsageStateByEntityId(EntityId entityId) {
return DaoUtil.getData(apiUsageStateRepository.findByEntityIdAndEntityType(entityId.getId(), entityId.getEntityType().name()));
}
@Override
public void deleteApiUsageStateByTenantId(TenantId tenantId) {
apiUsageStateRepository.deleteApiUsageStateByTenantId(tenantId.getId());
}
@Override
public void deleteApiUsageStateByEntityId(EntityId entityId) {
apiUsageStateRepository.deleteByEntityIdAndEntityType(entityId.getId(), entityId.getEntityType().name());
|
}
@Override
public PageData<ApiUsageState> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(apiUsageStateRepository.findAllByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)));
}
@Override
public List<ApiUsageStateFields> findNextBatch(UUID id, int batchSize) {
return apiUsageStateRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.API_USAGE_STATE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\usagerecord\JpaApiUsageStateDao.java
| 1
|
请完成以下Java代码
|
public class Logger {
private static volatile Logger instance;
private PrintWriter fileWriter;
public static Logger getInstance() {
if (instance == null) {
synchronized (Logger.class) {
if (instance == null) {
instance = new Logger();
}
}
}
return instance;
}
|
private Logger() {
try {
fileWriter = new PrintWriter(new FileWriter("app.log"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void log(String message) {
String log = String.format("[%s]- %s", LocalDateTime.now(), message);
fileWriter.println(log);
fileWriter.flush();
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-creational-2\src\main\java\com\baeldung\singleton\Logger.java
| 1
|
请完成以下Java代码
|
protected final void recalculateWeightNet(final IAttributeSet attributeSet)
{
final IWeightable weightable = getWeightableOrNull(attributeSet);
Weightables.updateWeightNet(weightable);
}
protected boolean isLUorTUorTopLevelVHU(IAttributeSet attributeSet)
{
if (!isVirtualHU(attributeSet))
{
return true;
}
final I_M_HU hu = huAttributesBL.getM_HU_OrNull(attributeSet);
final boolean virtualTopLevelHU = handlingUnitsBL.isTopLevel(hu);
return virtualTopLevelHU;
}
|
@Override
public final String generateStringValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
throw new UnsupportedOperationException("Not supported");
}
@Override
public final Date generateDateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
throw new UnsupportedOperationException("Not supported");
}
@Override
public final AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName)
{
throw new UnsupportedOperationException("Not supported");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\AbstractWeightAttributeValueCallout.java
| 1
|
请完成以下Java代码
|
public class XssUtils {
private static Pattern[] patterns = new Pattern[]{
//Script fragments
Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
//src='...'
Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
//script tags
Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
//eval(...)
Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
//expression(...)
Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
//javascript:...
Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
//vbscript:...
Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
//onload(...)=...
Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
|
};
public static String scriptXss(String value) {
if (value != null) {
value = value.replaceAll(" ", "");
for(Pattern scriptPattern: patterns){
value = scriptPattern.matcher(value).replaceAll("");
}
}
return HtmlUtils.htmlEscape(value);
}
public static void main(String[] args) {
String s = scriptXss("<img src=x onload=alert(111).*?><script></script>javascript:eval()\\\\.");
System.err.println("s======>" + s);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\XssUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WorkplaceQRCode
{
@NonNull WorkplaceId workplaceId;
@NonNull String caption;
public static boolean equals(@Nullable final WorkplaceQRCode o1, @Nullable final WorkplaceQRCode o2)
{
return Objects.equals(o1, o2);
}
public static WorkplaceQRCode ofWorkplace(final Workplace workplace)
{
return builder()
.workplaceId(workplace.getId())
.caption(workplace.getName())
.build();
}
public static WorkplaceQRCode ofGlobalQRCodeJsonString(final String json) {return WorkplaceQRCodeJsonConverter.fromGlobalQRCodeJsonString(json);}
public static WorkplaceQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return WorkplaceQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);}
|
public String toGlobalQRCodeJsonString() {return WorkplaceQRCodeJsonConverter.toGlobalQRCodeJsonString(this);}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
.qrCode(toGlobalQRCodeJsonString())
.bottomText(caption)
.build();
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return WorkplaceQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\qrcode\WorkplaceQRCode.java
| 2
|
请完成以下Java代码
|
public Batch execute(CommandContext commandContext) {
String processInstanceId = builder.getProcessInstanceId();
ExecutionManager executionManager = commandContext.getExecutionManager();
ExecutionEntity processInstance = executionManager.findExecutionById(processInstanceId);
ensureProcessInstanceExists(processInstanceId, processInstance);
String processDefinitionId = processInstance.getProcessDefinitionId();
String tenantId = processInstance.getTenantId();
String deploymentId = commandContext.getProcessEngineConfiguration().getDeploymentCache()
.findDeployedProcessDefinitionById(processDefinitionId)
.getDeploymentId();
return new BatchBuilder(commandContext)
.type(Batch.TYPE_PROCESS_INSTANCE_MODIFICATION)
.config(getConfiguration(processDefinitionId, deploymentId))
.tenantId(tenantId)
.totalJobs(1)
.permission(BatchPermissions.CREATE_BATCH_MODIFY_PROCESS_INSTANCES)
.operationLogHandler(this::writeOperationLog)
.build();
}
protected void ensureProcessInstanceExists(String processInstanceId,
ExecutionEntity processInstance) {
if (processInstance == null) {
throw LOG.processInstanceDoesNotExist(processInstanceId);
}
|
}
protected String getLogEntryOperation() {
return UserOperationLogEntry.OPERATION_TYPE_MODIFY_PROCESS_INSTANCE;
}
protected void writeOperationLog(CommandContext commandContext) {
commandContext.getOperationLogManager().logProcessInstanceOperation(getLogEntryOperation(),
builder.getProcessInstanceId(),
null,
null,
Collections.singletonList(PropertyChange.EMPTY_CHANGE),
builder.getAnnotation());
}
public BatchConfiguration getConfiguration(String processDefinitionId, String deploymentId) {
return new ModificationBatchConfiguration(
Collections.singletonList(builder.getProcessInstanceId()),
DeploymentMappings.of(new DeploymentMapping(deploymentId, 1)),
processDefinitionId,
builder.getModificationOperations(),
builder.isSkipCustomListeners(),
builder.isSkipIoMappings());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ModifyProcessInstanceAsyncCmd.java
| 1
|
请完成以下Java代码
|
public void deleteHistoricDetailsByProcessInstanceId(String historicProcessInstanceId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.AUDIT)) {
List<HistoricDetailEntity> historicDetails = (List) getDbSqlSession()
.createHistoricDetailQuery()
.processInstanceId(historicProcessInstanceId)
.list();
for (HistoricDetailEntity historicDetail : historicDetails) {
historicDetail.delete();
}
}
}
public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) {
return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByQueryCriteria", historicVariableUpdateQuery);
}
@SuppressWarnings("unchecked")
public List<HistoricDetail> findHistoricDetailsByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery, Page page) {
return getDbSqlSession().selectList("selectHistoricDetailsByQueryCriteria", historicVariableUpdateQuery, page);
}
|
public void deleteHistoricDetailsByTaskId(String taskId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.FULL)) {
HistoricDetailQueryImpl detailsQuery = new HistoricDetailQueryImpl().taskId(taskId);
List<HistoricDetail> details = detailsQuery.list();
for (HistoricDetail detail : details) {
((HistoricDetailEntity) detail).delete();
}
}
}
@SuppressWarnings("unchecked")
public List<HistoricDetail> findHistoricDetailsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectHistoricDetailByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByNativeQuery", parameterMap);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityManager.java
| 1
|
请完成以下Java代码
|
protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (this.forwardToDestination) {
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
return;
}
HttpSession session = request.getSession(false);
if (session != null || this.allowSessionCreation) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
}
/**
* The URL which will be used as the failure destination.
* @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp".
*/
public void setDefaultFailureUrl(String defaultFailureUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl),
() -> "'" + defaultFailureUrl + "' is not a valid redirect URL");
this.defaultFailureUrl = defaultFailureUrl;
}
protected boolean isUseForward() {
return this.forwardToDestination;
}
/**
* If set to <tt>true</tt>, performs a forward to the failure destination URL instead
* of a redirect. Defaults to <tt>false</tt>.
*/
public void setUseForward(boolean forwardToDestination) {
this.forwardToDestination = forwardToDestination;
}
|
/**
* Allows overriding of the behaviour when redirecting to a target URL.
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return this.redirectStrategy;
}
protected boolean isAllowSessionCreation() {
return this.allowSessionCreation;
}
public void setAllowSessionCreation(boolean allowSessionCreation) {
this.allowSessionCreation = allowSessionCreation;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\SimpleUrlAuthenticationFailureHandler.java
| 1
|
请完成以下Java代码
|
public ITranslatableString computeCaption(final ITranslatableString originalProcessCaption)
{
return captionOverride;
}
}
public ProcessPreconditionsResolution withCaptionMapper(@Nullable final ProcessCaptionMapper captionMapper)
{
return toBuilder().captionMapper(captionMapper).build();
}
/**
* Override default SortNo used with ordering related processes
*/
public ProcessPreconditionsResolution withSortNo(final int sortNo)
{
return !this.sortNo.isPresent() || this.sortNo.getAsInt() != sortNo
? toBuilder().sortNo(OptionalInt.of(sortNo)).build()
: this;
}
public @NonNull OptionalInt getSortNo() {return this.sortNo;}
public ProcessPreconditionsResolution and(final Supplier<ProcessPreconditionsResolution> resolutionSupplier)
|
{
if (isRejected())
{
return this;
}
return resolutionSupplier.get();
}
public void throwExceptionIfRejected()
{
if (isRejected())
{
throw new AdempiereException(getRejectReason());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionsResolution.java
| 1
|
请完成以下Java代码
|
public class PP_Order_Candidate_ReOpenSelection extends JavaProcess implements IProcessPrecondition
{
private static final AdMessageKey MSG_SELECTED_CLOSED_CANDIDATE = AdMessageKey.of("org.eevolution.productioncandidate.process.ClosedManufacturingCandidateSelection");
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final PPOrderCandidateService ppOrderCandidateService = SpringContextHolder.instance.getBean(PPOrderCandidateService.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final PInstanceId pinstanceId = getPinstanceId();
final Iterator<I_PP_Order_Candidate> orderCandidates = ppOrderCandidateService.retrieveOCForSelection(pinstanceId);
while (orderCandidates.hasNext())
{
ppOrderCandidateService.reopenCandidate(orderCandidates.next());
}
return MSG_OK;
}
@Override
@RunOutOfTrx
protected void prepare()
{
if (createSelection() <= 0)
{
throw new AdempiereException(MSG_SELECTED_CLOSED_CANDIDATE);
}
}
private int createSelection()
{
final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder();
|
final PInstanceId adPInstanceId = getPinstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null");
DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
return queryBuilder
.create()
.createSelection(adPInstanceId);
}
@NonNull
private IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder()
{
final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
.createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None)
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_Processed, true)
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false)
.filter(userSelectionFilter)
.addOnlyActiveRecordsFilter();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_ReOpenSelection.java
| 1
|
请完成以下Java代码
|
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return this.credentials;
}
/**
* Get the token bound to this {@link Authentication}.
*/
public final T getToken() {
return this.token;
}
/**
* Returns the attributes of the access token.
* @return a {@code Map} of the attributes in the access token.
*/
public abstract Map<String, Object> getTokenAttributes();
/**
* A builder for {@link AbstractOAuth2TokenAuthenticationToken} implementations
*
* @param <B>
* @since 7.0
*/
public abstract static class AbstractOAuth2TokenAuthenticationBuilder<T extends OAuth2Token, B extends AbstractOAuth2TokenAuthenticationBuilder<T, B>>
extends AbstractAuthenticationBuilder<B> {
private Object principal;
private Object credentials;
private T token;
protected AbstractOAuth2TokenAuthenticationBuilder(AbstractOAuth2TokenAuthenticationToken<T> token) {
super(token);
this.principal = token.getPrincipal();
this.credentials = token.getCredentials();
this.token = token.getToken();
}
@Override
public B principal(@Nullable Object principal) {
|
Assert.notNull(principal, "principal cannot be null");
this.principal = principal;
return (B) this;
}
@Override
public B credentials(@Nullable Object credentials) {
Assert.notNull(credentials, "credentials cannot be null");
this.credentials = credentials;
return (B) this;
}
/**
* The OAuth 2.0 Token to use
* @param token the token to use
* @return the {@link Builder} for further configurations
*/
public B token(T token) {
Assert.notNull(token, "token cannot be null");
this.token = token;
return (B) this;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\AbstractOAuth2TokenAuthenticationToken.java
| 1
|
请完成以下Java代码
|
public class UniqueDigitCounter {
public static int countWithSet(int number) {
number = Math.abs(number);
Set<Character> uniqueDigits = new HashSet<>();
String numberStr = String.valueOf(number);
for (char digit : numberStr.toCharArray()) {
uniqueDigits.add(digit);
}
return uniqueDigits.size();
}
public static int countWithBitManipulation(int number) {
if (number == 0) {
return 1;
|
}
number = Math.abs(number);
int mask = 0;
while (number > 0) {
int digit = number % 10;
mask |= 1 << digit;
number /= 10;
}
return Integer.bitCount(mask);
}
public static long countWithStreamApi(int number) {
return String.valueOf(Math.abs(number)).chars().distinct().count();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\uniquedigit\UniqueDigitCounter.java
| 1
|
请完成以下Java代码
|
public static int findLargestNumberUsingStack(int num, int k) {
String numStr = Integer.toString(num);
int length = numStr.length();
if (k == length) return 0;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < length; i++) {
char digit = numStr.charAt(i);
while (k > 0 && !stack.isEmpty() && stack.peek() < digit) {
stack.pop();
k--;
}
stack.push(digit);
|
}
while (k > 0) {
stack.pop();
k--;
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return Integer.parseInt(result.toString());
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\largestNumberRemovingK\LargestNumberRemoveKDigits.java
| 1
|
请完成以下Java代码
|
public Object getValue() {
if (m_value instanceof String)
return super.isSelected() ? "Y" : "N";
return new Boolean(isSelected());
} // getValue
/**
* Return Display Value
*
* @return displayed String value
*/
@Override
public String getDisplay() {
if (m_value instanceof String)
return super.isSelected() ? "Y" : "N";
return Boolean.toString(super.isSelected());
} // getDisplay
/**
* Set Text
*
* @param mnemonicLabel
* text
*/
@Override
public void setText(String mnemonicLabel) {
super.setText(createMnemonic(mnemonicLabel));
} // setText
/**
* Create Mnemonics of text containing "&". Based on MS notation of &Help =>
* H is Mnemonics Creates ALT_
*
* @param text
* test with Mnemonics
* @return text w/o &
*/
private String createMnemonic(String text) {
if (text == null)
return text;
int pos = text.indexOf('&');
if (pos != -1) // We have a nemonic
{
char ch = text.charAt(pos + 1);
if (ch != ' ') // &_ - is the & character
{
setMnemonic(ch);
|
return text.substring(0, pos) + text.substring(pos + 1);
}
}
return text;
} // createMnemonic
/**
* Overrides the JCheckBox.setMnemonic() method, setting modifier keys to
* CTRL+SHIFT.
*
* @param mnemonic
* The mnemonic character code.
*/
@Override
public void setMnemonic(int mnemonic) {
super.setMnemonic(mnemonic);
InputMap map = SwingUtilities.getUIInputMap(this,
JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map == null) {
map = new ComponentInputMapUIResource(this);
SwingUtilities.replaceUIInputMap(this,
JComponent.WHEN_IN_FOCUSED_WINDOW, map);
}
map.clear();
String className = this.getClass().getName();
int mask = InputEvent.ALT_MASK; // Default Buttons
if (this instanceof JCheckBox // In Tab
|| className.indexOf("VButton") != -1)
mask = InputEvent.SHIFT_MASK + InputEvent.CTRL_MASK;
map.put(KeyStroke.getKeyStroke(mnemonic, mask, false), "pressed");
map.put(KeyStroke.getKeyStroke(mnemonic, mask, true), "released");
map.put(KeyStroke.getKeyStroke(mnemonic, 0, true), "released");
setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, map);
} // setMnemonic
} // CCheckBox
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CCheckBox.java
| 1
|
请完成以下Java代码
|
public void setAD_Task_ID (int AD_Task_ID)
{
if (AD_Task_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Task_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Task_ID, Integer.valueOf(AD_Task_ID));
}
/** Get OS Task.
@return Operation System Task
*/
public int getAD_Task_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Task_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Server Process.
@param IsServerProcess
Run this Process on Server only
*/
public void setIsServerProcess (boolean IsServerProcess)
{
set_Value (COLUMNNAME_IsServerProcess, Boolean.valueOf(IsServerProcess));
}
/** Get Server Process.
@return Run this Process on Server only
*/
public boolean isServerProcess ()
{
Object oo = get_Value(COLUMNNAME_IsServerProcess);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
|
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set OS Command.
@param OS_Command
Operating System Command
*/
public void setOS_Command (String OS_Command)
{
set_Value (COLUMNNAME_OS_Command, OS_Command);
}
/** Get OS Command.
@return Operating System Command
*/
public String getOS_Command ()
{
return (String)get_Value(COLUMNNAME_OS_Command);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Task.java
| 1
|
请完成以下Java代码
|
public Instant getStartTime() {
return this.step.getStartTime();
}
/**
* Return the end time of this event.
* @return the end time
*/
public Instant getEndTime() {
return this.endTime;
}
/**
* Return the duration of this event, i.e. the processing time of the associated
* {@link StartupStep} with nanoseconds precision.
* @return the event duration
*/
|
public Duration getDuration() {
return this.duration;
}
/**
* Return the {@link StartupStep} information for this event.
* @return the step information.
*/
public StartupStep getStartupStep() {
return this.step;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\StartupTimeline.java
| 1
|
请完成以下Java代码
|
public int getR_Request_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_Status getR_Status() throws RuntimeException
{
return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name)
.getPO(getR_Status_ID(), get_TrxName()); }
/** Set Status.
@param R_Status_ID
Request Status
|
*/
public void setR_Status_ID (int R_Status_ID)
{
throw new IllegalArgumentException ("R_Status_ID is virtual column"); }
/** Get Status.
@return Request Status
*/
public int getR_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_R_Group_Prospect.java
| 1
|
请完成以下Java代码
|
public boolean isCompleted(final I_C_RfQResponseLine rfqResponseLine)
{
return X_C_RfQResponseLine.DOCSTATUS_Completed.equals(rfqResponseLine.getDocStatus());
}
@Override
public boolean isClosed(final I_C_RfQResponse rfqResponse)
{
return X_C_RfQResponse.DOCSTATUS_Closed.equals(rfqResponse.getDocStatus());
}
@Override
public boolean isClosed(final I_C_RfQResponseLine rfqResponseLine)
{
return X_C_RfQResponseLine.DOCSTATUS_Closed.equals(rfqResponseLine.getDocStatus());
}
@Override
public String getSummary(final I_C_RfQ rfq)
{
// NOTE: nulls shall be tolerated because the method is used for building exception error messages
if (rfq == null)
{
return "@C_RfQ_ID@ ?";
}
return "@C_RfQ_ID@ #" + rfq.getDocumentNo();
}
@Override
public String getSummary(final I_C_RfQResponse rfqResponse)
{
// NOTE: nulls shall be tolerated because the method is used for building exception error messages
if (rfqResponse == null)
{
return "@C_RfQResponse_ID@ ?";
}
return "@C_RfQResponse_ID@ #" + rfqResponse.getName();
|
}
@Override
public void updateQtyPromisedAndSave(final I_C_RfQResponseLine rfqResponseLine)
{
final BigDecimal qtyPromised = Services.get(IRfqDAO.class).calculateQtyPromised(rfqResponseLine);
rfqResponseLine.setQtyPromised(qtyPromised);
InterfaceWrapperHelper.save(rfqResponseLine);
}
// @Override
// public void uncloseInTrx(final I_C_RfQResponse rfqResponse)
// {
// if (!isClosed(rfqResponse))
// {
// throw new RfQDocumentNotClosedException(getSummary(rfqResponse));
// }
//
// //
// final IRfQEventDispacher rfQEventDispacher = getRfQEventDispacher();
// rfQEventDispacher.fireBeforeUnClose(rfqResponse);
//
// //
// // Mark as NOT closed
// rfqResponse.setDocStatus(X_C_RfQResponse.DOCSTATUS_Completed);
// InterfaceWrapperHelper.save(rfqResponse);
// updateRfQResponseLinesStatus(rfqResponse);
//
// //
// rfQEventDispacher.fireAfterUnClose(rfqResponse);
//
// // Make sure it's saved
// InterfaceWrapperHelper.save(rfqResponse);
// }
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqBL.java
| 1
|
请完成以下Java代码
|
public CashAccount16 getCdtrAcct() {
return cdtrAcct;
}
/**
* Sets the value of the cdtrAcct property.
*
* @param value
* allowed object is
* {@link CashAccount16 }
*
*/
public void setCdtrAcct(CashAccount16 value) {
this.cdtrAcct = value;
}
/**
* Gets the value of the ultmtCdtr property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getUltmtCdtr() {
return ultmtCdtr;
}
/**
* Sets the value of the ultmtCdtr property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setUltmtCdtr(PartyIdentification32 value) {
this.ultmtCdtr = value;
}
/**
* Gets the value of the tradgPty property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getTradgPty() {
|
return tradgPty;
}
/**
* Sets the value of the tradgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setTradgPty(PartyIdentification32 value) {
this.tradgPty = value;
}
/**
* Gets the value of the prtry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryParty2 }
*
*
*/
public List<ProprietaryParty2> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryParty2>();
}
return this.prtry;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionParty2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Long studentCount(String className) {
if (StrUtil.isBlank(className)) {
return studentRepo.count();
} else {
return studentRepo.countByClassName(className);
}
}
/**
* 查询同学关系,根据课程
*
* @return 返回同学关系
*/
public Map<String, List<Student>> findClassmatesGroupByLesson() {
List<ClassmateInfoGroupByLesson> groupByLesson = studentRepo.findByClassmateGroupByLesson();
Map<String, List<Student>> result = Maps.newHashMap();
groupByLesson.forEach(classmateInfoGroupByLesson -> result.put(classmateInfoGroupByLesson.getLessonName(), classmateInfoGroupByLesson.getStudents()));
return result;
}
/**
|
* 查询所有师生关系,包括班主任/学生,任课老师/学生
*
* @return 师生关系
*/
public Map<String, Set<Student>> findTeacherStudent() {
List<TeacherStudent> teacherStudentByClass = studentRepo.findTeacherStudentByClass();
List<TeacherStudent> teacherStudentByLesson = studentRepo.findTeacherStudentByLesson();
Map<String, Set<Student>> result = Maps.newHashMap();
teacherStudentByClass.forEach(teacherStudent -> result.put(teacherStudent.getTeacherName(), Sets.newHashSet(teacherStudent.getStudents())));
teacherStudentByLesson.forEach(teacherStudent -> result.put(teacherStudent.getTeacherName(), Sets.newHashSet(teacherStudent.getStudents())));
return result;
}
}
|
repos\spring-boot-demo-master\demo-neo4j\src\main\java\com\xkcoding\neo4j\service\NeoService.java
| 2
|
请完成以下Java代码
|
void setId(@NonNull final DataEntryRecordId id)
{
this.id = Optional.of(id);
}
/**
* @return {@code true} if the given value is different from the previous one.
*/
public boolean setRecordField(
@NonNull final DataEntryFieldId dataEntryFieldId,
@NonNull final UserId updatedBy,
@Nullable final Object value)
{
assertReadWrite();
final DataEntryRecordField<?> previousFieldVersion = fields.get(dataEntryFieldId);
final Object previousValue = previousFieldVersion == null ? null : previousFieldVersion.getValue();
final boolean valueChanged = !Objects.equals(previousValue, value);
if (!valueChanged)
{
return false;
}
final ZonedDateTime updated = ZonedDateTime.now();
final CreatedUpdatedInfo createdUpdatedInfo;
if (previousFieldVersion == null)
{
createdUpdatedInfo = CreatedUpdatedInfo.createNew(updatedBy, updated);
}
else
{
createdUpdatedInfo = previousFieldVersion.getCreatedUpdatedInfo().updated(updatedBy, updated);
}
final DataEntryRecordField<?> dataEntryRecordField = value != null
? DataEntryRecordField.createDataEntryRecordField(dataEntryFieldId, createdUpdatedInfo, value)
: DataEntryRecordFieldString.of(dataEntryFieldId, createdUpdatedInfo, null);
fields.put(dataEntryFieldId, dataEntryRecordField);
return true;
}
public boolean isEmpty()
{
return fields.isEmpty();
}
public ImmutableList<DataEntryRecordField<?>> getFields()
{
return ImmutableList.copyOf(fields.values());
}
public Optional<ZonedDateTime> getCreatedValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getCreated);
}
public Optional<UserId> getCreatedByValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
|
.map(CreatedUpdatedInfo::getCreatedBy);
}
public Optional<ZonedDateTime> getUpdatedValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getUpdated);
}
public Optional<UserId> getUpdatedByValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getUpdatedBy);
}
public Optional<CreatedUpdatedInfo> getCreatedUpdatedInfo(@NonNull final DataEntryFieldId fieldId)
{
return getOptional(fieldId)
.map(DataEntryRecordField::getCreatedUpdatedInfo);
}
public Optional<Object> getFieldValue(@NonNull final DataEntryFieldId fieldId)
{
return getOptional(fieldId)
.map(DataEntryRecordField::getValue);
}
private Optional<DataEntryRecordField<?>> getOptional(@NonNull final DataEntryFieldId fieldId)
{
return Optional.ofNullable(fields.get(fieldId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecord.java
| 1
|
请完成以下Java代码
|
public void onBeforeConvert(BeforeConvertEvent<IncIdEntity> event) {
IncIdEntity entity = event.getSource();
// 判断 id 为空
if (entity.getId() == null) {
// 获得下一个编号
Number id = this.getNextId(entity);
// 设置到实体中
// noinspection unchecked
entity.setId(id);
}
}
/**
* 获得实体的下一个主键 ID 编号
*
* @param entity 实体对象
* @return ID 编号
*/
private Number getNextId(IncIdEntity entity) {
// 使用实体名的简单类名,作为 ID 编号
String id = entity.getClass().getSimpleName();
// 创建 Query 对象
Query query = new Query(Criteria.where("_id").is(id));
|
// 创建 Update 对象
Update update = new Update();
update.inc(SEQUENCE_FIELD_VALUE, 1); // 自增值
// 创建 FindAndModifyOptions 对象
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true); // 如果不存在时,则进行插入
options.returnNew(true); // 返回新值
// 执行操作
@SuppressWarnings("unchecked")
HashMap<String, Object> result = mongoTemplate.findAndModify(query, update, options,
HashMap.class, SEQUENCE_COLLECTION_NAME);
// 返回主键
return (Number) result.get(SEQUENCE_FIELD_VALUE);
}
}
|
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\mongo\MongoInsertEventListener.java
| 1
|
请完成以下Java代码
|
public class DeferredFileValueImpl extends FileValueImpl implements DeferredFileValue {
private static final long serialVersionUID = 1L;
protected static final ExternalTaskClientLogger LOG = ExternalTaskClientLogger.CLIENT_LOGGER;
protected boolean isLoaded = false;
protected String variableName;
protected String executionId;
protected EngineClient engineClient;
public DeferredFileValueImpl(String filename, EngineClient engineClient) {
super(PrimitiveValueType.FILE, filename);
this.engineClient = engineClient;
}
protected void load() {
try {
byte[] bytes = engineClient.getLocalBinaryVariable(variableName, executionId);
setValue(bytes);
this.isLoaded = true;
} catch (EngineClientException e) {
throw LOG.handledEngineClientException("loading deferred file", e);
}
}
public boolean isLoaded() {
return isLoaded;
}
@Override
public InputStream getValue() {
if (!isLoaded()) {
load();
}
|
return super.getValue();
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public void setExecutionId(String executionId){
this.executionId = executionId;
};
public String getExecutionId() {
return executionId;
}
@Override
public String toString() {
return "DeferredFileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", "
+ "isTransient=" + isTransient + ", isLoaded=" + isLoaded + "]";
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\value\DeferredFileValueImpl.java
| 1
|
请完成以下Java代码
|
public String getCtry() {
return ctry;
}
/**
* Sets the value of the ctry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtry(String value) {
this.ctry = value;
}
/**
* Gets the value of the adrLine property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adrLine property.
|
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdrLine().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAdrLine() {
if (adrLine == null) {
adrLine = new ArrayList<String>();
}
return this.adrLine;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PostalAddress6.java
| 1
|
请完成以下Java代码
|
public final class UsernamePasswordMetadata {
/**
* Represents a username password which is encoded as
* {@code ${username-bytes-length}${username-bytes}${password-bytes}}.
*
* See <a href="https://github.com/rsocket/rsocket/issues/272">rsocket/rsocket#272</a>
* @deprecated Basic did not evolve into the standard. Instead use Simple
* Authentication
* MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())
*/
@Deprecated
public static final MimeType BASIC_AUTHENTICATION_MIME_TYPE = new MediaType("message",
"x.rsocket.authentication.basic.v0");
private final String username;
private final String password;
|
public UsernamePasswordMetadata(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
}
|
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\metadata\UsernamePasswordMetadata.java
| 1
|
请完成以下Java代码
|
private static void setDropShipLocationOverride(@NonNull final I_C_OLCand olCand, @Nullable final I_C_BPartner_Location dropShipLocation)
{
olCand.setDropShip_Location_Override_ID(dropShipLocation != null ? dropShipLocation.getC_BPartner_Location_ID() : -1);
olCand.setDropShip_Location_Override_Value_ID(dropShipLocation != null ? dropShipLocation.getC_Location_ID() : -1);
}
public void updateHandoverLocationOverride(@NonNull final I_C_OLCand olCand)
{
try (final MDC.MDCCloseable ignore = TableRecordMDC.putTableRecordReference(olCand))
{
setHandOverLocationOverride(olCand, computeHandoverLocationOverride(olCand));
}
}
private I_C_BPartner_Location computeHandoverLocationOverride(@NonNull final I_C_OLCand olCand)
{
final BPartnerId handOverPartnerOverrideId = BPartnerId.ofRepoIdOrNull(olCand.getHandOver_Partner_Override_ID());
if (handOverPartnerOverrideId == null)
{
// in case the handover bpartner Override was deleted, also delete the handover Location Override
return null;
}
else
{
final I_C_BPartner partner = olCandEffectiveValuesBL.getC_BPartner_Effective(olCand);
final I_C_BPartner handoverPartnerOverride = bPartnerDAO.getById(handOverPartnerOverrideId);
final I_C_BP_Relation handoverRelation = bpRelationDAO.retrieveHandoverBPRelation(partner, handoverPartnerOverride);
if (handoverRelation == null)
{
// this shall never happen, since both Handover_BPartner and Handover_BPartner_Override must come from such a bpp relation.
// but I will leave this condition here as extra safety
return null;
|
}
else
{
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(handoverRelation.getC_BPartnerRelation_ID(), handoverRelation.getC_BPartnerRelation_Location_ID());
return bPartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId);
}
}
}
private static void setHandOverLocationOverride(
@NonNull final I_C_OLCand olCand,
@Nullable final I_C_BPartner_Location handOverLocation)
{
olCand.setHandOver_Location_Override_ID(handOverLocation != null ? handOverLocation.getC_BPartner_Location_ID() : -1);
olCand.setHandOver_Location_Override_Value_ID(handOverLocation != null ? handOverLocation.getC_Location_ID() : -1);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\OLCandLocationsUpdaterService.java
| 1
|
请完成以下Java代码
|
public Config setAlpha(float alpha)
{
this.alpha = alpha;
return this;
}
public float getAlpha()
{
return alpha;
}
public Config setInputFile(String inputFile)
{
this.inputFile = inputFile;
return this;
}
|
public String getInputFile()
{
return inputFile;
}
public TrainingCallback getCallback()
{
return callback;
}
public void setCallback(TrainingCallback callback)
{
this.callback = callback;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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 void setPending(PendingType value) {
this.pending = value;
}
/**
* Gets the value of the accepted property.
*
* @return
* possible object is
* {@link AcceptedType }
*
*/
public AcceptedType getAccepted() {
return accepted;
}
/**
* Sets the value of the accepted property.
*
* @param value
* allowed object is
* {@link AcceptedType }
*
*/
public void setAccepted(AcceptedType value) {
this.accepted = value;
}
/**
* Gets the value of the rejected property.
*
* @return
* possible object is
* {@link RejectedType }
*
*/
public RejectedType getRejected() {
return rejected;
}
/**
|
* Sets the value of the rejected property.
*
* @param value
* allowed object is
* {@link RejectedType }
*
*/
public void setRejected(RejectedType value) {
this.rejected = value;
}
/**
* Gets the value of the documents property.
*
* @return
* possible object is
* {@link DocumentsType }
*
*/
public DocumentsType getDocuments() {
return documents;
}
/**
* Sets the value of the documents property.
*
* @param value
* allowed object is
* {@link DocumentsType }
*
*/
public void setDocuments(DocumentsType value) {
this.documents = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\BodyType.java
| 1
|
请完成以下Java代码
|
public BpmnParse createParse() {
return bpmnParseFactory.createBpmnParse(this);
}
public ActivityBehaviorFactory getActivityBehaviorFactory() {
return activityBehaviorFactory;
}
public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) {
this.activityBehaviorFactory = activityBehaviorFactory;
}
public ListenerFactory getListenerFactory() {
return listenerFactory;
}
public void setListenerFactory(ListenerFactory listenerFactory) {
this.listenerFactory = listenerFactory;
}
|
public BpmnParseFactory getBpmnParseFactory() {
return bpmnParseFactory;
}
public void setBpmnParseFactory(BpmnParseFactory bpmnParseFactory) {
this.bpmnParseFactory = bpmnParseFactory;
}
public BpmnParseHandlers getBpmnParserHandlers() {
return bpmnParserHandlers;
}
public void setBpmnParserHandlers(BpmnParseHandlers bpmnParserHandlers) {
this.bpmnParserHandlers = bpmnParserHandlers;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParser.java
| 1
|
请完成以下Java代码
|
public FlowableHttpRequestHandler getHttpRequestHandler() {
return httpRequestHandler;
}
public void setHttpRequestHandler(FlowableHttpRequestHandler httpRequestHandler) {
this.httpRequestHandler = httpRequestHandler;
}
public FlowableHttpResponseHandler getHttpResponseHandler() {
return httpResponseHandler;
}
public void setHttpResponseHandler(FlowableHttpResponseHandler httpResponseHandler) {
this.httpResponseHandler = httpResponseHandler;
}
public Boolean getParallelInSameTransaction() {
return parallelInSameTransaction;
}
public void setParallelInSameTransaction(Boolean parallelInSameTransaction) {
this.parallelInSameTransaction = parallelInSameTransaction;
}
@Override
public HttpServiceTask clone() {
HttpServiceTask clone = new HttpServiceTask();
clone.setValues(this);
return clone;
|
}
public void setValues(HttpServiceTask otherElement) {
super.setValues(otherElement);
setParallelInSameTransaction(otherElement.getParallelInSameTransaction());
if (otherElement.getHttpRequestHandler() != null) {
setHttpRequestHandler(otherElement.getHttpRequestHandler().clone());
}
if (otherElement.getHttpResponseHandler() != null) {
setHttpResponseHandler(otherElement.getHttpResponseHandler().clone());
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\HttpServiceTask.java
| 1
|
请完成以下Java代码
|
public int getC_ConversionType_Default_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_Default_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ConversionType getC_ConversionType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class);
}
@Override
public void setC_ConversionType(org.compiere.model.I_C_ConversionType C_ConversionType)
{
set_ValueFromPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class, C_ConversionType);
}
/** Set Kursart.
@param C_ConversionType_ID
Kursart
*/
@Override
public void setC_ConversionType_ID (int C_ConversionType_ID)
{
if (C_ConversionType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, Integer.valueOf(C_ConversionType_ID));
}
/** Get Kursart.
@return Kursart
*/
@Override
public int getC_ConversionType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType_Default.java
| 1
|
请完成以下Java代码
|
private String getInvoker(int depth) {
Exception e = new Exception();
StackTraceElement[] stes = e.getStackTrace();
if (stes.length > depth) {
return ClassUtils.getShortClassName(stes[depth].getClassName());
}
return getClass().getSimpleName();
}
/**
* Get sequence for different naming prefix
*
* @param invoker
* @return
*/
private long getSequence(String invoker) {
AtomicLong r = this.sequences.get(invoker);
if (r == null) {
r = new AtomicLong(0);
AtomicLong previous = this.sequences.putIfAbsent(invoker, r);
if (previous != null) {
r = previous;
}
}
return r.incrementAndGet();
}
/**
|
* Getters & Setters
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDaemon() {
return daemon;
}
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler;
}
public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
this.uncaughtExceptionHandler = handler;
}
}
|
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\NamingThreadFactory.java
| 1
|
请完成以下Java代码
|
public void updateExecutionSuspensionStateByProcessDefinitionId(String processDefinitionId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(ExecutionEntity.class, "updateExecutionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateExecutionSuspensionStateByProcessInstanceId(String processInstanceId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(ExecutionEntity.class, "updateExecutionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateExecutionSuspensionStateByProcessDefinitionKey(String processDefinitionKey, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isTenantIdSet", false);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(ExecutionEntity.class, "updateExecutionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateExecutionSuspensionStateByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String tenantId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isTenantIdSet", true);
parameters.put("tenantId", tenantId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(ExecutionEntity.class, "updateExecutionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
// helper ///////////////////////////////////////////////////////////
|
protected void createDefaultAuthorizations(ExecutionEntity execution) {
if(execution.isProcessInstanceExecution() && isAuthorizationEnabled()) {
ResourceAuthorizationProvider provider = getResourceAuthorizationProvider();
AuthorizationEntity[] authorizations = provider.newProcessInstance(execution);
saveDefaultAuthorizations(authorizations);
}
}
protected void configureQuery(AbstractQuery<?, ?> query) {
getAuthorizationManager().configureExecutionQuery(query);
getTenantManager().configureQuery(query);
}
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExecutionManager.java
| 1
|
请完成以下Java代码
|
protected Class<UserCredentialsEntity> getEntityClass() {
return UserCredentialsEntity.class;
}
@Override
protected JpaRepository<UserCredentialsEntity, UUID> getRepository() {
return userCredentialsRepository;
}
@Override
public UserCredentials findByUserId(TenantId tenantId, UUID userId) {
return DaoUtil.getData(userCredentialsRepository.findByUserId(userId));
}
@Override
public UserCredentials findByActivateToken(TenantId tenantId, String activateToken) {
return DaoUtil.getData(userCredentialsRepository.findByActivateToken(activateToken));
}
@Override
public UserCredentials findByResetToken(TenantId tenantId, String resetToken) {
return DaoUtil.getData(userCredentialsRepository.findByResetToken(resetToken));
}
@Override
public void removeByUserId(TenantId tenantId, UserId userId) {
userCredentialsRepository.removeByUserId(userId.getId());
}
@Override
public void setLastLoginTs(TenantId tenantId, UserId userId, long lastLoginTs) {
userCredentialsRepository.updateLastLoginTsByUserId(userId.getId(), lastLoginTs);
}
|
@Override
public int incrementFailedLoginAttempts(TenantId tenantId, UserId userId) {
return userCredentialsRepository.incrementFailedLoginAttemptsByUserId(userId.getId());
}
@Override
public void setFailedLoginAttempts(TenantId tenantId, UserId userId, int failedLoginAttempts) {
userCredentialsRepository.updateFailedLoginAttemptsByUserId(userId.getId(), failedLoginAttempts);
}
@Override
public PageData<UserCredentials> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(userCredentialsRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)));
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserCredentialsDao.java
| 1
|
请完成以下Java代码
|
static <T extends ClientHttpRequestFactory> ClientHttpRequestFactoryBuilder<T> of(
Supplier<T> requestFactorySupplier) {
return new ReflectiveComponentsClientHttpRequestFactoryBuilder<>(requestFactorySupplier);
}
/**
* Detect the most suitable {@link ClientHttpRequestFactoryBuilder} based on the
* classpath. The method favors builders in the following order:
* <ol>
* <li>{@link #httpComponents()}</li>
* <li>{@link #jetty()}</li>
* <li>{@link #reactor()}</li>
* <li>{@link #jdk()}</li>
* <li>{@link #simple()}</li>
* </ol>
* @return the most suitable {@link ClientHttpRequestFactoryBuilder} for the classpath
*/
static ClientHttpRequestFactoryBuilder<? extends ClientHttpRequestFactory> detect() {
return detect(null);
}
/**
* Detect the most suitable {@link ClientHttpRequestFactoryBuilder} based on the
* classpath. The method favors builders in the following order:
* <ol>
* <li>{@link #httpComponents()}</li>
* <li>{@link #jetty()}</li>
* <li>{@link #reactor()}</li>
* <li>{@link #jdk()}</li>
* <li>{@link #simple()}</li>
* </ol>
* @param classLoader the class loader to use for detection
* @return the most suitable {@link ClientHttpRequestFactoryBuilder} for the classpath
* @since 3.5.0
*/
|
static ClientHttpRequestFactoryBuilder<? extends ClientHttpRequestFactory> detect(
@Nullable ClassLoader classLoader) {
if (HttpComponentsClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return httpComponents();
}
if (JettyClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return jetty();
}
if (ReactorClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return reactor();
}
if (JdkClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return jdk();
}
return simple();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ClientHttpRequestFactoryBuilder.java
| 1
|
请完成以下Java代码
|
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** ModerationType AD_Reference_ID=395 */
public static final int MODERATIONTYPE_AD_Reference_ID=395;
/** Not moderated = N */
public static final String MODERATIONTYPE_NotModerated = "N";
/** Before Publishing = B */
public static final String MODERATIONTYPE_BeforePublishing = "B";
/** After Publishing = A */
public static final String MODERATIONTYPE_AfterPublishing = "A";
/** Set Moderation Type.
@param ModerationType
Type of moderation
*/
public void setModerationType (String ModerationType)
{
set_Value (COLUMNNAME_ModerationType, ModerationType);
}
/** Get Moderation Type.
@return Type of moderation
*/
|
public String getModerationType ()
{
return (String)get_Value(COLUMNNAME_ModerationType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ConfigurationMetadataSource implements Serializable {
private String groupId;
private String type;
private String description;
private String shortDescription;
private String sourceType;
private String sourceMethod;
private final Map<String, ConfigurationMetadataProperty> properties = new HashMap<>();
/**
* The identifier of the group to which this source is associated.
* @return the group id
*/
public String getGroupId() {
return this.groupId;
}
void setGroupId(String groupId) {
this.groupId = groupId;
}
/**
* The type of the source. Usually this is the fully qualified name of a class that
* defines configuration items. This class may or may not be available at runtime.
* @return the type
*/
public String getType() {
return this.type;
}
void setType(String type) {
this.type = type;
}
/**
* A description of this source, if any. Can be multi-lines.
* @return the description
* @see #getShortDescription()
*/
public String getDescription() {
return this.description;
}
void setDescription(String description) {
this.description = description;
}
/**
|
* A single-line, single-sentence description of this source, if any.
* @return the short description
* @see #getDescription()
*/
public String getShortDescription() {
return this.shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
/**
* The type where this source is defined. This can be identical to the
* {@link #getType() type} if the source is self-defined.
* @return the source type
*/
public String getSourceType() {
return this.sourceType;
}
void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
/**
* The method name that defines this source, if any.
* @return the source method
*/
public String getSourceMethod() {
return this.sourceMethod;
}
void setSourceMethod(String sourceMethod) {
this.sourceMethod = sourceMethod;
}
/**
* Return the properties defined by this source.
* @return the properties
*/
public Map<String, ConfigurationMetadataProperty> getProperties() {
return this.properties;
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataSource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AvailableToPromiseMultiQuery
{
/**
* Creates a multi-query with one query for the given {@code materialDescriptor}
* and - if that descriptor has a specific partner - another one for ATP stuff that has no specific partner.
*/
public static AvailableToPromiseMultiQuery forDescriptorAndAllPossibleBPartnerIds(@NonNull final MaterialDescriptor materialDescriptor)
{
final AvailableToPromiseQuery bPartnerQuery = AvailableToPromiseQuery.forMaterialDescriptor(materialDescriptor);
final AvailableToPromiseMultiQueryBuilder multiQueryBuilder = AvailableToPromiseMultiQuery.builder()
.addToPredefinedBuckets(false)
.query(bPartnerQuery);
if (bPartnerQuery.getBpartner().isSpecificBPartner())
{
final AvailableToPromiseQuery noPartnerQuery = bPartnerQuery
.toBuilder()
.bpartner(BPartnerClassifier.none())
.build();
multiQueryBuilder.query(noPartnerQuery);
}
return multiQueryBuilder.build();
}
public static final AvailableToPromiseMultiQuery of(@NonNull final AvailableToPromiseQuery query)
{
return builder()
.query(query)
.addToPredefinedBuckets(DEFAULT_addToPredefinedBuckets)
.build();
}
|
private final Set<AvailableToPromiseQuery> queries;
private static final boolean DEFAULT_addToPredefinedBuckets = true;
private final boolean addToPredefinedBuckets;
@Builder
private AvailableToPromiseMultiQuery(
@NonNull @Singular final ImmutableSet<AvailableToPromiseQuery> queries,
final Boolean addToPredefinedBuckets)
{
Check.assumeNotEmpty(queries, "queries is not empty");
this.queries = queries;
this.addToPredefinedBuckets = CoalesceUtil.coalesce(addToPredefinedBuckets, DEFAULT_addToPredefinedBuckets);
}
/**
* {@code true} means that the system will initially create one empty result group for the {@link AttributesKey}s of each included {@link AvailableToPromiseQuery}.
* ATP quantity that are retrieved may be added to multiple result groups, depending on those groups attributes keys
* If no ATP quantity matches a particular group, it will remain empty.<br>
* {@code false} means that the system will create result groups on the fly for the respective ATP records that it finds.
*/
public boolean isAddToPredefinedBuckets()
{
return addToPredefinedBuckets;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseMultiQuery.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public HttpMethodEnum getHttpMethodEnum() {
return httpMethodEnum;
}
public void setHttpMethodEnum(HttpMethodEnum httpMethodEnum) {
this.httpMethodEnum = httpMethodEnum;
}
public boolean isLogin() {
return isLogin;
}
public void setLogin(boolean login) {
isLogin = login;
|
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
@Override
public String toString() {
return "AccessAuthEntity{" +
"url='" + url + '\'' +
", methodName='" + methodName + '\'' +
", httpMethodEnum=" + httpMethodEnum +
", isLogin=" + isLogin +
", permission='" + permission + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\AccessAuthEntity.java
| 2
|
请完成以下Java代码
|
public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) {
return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId));
}
@Override
public void deleteEventLogEntry(long logNr) {
commandExecutor.execute(new DeleteEventLogEntry(logNr));
}
@Override
public ExternalWorkerJobAcquireBuilder createExternalWorkerJobAcquireBuilder() {
return new ExternalWorkerJobAcquireBuilderImpl(commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String externalJobId, String workerId) {
return new ExternalWorkerJobFailureBuilderImpl(externalJobId, workerId, commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public ExternalWorkerCompletionBuilder createExternalWorkerCompletionBuilder(String externalJobId, String workerId) {
return new ExternalWorkerCompletionBuilderImpl(commandExecutor, externalJobId, workerId, configuration.getJobServiceConfiguration());
}
@Override
public void unacquireExternalWorkerJob(String jobId, String workerId) {
commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration()));
}
|
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration()));
}
@Override
public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) {
return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager());
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ManagementServiceImpl.java
| 1
|
请完成以下Java代码
|
public String getCaseInstanceId() {
return caseExecutionId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getActivityId() {
return null;
}
public String getBusinessKey() {
return businessKey;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getDeploymentId() {
return deploymentId;
}
public CaseExecutionState getState() {
return state;
}
public boolean isCaseInstancesOnly() {
return true;
|
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public Boolean isRequired() {
return required;
}
public Boolean isRepeatable() {
return repeatable;
}
public Boolean isRepetition() {
return repetition;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public void setDunningGrace (java.sql.Timestamp DunningGrace)
{
set_Value (COLUMNNAME_DunningGrace, DunningGrace);
}
/** Get Dunning Grace Date.
@return Dunning Grace Date */
@Override
public java.sql.Timestamp getDunningGrace ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DunningGrace);
}
/** Set Summe Gesamt.
@param GrandTotal
Summe über Alles zu diesem Beleg
*/
@Override
public void setGrandTotal (java.math.BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Summe Gesamt.
@return Summe über Alles zu diesem Beleg
*/
@Override
public java.math.BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
@Override
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
@Override
public boolean isInDispute ()
{
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Offener Betrag.
@param OpenAmt Offener Betrag */
@Override
public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java
| 1
|
请完成以下Java代码
|
public CurrencyConversionContext getCurrencyConversionContext(final AcctSchema ignoredAcctSchema)
{
CurrencyConversionContext invoiceCurrencyConversionCtx = this._invoiceCurrencyConversionCtx;
if (invoiceCurrencyConversionCtx == null)
{
final I_C_Invoice invoice = getModel(I_C_Invoice.class);
invoiceCurrencyConversionCtx = this._invoiceCurrencyConversionCtx = invoiceBL.getCurrencyConversionCtx(invoice);
}
return invoiceCurrencyConversionCtx;
}
@Override
protected void afterPost()
{
postDependingMatchInvsIfNeeded();
}
private void postDependingMatchInvsIfNeeded()
{
if (!services.getSysConfigBooleanValue(SYSCONFIG_PostMatchInvs, DEFAULT_PostMatchInvs))
{
return;
}
final Set<InvoiceAndLineId> invoiceAndLineIds = new HashSet<>();
for (final DocLine_Invoice line : getDocLines())
{
invoiceAndLineIds.add(line.getInvoiceAndLineId());
}
// 08643
// Do nothing in case there are no invoice lines
if (invoiceAndLineIds.isEmpty())
{
return;
}
|
final Set<MatchInvId> matchInvIds = matchInvoiceService.getIdsProcessedButNotPostedByInvoiceLineIds(invoiceAndLineIds);
postDependingDocuments(I_M_MatchInv.Table_Name, matchInvIds);
}
@Nullable
@Override
protected OrderId getSalesOrderId()
{
final Optional<OrderId> optionalSalesOrderId = CollectionUtils.extractSingleElementOrDefault(
getDocLines(),
docLine -> Optional.ofNullable(docLine.getSalesOrderId()),
Optional.empty());
//noinspection DataFlowIssue
return optionalSalesOrderId.orElse(null);
}
public static void unpostIfNeeded(final I_C_Invoice invoice)
{
if (!invoice.isPosted())
{
return;
}
// Make sure the period is open
final Properties ctx = InterfaceWrapperHelper.getCtx(invoice);
MPeriod.testPeriodOpen(ctx, invoice.getDateAcct(), invoice.getC_DocType_ID(), invoice.getAD_Org_ID());
Services.get(IFactAcctDAO.class).deleteForDocumentModel(invoice);
invoice.setPosted(false);
InterfaceWrapperHelper.save(invoice);
}
} // Doc_Invoice
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Invoice.java
| 1
|
请完成以下Java代码
|
public Optional<DocTypeInvoicingPoolId> getDocTypeInvoicingPoolId()
{
return Optional.ofNullable(docTypeInvoicingPoolId);
}
@Override
public boolean isTakeDocTypeFromPool()
{
return isTakeDocTypeFromPool;
}
public void setIsTakeDocTypeFromPool(final boolean isTakeDocTypeFromPool)
{
this.isTakeDocTypeFromPool = isTakeDocTypeFromPool;
}
@Override
public void setDocTypeInvoicingPoolId(@Nullable final DocTypeInvoicingPoolId docTypeInvoicingPoolId)
{
this.docTypeInvoicingPoolId = docTypeInvoicingPoolId;
}
@Override
public void setDocTypeInvoiceId(@Nullable final DocTypeId docTypeId)
{
this.docTypeInvoiceId = docTypeId;
}
@Override
public boolean isTaxIncluded()
{
return taxIncluded;
}
public void setTaxIncluded(boolean taxIncluded)
{
this.taxIncluded = taxIncluded;
}
/**
* Negate all line amounts
*/
public void negateAllLineAmounts()
{
for (final IInvoiceCandAggregate lineAgg : getLines())
{
lineAgg.negateLineAmounts();
}
}
/**
* Calculates total net amount by summing up all {@link IInvoiceLineRW#getNetLineAmt()}s.
*
* @return total net amount
*/
public Money calculateTotalNetAmtFromLines()
{
final List<IInvoiceCandAggregate> lines = getLines();
Check.assume(lines != null && !lines.isEmpty(), "Invoice {} was not aggregated yet", this);
Money totalNetAmt = Money.zero(currencyId);
for (final IInvoiceCandAggregate lineAgg : lines)
{
for (final IInvoiceLineRW line : lineAgg.getAllLines())
{
final Money lineNetAmt = line.getNetLineAmt();
totalNetAmt = totalNetAmt.add(lineNetAmt);
}
}
return totalNetAmt;
}
public void setPaymentTermId(@Nullable final PaymentTermId paymentTermId)
{
this.paymentTermId = paymentTermId;
}
|
@Override
public PaymentTermId getPaymentTermId()
{
return paymentTermId;
}
public void setPaymentRule(@Nullable final String paymentRule)
{
this.paymentRule = paymentRule;
}
@Override
public String getPaymentRule()
{
return paymentRule;
}
@Override
public String getExternalId()
{
return externalId;
}
@Override
public int getC_Async_Batch_ID()
{
return C_Async_Batch_ID;
}
public void setC_Async_Batch_ID(final int C_Async_Batch_ID)
{
this.C_Async_Batch_ID = C_Async_Batch_ID;
}
public String setExternalId(String externalId)
{
return this.externalId = externalId;
}
@Override
public int getC_Incoterms_ID()
{
return C_Incoterms_ID;
}
public void setC_Incoterms_ID(final int C_Incoterms_ID)
{
this.C_Incoterms_ID = C_Incoterms_ID;
}
@Override
public String getIncotermLocation()
{
return incotermLocation;
}
public void setIncotermLocation(final String incotermLocation)
{
this.incotermLocation = incotermLocation;
}
@Override
public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;}
public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
| 1
|
请完成以下Java代码
|
public String getCompletedBy() {
return completedBy;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getDeleteReason() {
return deleteReason;
}
|
public String getDeleteReasonLike() {
return deleteReasonLike;
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getProcessInstanceIds() {
return processInstanceIds;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ActivityInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public class C_Order_AddTo_M_ShipperTransportation extends JavaProcess implements IProcessPrecondition
{
private static final int MAX_SELECTION_SIZE = 100;
private final static AdMessageKey MSG_DOCUMENT_NOT_COMPLETE = AdMessageKey.of("DocumentNotComplete");
private final static AdMessageKey MSG_ORDER_ASSIGNED_TO_DIFFERENT_TRANSPORTATION_ORDER = AdMessageKey.of("OrderAssignedToDifferentTransportationOrder");
private final PurchaseOrderToShipperTransportationService orderToShipperTransportationService = SpringContextHolder.instance.getBean(PurchaseOrderToShipperTransportationService.class);
private final IOrderBL orderBL = Services.get(IOrderBL.class);
private final IShipperTransportationBL shipperTransportationBL = Services.get(IShipperTransportationBL.class);
@Param(parameterName = I_M_ShipperTransportation.COLUMNNAME_M_ShipperTransportation_ID)
private ShipperTransportationId p_M_ShipperTransportation_ID;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
if (context.isMoreThanAllowedSelected(MAX_SELECTION_SIZE))
{
return ProcessPreconditionsResolution.rejectBecauseTooManyRecordsSelected(MAX_SELECTION_SIZE);
}
final IQueryFilter<I_C_Order> queryFilter = context.getQueryFilter(I_C_Order.class);
final List<I_C_Order> selectedOrders = orderBL.getByQueryFilter(queryFilter);
if (selectedOrders.stream().anyMatch(orderBL::isRequisition))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("is purchase requisition");
}
if (selectedOrders.stream().anyMatch(o -> !orderBL.isCompleted(o)))
{
return ProcessPreconditionsResolution.reject(MSG_DOCUMENT_NOT_COMPLETE);
}
return ProcessPreconditionsResolution.accept();
}
|
@Override
protected String doIt() throws Exception
{
final Set<OrderId> orderIds = orderBL.getByQueryFilter(getProcessInfo().getQueryFilterOrElseFalse())
.stream()
.map(o -> OrderId.ofRepoId(o.getC_Order_ID()))
.collect(Collectors.toSet());
if (shipperTransportationBL.isAnyOrderAssignedToDifferentTransportationOrder(p_M_ShipperTransportation_ID, orderIds))
{
throw new AdempiereException(MSG_ORDER_ASSIGNED_TO_DIFFERENT_TRANSPORTATION_ORDER);
}
orderToShipperTransportationService.addPurchaseOrdersToShipperTransportation(p_M_ShipperTransportation_ID, orderIds);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\process\C_Order_AddTo_M_ShipperTransportation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class DirectExchangeDemoConfiguration {
// 创建 Queue
@Bean
public Queue demo10Queue0() {
return new Queue(Demo10Message.QUEUE_0);
}
@Bean
public Queue demo10Queue1() {
return new Queue(Demo10Message.QUEUE_1);
}
@Bean
public Queue demo10Queue2() {
return new Queue(Demo10Message.QUEUE_2);
}
@Bean
public Queue demo10Queue3() {
return new Queue(Demo10Message.QUEUE_3);
}
// 创建 Direct Exchange
@Bean
public DirectExchange demo10Exchange() {
return new DirectExchange(Demo10Message.EXCHANGE,
true, // durable: 是否持久化
false); // exclusive: 是否排它
}
// 创建 Binding
@Bean
public Binding demo10Binding0() {
return BindingBuilder.bind(demo10Queue0()).to(demo10Exchange()).with("0");
}
@Bean
|
public Binding demo10Binding1() {
return BindingBuilder.bind(demo10Queue1()).to(demo10Exchange()).with("1");
}
@Bean
public Binding demo10Binding2() {
return BindingBuilder.bind(demo10Queue2()).to(demo10Exchange()).with("2");
}
@Bean
public Binding demo10Binding3() {
return BindingBuilder.bind(demo10Queue3()).to(demo10Exchange()).with("3");
}
}
}
|
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-orderly\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
| 2
|
请完成以下Java代码
|
public String getDocumentNo()
{
return model.getDocumentNo();
}
@Override
public File createPDF()
{
return handler.createPDF(model);
}
@Override
public String getProcessMsg()
{
return processMsg;
}
@Override
public int getDoc_User_ID()
{
return handler.getDoc_User_ID(model);
}
@Override
public int getC_Currency_ID()
{
return handler.getC_Currency_ID(model);
}
@Override
public BigDecimal getApprovalAmt()
{
return handler.getApprovalAmt(model);
}
@Override
public int getAD_Client_ID()
{
return model.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return model.getAD_Org_ID();
}
@Override
public String getDocAction()
{
return model.getDocAction();
}
@Override
public boolean save()
|
{
InterfaceWrapperHelper.save(model);
return true;
}
@Override
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(model);
}
@Override
public int get_ID()
{
return InterfaceWrapperHelper.getId(model);
}
@Override
public int get_Table_ID()
{
return InterfaceWrapperHelper.getModelTableId(model);
}
@Override
public String get_TrxName()
{
return InterfaceWrapperHelper.getTrxName(model);
}
@Override
public void set_TrxName(final String trxName)
{
InterfaceWrapperHelper.setTrxName(model, trxName);
}
@Override
public boolean isActive()
{
return model.isActive();
}
@Override
public Object getModel()
{
return getDocumentModel();
}
@Override
public Object getDocumentModel()
{
return model;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java
| 1
|
请完成以下Java代码
|
public static AppEngine getAppEngine(String appEngineName) {
if (!isInitialized()) {
init();
}
return appEngines.get(appEngineName);
}
/**
* retries to initialize an app engine that previously failed.
*/
public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initAppEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to app engine to application clients in a managed server environment.
*/
public static Map<String, AppEngine> getAppEngines() {
return appEngines;
}
/**
* closes all app engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, AppEngine> engines = new HashMap<>(appEngines);
appEngines = new HashMap<>();
for (String appEngineName : engines.keySet()) {
AppEngine appEngine = engines.get(appEngineName);
|
try {
appEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (appEngineName == null ? "the default app engine" : "app engine " + appEngineName), e);
}
}
appEngineInfosByName.clear();
appEngineInfosByResourceUrl.clear();
appEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
AppEngines.isInitialized = isInitialized;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\AppEngines.java
| 1
|
请完成以下Java代码
|
public static BPartnerDepartmentId ofRepoId(final int bpartnerId, final int bpartnerDepartmentId)
{
return new BPartnerDepartmentId(BPartnerId.ofRepoId(bpartnerId), bpartnerDepartmentId);
}
@NonNull
public static BPartnerDepartmentId ofRepoIdOrNone(
@NonNull final BPartnerId bpartnerId,
@Nullable final Integer bpartnerDepartmentId)
{
return bpartnerDepartmentId != null && bpartnerDepartmentId > 0
? ofRepoId(bpartnerId, bpartnerDepartmentId)
: none(bpartnerId);
}
private BPartnerDepartmentId(@NonNull final BPartnerId bpartnerId, final int bpartnerDepartmentId)
{
this.repoId = Check.assumeGreaterThanZero(bpartnerDepartmentId, "bpartnerDepartmentId");
this.bpartnerId = bpartnerId;
}
private BPartnerDepartmentId(@NonNull final BPartnerId bpartnerId)
|
{
this.repoId = -1;
this.bpartnerId = bpartnerId;
}
public static int toRepoId(@Nullable final BPartnerDepartmentId bpartnerDepartmentId)
{
return bpartnerDepartmentId != null && !bpartnerDepartmentId.isNone() ? bpartnerDepartmentId.getRepoId() : -1;
}
public boolean isNone()
{
return repoId <= 0;
}
@Nullable
public static Integer toRepoIdOrNull(@Nullable final BPartnerDepartmentId bPartnerDepartmentId)
{
return bPartnerDepartmentId != null && !bPartnerDepartmentId.isNone() ? bPartnerDepartmentId.getRepoId() : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\department\BPartnerDepartmentId.java
| 1
|
请完成以下Java代码
|
public void onMsg(TbContext ctx, TbMsg msg) {
var tbMsg = ackIfNeeded(ctx, msg);
withCallback(publishMessageAsync(ctx, tbMsg),
m -> tellSuccess(ctx, m),
t -> tellFailure(ctx, processException(tbMsg, t), t));
}
private ListenableFuture<TbMsg> publishMessageAsync(TbContext ctx, TbMsg msg) {
return ctx.getExternalCallExecutor().executeAsync(() -> publishMessage(msg));
}
private TbMsg publishMessage(TbMsg msg) {
String topicArn = TbNodeUtils.processPattern(this.config.getTopicArnPattern(), msg);
PublishRequest publishRequest = new PublishRequest()
.withTopicArn(topicArn)
.withMessage(msg.getData());
PublishResult result = this.snsClient.publish(publishRequest);
return processPublishResult(msg, result);
}
private TbMsg processPublishResult(TbMsg origMsg, PublishResult result) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(MESSAGE_ID, result.getMessageId());
metaData.putValue(REQUEST_ID, result.getSdkResponseMetadata().getRequestId());
return origMsg.transform()
|
.metaData(metaData)
.build();
}
private TbMsg processException(TbMsg origMsg, Throwable t) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage());
return origMsg.transform()
.metaData(metaData)
.build();
}
@Override
public void destroy() {
if (this.snsClient != null) {
try {
this.snsClient.shutdown();
} catch (Exception e) {
log.error("Failed to shutdown SNS client during destroy()", e);
}
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\sns\TbSnsNode.java
| 1
|
请完成以下Java代码
|
public void start(String bootstrapServer) {
StreamsBuilder builder = new StreamsBuilder();
KStream<String, User> userStream = builder.stream(
"user-topic",
Consumed.with(Serdes.String(), new UserSerde())
);
KTable<String, Long> usersPerCountry = userStream
.filter((key, user) ->
Objects.nonNull(user) && user.country() != null && !user.country().isEmpty())
.groupBy((key, user) -> user.country(), Grouped.with(Serdes.String(),
new UserSerde()))
.count(Materialized.as("users_per_country_store"));
usersPerCountry.toStream()
.peek((country, count) -> log.info("Aggregated for country {} with count {}",country, count))
.to("users_per_country", Produced.with(Serdes.String(), Serdes.Long()));
Properties props = getStreamProperties(bootstrapServer);
kafkaStreams = new KafkaStreams(builder.build(), props);
kafkaStreams.setUncaughtExceptionHandler(new StreamExceptionHandler());
Runtime.getRuntime().addShutdownHook(new Thread(kafkaStreams::close));
kafkaStreams.start();
}
public void stop() {
if (kafkaStreams != null) {
kafkaStreams.close();
}
}
|
public void cleanUp() {
if (kafkaStreams != null) {
kafkaStreams.cleanUp();
}
}
private static Properties getStreamProperties(String bootstrapServer) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "user-country-aggregator" + UUID.randomUUID());
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG,
LogAndContinueExceptionHandler.class);
props.put(StreamsConfig.PROCESSING_EXCEPTION_HANDLER_CLASS_CONFIG,
CustomProcessingExceptionHandler.class);
props.put(StreamsConfig.DEFAULT_PRODUCTION_EXCEPTION_HANDLER_CLASS_CONFIG,
CustomProductionExceptionHandler.class);
return props;
}
}
|
repos\tutorials-master\apache-kafka-4\src\main\java\com\baeldung\kafkastreams\UserStreamService.java
| 1
|
请完成以下Java代码
|
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSpeed() {
return speed;
}
public int increaseSpeed(int increment) {
if (increment > 0) {
this.speed += increment;
} else {
System.out.println("Increment can't be negative.");
}
return this.speed;
}
|
public int decreaseSpeed(int decrement) {
if (decrement > 0 && decrement <= this.speed) {
this.speed -= decrement;
} else {
System.out.println("Decrement can't be negative or greater than current speed.");
}
return this.speed;
}
@Override
public String toString() {
return "Car [type=" + type + ", model=" + model + ", color=" + color + ", speed=" + speed + "]";
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\objects\Car.java
| 1
|
请完成以下Java代码
|
public boolean isReadOnly(ELContext context, Object base, Object property) {
if (base == null) {
String variable = (String) property;
return !getVariableContainer(context).hasVariable(variable);
}
return true;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
if (base == null) {
String variable = (String) property;
VariableContainer variableContainer = getVariableContainer(context);
if (variableContainer.hasVariable(variable)) {
context.setPropertyResolved(true);
if (variableContainer instanceof VariableScope) {
VariableInstance variableInstance = ((VariableScope) variableContainer).getVariableInstance(variable);
if (variableInstance == null || !variableInstance.isReadOnly()) {
variableContainer.setVariable(variable, value);
}
} else {
variableContainer.setVariable(variable, value);
|
}
}
}
}
protected VariableContainer getVariableContainer(ELContext elContext) {
return (VariableContainer) elContext.getContext(VariableContainer.class);
}
@Override
public Class<?> getCommonPropertyType(ELContext arg0, Object arg1) {
return Object.class;
}
@Override
public Class<?> getType(ELContext arg0, Object arg1, Object arg2) {
return Object.class;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\VariableContainerELResolver.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@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);
}
/**
* HU_UnitType AD_Reference_ID=540472
* Reference name: HU_UnitType
*/
public static final int HU_UNITTYPE_AD_Reference_ID=540472;
/** TransportUnit = TU */
public static final String HU_UNITTYPE_TransportUnit = "TU";
/** LoadLogistiqueUnit = LU */
public static final String HU_UNITTYPE_LoadLogistiqueUnit = "LU";
/** VirtualPI = V */
public static final String HU_UNITTYPE_VirtualPI = "V";
@Override
public void setHU_UnitType (final @Nullable java.lang.String HU_UnitType)
{
set_Value (COLUMNNAME_HU_UnitType, HU_UnitType);
}
@Override
|
public java.lang.String getHU_UnitType()
{
return get_ValueAsString(COLUMNNAME_HU_UnitType);
}
@Override
public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID)
{
if (M_HU_PackagingCode_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID);
}
@Override
public int getM_HU_PackagingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID);
}
@Override
public void setPackagingCode (final java.lang.String PackagingCode)
{
set_Value (COLUMNNAME_PackagingCode, PackagingCode);
}
@Override
public java.lang.String getPackagingCode()
{
return get_ValueAsString(COLUMNNAME_PackagingCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackagingCode.java
| 1
|
请完成以下Java代码
|
public void setAD_Form_ID(int aD_Form_ID)
{
AD_Form_ID = aD_Form_ID;
}
public int getAD_Workflow_ID()
{
return AD_Workflow_ID;
}
public void setAD_Workflow_ID(int aD_Workflow_ID)
{
AD_Workflow_ID = aD_Workflow_ID;
}
public int getAD_Task_ID()
{
return AD_Task_ID;
}
public void setAD_Task_ID(int aD_Task_ID)
{
AD_Task_ID = aD_Task_ID;
}
public int getWEBUI_Board_ID()
{
return WEBUI_Board_ID;
}
public void setWEBUI_Board_ID(final int WEBUI_Board_ID)
{
this.WEBUI_Board_ID = WEBUI_Board_ID;
}
public void setIsCreateNewRecord(final boolean isCreateNewRecord)
{
this.isCreateNewRecord = isCreateNewRecord;
}
public boolean isCreateNewRecord()
{
return isCreateNewRecord;
}
public void setWEBUI_NameBrowse(final String webuiNameBrowse)
{
this.webuiNameBrowse = webuiNameBrowse;
}
public String getWEBUI_NameBrowse()
{
return webuiNameBrowse;
}
public void setWEBUI_NameNew(final String webuiNameNew)
{
this.webuiNameNew = webuiNameNew;
}
public String getWEBUI_NameNew()
|
{
return webuiNameNew;
}
public void setWEBUI_NameNewBreadcrumb(final String webuiNameNewBreadcrumb)
{
this.webuiNameNewBreadcrumb = webuiNameNewBreadcrumb;
}
public String getWEBUI_NameNewBreadcrumb()
{
return webuiNameNewBreadcrumb;
}
/**
* @param mainTableName table name of main tab or null
*/
public void setMainTableName(String mainTableName)
{
this.mainTableName = mainTableName;
}
/**
* @return table name of main tab or null
*/
public String getMainTableName()
{
return mainTableName;
}
} // MTreeNode
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTreeNode.java
| 1
|
请完成以下Java代码
|
public class CsvReaderExamples {
public static List<String[]> readAllLines(Path filePath) throws Exception {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
try (Reader reader = Files.newBufferedReader(filePath)) {
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser);
try (CSVReader csvReader = csvReaderBuilder.build()) {
return csvReader.readAll();
}
}
}
public static List<String[]> readLineByLine(Path filePath) throws Exception {
List<String[]> list = new ArrayList<>();
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
|
.build();
try (Reader reader = Files.newBufferedReader(filePath)) {
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser);
try (CSVReader csvReader = csvReaderBuilder.build()) {
String[] line;
while ((line = csvReader.readNext()) != null) {
list.add(line);
}
}
}
return list;
}
}
|
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\examples\sync\CsvReaderExamples.java
| 1
|
请完成以下Java代码
|
public void rateLimit() {
}
@Around("rateLimit()")
public Object pointcut(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
// 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
if (rateLimiter != null) {
String key = rateLimiter.key();
// 默认用类名+方法名做限流的 key 前缀
if (StrUtil.isBlank(key)) {
key = method.getDeclaringClass().getName() + StrUtil.DOT + method.getName();
}
// 最终限流的 key 为 前缀 + IP地址
// TODO: 此时需要考虑局域网多用户访问的情况,因此 key 后续需要加上方法参数更加合理
key = key + SEPARATOR + IpUtil.getIpAddr();
long max = rateLimiter.max();
long timeout = rateLimiter.timeout();
TimeUnit timeUnit = rateLimiter.timeUnit();
boolean limited = shouldLimited(key, max, timeout, timeUnit);
if (limited) {
throw new RuntimeException("手速太快了,慢点儿吧~");
}
}
return point.proceed();
|
}
private boolean shouldLimited(String key, long max, long timeout, TimeUnit timeUnit) {
// 最终的 key 格式为:
// limit:自定义key:IP
// limit:类名.方法名:IP
key = REDIS_LIMIT_KEY_PREFIX + key;
// 统一使用单位毫秒
long ttl = timeUnit.toMillis(timeout);
// 当前时间毫秒数
long now = Instant.now().toEpochMilli();
long expired = now - ttl;
// 注意这里必须转为 String,否则会报错 java.lang.Long cannot be cast to java.lang.String
Long executeTimes = stringRedisTemplate.execute(limitRedisScript, Collections.singletonList(key), now + "", ttl + "", expired + "", max + "");
if (executeTimes != null) {
if (executeTimes == 0) {
log.error("【{}】在单位时间 {} 毫秒内已达到访问上限,当前接口上限 {}", key, ttl, max);
return true;
} else {
log.info("【{}】在单位时间 {} 毫秒内访问 {} 次", key, ttl, executeTimes);
return false;
}
}
return false;
}
}
|
repos\spring-boot-demo-master\demo-ratelimit-redis\src\main\java\com\xkcoding\ratelimit\redis\aspect\RateLimiterAspect.java
| 1
|
请完成以下Java代码
|
public I_M_Product getM_Product()
{
return qtyReportEvent.getM_Product();
}
@Override
public int getProductId()
{
return qtyReportEvent.getM_Product_ID();
}
@Override
public I_C_UOM getC_UOM()
{
return qtyReportEvent.getC_UOM();
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
return qtyReportEvent.getC_Flatrate_Term();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return InterfaceWrapperHelper.create(qtyReportEvent.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class);
}
@Override
public Object getWrappedModel()
{
return qtyReportEvent;
}
@Override
public Timestamp getDate()
{
return qtyReportEvent.getDatePromised();
}
@Override
public BigDecimal getQty()
{
|
return qtyReportEvent.getQtyPromised();
}
@Override
public void setM_PricingSystem_ID(final int M_PricingSystem_ID)
{
qtyReportEvent.setM_PricingSystem_ID(M_PricingSystem_ID);
}
@Override
public void setM_PriceList_ID(final int M_PriceList_ID)
{
qtyReportEvent.setM_PriceList_ID(M_PriceList_ID);
}
@Override
public void setCurrencyId(final CurrencyId currencyId)
{
qtyReportEvent.setC_Currency_ID(CurrencyId.toRepoId(currencyId));
}
@Override
public void setPrice(final BigDecimal price)
{
qtyReportEvent.setPrice(price);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMPricingAware_QtyReportEvent.java
| 1
|
请完成以下Java代码
|
public ModelQuery modelTenantId(String tenantId) {
if (tenantId == null) {
throw new ActivitiIllegalArgumentException("Model tenant id is null");
}
this.tenantId = tenantId;
return this;
}
@Override
public ModelQuery modelTenantIdLike(String tenantIdLike) {
if (tenantIdLike == null) {
throw new ActivitiIllegalArgumentException("Model tenant id is null");
}
this.tenantIdLike = tenantIdLike;
return this;
}
@Override
public ModelQuery modelWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
// sorting ////////////////////////////////////////////
@Override
public ModelQuery orderByModelCategory() {
return orderBy(ModelQueryProperty.MODEL_CATEGORY);
}
@Override
public ModelQuery orderByModelId() {
return orderBy(ModelQueryProperty.MODEL_ID);
}
@Override
public ModelQuery orderByModelKey() {
return orderBy(ModelQueryProperty.MODEL_KEY);
}
@Override
public ModelQuery orderByModelVersion() {
return orderBy(ModelQueryProperty.MODEL_VERSION);
}
@Override
public ModelQuery orderByModelName() {
return orderBy(ModelQueryProperty.MODEL_NAME);
}
@Override
public ModelQuery orderByCreateTime() {
return orderBy(ModelQueryProperty.MODEL_CREATE_TIME);
}
@Override
public ModelQuery orderByLastUpdateTime() {
return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME);
}
@Override
public ModelQuery orderByTenantId() {
return orderBy(ModelQueryProperty.MODEL_TENANT_ID);
}
// results ////////////////////////////////////////////
|
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getModelEntityManager()
.findModelCountByQueryCriteria(this);
}
@Override
public List<Model> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getModelEntityManager()
.findModelsByQueryCriteria(this, page);
}
// getters ////////////////////////////////////////////
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public Integer getVersion() {
return version;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DemoServiceImpl implements DemoService {
@Autowired
private PmsBrandMapper brandMapper;
@Override
public List<PmsBrand> listAllBrand() {
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public int createBrand(PmsBrandDto pmsBrandDto) {
PmsBrand pmsBrand = new PmsBrand();
BeanUtils.copyProperties(pmsBrandDto,pmsBrand);
return brandMapper.insertSelective(pmsBrand);
}
@Override
public int updateBrand(Long id, PmsBrandDto pmsBrandDto) {
PmsBrand pmsBrand = new PmsBrand();
BeanUtils.copyProperties(pmsBrandDto,pmsBrand);
|
pmsBrand.setId(id);
return brandMapper.updateByPrimaryKeySelective(pmsBrand);
}
@Override
public int deleteBrand(Long id) {
return brandMapper.deleteByPrimaryKey(id);
}
@Override
public List<PmsBrand> listBrand(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public PmsBrand getBrand(Long id) {
return brandMapper.selectByPrimaryKey(id);
}
}
|
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\service\impl\DemoServiceImpl.java
| 2
|
请完成以下Java代码
|
public class WorkplaceQRCodeJsonConverter
{
public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("WORKPLACE");
public static String toGlobalQRCodeJsonString(final WorkplaceQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final WorkplaceQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
public static WorkplaceQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static WorkplaceQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!isTypeMatching(globalQRCode))
{
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);
}
}
public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode)
{
return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\qrcode\WorkplaceQRCodeJsonConverter.java
| 1
|
请完成以下Java代码
|
public class CandidateUsersPayload implements Payload {
private String id;
private String taskId;
private List<String> candidateUsers;
public CandidateUsersPayload() {
this.id = UUID.randomUUID().toString();
}
public CandidateUsersPayload(String taskId, List<String> candidateUsers) {
this();
this.setTaskId(taskId);
this.candidateUsers = candidateUsers;
}
@Override
public String getId() {
return id;
}
|
public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
}
|
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\CandidateUsersPayload.java
| 1
|
请完成以下Java代码
|
public void setSortNo (int SortNo)
{
set_Value (COLUMNNAME_SortNo, Integer.valueOf(SortNo));
}
/** Get Record Sort No.
@return Determines in what order the records are displayed
*/
public int getSortNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SortNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set X Position.
@param XPosition
Absolute X (horizontal) position in 1/72 of an inch
*/
public void setXPosition (int XPosition)
{
set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition));
}
/** Get X Position.
@return Absolute X (horizontal) position in 1/72 of an inch
*/
public int getXPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_XPosition);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set X Space.
@param XSpace
Relative X (horizontal) space in 1/72 of an inch
*/
public void setXSpace (int XSpace)
{
set_Value (COLUMNNAME_XSpace, Integer.valueOf(XSpace));
}
/** Get X Space.
@return Relative X (horizontal) space in 1/72 of an inch
*/
public int getXSpace ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_XSpace);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Y Position.
@param YPosition
Absolute Y (vertical) position in 1/72 of an inch
*/
public void setYPosition (int YPosition)
{
set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition));
}
/** Get Y Position.
@return Absolute Y (vertical) position in 1/72 of an inch
*/
public int getYPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_YPosition);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Y Space.
@param YSpace
Relative Y (vertical) space in 1/72 of an inch
*/
public void setYSpace (int YSpace)
{
set_Value (COLUMNNAME_YSpace, Integer.valueOf(YSpace));
}
/** Get Y Space.
@return Relative Y (vertical) space in 1/72 of an inch
*/
public int getYSpace ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_YSpace);
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_AD_PrintFormatItem.java
| 1
|
请完成以下Java代码
|
public QueueableForwardingEventBus queueEventsUntilCurrentTrxCommit()
{
return queueEventsUntilTrxCommit(ITrx.TRXNAME_ThreadInherited);
}
private final void clearQueuedEvents()
{
queuedEvents.clear();
}
private final List<Event> getQueuedEventsAndClear()
{
if (queuedEvents.isEmpty())
{
return Collections.emptyList();
}
final List<Event> copy = new ArrayList<>(queuedEvents);
queuedEvents.clear();
return copy;
}
/**
* Post all queued events.
|
*/
public final void flush()
{
final List<Event> queuedEventsList = getQueuedEventsAndClear();
logger.debug("flush - posting {} queued events to event bus; this={}", queuedEventsList.size(), this);
for (final Event event : queuedEventsList)
{
super.processEvent(event);
}
}
@Override
public String toString()
{
final Topic topic = getTopic();
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("topicName", topic.getName())
.add("type", topic.getType())
.add("destroyed", isDestroyed() ? Boolean.TRUE : null)
.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\QueueableForwardingEventBus.java
| 1
|
请完成以下Java代码
|
private Set<String> determineFunctionImports(KotlinFunctionDeclaration functionDeclaration) {
Set<String> imports = new LinkedHashSet<>();
imports.add(functionDeclaration.getReturnType());
imports.addAll(appendImports(functionDeclaration.annotations().values(), Annotation::getImports));
for (Parameter parameter : functionDeclaration.getParameters()) {
imports.add(parameter.getType());
imports.addAll(appendImports(parameter.annotations().values(), Annotation::getImports));
}
imports.addAll(functionDeclaration.getCode().getImports());
return imports;
}
private <T> List<String> appendImports(Stream<T> candidates, Function<T, Collection<String>> mapping) {
return candidates.map(mapping).flatMap(Collection::stream).collect(Collectors.toList());
}
private String getUnqualifiedName(String name) {
if (!name.contains(".")) {
return name;
}
return name.substring(name.lastIndexOf(".") + 1);
}
private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) {
if (name == null || !name.contains(".")) {
return false;
}
|
String packageName = name.substring(0, name.lastIndexOf('.'));
return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName);
}
static class KotlinFormattingOptions implements FormattingOptions {
@Override
public String statementSeparator() {
return "";
}
@Override
public CodeBlock arrayOf(CodeBlock... values) {
return CodeBlock.of("[$L]", CodeBlock.join(Arrays.asList(values), ", "));
}
@Override
public CodeBlock classReference(ClassName className) {
return CodeBlock.of("$T::class", className);
}
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinSourceCodeWriter.java
| 1
|
请完成以下Java代码
|
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(name);
if (mandatory)
{
sb.append("!");
}
return sb.toString();
}
@Override
public int hashCode()
{
if (_hashcode == null)
{
_hashcode = new HashcodeBuilder()
.append(name)
.append(index)
.append(mandatory)
.toHashcode();
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final Part other = EqualsBuilder.getOther(this, obj);
if (other == null)
|
{
return false;
}
return new EqualsBuilder()
.append(name, other.name)
.append(index, other.index)
.append(mandatory, other.mandatory)
.isEqual();
}
public String getName()
{
return name;
}
public boolean isMandatory()
{
return mandatory;
}
public int getIndex()
{
return index;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\LocationCaptureSequence.java
| 1
|
请完成以下Java代码
|
public class ResourceDataAccessException extends RuntimeException {
/**
* Constructs a new instance of {@link ResourceDataAccessException} with no {@link String message}
* or known {@link Throwable cause}.
*/
public ResourceDataAccessException() { }
/**
* Constructs a new instance of {@link ResourceDataAccessException} initialized with the given {@link String message}
* to describe the error.
*
* @param message {@link String} describing the {@link RuntimeException}.
*/
public ResourceDataAccessException(String message) {
super(message);
}
/**
* Constructs a new instance of {@link ResourceDataAccessException} initialized with the given {@link Throwable}
* signifying the underlying cause of this {@link RuntimeException}.
|
*
* @param cause {@link Throwable} signifying the underlying cause of this {@link RuntimeException}.
* @see java.lang.Throwable
*/
public ResourceDataAccessException(Throwable cause) {
super(cause);
}
/**
* Constructs a new instance of {@link ResourceDataAccessException} initialized with the given {@link String message}
* describing the error along with a {@link Throwable} signifying the underlying cause of this
* {@link RuntimeException}.
*
* @param message {@link String} describing the {@link RuntimeException}.
* @param cause {@link Throwable} signifying the underlying cause of this {@link RuntimeException}.
* @see java.lang.Throwable
*/
public ResourceDataAccessException(String message, Throwable cause) {
super(message, cause);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\ResourceDataAccessException.java
| 1
|
请完成以下Java代码
|
public BigDecimal getPercentage()
{
return percentage;
}
@Override
public void setPercentage(final BigDecimal percentage)
{
this.percentage = percentage;
}
@Override
public boolean isNegateQtyInReport()
{
return negateQtyInReport;
}
@Override
public void setNegateQtyInReport(final boolean negateQtyInReport)
{
this.negateQtyInReport = negateQtyInReport;
}
@Override
public String getComponentType()
{
return componentType;
}
@Override
public void setComponentType(final String componentType)
{
this.componentType = componentType;
}
@Override
public String getVariantGroup()
{
return variantGroup;
}
@Override
public void setVariantGroup(final String variantGroup)
{
this.variantGroup = variantGroup;
}
@Override
|
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
handlingUnitsInfoProjected = handlingUnitsInfo;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfoProjected()
{
return handlingUnitsInfoProjected;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java
| 1
|
请完成以下Java代码
|
public abstract class DmnElementImpl extends DmnModelElementInstanceImpl implements DmnElement {
protected static Attribute<String> idAttribute;
protected static Attribute<String> labelAttribute;
protected static ChildElement<Description> descriptionChild;
protected static ChildElement<ExtensionElements> extensionElementsChild;
public DmnElementImpl (ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getId() {
return idAttribute.getValue(this);
}
public void setId(String id) {
idAttribute.setValue(this, id);
}
public String getLabel() {
return labelAttribute.getValue(this);
}
public void setLabel(String label) {
labelAttribute.setValue(this, label);
}
public Description getDescription() {
return descriptionChild.getChild(this);
}
public void setDescription(Description description) {
descriptionChild.setChild(this, description);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DmnElement.class, DMN_ELEMENT)
.namespaceUri(LATEST_DMN_NS)
.abstractType();
idAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_ID)
.idAttribute()
.build();
labelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LABEL)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
descriptionChild = sequenceBuilder.element(Description.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DmnElementImpl.java
| 1
|
请完成以下Java代码
|
public String getTypeName() {
if(value != null) {
return value.getType().getName();
}
else {
return null;
}
}
public String getName() {
return name;
}
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
return value;
}
public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
|
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java
| 1
|
请完成以下Java代码
|
public void setC_UOM_ID (int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, Integer.valueOf(C_UOM_ID));
}
/** Get Maßeinheit.
@return Unit of Measure
*/
@Override
public int getC_UOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_UOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rabatt %.
@param Discount
Discount in percent
*/
@Override
public void setDiscount (java.math.BigDecimal Discount)
{
set_ValueNoCheck (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;
}
@Override
public org.compiere.model.I_C_ValidCombination getPr() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Price, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPr(org.compiere.model.I_C_ValidCombination Pr)
{
set_ValueFromPO(COLUMNNAME_Price, org.compiere.model.I_C_ValidCombination.class, Pr);
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (int Price)
{
set_ValueNoCheck (COLUMNNAME_Price, Integer.valueOf(Price));
}
/** Get Preis.
@return Price
*/
@Override
public int getPrice ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Price);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
@Override
public void setUOMSymbol (java.lang.String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
@Override
public java.lang.String getUOMSymbol ()
{
return (java.lang.String)get_Value(COLUMNNAME_UOMSymbol);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty_v.java
| 1
|
请完成以下Java代码
|
public String modelChange(final PO po, final int type)
{
if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE)
{
if (isDocument())
{
if (!acceptDocument(po))
{
return null;
}
if (po.is_ValueChanged(IDocument.COLUMNNAME_DocStatus) && Services.get(IDocumentBL.class).isDocumentReversedOrVoided(po))
{
voidDocOutbound(po);
}
}
if (isJustProcessed(po, type))
{
createDocOutbound(po);
}
}
return null;
}
@Override
public String docValidate(@NonNull final PO po, final int timing)
{
Check.assume(isDocument(), "PO '{}' is a document", po);
if (!acceptDocument(po))
{
return null;
}
if (timing == ModelValidator.TIMING_AFTER_COMPLETE
&& !Services.get(IDocumentBL.class).isReversalDocument(po))
{
createDocOutbound(po);
}
if (timing == ModelValidator.TIMING_AFTER_VOID
|| timing == ModelValidator.TIMING_AFTER_REVERSEACCRUAL
|| timing == ModelValidator.TIMING_AFTER_REVERSECORRECT)
{
voidDocOutbound(po);
}
|
return null;
}
/**
* @return true if the given PO was just processed
*/
private boolean isJustProcessed(final PO po, final int changeType)
{
if (!po.isActive())
{
return false;
}
final boolean isNew = changeType == ModelValidator.TYPE_BEFORE_NEW || changeType == ModelValidator.TYPE_AFTER_NEW;
final int idxProcessed = po.get_ColumnIndex(DocOutboundProducerValidator.COLUMNNAME_Processed);
final boolean processedColumnAvailable = idxProcessed > 0;
final boolean processed = processedColumnAvailable ? po.get_ValueAsBoolean(idxProcessed) : true;
if (processedColumnAvailable)
{
if (isNew)
{
return processed;
}
else if (po.is_ValueChanged(idxProcessed))
{
return processed;
}
else
{
return false;
}
}
else
// Processed column is not available
{
// If is not available, we always consider the record as processed right after it was created
// This condition was introduced because we need to archive/print records which does not have such a column (e.g. letters)
return isNew;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\DocOutboundProducerValidator.java
| 1
|
请完成以下Java代码
|
public String getType() {
return TYPE;
}
@Override
protected void postExecute(CommandContext commandContext) {
LOG.debugJobExecuted(this);
if (repeat != null && !repeat.isEmpty()) {
init(commandContext, false, true);
} else {
delete(true);
}
commandContext.getHistoricJobLogManager().fireJobSuccessfulEvent(this);
}
@Override
public void init(CommandContext commandContext, boolean shouldResetLock, boolean shouldCallDeleteHandler) {
super.init(commandContext, shouldResetLock, shouldCallDeleteHandler);
repeat = null;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[repeat=" + repeat
+ ", id=" + id
+ ", revision=" + revision
|
+ ", duedate=" + duedate
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ ", retries=" + retries
+ ", jobHandlerType=" + jobHandlerType
+ ", jobHandlerConfiguration=" + jobHandlerConfiguration
+ ", exceptionByteArray=" + exceptionByteArray
+ ", exceptionByteArrayId=" + exceptionByteArrayId
+ ", exceptionMessage=" + exceptionMessage
+ ", deploymentId=" + deploymentId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MessageEntity.java
| 1
|
请完成以下Java代码
|
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
|
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeObject(address.getHouseNumber());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
Integer houseNumber = (Integer) ois.readObject();
Address a = new Address();
a.setHouseNumber(houseNumber);
this.setAddress(a);
}
}
|
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\serialization\Employee.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ConfigureNotifyKeyspaceEventsReactiveAction implements ConfigureReactiveRedisAction {
static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events";
@Override
public Mono<Void> configure(ReactiveRedisConnection connection) {
return getNotifyOptions(connection).map((notifyOptions) -> {
String customizedNotifyOptions = notifyOptions;
if (!customizedNotifyOptions.contains("E")) {
customizedNotifyOptions += "E";
}
boolean A = customizedNotifyOptions.contains("A");
if (!(A || customizedNotifyOptions.contains("g"))) {
customizedNotifyOptions += "g";
}
if (!(A || customizedNotifyOptions.contains("x"))) {
customizedNotifyOptions += "x";
}
return Tuples.of(notifyOptions, customizedNotifyOptions);
})
.filter((optionsTuple) -> !optionsTuple.getT1().equals(optionsTuple.getT2()))
|
.flatMap((optionsTuple) -> connection.serverCommands()
.setConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS, optionsTuple.getT2()))
.filter("OK"::equals)
.doFinally((unused) -> connection.close())
.then();
}
private Mono<String> getNotifyOptions(ReactiveRedisConnection connection) {
return connection.serverCommands()
.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)
.filter(Predicate.not(Properties::isEmpty))
.map((config) -> config.getProperty(config.stringPropertyNames().iterator().next()))
.onErrorMap(InvalidDataAccessApiUsageException.class,
(ex) -> new IllegalStateException("Unable to configure Reactive Redis to keyspace notifications",
ex));
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\ConfigureNotifyKeyspaceEventsReactiveAction.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.