instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
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 BigDecimal getPriceLimit()
{
calculatePrice(false);
return round(result.getPriceLimit());
}
/**
* Is Price List enforded?
*
* @return enforce limit
*/
public boolean isEnforcePriceLimit()
{
calculatePrice(false);
return result.getEnforcePriceLimit().isTrue();
} // isEnforcePriceLimit
/**
* Is a DiscountSchema active?
*
* @return active Discount Schema
*/
public boolean isDiscountSchema()
{
return !result.isDisallowDiscount()
&& result.isUsesDiscountSchema();
} // isDiscountSchema
/**
* Is the Price Calculated (i.e. found)?
*
* @return calculated
*/
public boolean isCalculated()
{
return result.isCalculated();
} // isCalculated
/**
* Convenience method to get priceStd with the discount already subtracted. Note that the result matches the former behavior of {@link #getPriceStd()}.
*/
public BigDecimal mkPriceStdMinusDiscount()
{
calculatePrice(false);
return result.getDiscount().subtractFromBase(result.getPriceStd(), result.getPrecision().toInt());
}
@Override
public String toString()
{
return "MProductPricing ["
+ pricingCtx
+ ", " + result
+ "]";
}
public void setConvertPriceToContextUOM(boolean convertPriceToContextUOM)
|
{
pricingCtx.setConvertPriceToContextUOM(convertPriceToContextUOM);
}
public void setReferencedObject(Object referencedObject)
{
pricingCtx.setReferencedObject(referencedObject);
}
// metas: end
public int getC_TaxCategory_ID()
{
return TaxCategoryId.toRepoId(result.getTaxCategoryId());
}
public boolean isManualPrice()
{
return pricingCtx.getManualPriceEnabled().isTrue();
}
public void setManualPrice(boolean manualPrice)
{
pricingCtx.setManualPriceEnabled(manualPrice);
}
public void throwProductNotOnPriceListException()
{
throw new ProductNotOnPriceListException(pricingCtx);
}
} // MProductPrice
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProductPricing.java
| 1
|
请完成以下Java代码
|
private List<Long> generateShotList() {
return Flux.range(1, SHOT_COUNT)
.map(x -> (long) Math.ceil(Math.random() * 1000))
.collectList()
.block();
}
@Override
public void subscribe(Subscriber<? super Payload> subscriber) {
this.subscriber = subscriber;
fireAtWill();
}
/**
* Publish game events asynchronously
*/
private void fireAtWill() {
new Thread(() -> {
for (Long shotDelay : shots) {
try { Thread.sleep(shotDelay); } catch (Exception x) {}
if (truce) {
break;
}
LOG.info("{}: bang!", playerName);
subscriber.onNext(DefaultPayload.create("bang!"));
}
if (!truce) {
LOG.info("{}: I give up!", playerName);
subscriber.onNext(DefaultPayload.create("I give up"));
}
subscriber.onComplete();
}).start();
}
|
/**
* Process events from the opponent
*
* @param payload Payload received from the rSocket
*/
public void processPayload(Payload payload) {
String message = payload.getDataUtf8();
switch (message) {
case "bang!":
String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!";
LOG.info("{}: {}", playerName, result);
break;
case "I give up":
truce = true;
LOG.info("{}: OK, truce", playerName);
break;
}
}
}
|
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\support\GameController.java
| 1
|
请完成以下Java代码
|
protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() {
return Collections.emptyList();
}
// toString /////////////////////////////////////////////////////////////////
public String toString() {
if (isCaseInstanceExecution()) {
return "CaseInstance[" + getToStringIdentity() + "]";
} else {
return "CmmnExecution["+getToStringIdentity() + "]";
}
}
protected String getToStringIdentity() {
return Integer.toString(System.identityHashCode(this));
}
public String getId() {
return String.valueOf(System.identityHashCode(this));
|
}
public ProcessEngineServices getProcessEngineServices() {
throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName());
}
public ProcessEngine getProcessEngine() {
throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName());
}
public CmmnElement getCmmnModelElementInstance() {
throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName());
}
public CmmnModelInstance getCmmnModelInstance() {
throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java
| 1
|
请完成以下Java代码
|
private void reverseAllocations(final List<I_M_ReceiptSchedule_Alloc> lineAllocs, final I_M_InOutLine reversalLine)
{
for (final I_M_ReceiptSchedule_Alloc lineAlloc : lineAllocs)
{
reverseAllocation(lineAlloc, reversalLine);
}
}
private void reverseAllocation(I_M_ReceiptSchedule_Alloc lineAlloc, I_M_InOutLine reversalLine)
{
final I_M_ReceiptSchedule_Alloc reversalLineAlloc = Services.get(IReceiptScheduleBL.class).reverseAllocation(lineAlloc);
reversalLineAlloc.setM_InOutLine(reversalLine);
InterfaceWrapperHelper.save(reversalLineAlloc);
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_VOID })
|
public void deleteReceiptScheduleAllocs(final I_M_InOut receipt)
{
// Only if it's a receipt
if (receipt.isSOTrx())
{
return;
}
Services.get(IReceiptScheduleDAO.class)
.retrieveRsaForInOut(receipt)
.forEach(rsa -> InterfaceWrapperHelper.delete(rsa));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_InOut_Receipt.java
| 1
|
请完成以下Java代码
|
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
|
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock_WarehouseAndProduct_v.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AllocationStrategySupportingServicesFacade
{
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
private final IDeveloperModeBL developerModeBL = Services.get(IDeveloperModeBL.class);
private IHandlingUnitsDAO getHandlingUnitsDAO()
{
// FIXME: find out why if we are using the "handlingUnitsDAO" field, tests are failing
return Services.get(IHandlingUnitsDAO.class);
}
public boolean isDeveloperMode()
{
return developerModeBL.isEnabled();
}
public I_M_HU_PI getVirtualPI(final Properties ctx)
{
return getHandlingUnitsDAO().retrieveVirtualPI(ctx);
}
public I_M_HU_Item getFirstNotPureVirtualItem(@NonNull final I_M_HU_Item item)
{
final IHandlingUnitsDAO handlingUnitsDAO = getHandlingUnitsDAO();
I_M_HU_Item itemFirstNotPureVirtual = item;
while (itemFirstNotPureVirtual != null && handlingUnitsBL.isPureVirtual(itemFirstNotPureVirtual))
{
final I_M_HU parentHU = itemFirstNotPureVirtual.getM_HU();
itemFirstNotPureVirtual = handlingUnitsDAO.retrieveParentItem(parentHU);
}
// shall not happen
if (itemFirstNotPureVirtual == null)
{
throw new AdempiereException("No not pure virtual HU item found for " + item);
}
|
return itemFirstNotPureVirtual;
}
public boolean isVirtual(final I_M_HU_Item item)
{
return handlingUnitsBL.isVirtual(item);
}
public List<I_M_HU_Item> retrieveItems(@NonNull final I_M_HU hu)
{
return getHandlingUnitsDAO().retrieveItems(hu);
}
public HUItemType getItemType(final I_M_HU_Item item)
{
return HUItemType.ofCode(handlingUnitsBL.getItemType(item));
}
public List<I_M_HU> retrieveIncludedHUs(final I_M_HU_Item item)
{
return getHandlingUnitsDAO().retrieveIncludedHUs(item);
}
public I_M_HU_PI getIncluded_HU_PI(@NonNull final I_M_HU_Item item)
{
return handlingUnitsBL.getIncludedPI(item);
}
public void deleteHU(final I_M_HU hu)
{
getHandlingUnitsDAO().delete(hu);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\AllocationStrategySupportingServicesFacade.java
| 2
|
请完成以下Java代码
|
public abstract class PrimitiveValueMapper<T extends PrimitiveValue<?>> extends AbstractTypedValueMapper<T> {
public PrimitiveValueMapper(PrimitiveValueType variableType) {
super(variableType);
}
public T readValue(TypedValueField typedValueField, boolean deserializeObjectValue) {
return readValue(typedValueField);
}
public abstract T readValue(TypedValueField typedValueField);
public PrimitiveValueType getType() {
return (PrimitiveValueType) super.getType();
}
|
protected boolean isAssignable(Object value) {
Class<?> javaType = getType().getJavaType();
return javaType.isAssignableFrom(value.getClass());
}
protected boolean canWriteValue(TypedValue typedValue) {
Object value = typedValue.getValue();
return value == null || isAssignable(value);
}
protected boolean canReadValue(TypedValueField typedValueField) {
Object value = typedValueField.getValue();
return value == null || isAssignable(value);
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\PrimitiveValueMapper.java
| 1
|
请完成以下Java代码
|
public class RemoteMysqlConnection {
private static final String HOST = "HOST";
private static final String USER = "USERNAME";
private static final String PRIVATE_KEY = "PATH_TO_KEY";
private static final int PORT = 22;
private static final String DATABASE_HOST = "DATABASE_HOST";
private static final int DATABASE_PORT = 3306;
private static final String DATABASE_USERNAME = "DATABASE_USERNAME";
private static final String DATABASE_PASSWORD = "DATABASE_PASSWORD";
public static JSch setUpJsch() throws JSchException {
JSch jsch = new JSch();
jsch.addIdentity(PRIVATE_KEY);
return jsch;
}
public static Session createSession(JSch jsch) throws JSchException {
Session session = jsch.getSession(USER, HOST, PORT);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
}
public static int tunnelNetwork(Session session) throws JSchException {
int portForwarding = session.setPortForwardingL(0, DATABASE_HOST, DATABASE_PORT);
return portForwarding;
}
public static Connection databaseConnection(int port) throws SQLException {
String databaseUrl = "jdbc:mysql://" + DATABASE_HOST + ":" + port + "/baeldung";
Connection connection = DriverManager.getConnection(databaseUrl, DATABASE_USERNAME, DATABASE_PASSWORD);
return connection;
}
|
public static void createTable(Connection connection, String tableName) throws SQLException {
String createTableSQL = "CREATE TABLE " + tableName + " (id INT, data VARCHAR(255))";
try (Statement statement = connection.createStatement()) {
statement.execute(createTableSQL);
}
}
public static void insertData(Connection connection, String tableName) throws SQLException {
String insertDataSQL = "INSERT INTO " + tableName + " (id, data) VALUES (1, 'test data')";
try (Statement statement = connection.createStatement()) {
statement.execute(insertDataSQL);
}
}
public static boolean isTableExists(Connection connection, String tableName) throws SQLException {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SHOW TABLES LIKE '" + tableName + "'");
return resultSet.next();
}
}
public static void disconnect(Session session, Connection connection) throws SQLException {
session.disconnect();
connection.close();
}
}
|
repos\tutorials-master\persistence-modules\jdbc-mysql\src\main\java\com\baeldung\connectingtoremotemysqlssh\RemoteMysqlConnection.java
| 1
|
请完成以下Java代码
|
public Object string()
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object number()
{
return DB.getSQLValueBDEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object date()
{
return DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object list()
{
// TODO: resolve the M_AttributeValue
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
});
|
return Optional.of(Null.box(defaultValue));
}
else
{
return Optional.empty();
}
}
catch (Exception ex)
{
logger.warn("Failed generating default value for {}. Returning empty.", attribute, ex);
return Optional.empty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetInstanceBL.java
| 1
|
请完成以下Java代码
|
public class Car implements Cloneable {
private String make;
private int year;
public Car(String make, int year) {
this.make = make;
this.year = year;
}
// Getters for external access (useful for testing)
public String getMake() {
return make;
}
public int getYear() {
return year;
}
/**
* Standard implementation of equals() for value equality.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Car car = (Car) obj;
// Use Objects.equals for safe String comparison
return year == car.year && Objects.equals(make, car.make);
}
/**
* Standard implementation of hashCode() based on make and year.
*/
@Override
public int hashCode() {
return Objects.hash(make, year);
}
/**
* Standard implementation of toString() for debugging and logging.
|
*/
@Override
public String toString() {
return "Car{"
+ "make='" + make + '\''
+ ", year=" + year
+ '}';
}
/**
* Overrides the protected clone() method from Object to perform a shallow copy.
* This is the standard pattern when implementing the Cloneable marker interface.
*/
@Override
public Object clone() throws CloneNotSupportedException {
// Calls Object's native clone() method
return super.clone();
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\objectclassguide\Car.java
| 1
|
请完成以下Java代码
|
private ProcessInstance startProcess() {
ProcessInstance processInstance = processRuntime.start(
ProcessPayloadBuilder.start()
.withProcessDefinitionKey("RankMovieId")
.withName("myProcess")
.withVariable("movieToRank", "Lord of the rings")
.build()
);
logger.info(">>> Created Process Instance: " + processInstance);
return processInstance;
}
private void listAvailableProcesses() {
Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
logger.info("> Available Process definitions: " + processDefinitionPage.getTotalItems());
for (ProcessDefinition pd : processDefinitionPage.getContent()) {
logger.info("\t > Process definition: " + pd);
}
}
@Bean("Movies.getMovieDesc")
public Connector getMovieDesc() {
return getConnector();
}
@Bean("MoviesWithUUIDs.getMovieDesc")
public Connector getMovieDescUUIDs() {
return getConnector();
}
|
private Connector getConnector() {
return integrationContext -> {
Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
logger.info(">>inbound: " + inBoundVariables);
integrationContext.addOutBoundVariable(
"movieDescription",
"The Lord of the Rings is an epic high fantasy novel written by English author and scholar J. R. R. Tolkien"
);
return integrationContext;
};
}
@Bean
public VariableEventListener<VariableCreatedEvent> variableCreatedEventListener() {
return variableCreatedEvent -> variableCreatedEvents.add(variableCreatedEvent);
}
@Bean
public ProcessRuntimeEventListener<ProcessCompletedEvent> processCompletedEventListener() {
return processCompletedEvent -> processCompletedEvents.add(processCompletedEvent);
}
}
|
repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\DemoApplication.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InsuranceContractSalesContracts name(String name) {
this.name = name;
return this;
}
/**
* ERP-Vertragsnr.
* @return name
**/
@Schema(example = "34251532", description = "ERP-Vertragsnr.")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InsuranceContractSalesContracts careType(BigDecimal careType) {
this.careType = careType;
return this;
}
/**
* Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)
* @return careType
**/
@Schema(example = "1", description = "Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)")
public BigDecimal getCareType() {
return careType;
}
public void setCareType(BigDecimal careType) {
this.careType = careType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractSalesContracts insuranceContractSalesContracts = (InsuranceContractSalesContracts) o;
return Objects.equals(this.name, insuranceContractSalesContracts.name) &&
|
Objects.equals(this.careType, insuranceContractSalesContracts.careType);
}
@Override
public int hashCode() {
return Objects.hash(name, careType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractSalesContracts {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" careType: ").append(toIndentedString(careType)).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(java.lang.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\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractSalesContracts.java
| 2
|
请完成以下Java代码
|
public void setSurchargeAmt (final BigDecimal SurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_SurchargeAmt, SurchargeAmt);
}
@Override
public BigDecimal getSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmt (final @Nullable BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmtWithSurchargeAmt (final BigDecimal TaxAmtWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtWithSurchargeAmt, TaxAmtWithSurchargeAmt);
}
@Override
public BigDecimal getTaxAmtWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmt (final @Nullable BigDecimal TaxBaseAmt)
{
set_Value (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
@Override
public BigDecimal getTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setTaxBaseAmtWithSurchargeAmt (final BigDecimal TaxBaseAmtWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmtWithSurchargeAmt, TaxBaseAmtWithSurchargeAmt);
}
@Override
public BigDecimal getTaxBaseAmtWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmtWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalAmt (final @Nullable BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
@Override
public BigDecimal getTotalAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_901_991_v.java
| 1
|
请完成以下Java代码
|
private boolean contains(Status status) {
return this.order.contains(getUniformCode(status.getCode()));
}
private static List<String> getUniformCodes(Stream<String> codes) {
return codes.map(SimpleStatusAggregator::getUniformCode).toList();
}
@Contract("!null -> !null")
private static @Nullable String getUniformCode(@Nullable String code) {
if (code == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
builder.append(Character.toLowerCase(ch));
}
}
return builder.toString();
|
}
/**
* {@link Comparator} used to order {@link Status}.
*/
private final class StatusComparator implements Comparator<Status> {
@Override
public int compare(Status s1, Status s2) {
List<String> order = SimpleStatusAggregator.this.order;
int i1 = order.indexOf(getUniformCode(s1.getCode()));
int i2 = order.indexOf(getUniformCode(s2.getCode()));
return (i1 < i2) ? -1 : (i1 != i2) ? 1 : s1.getCode().compareTo(s2.getCode());
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\SimpleStatusAggregator.java
| 1
|
请完成以下Java代码
|
public List<IOParameter> getOutParameters() {
return outParameters;
}
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public boolean isInheritBusinessKey() {
return inheritBusinessKey;
}
public void setInheritBusinessKey(boolean inheritBusinessKey) {
this.inheritBusinessKey = inheritBusinessKey;
}
public CallActivity clone() {
CallActivity clone = new CallActivity();
clone.setValues(this);
return clone;
}
public void setValues(CallActivity otherElement) {
|
super.setValues(otherElement);
setCalledElement(otherElement.getCalledElement());
setBusinessKey(otherElement.getBusinessKey());
setInheritBusinessKey(otherElement.isInheritBusinessKey());
inParameters = new ArrayList<IOParameter>();
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<IOParameter>();
if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\CallActivity.java
| 1
|
请完成以下Java代码
|
public void setValueMax (final @Nullable java.lang.String ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
@Override
public java.lang.String getValueMax()
{
return get_ValueAsString(COLUMNNAME_ValueMax);
}
@Override
public void setValueMin (final @Nullable java.lang.String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public java.lang.String getValueMin()
{
return get_ValueAsString(COLUMNNAME_ValueMin);
}
@Override
public void setVersion (final BigDecimal Version)
|
{
set_Value (COLUMNNAME_Version, Version);
}
@Override
public BigDecimal getVersion()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Version);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVFormat (final @Nullable java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
@Override
public java.lang.String getVFormat()
{
return get_ValueAsString(COLUMNNAME_VFormat);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class AdviseRegionOnPdxReadSerializedCondition { }
}
static class PdxReadSerializedCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return isPdxReadSerializedEnabled(context.getEnvironment()) || isCachePdxReadSerializedEnabled();
}
private boolean isCachePdxReadSerializedEnabled() {
return SimpleCacheResolver.getInstance().resolve()
.filter(GemFireCache::getPdxReadSerialized)
.isPresent();
}
private boolean isPdxReadSerializedEnabled(@NonNull Environment environment) {
return Optional.ofNullable(environment)
.filter(env -> env.getProperty(PDX_READ_SERIALIZED_PROPERTY, Boolean.class, false))
.isPresent();
}
}
private static final boolean DEFAULT_EXPORT_ENABLED = false;
private static final Predicate<Environment> disableGemFireShutdownHookPredicate = environment ->
Optional.ofNullable(environment)
.filter(env -> env.getProperty(CacheDataImporterExporterReference.EXPORT_ENABLED_PROPERTY_NAME,
Boolean.class, DEFAULT_EXPORT_ENABLED))
.isPresent();
static abstract class AbstractDisableGemFireShutdownHookSupport {
boolean shouldDisableGemFireShutdownHook(@Nullable Environment environment) {
return disableGemFireShutdownHookPredicate.test(environment);
}
/**
* If we do not disable Apache Geode's {@link org.apache.geode.distributed.DistributedSystem} JRE/JVM runtime
* shutdown hook then the {@link org.apache.geode.cache.Region} is prematurely closed by the JRE/JVM shutdown hook
* before Spring's {@link org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor}s can do
* their work of exporting data from the {@link org.apache.geode.cache.Region} as JSON.
*/
void disableGemFireShutdownHook(@Nullable Environment environment) {
System.setProperty(GEMFIRE_DISABLE_SHUTDOWN_HOOK, Boolean.TRUE.toString());
}
}
static abstract class CacheDataImporterExporterReference extends AbstractCacheDataImporterExporter {
static final String EXPORT_ENABLED_PROPERTY_NAME =
|
AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME;
}
static class DisableGemFireShutdownHookCondition extends AbstractDisableGemFireShutdownHookSupport
implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return shouldDisableGemFireShutdownHook(context.getEnvironment());
}
}
public static class DisableGemFireShutdownHookEnvironmentPostProcessor
extends AbstractDisableGemFireShutdownHookSupport implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (shouldDisableGemFireShutdownHook(environment)) {
disableGemFireShutdownHook(environment);
}
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\DataImportExportAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public AttributeBuilder<T> namespace(String namespaceUri) {
attribute.setNamespaceUri(namespaceUri);
return this;
}
public AttributeBuilder<T> idAttribute() {
attribute.setId();
return this;
}
public AttributeBuilder<T> defaultValue(T defaultValue) {
attribute.setDefaultValue(defaultValue);
return this;
}
|
public AttributeBuilder<T> required() {
attribute.setRequired(true);
return this;
}
public Attribute<T> build() {
modelType.registerAttribute(attribute);
return attribute;
}
public void performModelBuild(Model model) {
// do nothing
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\AttributeBuilderImpl.java
| 1
|
请完成以下Java代码
|
public List<UserExpense> getExpenses() {
return expenses;
}
public void setExpenses(List<UserExpense> expenses) {
this.expenses = expenses;
}
public UUID getId() {
return id;
}
public void setId(final UUID id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(final Integer version) {
this.version = version;
}
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public Boolean getActive() {
return active;
}
public void setActive(final Boolean active) {
this.active = active;
}
public void setPassword(final String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
|
return authorities != null ? authorities : Collections.emptyList();
}
@Override
public void setAuthorities(final Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return Boolean.TRUE.equals(active);
}
@InstanceName
@DependsOnProperties({"firstName", "lastName", "username"})
public String getDisplayName() {
return String.format("%s %s [%s]", (firstName != null ? firstName : ""),
(lastName != null ? lastName : ""), username).trim();
}
@Override
public String getTimeZoneId() {
return timeZoneId;
}
public void setTimeZoneId(final String timeZoneId) {
this.timeZoneId = timeZoneId;
}
}
|
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalSystemOtherConfigId implements IExternalSystemChildConfigId
{
@NonNull
ExternalSystemParentConfigId externalSystemParentConfigId;
public static ExternalSystemOtherConfigId cast(@NonNull final IExternalSystemChildConfigId id)
{
return (ExternalSystemOtherConfigId)id;
}
@NonNull
public static ExternalSystemOtherConfigId ofExternalSystemParentConfigId(@NonNull final ExternalSystemParentConfigId externalSystemParentConfigId)
{
return new ExternalSystemOtherConfigId(externalSystemParentConfigId);
}
@NonNull
|
public ExternalSystemParentConfigId getParentConfigId()
{
return externalSystemParentConfigId;
}
@Override
public ExternalSystemType getType()
{
return ExternalSystemType.Other;
}
@Override
public int getRepoId()
{
return externalSystemParentConfigId.getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\other\ExternalSystemOtherConfigId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class RabbitStreamTemplateConfigurer {
private @Nullable MessageConverter messageConverter;
private @Nullable StreamMessageConverter streamMessageConverter;
private @Nullable ProducerCustomizer producerCustomizer;
/**
* Set the {@link MessageConverter} to use or {@code null} if the out-of-the-box
* converter should be used.
* @param messageConverter the {@link MessageConverter}
*/
public void setMessageConverter(@Nullable MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
/**
* Set the {@link StreamMessageConverter} to use or {@code null} if the out-of-the-box
* stream message converter should be used.
* @param streamMessageConverter the {@link StreamMessageConverter}
*/
public void setStreamMessageConverter(@Nullable StreamMessageConverter streamMessageConverter) {
this.streamMessageConverter = streamMessageConverter;
}
/**
* Set the {@link ProducerCustomizer} instances to use.
* @param producerCustomizer the producer customizer
*/
public void setProducerCustomizer(@Nullable ProducerCustomizer producerCustomizer) {
this.producerCustomizer = producerCustomizer;
}
/**
* Configure the specified {@link RabbitStreamTemplate}. The template can be further
|
* tuned and default settings can be overridden.
* @param template the {@link RabbitStreamTemplate} instance to configure
*/
public void configure(RabbitStreamTemplate template) {
if (this.messageConverter != null) {
template.setMessageConverter(this.messageConverter);
}
if (this.streamMessageConverter != null) {
template.setStreamConverter(this.streamMessageConverter);
}
if (this.producerCustomizer != null) {
template.setProducerCustomizer(this.producerCustomizer);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitStreamTemplateConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ApiAuditController
{
@NonNull private final ApiAuditService apiAuditService;
@ApiOperation("Retrieve and mimic the original API response by request audit ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved and mimicked original response"),
@ApiResponse(code = 404, message = "API request audit record not found"),
@ApiResponse(code = 500, message = "Internal server error while processing the response")
})
@GetMapping("/requests/{requestId}/response")
public ResponseEntity<Object> mimicOriginalResponse(
@ApiParam(required = true, value = "The API request audit ID to mimic response for")
@PathVariable("requestId")
@NonNull final String requestId)
{
try
{
final ApiResponseAudit apiResponse = apiAuditService
.getLatestByRequestId(ApiRequestAuditId.ofRepoId(Integer.parseInt(requestId)))
.orElse(null);
if (apiResponse == null)
{
return ResponseEntity.notFound().build();
}
final HttpStatus httpStatus = parseHttpStatus(apiResponse.getHttpCode());
final HttpHeaders headers = reconstructHeaders(apiResponse.getHttpHeaders());
return new ResponseEntity<>(apiResponse.getBody(), headers, httpStatus);
}
catch (final Exception e)
{
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error while mimicking original response: " + e.getMessage());
}
}
@NonNull
private HttpStatus parseHttpStatus(@Nullable final String httpCode)
{
try
{
|
if (Check.isBlank(httpCode))
{
throw new AdempiereException("HTTP Code is blank")
.appendParametersToMessage()
.setParameter("HttpCode", httpCode);
}
final int statusCode = Integer.parseInt(httpCode.trim());
return HttpStatus.valueOf(statusCode);
}
catch (final Exception e)
{
throw new AdempiereException("Error while parsing HTTP Code", e)
.appendParametersToMessage()
.setParameter("HttpCode", httpCode);
}
}
@NonNull
private HttpHeaders reconstructHeaders(@Nullable final String httpHeadersJson)
{
final HttpHeaders headers = new HttpHeaders();
if (Check.isNotBlank(httpHeadersJson))
{
final HttpHeadersWrapper headersWrapper = HttpHeadersWrapper
.fromJson(httpHeadersJson, JsonObjectMapperHolder.sharedJsonObjectMapper());
headersWrapper.streamHeaders()
.forEach(entry -> headers.add(entry.getKey(), entry.getValue()));
}
return headers;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\audit\ApiAuditController.java
| 2
|
请完成以下Java代码
|
public Relationship newInstance(ModelTypeInstanceContext instanceContext) {
return new RelationshipImpl(instanceContext);
}
});
typeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TYPE)
.required()
.build();
directionAttribute = typeBuilder.enumAttribute(BPMN_ATTRIBUTE_DIRECTION, RelationshipDirection.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
sourceCollection = sequenceBuilder.elementCollection(Source.class)
.minOccurs(1)
.build();
targetCollection = sequenceBuilder.elementCollection(Target.class)
.minOccurs(1)
.build();
typeBuilder.build();
}
public RelationshipImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
|
public String getType() {
return typeAttribute.getValue(this);
}
public void setType(String type) {
typeAttribute.setValue(this, type);
}
public RelationshipDirection getDirection() {
return directionAttribute.getValue(this);
}
public void setDirection(RelationshipDirection direction) {
directionAttribute.setValue(this, direction);
}
public Collection<Source> getSources() {
return sourceCollection.get(this);
}
public Collection<Target> getTargets() {
return targetCollection.get(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\RelationshipImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String create(String email, String name) {
User user = null;
try {
user = new User(email, name);
userDao.save(user);
}
catch (Exception ex) {
return "Error creating the user: " + ex.toString();
}
return "User succesfully created! (id = " + user.getId() + ")";
}
/**
* /delete --> Delete the user having the passed id.
*
* @param id The id of the user to delete
* @return A string describing if the user is successfully deleted or not.
*/
@RequestMapping("/delete")
@ResponseBody
public String delete(long id) {
try {
User user = new User(id);
userDao.delete(user);
}
catch (Exception ex) {
return "Error deleting the user: " + ex.toString();
}
return "User successfully deleted!";
}
/**
* /get-by-email --> Return the id for the user having the passed email.
*
* @param email The email to search in the database.
* @return The user id or a message error if the user is not found.
*/
@RequestMapping("/get-by-email")
@ResponseBody
public String getByEmail(String email) {
String userId;
try {
User user = userDao.findByEmail(email);
userId = String.valueOf(user.getId());
}
catch (Exception ex) {
return "User not found";
}
return "The user id is: " + userId;
}
|
/**
* /update --> Update the email and the name for the user in the database
* having the passed id.
*
* @param id The id for the user to update.
* @param email The new email.
* @param name The new name.
* @return A string describing if the user is successfully updated or not.
*/
@RequestMapping("/update")
@ResponseBody
public String updateUser(long id, String email, String name) {
try {
User user = userDao.findOne(id);
user.setEmail(email);
user.setName(name);
userDao.save(user);
}
catch (Exception ex) {
return "Error updating the user: " + ex.toString();
}
return "User successfully updated!";
}
// ------------------------
// PRIVATE FIELDS
// ------------------------
@Autowired
private UserDao userDao;
} // class UserController
|
repos\spring-boot-samples-master\spring-boot-mysql-springdatajpa-hibernate\src\main\java\netgloo\controllers\UserController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class OnlineController {
private final OnlineUserService onlineUserService;
@ApiOperation("查询在线用户")
@GetMapping
@PreAuthorize("@el.check()")
public ResponseEntity<PageResult<OnlineUserDto>> queryOnlineUser(String username, Pageable pageable){
return new ResponseEntity<>(onlineUserService.getAll(username, pageable),HttpStatus.OK);
}
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check()")
public void exportOnlineUser(HttpServletResponse response, String username) throws IOException {
|
onlineUserService.download(onlineUserService.getAll(username), response);
}
@ApiOperation("踢出用户")
@DeleteMapping
@PreAuthorize("@el.check()")
public ResponseEntity<Object> deleteOnlineUser(@RequestBody Set<String> keys) throws Exception {
for (String token : keys) {
// 解密Key
token = EncryptUtils.desDecrypt(token);
onlineUserService.logout(token);
}
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\rest\OnlineController.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public Quote symbol(String symbol) {
this.symbol = symbol;
return this;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public BigDecimal getPrice() {
return price;
}
public Quote price(BigDecimal price) {
this.price = price;
return this;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public ZonedDateTime getLastTrade() {
return lastTrade;
}
public Quote lastTrade(ZonedDateTime lastTrade) {
|
this.lastTrade = lastTrade;
return this;
}
public void setLastTrade(ZonedDateTime lastTrade) {
this.lastTrade = lastTrade;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Quote quote = (Quote) o;
if (quote.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), quote.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Quote{" +
"id=" + getId() +
", symbol='" + getSymbol() + "'" +
", price=" + getPrice() +
", lastTrade='" + getLastTrade() + "'" +
"}";
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\domain\Quote.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns())) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
source.registerCorsConfiguration("/swagger-ui/**", config);
source.registerCorsConfiguration("/*/api/**", config);
source.registerCorsConfiguration("/services/*/api/**", config);
source.registerCorsConfiguration("/*/management/**", config);
}
return source;
}
// TODO: remove when this is supported in spring-boot
@Bean
HandlerMethodArgumentResolver reactivePageableHandlerMethodArgumentResolver() {
return new ReactivePageableHandlerMethodArgumentResolver();
}
// TODO: remove when this is supported in spring-boot
@Bean
HandlerMethodArgumentResolver reactiveSortHandlerMethodArgumentResolver() {
return new ReactiveSortHandlerMethodArgumentResolver();
}
|
@Bean
@Order(-2) // The handler must have precedence over WebFluxResponseStatusExceptionHandler and Spring Boot's ErrorWebExceptionHandler
public WebExceptionHandler problemExceptionHandler(ObjectMapper mapper, ExceptionTranslator problemHandling) {
return new ReactiveWebExceptionHandler(problemHandling, mapper);
}
@Bean
ResourceHandlerRegistrationCustomizer registrationCustomizer() {
// Disable built-in cache control to use our custom filter instead
return registration -> registration.setCacheControl(null);
}
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_PRODUCTION)
public CachingHttpHeadersFilter cachingHttpHeadersFilter() {
// Use a cache filter that only match selected paths
return new CachingHttpHeadersFilter(TimeUnit.DAYS.toMillis(jHipsterProperties.getHttp().getCache().getTimeToLiveInDays()));
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\WebConfigurer.java
| 2
|
请完成以下Java代码
|
public int getC_Country_ID() {
return C_Country_ID;
}
public void setC_Country_ID(int cCountryID) {
C_Country_ID = cCountryID;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCity_7bitlc() {
return city_7bitlc;
}
public void setCity_7bitlc(String city_7bitlc) {
this.city_7bitlc = city_7bitlc;
}
public String getStringRepresentation() {
return stringRepresentation;
}
|
public void setStringRepresentation(String stringRepresentation) {
this.stringRepresentation = stringRepresentation;
}
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof GeodbObject))
return false;
if (this == obj)
return true;
//
GeodbObject go = (GeodbObject)obj;
return this.geodb_loc_id == go.geodb_loc_id
&& this.zip.equals(go.zip)
;
}
@Override
public String toString()
{
String str = getStringRepresentation();
if (str != null)
return str;
return city+", "+zip+" - "+countryName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\search\GeodbObject.java
| 1
|
请完成以下Java代码
|
public Map<String, Object> getUser(@Nullable Principal principal) {
if (principal != null) {
return singletonMap("name", principal.getName());
}
return emptyMap();
}
@GetMapping(path = "/", produces = MediaType.TEXT_HTML_VALUE)
@RegisterReflectionForBinding(String.class)
public String index() {
return "index";
}
@GetMapping(path = "/sba-settings.js", produces = "application/javascript")
public String sbaSettings() {
return "sba-settings.js";
}
@GetMapping(path = "/variables.css", produces = "text/css")
public String variablesCss() {
return "variables.css";
}
@GetMapping(path = "/login", produces = MediaType.TEXT_HTML_VALUE)
public String login() {
return "login";
}
@lombok.Data
@lombok.Builder
public static class Settings {
private final String title;
private final String brand;
private final String loginIcon;
private final String favicon;
private final String faviconDanger;
private final PollTimer pollTimer;
private final UiTheme theme;
private final boolean notificationFilterEnabled;
private final boolean rememberMeEnabled;
private final List<String> availableLanguages;
private final List<String> routes;
private final List<ExternalView> externalViews;
private final List<ViewSettings> viewSettings;
private final Boolean enableToasts;
private final Boolean hideInstanceUrl;
private final Boolean disableInstanceUrl;
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ExternalView {
/**
* Label to be shown in the navbar.
*/
private final String label;
/**
* Url for the external view to be linked
*/
private final String url;
/**
|
* Order in the navbar.
*/
private final Integer order;
/**
* Should the page shown as an iframe or open in a new window.
*/
private final boolean iframe;
/**
* A list of child views.
*/
private final List<ExternalView> children;
public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) {
Assert.hasText(label, "'label' must not be empty");
if (isEmpty(children)) {
Assert.hasText(url, "'url' must not be empty");
}
this.label = label;
this.url = url;
this.order = order;
this.iframe = iframe;
this.children = children;
}
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ViewSettings {
/**
* Name of the view to address.
*/
private final String name;
/**
* Set view enabled.
*/
private boolean enabled;
public ViewSettings(String name, boolean enabled) {
Assert.hasText(name, "'name' must not be empty");
this.name = name;
this.enabled = enabled;
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java
| 1
|
请完成以下Java代码
|
private static HUProcessDescriptor toHUProcessDescriptor(final I_M_HU_Process huProcessRecord)
{
final HUProcessDescriptorBuilder builder = HUProcessDescriptor.builder()
.processId(AdProcessId.ofRepoId(huProcessRecord.getAD_Process_ID()))
.internalName(huProcessRecord.getAD_Process().getValue());
if (huProcessRecord.isApplyToLUs())
{
builder.acceptHUUnitType(HuUnitType.LU);
}
if (huProcessRecord.isApplyToTUs())
{
builder.acceptHUUnitType(HuUnitType.TU);
}
if (huProcessRecord.isApplyToCUs())
{
builder.acceptHUUnitType(HuUnitType.VHU);
}
builder.provideAsUserAction(huProcessRecord.isProvideAsUserAction());
builder.acceptOnlyTopLevelHUs(huProcessRecord.isApplyToTopLevelHUsOnly());
return builder.build();
}
private static final class IndexedHUProcessDescriptors
{
|
private final ImmutableMap<AdProcessId, HUProcessDescriptor> huProcessDescriptorsByProcessId;
private IndexedHUProcessDescriptors(final List<HUProcessDescriptor> huProcessDescriptors)
{
huProcessDescriptorsByProcessId = Maps.uniqueIndex(huProcessDescriptors, HUProcessDescriptor::getProcessId);
}
public Collection<HUProcessDescriptor> getAsCollection()
{
return huProcessDescriptorsByProcessId.values();
}
public HUProcessDescriptor getByProcessIdOrNull(final AdProcessId processId)
{
return huProcessDescriptorsByProcessId.get(processId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\api\impl\MHUProcessDAO.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.namespace.hashCode();
result = prime * result + this.canonicalValue.hashCode();
return result;
}
@Override
public String toString() {
return this.namespace.getValue() + ":" + this.value;
}
/**
* Creates an {@link AdditionalHealthEndpointPath} from the given input. The input
* must contain a prefix and value separated by a `:`. The value must be limited to
* one path segment. For example, `server:/healthz`.
* @param value the value to parse
* @return the new instance
*/
public static AdditionalHealthEndpointPath from(String value) {
Assert.hasText(value, "'value' must not be null");
String[] values = value.split(":");
Assert.isTrue(values.length == 2, "'value' must contain a valid namespace and value separated by ':'.");
Assert.isTrue(StringUtils.hasText(values[0]), "'value' must contain a valid namespace.");
WebServerNamespace namespace = WebServerNamespace.from(values[0]);
validateValue(values[1]);
return new AdditionalHealthEndpointPath(namespace, values[1]);
}
/**
|
* Creates an {@link AdditionalHealthEndpointPath} from the given
* {@link WebServerNamespace} and value.
* @param webServerNamespace the server namespace
* @param value the value
* @return the new instance
*/
public static AdditionalHealthEndpointPath of(WebServerNamespace webServerNamespace, String value) {
Assert.notNull(webServerNamespace, "'webServerNamespace' must not be null.");
Assert.notNull(value, "'value' must not be null.");
validateValue(value);
return new AdditionalHealthEndpointPath(webServerNamespace, value);
}
private static void validateValue(String value) {
Assert.isTrue(StringUtils.countOccurrencesOf(value, "/") <= 1 && value.indexOf("/") <= 0,
"'value' must contain only one segment.");
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\AdditionalHealthEndpointPath.java
| 1
|
请完成以下Java代码
|
public void setStoreCreditCardData (final java.lang.String StoreCreditCardData)
{
set_Value (COLUMNNAME_StoreCreditCardData, StoreCreditCardData);
}
@Override
public java.lang.String getStoreCreditCardData()
{
return get_ValueAsString(COLUMNNAME_StoreCreditCardData);
}
@Override
public void setSupervisor_ID (final int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID);
}
@Override
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimeZone (final @Nullable java.lang.String TimeZone)
{
set_Value (COLUMNNAME_TimeZone, TimeZone);
}
@Override
public java.lang.String getTimeZone()
{
return get_ValueAsString(COLUMNNAME_TimeZone);
}
@Override
public void setTransferBank_ID (final int TransferBank_ID)
{
if (TransferBank_ID < 1)
set_Value (COLUMNNAME_TransferBank_ID, null);
else
set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID);
}
@Override
public int getTransferBank_ID()
{
|
return get_ValueAsInt(COLUMNNAME_TransferBank_ID);
}
@Override
public org.compiere.model.I_C_CashBook getTransferCashBook()
{
return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class);
}
@Override
public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook)
{
set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook);
}
@Override
public void setTransferCashBook_ID (final int TransferCashBook_ID)
{
if (TransferCashBook_ID < 1)
set_Value (COLUMNNAME_TransferCashBook_ID, null);
else
set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID);
}
@Override
public int getTransferCashBook_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java
| 1
|
请完成以下Java代码
|
public Long getDurationInMillis() {
return historicProcessInstance.getDurationInMillis();
}
@Override
public String getStartUserId() {
return historicProcessInstance.getStartUserId();
}
@Override
public String getStartActivityId() {
return historicProcessInstance.getStartActivityId();
}
@Override
public String getDeleteReason() {
return historicProcessInstance.getDeleteReason();
}
@Override
public String getSuperProcessInstanceId() {
return historicProcessInstance.getSuperProcessInstanceId();
}
@Override
public String getTenantId() {
return historicProcessInstance.getTenantId();
}
@Override
public List<HistoricData> getHistoricData() {
return historicData;
}
|
public void addHistoricData(HistoricData historicEvent) {
historicData.add(historicEvent);
}
public void addHistoricData(Collection<? extends HistoricData> historicEvents) {
historicData.addAll(historicEvents);
}
public void orderHistoricData() {
Collections.sort(
historicData,
new Comparator<HistoricData>() {
@Override
public int compare(HistoricData data1, HistoricData data2) {
return data1.getTime().compareTo(data2.getTime());
}
}
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceHistoryLogImpl.java
| 1
|
请完成以下Java代码
|
public static MHRConceptCategory get(Properties ctx, int HR_Concept_Category_ID)
{
if (HR_Concept_Category_ID <= 0)
{
return null;
}
// Try cache
MHRConceptCategory cc = s_cache.get(HR_Concept_Category_ID);
if (cc != null)
{
return cc;
}
// Load from DB
cc = new MHRConceptCategory(ctx, HR_Concept_Category_ID, null);
if (cc.get_ID() != HR_Concept_Category_ID)
{
return null;
}
if (cc != null)
{
s_cache.put(HR_Concept_Category_ID, cc);
}
return cc;
}
public static MHRConceptCategory forValue(Properties ctx, String value)
{
if (value == null)
{
return null;
}
final int AD_Client_ID = Env.getAD_Client_ID(ctx);
// Try cache
final String key = AD_Client_ID+"#"+value;
MHRConceptCategory cc = s_cacheValue.get(key);
|
if (cc != null)
{
return cc;
}
// Try database
final String whereClause = COLUMNNAME_Value+"=? AND AD_Client_ID IN (?,?)";
cc = new Query(ctx, Table_Name, whereClause, null)
.setParameters(new Object[]{value, 0, AD_Client_ID})
.setOnlyActiveRecords(true)
.setOrderBy("AD_Client_ID DESC")
.first();
if (cc != null)
{
s_cacheValue.put(key, cc);
s_cache.put(cc.get_ID(), cc);
}
return cc;
}
public MHRConceptCategory(Properties ctx, int HR_Concept_Category_ID, String trxName)
{
super(ctx, HR_Concept_Category_ID, trxName);
}
public MHRConceptCategory(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRConceptCategory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class C_OLCand
{
private final OLCandLocationsUpdaterService olCandLocationsUpdaterService;
public C_OLCand(@NonNull final OLCandLocationsUpdaterService olCandLocationsUpdaterService)
{
this.olCandLocationsUpdaterService = olCandLocationsUpdaterService;
}
@PostConstruct
public void postConstruct()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@CalloutMethod(columnNames = { I_C_OLCand.COLUMNNAME_C_BPartner_Override_ID })
public void onBPartnerOverride(final I_C_OLCand olCand)
{
|
olCandLocationsUpdaterService.updateBPartnerLocationOverride(olCand);
}
@CalloutMethod(columnNames = { I_C_OLCand.COLUMNNAME_DropShip_BPartner_Override_ID })
public void onDropShipPartnerOverride(final I_C_OLCand olCand)
{
olCandLocationsUpdaterService.updateDropShipLocationOverride(olCand);
}
@CalloutMethod(columnNames = { I_C_OLCand.COLUMNNAME_HandOver_Partner_Override_ID })
public void onHandOverPartnerOverrideCallout(@NonNull final I_C_OLCand olCand)
{
olCandLocationsUpdaterService.updateHandoverLocationOverride(olCand);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\callout\C_OLCand.java
| 2
|
请完成以下Java代码
|
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
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 Send dunning letters.
@param SendDunningLetter
Indicates if dunning letters will be sent
*/
|
public void setSendDunningLetter (boolean SendDunningLetter)
{
set_Value (COLUMNNAME_SendDunningLetter, Boolean.valueOf(SendDunningLetter));
}
/** Get Send dunning letters.
@return Indicates if dunning letters will be sent
*/
public boolean isSendDunningLetter ()
{
Object oo = get_Value(COLUMNNAME_SendDunningLetter);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Dunning.java
| 1
|
请完成以下Java代码
|
public Iterator<E> iterator() {
return new ShoppingCartIterator();
}
public class ShoppingCartIterator implements Iterator<E> {
int cursor;
int lastReturned = -1;
public boolean hasNext() {
return cursor != size;
}
public E next() {
return getNextElement();
}
private E getNextElement() {
int current = cursor;
exist(current);
E[] elements = ShoppingCart.this.elementData;
validate(elements, current);
|
cursor = current + 1;
lastReturned = current;
return elements[lastReturned];
}
private void exist(int current) {
if (current >= size) {
throw new NoSuchElementException();
}
}
private void validate(E[] elements, int current) {
if (current >= elements.length) {
throw new ConcurrentModificationException();
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-2\src\main\java\com\baeldung\collections\iterable\ShoppingCart.java
| 1
|
请完成以下Java代码
|
private static final class DocumentKey
{
public static DocumentKey of(@NonNull final Document document)
{
final DocumentPath documentPath = document.getDocumentPath();
return ofRootDocumentPath(documentPath);
}
public static DocumentKey ofRootDocumentPath(@NonNull final DocumentPath documentPath)
{
if (!documentPath.isRootDocument())
{
throw new InvalidDocumentPathException(documentPath, "shall be a root document path");
}
if (documentPath.isNewDocument())
{
throw new InvalidDocumentPathException(documentPath, "document path for creating new documents is not allowed");
}
return new DocumentKey(
documentPath.getDocumentType(),
documentPath.getDocumentTypeId(),
documentPath.getDocumentId());
}
public static DocumentKey of(
@NonNull final WindowId windowId,
@NonNull final DocumentId documentId)
{
return new DocumentKey(DocumentType.Window, windowId.toDocumentId(), documentId);
}
private final DocumentType documentType;
private final DocumentId documentTypeId;
private final DocumentId documentId;
private Integer _hashcode = null;
private DocumentKey(
@NonNull final DocumentType documentType,
@NonNull final DocumentId documentTypeId,
@NonNull final DocumentId documentId)
{
this.documentType = documentType;
this.documentTypeId = documentTypeId;
this.documentId = documentId;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("type", documentType)
.add("typeId", documentTypeId)
.add("documentId", documentId)
.toString();
}
@Override
|
public int hashCode()
{
if (_hashcode == null)
{
_hashcode = Objects.hash(documentType, documentTypeId, documentId);
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof DocumentKey))
{
return false;
}
final DocumentKey other = (DocumentKey)obj;
return Objects.equals(documentType, other.documentType)
&& Objects.equals(documentTypeId, other.documentTypeId)
&& Objects.equals(documentId, other.documentId);
}
public WindowId getWindowId()
{
Check.assume(documentType == DocumentType.Window, "documentType shall be {} but it was {}", DocumentType.Window, documentType);
return WindowId.of(documentTypeId);
}
public DocumentId getDocumentId()
{
return documentId;
}
public DocumentPath getDocumentPath()
{
return DocumentPath.rootDocumentPath(documentType, documentTypeId, documentId);
}
} // DocumentKey
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentCollection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<Employee> getEmployeeById(Integer employeeId) {
return webClient
.get()
.uri(PATH_PARAM_BY_ID, employeeId)
.retrieve()
.bodyToMono(Employee.class);
}
public Mono<Employee> addNewEmployee(Employee newEmployee) {
return webClient
.post()
.uri(ADD_EMPLOYEE)
.syncBody(newEmployee)
.retrieve().
bodyToMono(Employee.class);
}
public Mono<Employee> updateEmployee(Integer employeeId, Employee updateEmployee) {
|
return webClient
.put()
.uri(PATH_PARAM_BY_ID,employeeId)
.syncBody(updateEmployee)
.retrieve()
.bodyToMono(Employee.class);
}
public Mono<String> deleteEmployeeById(Integer employeeId) {
return webClient
.delete()
.uri(PATH_PARAM_BY_ID,employeeId)
.retrieve()
.bodyToMono(String.class);
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\reactive\service\EmployeeService.java
| 2
|
请完成以下Java代码
|
private void pushUpMin(List<T> h, int i) {
while (hasGrandparent(i) && h.get(i - 1).compareTo(h.get(getGrandparentIndex(i) - 1)) < 0) {
swap(i - 1, getGrandparentIndex(i) - 1, h);
i = getGrandparentIndex(i);
}
}
private void pushUpMax(List<T> h, int i) {
while (hasGrandparent(i) && h.get(i - 1).compareTo(h.get(getGrandparentIndex(i) - 1)) > 0) {
swap(i - 1, getGrandparentIndex(i) - 1, h);
i = getGrandparentIndex(i);
}
}
private boolean hasGrandparent(int i) {
return getParentIndex(i) > 1;
}
private void pushUp(List<T> h, int i) {
if (i != 1) {
if (isEvenLevel(i)) {
if (h.get(i - 1).compareTo(h.get(getParentIndex(i) - 1)) < 0) {
pushUpMin(h, i);
} else {
swap(i - 1, getParentIndex(i) - 1, h);
i = getParentIndex(i);
pushUpMax(h, i);
}
} else if (h.get(i - 1).compareTo(h.get(getParentIndex(i) - 1)) > 0) {
pushUpMax(h, i);
} else {
swap(i - 1, getParentIndex(i) - 1, h);
i = getParentIndex(i);
pushUpMin(h, i);
}
}
}
public T min() {
if (!isEmpty()) {
return array.get(0);
}
return null;
}
public T max() {
if (!isEmpty()) {
if (indicator == 2) {
return array.get(0);
}
if (indicator == 3) {
return array.get(1);
}
return array.get(1).compareTo(array.get(2)) < 0 ? array.get(2) : array.get(1);
}
return null;
|
}
public T removeMin() {
T min = min();
if (min != null) {
if (indicator == 2) {
array.remove(indicator--);
return min;
}
array.set(0, array.get(--indicator - 1));
array.remove(indicator - 1);
pushDown(array, 1);
}
return min;
}
public T removeMax() {
T max = max();
if (max != null) {
int maxIndex;
if (indicator == 2) {
maxIndex = 0;
array.remove(--indicator - 1);
return max;
} else if (indicator == 3) {
maxIndex = 1;
array.remove(--indicator - 1);
return max;
} else {
maxIndex = array.get(1).compareTo(array.get(2)) < 0 ? 2 : 1;
}
array.set(maxIndex, array.get(--indicator - 1));
array.remove(indicator - 1);
pushDown(array, maxIndex + 1);
}
return max;
}
}
|
repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\minmaxheap\MinMaxHeap.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected Class<?> getBeanClass(Element element) {
return CachingConnectionFactory.class;
}
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
if (element.hasAttribute(ADDRESSES) &&
(element.hasAttribute(HOST_ATTRIBUTE) || element.hasAttribute(PORT_ATTRIBUTE))) {
parserContext.getReaderContext().error("If the 'addresses' attribute is provided, a connection " +
"factory can not have 'host' or 'port' attributes.", element);
}
NamespaceUtils.addConstructorArgParentRefIfAttributeDefined(builder, element, CONNECTION_FACTORY_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, CHANNEL_CACHE_SIZE_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, HOST_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, PORT_ATTRIBUTE);
|
NamespaceUtils.setValueIfAttributeDefined(builder, element, USER_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, PASSWORD_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, VIRTUAL_HOST_ATTRIBUTE);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, EXECUTOR_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, ADDRESSES);
NamespaceUtils.setValueIfAttributeDefined(builder, element, SHUFFLE_ADDRESSES);
if (element.hasAttribute(SHUFFLE_ADDRESSES) && element.hasAttribute(SHUFFLE_MODE)) {
parserContext.getReaderContext()
.error("You must not specify both '" + SHUFFLE_ADDRESSES + "' and '" + SHUFFLE_MODE + "'", element);
}
NamespaceUtils.setValueIfAttributeDefined(builder, element, SHUFFLE_MODE);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, ADDRESS_RESOLVER);
NamespaceUtils.setValueIfAttributeDefined(builder, element, PUBLISHER_RETURNS);
NamespaceUtils.setValueIfAttributeDefined(builder, element, REQUESTED_HEARTBEAT, "requestedHeartBeat");
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_TIMEOUT);
NamespaceUtils.setValueIfAttributeDefined(builder, element, CACHE_MODE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_CACHE_SIZE_ATTRIBUTE);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, THREAD_FACTORY, "connectionThreadFactory");
NamespaceUtils.setValueIfAttributeDefined(builder, element, FACTORY_TIMEOUT, "channelCheckoutTimeout");
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_LIMIT);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, "connection-name-strategy");
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONFIRM_TYPE, "publisherConfirmType");
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\ConnectionFactoryParser.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AppRepositoryServiceImpl extends CommonEngineServiceImpl<AppEngineConfiguration> implements AppRepositoryService {
public AppRepositoryServiceImpl(AppEngineConfiguration engineConfiguration) {
super(engineConfiguration);
}
@Override
public AppDeploymentBuilder createDeployment() {
return commandExecutor.execute(new Command<>() {
@Override
public AppDeploymentBuilder execute(CommandContext commandContext) {
return new AppDeploymentBuilderImpl();
}
});
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return commandExecutor.execute(new GetDeploymentResourceNamesCmd(deploymentId));
}
@Override
public InputStream getResourceAsStream(String deploymentId, String resourceName) {
return commandExecutor.execute(new GetDeploymentResourceCmd(deploymentId, resourceName));
}
public AppDeployment deploy(AppDeploymentBuilderImpl deploymentBuilder) {
return commandExecutor.execute(new DeployCmd(deploymentBuilder));
}
@Override
public AppDefinition getAppDefinition(String appDefinitionId) {
|
return commandExecutor.execute(new GetDeploymentAppDefinitionCmd(appDefinitionId));
}
@Override
public AppModel getAppModel(String appDefinitionId) {
return commandExecutor.execute(new GetAppModelCmd(appDefinitionId));
}
@Override
public String convertAppModelToJson(String appDefinitionId) {
return commandExecutor.execute(new GetAppModelJsonCmd(appDefinitionId));
}
@Override
public void deleteDeployment(String deploymentId, boolean cascade) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, cascade));
}
@Override
public AppDeploymentQuery createDeploymentQuery() {
return configuration.getAppDeploymentEntityManager().createDeploymentQuery();
}
@Override
public AppDefinitionQuery createAppDefinitionQuery() {
return configuration.getAppDefinitionEntityManager().createAppDefinitionQuery();
}
@Override
public void setAppDefinitionCategory(String appDefinitionId, String category) {
commandExecutor.execute(new SetAppDefinitionCategoryCmd(appDefinitionId, category));
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AppRepositoryServiceImpl.java
| 2
|
请完成以下Java代码
|
public void setFirstname (final @Nullable java.lang.String Firstname)
{
set_Value (COLUMNNAME_Firstname, Firstname);
}
@Override
public java.lang.String getFirstname()
{
return get_ValueAsString(COLUMNNAME_Firstname);
}
@Override
public void setIsCompany (final boolean IsCompany)
{
set_ValueNoCheck (COLUMNNAME_IsCompany, IsCompany);
}
@Override
public boolean isCompany()
{
return get_ValueAsBoolean(COLUMNNAME_IsCompany);
}
@Override
public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
|
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Adv_Search.java
| 1
|
请完成以下Java代码
|
public class PrimeFactorizationAlgorithm {
public static Map<Integer, Integer> getPrimeFactors(int number) {
int absNumber = Math.abs(number);
Map<Integer, Integer> primeFactorsMap = new HashMap<Integer, Integer>();
for (int factor = 2; factor <= absNumber; factor++) {
while (absNumber % factor == 0) {
Integer power = primeFactorsMap.get(factor);
if (power == null) {
power = 0;
}
primeFactorsMap.put(factor, power + 1);
absNumber /= factor;
}
}
return primeFactorsMap;
}
public static int lcm(int number1, int number2) {
|
if (number1 == 0 || number2 == 0) {
return 0;
}
Map<Integer, Integer> primeFactorsForNum1 = getPrimeFactors(number1);
Map<Integer, Integer> primeFactorsForNum2 = getPrimeFactors(number2);
Set<Integer> primeFactorsUnionSet = new HashSet<Integer>(primeFactorsForNum1.keySet());
primeFactorsUnionSet.addAll(primeFactorsForNum2.keySet());
int lcm = 1;
for (Integer primeFactor : primeFactorsUnionSet) {
lcm *= Math.pow(primeFactor, Math.max(primeFactorsForNum1.getOrDefault(primeFactor, 0),
primeFactorsForNum2.getOrDefault(primeFactor, 0)));
}
return lcm;
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\lcm\PrimeFactorizationAlgorithm.java
| 1
|
请完成以下Java代码
|
public String getId()
{
return id;
}
@Override
public String getTitle()
{
return title;
}
@Override
public boolean isDefaultCollapsed()
{
return defaultCollapsed;
}
@Override
public ListModel<ISideAction> getActions()
{
return actions;
}
@Override
public List<ISideAction> getActionsList()
{
final ISideAction[] actionsArr = new ISideAction[actions.getSize()];
actions.copyInto(actionsArr);
return ImmutableList.copyOf(actionsArr);
}
@Override
public void removeAllActions()
{
actions.clear();
}
@Override
public void addAction(final ISideAction action)
{
if (actions.contains(action))
{
return;
}
actions.addElement(action);
|
}
@Override
public void removeAction(final int index)
{
actions.remove(index);
}
@Override
public void setActions(final Iterable<? extends ISideAction> actions)
{
this.actions.clear();
if (actions != null)
{
final List<ISideAction> actionsList = ListUtils.copyAsList(actions);
Collections.sort(actionsList, ISideAction.COMPARATOR_ByDisplayName);
for (final ISideAction action : actionsList)
{
this.actions.addElement(action);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\SideActionsGroupModel.java
| 1
|
请完成以下Java代码
|
public boolean save(String trxName) {
return po.save(trxName); // save
}
/**
* Is there a Change to be saved?
* @return true if record changed
*/
public boolean is_Changed() {
return po.is_Changed(); // is_Change
}
/**
* Create Single/Multi Key Where Clause
* @param withValues if true uses actual values otherwise ?
* @return where clause
*/
public String get_WhereClause(boolean withValues) {
return po.get_WhereClause(withValues); // getWhereClause
}
/**************************************************************************
* Delete Current Record
* @param force delete also processed records
* @return true if deleted
*/
public boolean delete(boolean force) {
return po.delete(force); // delete
}
/**
* Delete Current Record
* @param force delete also processed records
* @param trxName transaction
*/
public boolean delete(boolean force, String trxName) {
return po.delete(force, trxName); // delete
}
/**************************************************************************
* Lock it.
* @return true if locked
*/
public boolean lock() {
return po.lock(); // lock
}
|
/**
* UnLock it
* @return true if unlocked (false only if unlock fails)
*/
public boolean unlock(String trxName) {
return po.unlock(trxName); // unlock
}
/**
* Set Trx
* @param trxName transaction
*/
public void set_TrxName(String trxName) {
po.set_TrxName(trxName); // setTrx
}
/**
* Get Trx
* @return transaction
*/
public String get_TrxName() {
return po.get_TrxName(); // getTrx
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
| 1
|
请完成以下Java代码
|
public static class RecordKey {
protected String fixedValue;
protected String eventField;
protected String delegateExpression;
public String getFixedValue() {
return fixedValue;
}
public void setFixedValue(String fixedValue) {
this.fixedValue = fixedValue;
}
public String getEventField() {
return eventField;
}
|
public void setEventField(String eventField) {
this.eventField = eventField;
}
public String getDelegateExpression() {
return delegateExpression;
}
public void setDelegateExpression(String delegateExpression) {
this.delegateExpression = delegateExpression;
}
// backward compatibility
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static RecordKey fromFixedValue(String fixedValue) {
RecordKey recordKey = new RecordKey();
recordKey.setFixedValue(fixedValue);
return recordKey;
}
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaOutboundChannelModel.java
| 1
|
请完成以下Java代码
|
public void addDeployedArtifact(Object deployedArtifact) {
if (deployedArtifacts == null) {
deployedArtifacts = new HashMap<Class<?>, List<Object>>();
}
Class<?> clazz = deployedArtifact.getClass();
List<Object> artifacts = deployedArtifacts.get(clazz);
if (artifacts == null) {
artifacts = new ArrayList<Object>();
deployedArtifacts.put(clazz, artifacts);
}
artifacts.add(deployedArtifact);
}
@SuppressWarnings("unchecked")
public <T> List<T> getDeployedArtifacts(Class<T> clazz) {
for (Class<?> deployedArtifactsClass : deployedArtifacts.keySet()) {
if (clazz.isAssignableFrom(deployedArtifactsClass)) {
return (List<T>) deployedArtifacts.get(deployedArtifactsClass);
}
}
return null;
}
// getters and setters ////////////////////////////////////////////////////////
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
}
public Date getDeploymentTime() {
|
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getProjectReleaseVersion() {
return projectReleaseVersion;
}
public void setProjectReleaseVersion(String projectReleaseVersion) {
this.projectReleaseVersion = projectReleaseVersion;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java
| 1
|
请完成以下Java代码
|
public void putResult(@NonNull final ResultSet result)
{
m_resultSet = result;
if (resultFile != null)
{
exportToFile(resultFile);
}
else
{
resultFile = exportToTempFile(fileNamePrefix);
}
}
@Override
protected Properties getCtx()
{
return m_ctx;
}
@Override
public int getColumnCount()
{
try
{
return m_resultSet.getMetaData().getColumnCount();
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
@Override
public int getDisplayType(final int IGNORED, final int col)
{
final Object value = getValue(col);
return CellValues.extractDisplayTypeFromValue(value);
}
@Override
public List<CellValue> getHeaderNames()
{
final List<String> headerNames = new ArrayList<>();
if (m_columnHeaders == null || m_columnHeaders.isEmpty())
{
// use the next data row; can be the first, but if we add another sheet, it can also be another one.
final List<Object> currentRow = getNextRawDataRow();
for (Object headerNameObj : currentRow)
{
headerNames.add(headerNameObj != null ? headerNameObj.toString() : null);
}
}
else
{
headerNames.addAll(m_columnHeaders);
}
final ArrayList<CellValue> result = new ArrayList<>();
final String adLanguage = getLanguage().getAD_Language();
for (final String rawHeaderName : headerNames)
{
final String headerName;
if (translateHeaders)
{
headerName = msgBL.translatable(rawHeaderName).translate(adLanguage);
}
else
{
headerName = rawHeaderName;
}
result.add(CellValues.toCellValue(headerName));
}
return result;
}
private Object getValue(final int col)
{
try
{
return m_resultSet.getObject(col + 1);
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
@Override
public int getRowCount()
{
return -1; // TODO remove
}
@Override
public boolean isColumnPrinted(final int col)
{
return true;
}
|
@Override
public boolean isFunctionRow(final int row)
{
return false;
}
@Override
public boolean isPageBreak(final int row, final int col)
{
return false;
}
@Override
protected List<CellValue> getNextRow()
{
return CellValues.toCellValues(getNextRawDataRow());
}
private List<Object> getNextRawDataRow()
{
try
{
final List<Object> row = new ArrayList<>();
for (int col = 1; col <= getColumnCount(); col++)
{
final Object o = m_resultSet.getObject(col);
row.add(o);
}
noDataAddedYet = false;
return row;
}
catch (final SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
@Override
protected boolean hasNextRow()
{
try
{
return m_resultSet.next();
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\JdbcExcelExporter.java
| 1
|
请完成以下Java代码
|
public void setId(GenericIdentification32 value) {
this.id = value;
}
/**
* Gets the value of the sysNm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSysNm() {
return sysNm;
}
/**
* Sets the value of the sysNm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSysNm(String value) {
this.sysNm = value;
}
/**
* Gets the value of the grpId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGrpId() {
return grpId;
}
/**
* Sets the value of the grpId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGrpId(String value) {
this.grpId = value;
}
/**
* Gets the value of the cpblties property.
*
* @return
* possible object is
* {@link PointOfInteractionCapabilities1 }
*
*/
|
public PointOfInteractionCapabilities1 getCpblties() {
return cpblties;
}
/**
* Sets the value of the cpblties property.
*
* @param value
* allowed object is
* {@link PointOfInteractionCapabilities1 }
*
*/
public void setCpblties(PointOfInteractionCapabilities1 value) {
this.cpblties = value;
}
/**
* Gets the value of the cmpnt 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 cmpnt property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCmpnt().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PointOfInteractionComponent1 }
*
*
*/
public List<PointOfInteractionComponent1> getCmpnt() {
if (cmpnt == null) {
cmpnt = new ArrayList<PointOfInteractionComponent1>();
}
return this.cmpnt;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteraction1.java
| 1
|
请完成以下Java代码
|
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(Date startTimestamp) {
this.startTimestamp = startTimestamp;
}
public Date getLastAccessTime() {
return lastAccessTime;
}
|
public void setLastAccessTime(Date lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
}
|
repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\pojo\UserOnline.java
| 1
|
请完成以下Java代码
|
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
|
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
|
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\utils\PageResult.java
| 1
|
请完成以下Java代码
|
public class X_C_Project_Label extends org.compiere.model.PO implements I_C_Project_Label, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 400695341L;
/** Standard Constructor */
public X_C_Project_Label (final Properties ctx, final int C_Project_Label_ID, @Nullable final String trxName)
{
super (ctx, C_Project_Label_ID, trxName);
}
/** Load Constructor */
public X_C_Project_Label (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Project_Label_ID (final int C_Project_Label_ID)
{
if (C_Project_Label_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Project_Label_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Project_Label_ID, C_Project_Label_ID);
}
@Override
public int getC_Project_Label_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_Label_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
|
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Label.java
| 1
|
请完成以下Java代码
|
public static String patternLtrim(String s) {
return LTRIM.matcher(s)
.replaceAll("");
}
public static String patternRtrim(String s) {
return RTRIM.matcher(s)
.replaceAll("");
}
// Pattern matches() with replaceAll
@Benchmark
public boolean patternMatchesLTtrimRTrim() {
String ltrim = patternLtrim(src);
String rtrim = patternRtrim(src);
return checkStrings(ltrim, rtrim);
}
// Guava CharMatcher trimLeadingFrom / trimTrailingFrom
@Benchmark
public boolean guavaCharMatcher() {
String ltrim = CharMatcher.whitespace().trimLeadingFrom(src);
|
String rtrim = CharMatcher.whitespace().trimTrailingFrom(src);
return checkStrings(ltrim, rtrim);
}
// Apache Commons StringUtils containsIgnoreCase
@Benchmark
public boolean apacheCommonsStringUtils() {
String ltrim = StringUtils.stripStart(src, null);
String rtrim = StringUtils.stripEnd(src, null);
return checkStrings(ltrim, rtrim);
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\trim\LTrimRTrim.java
| 1
|
请完成以下Java代码
|
public HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return getSession(HistoricVariableInstanceEntityManager.class);
}
public HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getSession(HistoricActivityInstanceEntityManager.class);
}
public HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
}
public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
}
public EventLogEntryEntityManager getEventLogEntryEntityManager() {
return getSession(EventLogEntryEntityManager.class);
}
public JobEntityManager getJobEntityManager() {
return getSession(JobEntityManager.class);
}
public TimerJobEntityManager getTimerJobEntityManager() {
return getSession(TimerJobEntityManager.class);
}
public SuspendedJobEntityManager getSuspendedJobEntityManager() {
return getSession(SuspendedJobEntityManager.class);
}
public DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getSession(DeadLetterJobEntityManager.class);
}
public AttachmentEntityManager getAttachmentEntityManager() {
return getSession(AttachmentEntityManager.class);
}
public TableDataManager getTableDataManager() {
return getSession(TableDataManager.class);
}
public CommentEntityManager getCommentEntityManager() {
return getSession(CommentEntityManager.class);
}
public PropertyEntityManager getPropertyEntityManager() {
return getSession(PropertyEntityManager.class);
|
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getSession(EventSubscriptionEntityManager.class);
}
public Map<Class<?>, SessionFactory> getSessionFactories() {
return sessionFactories;
}
public HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
// getters and setters //////////////////////////////////////////////////////
public TransactionContext getTransactionContext() {
return transactionContext;
}
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public FlowableEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JdbiConfiguration {
@Bean
public Jdbi jdbi(DataSource ds,List<JdbiPlugin> jdbiPlugins, List<RowMapper<?>> rowMappers) {
TransactionAwareDataSourceProxy proxy = new TransactionAwareDataSourceProxy(ds);
Jdbi jdbi = Jdbi.create(proxy);
// Register all available plugins
log.info("[I27] Installing plugins... ({} found)", jdbiPlugins.size());
jdbiPlugins.forEach(jdbi::installPlugin);
// Register all available rowMappers
log.info("[I31] Installing rowMappers... ({} found)", rowMappers.size());
rowMappers.forEach(jdbi::registerRowMapper);
return jdbi;
}
|
@Bean
public JdbiPlugin sqlObjectPlugin() {
return new SqlObjectPlugin();
}
@Bean
public CarMakerDao carMakerDao(Jdbi jdbi) {
return jdbi.onDemand(CarMakerDao.class);
}
@Bean
public CarModelDao carModelDao(Jdbi jdbi) {
return jdbi.onDemand(CarModelDao.class);
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\boot\jdbi\JdbiConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PessimisticLockingCourse {
@Id
private Long courseId;
private String name;
@ManyToOne
@JoinTable(name = "student_course")
private PessimisticLockingStudent student;
public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) {
this.courseId = courseId;
this.name = name;
this.student = student;
}
public PessimisticLockingCourse() {
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
|
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PessimisticLockingStudent getStudent() {
return student;
}
public void setStudent(PessimisticLockingStudent students) {
this.student = students;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\pessimisticlocking\PessimisticLockingCourse.java
| 2
|
请完成以下Java代码
|
public class HistoricCaseInstanceMigrationDocumentImpl implements HistoricCaseInstanceMigrationDocument {
protected String migrateToCaseDefinitionId;
protected String migrateToCaseDefinitionKey;
protected Integer migrateToCaseDefinitionVersion;
protected String migrateToCaseDefinitionTenantId;
public static HistoricCaseInstanceMigrationDocument fromJson(String caseInstanceMigrationDocumentJson) {
return HistoricCaseInstanceMigrationDocumentConverter.convertFromJson(caseInstanceMigrationDocumentJson);
}
public void setMigrateToCaseDefinitionId(String caseDefinitionId) {
this.migrateToCaseDefinitionId = caseDefinitionId;
}
public void setMigrateToCaseDefinition(String caseDefinitionKey, Integer caseDefinitionVersion) {
this.migrateToCaseDefinitionKey = caseDefinitionKey;
this.migrateToCaseDefinitionVersion = caseDefinitionVersion;
}
public void setMigrateToCaseDefinition(String caseDefinitionKey, Integer caseDefinitionVersion, String caseDefinitionTenantId) {
this.migrateToCaseDefinitionKey = caseDefinitionKey;
this.migrateToCaseDefinitionVersion = caseDefinitionVersion;
this.migrateToCaseDefinitionTenantId = caseDefinitionTenantId;
}
@Override
public String getMigrateToCaseDefinitionId() {
return this.migrateToCaseDefinitionId;
}
@Override
public String getMigrateToCaseDefinitionKey() {
return this.migrateToCaseDefinitionKey;
}
|
@Override
public Integer getMigrateToCaseDefinitionVersion() {
return this.migrateToCaseDefinitionVersion;
}
@Override
public String getMigrateToCaseDefinitionTenantId() {
return this.migrateToCaseDefinitionTenantId;
}
@Override
public String asJsonString() {
return HistoricCaseInstanceMigrationDocumentConverter.convertToJsonString(this);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\HistoricCaseInstanceMigrationDocumentImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<File> mgetFile(String dir) {
return null;
}
@Override
public boolean rmFile(String file) {
return false;
}
@Override
public boolean mv(String sourceFile, String targetFile) {
return false;
}
@Override
public File putFile(String dir) {
return null;
}
@Override
public List<File> mputFile(String dir) {
return null;
}
@Override
public String nlstFile(String dir) {
return gateway.nlstFile(dir);
}
private static File convertInputStreamToFile(InputStream inputStream, String savePath) {
OutputStream outputStream = null;
File file = new File(savePath);
try {
outputStream = new FileOutputStream(file);
int read;
|
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
log.info("convert InputStream to file done, savePath is : {}", savePath);
} catch (IOException e) {
log.error("error:", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("error:", e);
}
}
}
return file;
}
private static File convert(MultipartFile file) throws IOException {
File convertFile = new File(file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convertFile);
fos.write(file.getBytes());
fos.close();
return convertFile;
}
}
|
repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\service\impl\SftpServiceImpl.java
| 2
|
请完成以下Java代码
|
public class DateAndDateTimeChoice {
@XmlElement(name = "Dt")
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar dt;
@XmlElement(name = "DtTm")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar dtTm;
/**
* Gets the value of the dt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDt() {
return dt;
}
/**
* Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDt(XMLGregorianCalendar value) {
this.dt = value;
}
/**
* Gets the value of the dtTm property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
|
*/
public XMLGregorianCalendar getDtTm() {
return dtTm;
}
/**
* Sets the value of the dtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDtTm(XMLGregorianCalendar value) {
this.dtTm = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DateAndDateTimeChoice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomerController {
@Autowired
private CustomerService customerService;
@Autowired
private OrderService orderService;
@GetMapping("/{customerId}")
public Customer getCustomerById(@PathVariable final String customerId) {
return customerService.getCustomerDetail(customerId);
}
@GetMapping("/{customerId}/{orderId}")
public Order getOrderById(@PathVariable final String customerId, @PathVariable final String orderId) {
return orderService.getOrderByIdForCustomer(customerId, orderId);
}
@GetMapping(value = "/{customerId}/orders", produces = { "application/hal+json" })
public CollectionModel<Order> getOrdersForCustomer(@PathVariable final String customerId) {
final List<Order> orders = orderService.getAllOrdersForCustomer(customerId);
for (final Order order : orders) {
final Link selfLink = linkTo(
methodOn(CustomerController.class).getOrderById(customerId, order.getOrderId())).withSelfRel();
order.add(selfLink);
}
Link link = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel();
CollectionModel<Order> result = CollectionModel.of(orders, link);
return result;
|
}
@GetMapping(produces = { "application/hal+json" })
public CollectionModel<Customer> getAllCustomers() {
final List<Customer> allCustomers = customerService.allCustomers();
for (final Customer customer : allCustomers) {
String customerId = customer.getCustomerId();
Link selfLink = linkTo(CustomerController.class).slash(customerId)
.withSelfRel();
customer.add(selfLink);
if (orderService.getAllOrdersForCustomer(customerId)
.size() > 0) {
final Link ordersLink = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId))
.withRel("allOrders");
customer.add(ordersLink);
}
}
Link link = linkTo(CustomerController.class).withSelfRel();
CollectionModel<Customer> result = CollectionModel.of(allCustomers, link);
return result;
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\controller\CustomerController.java
| 2
|
请完成以下Java代码
|
protected void writeErrorDefinition(Event parentEvent, ErrorEventDefinition errorDefinition, XMLStreamWriter xtw)
throws Exception {
xtw.writeStartElement(ELEMENT_EVENT_ERRORDEFINITION);
writeDefaultAttribute(ATTRIBUTE_ERROR_REF, errorDefinition.getErrorRef(), xtw);
boolean didWriteExtensionStartElement = BpmnXMLUtil.writeExtensionElements(errorDefinition, false, xtw);
if (didWriteExtensionStartElement) {
xtw.writeEndElement();
}
xtw.writeEndElement();
}
protected void writeTerminateDefinition(
Event parentEvent,
TerminateEventDefinition terminateDefinition,
XMLStreamWriter xtw
) throws Exception {
xtw.writeStartElement(ELEMENT_EVENT_TERMINATEDEFINITION);
if (terminateDefinition.isTerminateAll()) {
writeQualifiedAttribute(ATTRIBUTE_TERMINATE_ALL, "true", xtw);
}
if (terminateDefinition.isTerminateMultiInstance()) {
writeQualifiedAttribute(ATTRIBUTE_TERMINATE_MULTI_INSTANCE, "true", xtw);
}
boolean didWriteExtensionStartElement = BpmnXMLUtil.writeExtensionElements(terminateDefinition, false, xtw);
if (didWriteExtensionStartElement) {
xtw.writeEndElement();
}
|
xtw.writeEndElement();
}
protected void writeDefaultAttribute(String attributeName, String value, XMLStreamWriter xtw) throws Exception {
BpmnXMLUtil.writeDefaultAttribute(attributeName, value, xtw);
}
protected void writeQualifiedAttribute(String attributeName, String value, XMLStreamWriter xtw) throws Exception {
BpmnXMLUtil.writeQualifiedAttribute(attributeName, value, xtw);
}
protected void writeIncomingOutgoingFlowElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
if (FlowNode.class.isAssignableFrom(element.getClass())) {
BpmnXMLUtil.writeIncomingAndOutgoingFlowElement((FlowNode) element, xtw);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\BaseBpmnXMLConverter.java
| 1
|
请完成以下Java代码
|
public final class WebAsyncManagerIntegrationFilter extends OncePerRequestFilter {
private static final Object CALLABLE_INTERCEPTOR_KEY = new Object();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
SecurityContextCallableProcessingInterceptor securityProcessingInterceptor = (SecurityContextCallableProcessingInterceptor) asyncManager
.getCallableInterceptor(CALLABLE_INTERCEPTOR_KEY);
if (securityProcessingInterceptor == null) {
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor();
interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
asyncManager.registerCallableInterceptor(CALLABLE_INTERCEPTOR_KEY, interceptor);
}
|
filterChain.doFilter(request, response);
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\request\async\WebAsyncManagerIntegrationFilter.java
| 1
|
请完成以下Java代码
|
public CamundaBpmRunLdapProperties getLdap() {
return ldap;
}
public void setLdap(CamundaBpmRunLdapProperties ldap) {
this.ldap = ldap;
}
public CamundaBpmRunAdministratorAuthorizationProperties getAdminAuth() {
return adminAuth;
}
public void setAdminAuth(CamundaBpmRunAdministratorAuthorizationProperties adminAuth) {
this.adminAuth = adminAuth;
}
public List<CamundaBpmRunProcessEnginePluginProperty> getProcessEnginePlugins() {
return processEnginePlugins;
}
public void setProcessEnginePlugins(List<CamundaBpmRunProcessEnginePluginProperty> processEnginePlugins) {
this.processEnginePlugins = processEnginePlugins;
}
public CamundaBpmRunRestProperties getRest() {
return rest;
}
public void setRest(CamundaBpmRunRestProperties rest) {
this.rest = rest;
}
public CamundaBpmRunDeploymentProperties getDeployment() {
return deployment;
}
|
public void setDeployment(CamundaBpmRunDeploymentProperties deployment) {
this.deployment = deployment;
}
@Override
public String toString() {
return "CamundaBpmRunProperties [" +
"auth=" + auth +
", cors=" + cors +
", ldap=" + ldap +
", adminAuth=" + adminAuth +
", plugins=" + processEnginePlugins +
", rest=" + rest +
", deployment=" + deployment +
"]";
}
}
|
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunProperties.java
| 1
|
请完成以下Java代码
|
public static Window getParentWindow(final Component component)
{
Component element = component;
while (element != null)
{
if (element instanceof JDialog || element instanceof JFrame)
{
return (Window)element;
}
if (element instanceof Window)
{
return (Window)element;
}
element = element.getParent();
}
return null;
} // getParent
/**
* Get Graphics of container or its parent. The element may not have a Graphic if not displayed yet, but the parent might have.
*
|
* @param container Container
* @return Graphics of container or null
*/
public static Graphics getGraphics(final Container container)
{
Container element = container;
while (element != null)
{
final Graphics g = element.getGraphics();
if (g != null)
{
return g;
}
element = element.getParent();
}
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\SwingUtils.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8082
spring.artemis.mode=EMBEDDED
spring.artemis.host=localhost
spring.artemis.port=61616
spring.artemis.embedded.enabled=true
spring.jms.template.default-destination=my-queue-1
logging.level.
|
org.apache.activemq.audit.base=WARN
logging.level.org.apache.activemq.audit.message=WARN
|
repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String ajaxPaymentList(HttpServletRequest request,@RequestBody JSONParam[] params) throws IllegalAccessException, InvocationTargetException {
//convertToMap定义于父类,将参数数组中的所有元素加入一个HashMap
HashMap<String, String> paramMap = convertToMap(params);
String sEcho = paramMap.get("sEcho");
int start = Integer.parseInt(paramMap.get("iDisplayStart"));
int length = Integer.parseInt(paramMap.get("iDisplayLength"));
RpUserInfo userInfo = (RpUserInfo)request.getSession().getAttribute(ConstantClass.USER);
//customerService.search返回的第一个元素是满足查询条件的记录总数,后面的是
//页面当前页需要显示的记录数据
PageParam pageParam = new PageParam(start/length+1, length);
PaymentOrderQueryParam param = new PaymentOrderQueryParam();
param.setMerchantNo(userInfo.getUserNo());
param.setStatus(TradeStatusEnum.SUCCESS.name());
PageBean pageBean = rpTradePaymentQueryService.listPaymentRecordPage(pageParam, param);
Long count = Long.valueOf(pageBean.getTotalCount()+"");
String jsonString = JSON.toJSONString(pageBean.getRecordList());
|
String json = "{\"sEcho\":" + sEcho + ",\"iTotalRecords\":" + count.longValue() + ",\"iTotalDisplayRecords\":" + count.longValue() + ",\"aaData\":" + jsonString + "}";
return json;
}
@RequestMapping(value = "/ajaxPaymentReport", method ={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public List ajaxPaymentReport(HttpServletRequest request){
RpUserInfo userInfo = (RpUserInfo)request.getSession().getAttribute(ConstantClass.USER);
List<Map<String, String>> paymentReport = rpTradePaymentQueryService.getPaymentReport(userInfo.getUserNo());
String jsonString = JSON.toJSONString(paymentReport);
System.out.println(jsonString);
return paymentReport;
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-merchant\src\main\java\com\roncoo\pay\controller\trade\TradeController.java
| 2
|
请完成以下Java代码
|
public class JsonAlbertaContact
{
@ApiModelProperty(position = 10)
@Nullable
private String gender;
@ApiModelProperty(hidden = true)
private boolean genderSet;
@ApiModelProperty(position = 10)
@Nullable
private String title;
@ApiModelProperty(hidden = true)
private boolean titleSet;
@ApiModelProperty(position = 10)
@Nullable
private Instant timestamp;
|
@ApiModelProperty(hidden = true)
private boolean timestampSet;
public void setGender(@Nullable final String gender)
{
this.gender = gender;
this.genderSet = true;
}
public void setTitle(@Nullable final String title)
{
this.title = title;
this.titleSet = true;
}
public void setTimestamp(@Nullable final Instant timestamp)
{
this.timestamp = timestamp;
this.timestampSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaContact.java
| 1
|
请完成以下Java代码
|
protected <T> T execute(Command<T> command) {
if(commandExecutor != null) {
return commandExecutor.execute(command);
} else {
return command.execute(commandContext);
}
}
// getters //////////////////////////////////
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public CommandContext getCommandContext() {
return commandContext;
}
public String getMessageName() {
return messageName;
}
public String getBusinessKey() {
return businessKey;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public Map<String, Object> getCorrelationProcessInstanceVariables() {
return correlationProcessInstanceVariables;
}
public Map<String, Object> getCorrelationLocalVariables() {
return correlationLocalVariables;
|
}
public Map<String, Object> getPayloadProcessInstanceVariables() {
return payloadProcessInstanceVariables;
}
public VariableMap getPayloadProcessInstanceVariablesLocal() {
return payloadProcessInstanceVariablesLocal;
}
public VariableMap getPayloadProcessInstanceVariablesToTriggeredScope() {
return payloadProcessInstanceVariablesToTriggeredScope;
}
public boolean isExclusiveCorrelation() {
return isExclusiveCorrelation;
}
public String getTenantId() {
return tenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isExecutionsOnly() {
return executionsOnly;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationBuilderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("Persisting several authors ...");
bookstoreService.createAuthors();
|
System.out.println("\nFetch authors older than 40 ...");
List<Author> authorsOld40 = bookstoreService.fetchAuthorsByAgeGreaterThanEqual(40);
System.out.println(authorsOld40);
System.out.println("\nFetch the avatar of author with id 1 ...");
byte[] authorAvatar = bookstoreService.fetchAuthorAvatarViaId(1L);
System.out.println(authorAvatar.length + " bytes");
System.out.println("\nN+1 (avoid this) ...");
List<Author> authorsDetails = bookstoreService.fetchAuthorsDetailsByAgeGreaterThanEqual(40);
System.out.println(authorsDetails);
System.out.println("\nFetching DTO including avatars ...");
List<AuthorDto> authorsWithAvatars = bookstoreService.fetchAuthorsWithAvatarsByAgeGreaterThanEqual(40);
authorsWithAvatars.forEach(a -> System.out.println(a.getName() + ", " + a.getAvatar()));
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootAttributeLazyLoadingBasic\src\main\java\com\bookstore\MainApplication.java
| 2
|
请完成以下Java代码
|
public void linkToMaterialTracking(final I_C_Invoice_Candidate ic)
{
final boolean createLink = true;
updateLinkToTrackingIfNotNull(ic, createLink);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void unlinkFromMaterialTracking(final I_C_Invoice_Candidate ic)
{
final boolean createLink = false; // i.e. remove the link
updateLinkToTrackingIfNotNull(ic, createLink);
}
private void updateLinkToTrackingIfNotNull(final I_C_Invoice_Candidate ic, final boolean createLink)
{
final IMaterialTrackingAware materialTrackingAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(ic, IMaterialTrackingAware.class);
if (materialTrackingAware.getM_Material_Tracking_ID() <= 0)
|
{
return;
}
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
if (createLink)
{
materialTrackingBL.linkModelToMaterialTracking(MTLinkRequest.builder()
.model(ic)
.materialTrackingRecord(ic.getM_Material_Tracking())
.build());
}
else
{
materialTrackingBL.unlinkModelFromMaterialTrackings(ic);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_Invoice_Candidate.java
| 1
|
请完成以下Java代码
|
public HistoricProcessInstanceQuery createHistoricProcessInstanceQuery() {
return new HistoricProcessInstanceQueryImpl(commandExecutor);
}
public HistoricActivityInstanceQuery createHistoricActivityInstanceQuery() {
return new HistoricActivityInstanceQueryImpl(commandExecutor);
}
public HistoricTaskInstanceQuery createHistoricTaskInstanceQuery() {
return new HistoricTaskInstanceQueryImpl(commandExecutor, processEngineConfiguration.getDatabaseType());
}
public HistoricDetailQuery createHistoricDetailQuery() {
return new HistoricDetailQueryImpl(commandExecutor);
}
@Override
public NativeHistoricDetailQuery createNativeHistoricDetailQuery() {
return new NativeHistoricDetailQueryImpl(commandExecutor);
}
public HistoricVariableInstanceQuery createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl(commandExecutor);
}
@Override
public NativeHistoricVariableInstanceQuery createNativeHistoricVariableInstanceQuery() {
return new NativeHistoricVariableInstanceQueryImpl(commandExecutor);
}
public void deleteHistoricTaskInstance(String taskId) {
commandExecutor.execute(new DeleteHistoricTaskInstanceCmd(taskId));
}
public void deleteHistoricProcessInstance(String processInstanceId) {
commandExecutor.execute(new DeleteHistoricProcessInstanceCmd(processInstanceId));
}
|
public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() {
return new NativeHistoricProcessInstanceQueryImpl(commandExecutor);
}
public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() {
return new NativeHistoricTaskInstanceQueryImpl(commandExecutor);
}
public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() {
return new NativeHistoricActivityInstanceQueryImpl(commandExecutor);
}
@Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) {
return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId));
}
@Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) {
return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null));
}
@Override
public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) {
return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoryServiceImpl.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("viewId", viewId)
.add("fullyChanged", fullyChanged ? Boolean.TRUE : null)
.add("headerPropertiesChanged", headerPropertiesChanged ? Boolean.TRUE : null)
.add("changedRowIds", changedRowIds)
.toString();
}
public ViewId getViewId()
{
return viewId;
}
public void setFullyChanged()
{
fullyChanged = true;
}
public boolean isHeaderPropertiesChanged()
{
return headerPropertiesChanged;
}
public void setHeaderPropertiesChanged()
{
this.headerPropertiesChanged = true;
}
public boolean isFullyChanged()
{
return fullyChanged;
}
public boolean hasChanges()
{
if (fullyChanged)
{
return true;
}
if (headerPropertiesChanged)
{
return true;
}
return changedRowIds != null && !changedRowIds.isEmpty();
}
public void addChangedRowIds(@Nullable final DocumentIdsSelection rowIds)
{
// Don't collect rowIds if this was already flagged as fully changed.
if (fullyChanged)
{
return;
}
if (rowIds == null || rowIds.isEmpty())
{
return;
}
else if (rowIds.isAll())
{
fullyChanged = true;
changedRowIds = null;
}
else
{
|
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds.toSet());
}
}
public void addChangedRowIds(final Collection<DocumentId> rowIds)
{
if (rowIds.isEmpty())
{
return;
}
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds);
}
public void addChangedRowId(@NonNull final DocumentId rowId)
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.add(rowId);
}
public DocumentIdsSelection getChangedRowIds()
{
final boolean fullyChanged = this.fullyChanged;
final Set<DocumentId> changedRowIds = this.changedRowIds;
if (fullyChanged)
{
return DocumentIdsSelection.ALL;
}
else if (changedRowIds == null || changedRowIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
}
else
{
return DocumentIdsSelection.of(changedRowIds);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChanges.java
| 1
|
请完成以下Java代码
|
private static String buildRelationPathSql(EntityRelationPathQuery query) {
List<RelationPathLevel> levels = query.levels();
StringBuilder sb = new StringBuilder();
sb.append("WITH seed AS (\n")
.append(" SELECT ?::uuid AS id, ?::varchar AS type\n")
.append(")");
String prev = "seed";
for (int i = 0; i < levels.size() - 1; i++) {
RelationPathLevel lvl = levels.get(i);
boolean down = lvl.direction() == EntitySearchDirection.FROM;
String cur = "lvl" + (i + 1);
String joinCond = down
? "r.from_id = p.id AND r.from_type = p.type"
: "r.to_id = p.id AND r.to_type = p.type";
String selectNext = down
? "r.to_id AS id, r.to_type AS type"
: "r.from_id AS id, r.from_type AS type";
sb.append(",\n").append(cur).append(" AS (\n")
.append(" SELECT ").append(selectNext).append("\n")
.append(" FROM ").append(RELATION_TABLE_NAME).append(" r\n")
.append(" JOIN ").append(prev).append(" p ON ").append(joinCond).append("\n")
.append(" WHERE r.relation_type_group = '").append(RelationTypeGroup.COMMON).append("'\n")
|
.append(" AND r.relation_type = ?\n")
.append(")");
prev = cur;
}
RelationPathLevel last = levels.get(levels.size() - 1);
boolean lastDown = last.direction() == EntitySearchDirection.FROM;
String prevForLast = (levels.size() == 1) ? "seed" : prev;
String lastJoin = lastDown
? "r.from_id = p.id AND r.from_type = p.type"
: "r.to_id = p.id AND r.to_type = p.type";
sb.append("\n")
.append("SELECT r.from_id, r.from_type, r.to_id, r.to_type,\n")
.append(" r.relation_type_group, r.relation_type, r.version\n")
.append("FROM ").append(RELATION_TABLE_NAME).append(" r\n")
.append("JOIN ").append(prevForLast).append(" p ON ").append(lastJoin).append("\n")
.append("WHERE r.relation_type_group = '").append(RelationTypeGroup.COMMON).append("'\n")
.append(" AND r.relation_type = ?\n")
.append("LIMIT ?");
return sb.toString();
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\relation\JpaRelationDao.java
| 1
|
请完成以下Java代码
|
protected static void processParameters(List<IOParameter> parameters, VariableContainer sourceContainer, BiConsumer<String, Object> targetVariableConsumer,
BiConsumer<String, Object> targetTransientVariableConsumer, ExpressionManager expressionManager, String parameterType) {
if (parameters == null || parameters.isEmpty()) {
return;
}
for (IOParameter parameter : parameters) {
Object value;
if (StringUtils.isNotEmpty(parameter.getSourceExpression())) {
Expression expression = expressionManager.createExpression(parameter.getSourceExpression().trim());
value = expression.getValue(sourceContainer);
} else {
value = sourceContainer.getVariable(parameter.getSource());
}
if (value != null) {
value = JsonUtil.deepCopyIfJson(value);
}
String variableName = null;
if (StringUtils.isNotEmpty(parameter.getTargetExpression())) {
Expression expression = expressionManager.createExpression(parameter.getTargetExpression());
Object variableNameValue = expression.getValue(sourceContainer);
|
if (variableNameValue != null) {
variableName = variableNameValue.toString();
} else {
LOGGER.warn("{} parameter target expression {} did not resolve to a variable name, this is most likely a programmatic error",
parameterType, parameter.getTargetExpression());
}
} else if (StringUtils.isNotEmpty(parameter.getTarget())) {
variableName = parameter.getTarget();
}
if (parameter.isTransient()) {
targetTransientVariableConsumer.accept(variableName, value);
} else {
targetVariableConsumer.accept(variableName, value);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\IOParameterUtil.java
| 1
|
请完成以下Java代码
|
private char associativity(char ch) {
if (ch == '^')
return 'R';
return 'L';
}
public String infixToPostfix(String infix) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
if (isOperand(ch)) {
result.append(ch);
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
|
}
stack.pop();
} else {
while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) {
result.append(stack.pop());
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.toString();
}
private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) {
return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L';
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-operators-3\src\main\java\com\baeldung\infixpostfix\InfixToPostFixExpressionConversion.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class Jackson2JsonpMapperConfiguration {
@Bean
JacksonJsonpMapper jacksonJsonpMapper() {
return new JacksonJsonpMapper();
}
}
@ConditionalOnMissingBean(JsonpMapper.class)
@ConditionalOnBean(Jsonb.class)
@Configuration(proxyBeanMethods = false)
static class JsonbJsonpMapperConfiguration {
@Bean
JsonbJsonpMapper jsonbJsonpMapper(Jsonb jsonb) {
return new JsonbJsonpMapper(JsonProvider.provider(), jsonb);
}
}
@ConditionalOnMissingBean(JsonpMapper.class)
@Configuration(proxyBeanMethods = false)
static class SimpleJsonpMapperConfiguration {
@Bean
SimpleJsonpMapper simpleJsonpMapper() {
return new SimpleJsonpMapper();
}
}
@Configuration(proxyBeanMethods = false)
|
@ConditionalOnMissingBean(ElasticsearchTransport.class)
static class ElasticsearchTransportConfiguration {
@Bean
Rest5ClientTransport restClientTransport(Rest5Client restClient, JsonpMapper jsonMapper,
ObjectProvider<Rest5ClientOptions> restClientOptions) {
return new Rest5ClientTransport(restClient, jsonMapper, restClientOptions.getIfAvailable());
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ElasticsearchTransport.class)
static class ElasticsearchClientConfiguration {
@Bean
@ConditionalOnMissingBean
ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) {
return new ElasticsearchClient(transport);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchClientConfigurations.java
| 2
|
请完成以下Java代码
|
public Builder putAll(final ListMultimap<String, ICalloutInstance> calloutsByColumn)
{
if (calloutsByColumn == null || calloutsByColumn.isEmpty())
{
return this;
}
for (final Entry<String, ICalloutInstance> entry : calloutsByColumn.entries())
{
put(entry.getKey(), entry.getValue());
}
return this;
}
public Builder putAll(final Map<String, List<ICalloutInstance>> calloutsByColumn)
{
if (calloutsByColumn == null || calloutsByColumn.isEmpty())
{
return this;
}
for (final Entry<String, List<ICalloutInstance>> entry : calloutsByColumn.entrySet())
{
final List<ICalloutInstance> callouts = entry.getValue();
if (callouts == null || callouts.isEmpty())
{
continue;
}
final String columnName = entry.getKey();
for (final ICalloutInstance callout : callouts)
{
put(columnName, callout);
|
}
}
return this;
}
public Builder putAll(final TableCalloutsMap callouts)
{
if (callouts == null || callouts.isEmpty())
{
return this;
}
putAll(callouts.calloutsByColumn);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\TableCalloutsMap.java
| 1
|
请完成以下Java代码
|
Evaluation evaluate() {
return network.evaluate(dataSetService.testIterator());
}
private ConvolutionLayer conv5x5() {
return new ConvolutionLayer.Builder(5, 5)
.nIn(3)
.nOut(16)
.stride(1, 1)
.padding(1, 1)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private SubsamplingLayer pooling2x2Stride2() {
return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2)
.stride(2, 2)
.build();
}
private ConvolutionLayer conv3x3Stride1Padding2() {
return new ConvolutionLayer.Builder(3, 3)
.nOut(32)
.stride(1, 1)
.padding(2, 2)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private SubsamplingLayer pooling2x2Stride1() {
return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2)
.stride(1, 1)
.build();
}
|
private ConvolutionLayer conv3x3Stride1Padding1() {
return new ConvolutionLayer.Builder(3, 3)
.nOut(64)
.stride(1, 1)
.padding(1, 1)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private OutputLayer dense() {
return new OutputLayer.Builder(LossFunctions.LossFunction.MEAN_SQUARED_LOGARITHMIC_ERROR)
.activation(Activation.SOFTMAX)
.weightInit(WeightInit.XAVIER_UNIFORM)
.nOut(dataSetService.labels().size() - 1)
.build();
}
}
|
repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\deeplearning4j\cnn\CnnModel.java
| 1
|
请完成以下Java代码
|
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
/** Get Lager.
@return Lager oder Ort für Dienstleistung
*/
@Override
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lagerzuordnung.
@param M_Warehouse_Routing_ID Lagerzuordnung */
@Override
public void setM_Warehouse_Routing_ID (int M_Warehouse_Routing_ID)
{
if (M_Warehouse_Routing_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, Integer.valueOf(M_Warehouse_Routing_ID));
}
/** Get Lagerzuordnung.
@return Lagerzuordnung */
@Override
public int getM_Warehouse_Routing_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Routing_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_M_Warehouse_Routing.java
| 1
|
请完成以下Java代码
|
public void setVesselName (final @Nullable java.lang.String VesselName)
{
throw new IllegalArgumentException ("VesselName is virtual column"); }
@Override
public java.lang.String getVesselName()
{
return get_ValueAsString(COLUMNNAME_VesselName);
}
@Override
public void setExternalHeaderId (final @Nullable String ExternalHeaderId)
{
set_Value (COLUMNNAME_ExternalHeaderId, ExternalHeaderId);
}
@Override
public String getExternalHeaderId()
{
return get_ValueAsString(COLUMNNAME_ExternalHeaderId);
}
@Override
public void setExternalLineId (final @Nullable String ExternalLineId)
{
set_Value (COLUMNNAME_ExternalLineId, ExternalLineId);
}
@Override
public String getExternalLineId()
{
return get_ValueAsString(COLUMNNAME_ExternalLineId);
|
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public AdminUser updateTokenAndLogin(String userName, String password) {
AdminUser adminUser = adminUserDao.getAdminUserByUserNameAndPassword(userName, MD5Util.MD5Encode(password, "UTF-8"));
if (adminUser != null) {
//登录后即执行修改token的操作
String token = getNewToken(System.currentTimeMillis() + "", adminUser.getId());
if (adminUserDao.updateUserToken(adminUser.getId(), token) > 0) {
//返回数据时带上token
adminUser.setUserToken(token);
return adminUser;
}
}
return null;
}
/**
* 获取token值
*
* @param sessionId
* @param userId
* @return
*/
private String getNewToken(String sessionId, Long userId) {
String src = sessionId + userId + NumberUtil.genRandomNum(4);
return SystemUtil.genToken(src);
}
@Override
public AdminUser selectById(Long id) {
return adminUserDao.getAdminUserById(id);
}
@Override
public AdminUser selectByUserName(String userName) {
return adminUserDao.getAdminUserByUserName(userName);
}
|
@Override
public int save(AdminUser user) {
//密码加密
user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
return adminUserDao.addUser(user);
}
@Override
public int updatePassword(AdminUser user) {
return adminUserDao.updateUserPassword(user.getId(), MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
}
@Override
public int deleteBatch(Integer[] ids) {
return adminUserDao.deleteBatch(ids);
}
@Override
public AdminUser getAdminUserByToken(String userToken) {
return adminUserDao.getAdminUserByToken(userToken);
}
}
|
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\service\impl\AdminUserServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@ApiModelProperty(value = "Can be any arbitrary value. When a valid formatted media-type (e.g. application/xml, text/plain) is included, the binary content HTTP response content-type will be set the given value.")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
@ApiModelProperty(value = "contentUrl:In case the attachment is a link to an external resource, the externalUrl contains the URL to the external content. If the attachment content is present in the Flowable engine, the contentUrl will contain an URL where the binary content can be streamed from.")
|
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getContentUrl() {
return contentUrl;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\AttachmentResponse.java
| 2
|
请完成以下Java代码
|
public class CustomerFacetHandler implements PickingJobFacetHandler
{
@Override
public PickingJobFacetGroup getHandledGroup() {return PickingJobFacetGroup.CUSTOMER;}
@Override
public boolean isMatching(@NonNull final PickingJobFacet facet, @NonNull final PickingJobQuery.Facets queryFacets)
{
return queryFacets.getCustomerIds().contains(facet.asType(CustomerFacet.class).getBpartnerId());
}
@Override
public void collectHandled(final PickingJobQuery.Facets.FacetsBuilder collector, final PickingJobQuery.Facets from)
{
collector.customerIds(from.getCustomerIds());
}
@Override
public void collectFromFacetId(@NonNull final PickingJobQuery.Facets.FacetsBuilder collector, @NonNull WorkflowLaunchersFacetId facetId)
{
collector.customerId(facetId.getAsId(BPartnerId.class));
}
@Override
public WorkflowLaunchersFacetGroup toWorkflowLaunchersFacetGroup(@NonNull final PickingJobFacets facets)
{
return WorkflowLaunchersFacetGroup.builder()
.id(PickingJobFacetGroup.CUSTOMER.getWorkflowGroupFacetId())
.caption(TranslatableStrings.adRefList(PickingJobFacetGroup.PICKING_JOB_FILTER_OPTION_REFERENCE_ID, PickingJobFacetGroup.CUSTOMER))
.facets(facets.toList(CustomerFacet.class, CustomerFacetHandler::toWorkflowLaunchersFacet))
.build();
|
}
@NonNull
private static WorkflowLaunchersFacet toWorkflowLaunchersFacet(@NonNull final CustomerFacet facet)
{
return WorkflowLaunchersFacet.builder()
.facetId(WorkflowLaunchersFacetId.ofId(PickingJobFacetGroup.CUSTOMER.getWorkflowGroupFacetId(), facet.getBpartnerId()))
.caption(TranslatableStrings.anyLanguage(facet.getCustomerBPValue() + " " + facet.getCustomerName()))
.isActive(facet.isActive())
.build();
}
@Override
public List<CustomerFacet> extractFacets(@NonNull final Packageable packageable, @NonNull final CollectingParameters parameters)
{
return ImmutableList.of(
CustomerFacet.of(
false,
packageable.getCustomerId(),
packageable.getCustomerBPValue(),
packageable.getCustomerName())
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\facets\customer\CustomerFacetHandler.java
| 1
|
请完成以下Java代码
|
public Object getBean() {
if (this.invokerHandlerMethod != null) {
return this.invokerHandlerMethod.getBean();
}
else {
Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getBean();
}
}
/**
* Return true if any handler method has an async reply type.
* @return the asyncReply.
* @since 2.2.21
*/
public boolean isAsyncReplies() {
return this.asyncReplies;
}
|
/**
* Build an {@link InvocationResult} for the result and inbound payload.
* @param result the result.
* @param inboundPayload the payload.
* @return the invocation result.
* @since 2.1.7
*/
public @Nullable InvocationResult getInvocationResultFor(Object result, Object inboundPayload) {
if (this.invokerHandlerMethod != null) {
return new InvocationResult(result, null, this.invokerHandlerMethod.getMethod().getGenericReturnType(),
this.invokerHandlerMethod.getBean(), this.invokerHandlerMethod.getMethod());
}
else {
Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getInvocationResultFor(result, inboundPayload);
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\HandlerAdapter.java
| 1
|
请完成以下Java代码
|
public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(FunctionDefinition.class, DMN_ELEMENT_FUNCTION_DEFINITION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<FunctionDefinition>() {
public FunctionDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new FunctionDefinitionImpl(instanceContext);
|
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
formalParameterCollection = sequenceBuilder.elementCollection(FormalParameter.class)
.build();
expressionChild = sequenceBuilder.element(Expression.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\FunctionDefinitionImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String, String> updateAvatar(MultipartFile multipartFile) {
// 文件大小验证
FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
// 验证文件上传的格式
String image = "gif jpg png jpeg";
String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
if(fileType != null && !image.contains(fileType)){
throw new BadRequestException("文件格式错误!, 仅支持 " + image +" 格式");
}
User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
String oldPath = user.getAvatarPath();
File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
user.setAvatarPath(Objects.requireNonNull(file).getPath());
user.setAvatarName(file.getName());
userRepository.save(user);
if (StringUtils.isNotBlank(oldPath)) {
FileUtil.del(oldPath);
}
@NotBlank String username = user.getUsername();
flushCache(username);
return new HashMap<String, String>(1) {{
put("avatar", file.getName());
}};
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateEmail(String username, String email) {
userRepository.updateEmail(username, email);
flushCache(username);
}
@Override
public void download(List<UserDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (UserDto userDTO : queryAll) {
List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList());
Map<String, Object> map = new LinkedHashMap<>();
map.put("用户名", userDTO.getUsername());
map.put("角色", roles);
|
map.put("部门", userDTO.getDept().getName());
map.put("岗位", userDTO.getJobs().stream().map(JobSmallDto::getName).collect(Collectors.toList()));
map.put("邮箱", userDTO.getEmail());
map.put("状态", userDTO.getEnabled() ? "启用" : "禁用");
map.put("手机号码", userDTO.getPhone());
map.put("修改密码的时间", userDTO.getPwdResetTime());
map.put("创建日期", userDTO.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
/**
* 清理缓存
*
* @param id /
*/
public void delCaches(Long id, String username) {
redisUtils.del(CacheKey.USER_ID + id);
flushCache(username);
}
/**
* 清理 登陆时 用户缓存信息
*
* @param username /
*/
private void flushCache(String username) {
userCacheManager.cleanUserCache(username);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\UserServiceImpl.java
| 2
|
请完成以下Java代码
|
public ResponseEntity<PageResult<RoleDto>> queryRole(RoleQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(roleService.queryAll(criteria,pageable),HttpStatus.OK);
}
@ApiOperation("获取用户级别")
@GetMapping(value = "/level")
public ResponseEntity<Object> getRoleLevel(){
return new ResponseEntity<>(Dict.create().set("level", getLevels(null)),HttpStatus.OK);
}
@Log("新增角色")
@ApiOperation("新增角色")
@PostMapping
@PreAuthorize("@el.check('roles:add')")
public ResponseEntity<Object> createRole(@Validated @RequestBody Role resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
getLevels(resources.getLevel());
roleService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改角色")
@ApiOperation("修改角色")
@PutMapping
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateRole(@Validated(Role.Update.class) @RequestBody Role resources){
getLevels(resources.getLevel());
roleService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("修改角色菜单")
@ApiOperation("修改角色菜单")
@PutMapping(value = "/menu")
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateRoleMenu(@RequestBody Role resources){
RoleDto role = roleService.findById(resources.getId());
|
getLevels(role.getLevel());
roleService.updateMenu(resources,role);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除角色")
@ApiOperation("删除角色")
@DeleteMapping
@PreAuthorize("@el.check('roles:del')")
public ResponseEntity<Object> deleteRole(@RequestBody Set<Long> ids){
for (Long id : ids) {
RoleDto role = roleService.findById(id);
getLevels(role.getLevel());
}
// 验证是否被用户关联
roleService.verification(ids);
roleService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* 获取用户的角色级别
* @return /
*/
private int getLevels(Integer level){
List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
int min = Collections.min(levels);
if(level != null){
if(level < min){
throw new BadRequestException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + level);
}
}
return min;
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\RoleController.java
| 1
|
请完成以下Java代码
|
public void setM_Package_HU_ID (final int M_Package_HU_ID)
{
if (M_Package_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, M_Package_HU_ID);
}
@Override
public int getM_Package_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_HU_ID);
}
@Override
public org.compiere.model.I_M_Package getM_Package()
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(final org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
@Override
public void setM_Package_ID (final int M_Package_ID)
{
if (M_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_M_Package_ID, M_Package_ID);
}
@Override
public int getM_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_ID);
}
@Override
public void setM_PickingSlot_ID (final int M_PickingSlot_ID)
{
if (M_PickingSlot_ID < 1)
set_Value (COLUMNNAME_M_PickingSlot_ID, null);
else
set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID);
}
@Override
public int getM_PickingSlot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Package_HU.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setMaxInboundMessageSize(final DataSize maxInboundMessageSize) {
if (maxInboundMessageSize == null || maxInboundMessageSize.toBytes() >= 0) {
this.maxInboundMessageSize = maxInboundMessageSize;
} else if (maxInboundMessageSize.toBytes() == -1) {
this.maxInboundMessageSize = DataSize.ofBytes(Integer.MAX_VALUE);
} else {
throw new IllegalArgumentException("Unsupported maxInboundMessageSize: " + maxInboundMessageSize);
}
}
/**
* Sets the maximum metadata size allowed to be received by the server. If not set ({@code null}) then it will
* default to {@link GrpcUtil#DEFAULT_MAX_HEADER_LIST_SIZE gRPC's default}. If set to {@code -1} then it will use
* the highest possible limit (not recommended).
*
|
* @param maxInboundMetadataSize The new maximum size allowed for incoming metadata. {@code -1} for max possible.
* Null to use the gRPC's default.
*
* @see ServerBuilder#maxInboundMetadataSize(int)
*/
public void setMaxInboundMetadataSize(final DataSize maxInboundMetadataSize) {
if (maxInboundMetadataSize == null || maxInboundMetadataSize.toBytes() >= 0) {
this.maxInboundMetadataSize = maxInboundMetadataSize;
} else if (maxInboundMetadataSize.toBytes() == -1) {
this.maxInboundMetadataSize = DataSize.ofBytes(Integer.MAX_VALUE);
} else {
throw new IllegalArgumentException("Unsupported maxInboundMetadataSize: " + maxInboundMetadataSize);
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\config\GrpcServerProperties.java
| 2
|
请完成以下Java代码
|
public abstract class PvmAtomicOperationActivityInstanceStart extends AbstractPvmEventAtomicOperation {
@Override
protected PvmExecutionImpl eventNotificationsStarted(PvmExecutionImpl execution) {
execution.incrementSequenceCounter();
execution.activityInstanceStarting();
execution.enterActivityInstance();
execution.setTransition(null);
return execution;
}
protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
// hack around execution tree structure not being in sync with activity instance concept:
|
// if we start a scope activity, remember current activity instance in parent
PvmExecutionImpl parent = execution.getParent();
PvmActivity activity = execution.getActivity();
if(parent != null && execution.isScope() && activity.isScope() && canHaveChildScopes(execution)) {
parent.setActivityInstanceId(execution.getActivityInstanceId());
}
}
protected boolean canHaveChildScopes(PvmExecutionImpl execution) {
PvmActivity activity = execution.getActivity();
return activity.getActivityBehavior() instanceof CompositeActivityBehavior
|| CompensationBehavior.isCompensationThrowing(execution);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInstanceStart.java
| 1
|
请完成以下Java代码
|
public PageData<DeviceIdInfo> findDeviceIdInfos(Pageable pageable) {
String DEVICE_ID_INFO_QUERY = "SELECT tenant_id as tenantId, customer_id as customerId, id as id FROM device ORDER BY created_time ASC LIMIT %s OFFSET %s";
return find(COUNT_QUERY, DEVICE_ID_INFO_QUERY, pageable, row -> {
UUID id = (UUID) row.get("id");
var tenantIdObj = row.get("tenantId");
var customerIdObj = row.get("customerId");
return new DeviceIdInfo(tenantIdObj != null ? (UUID) tenantIdObj : TenantId.SYS_TENANT_ID.getId(), customerIdObj != null ? (UUID) customerIdObj : null, id);
});
}
@Override
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfos(Pageable pageable) {
String PROFILE_DEVICE_ID_INFO_QUERY = "SELECT tenant_id as tenantId, customer_id as customerId, device_profile_id as profileId, id as id FROM device ORDER BY created_time ASC LIMIT %s OFFSET %s";
return find(COUNT_QUERY, PROFILE_DEVICE_ID_INFO_QUERY, pageable, DefaultNativeDeviceRepository::toInfo);
}
@Override
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, Pageable pageable) {
|
String PROFILE_DEVICE_ID_INFO_QUERY = String.format("SELECT tenant_id as tenantId, customer_id as customerId, device_profile_id as profileId, id as id FROM device WHERE tenant_id = '%s' ORDER BY created_time ASC LIMIT %%s OFFSET %%s", tenantId);
return find(COUNT_QUERY, PROFILE_DEVICE_ID_INFO_QUERY, pageable, DefaultNativeDeviceRepository::toInfo);
}
private static ProfileEntityIdInfo toInfo(Map<String, Object> row) {
var tenantIdObj = row.get("tenantId");
UUID tenantId = tenantIdObj != null ? (UUID) tenantIdObj : TenantId.SYS_TENANT_ID.getId();
DeviceId id = new DeviceId((UUID) row.get("id"));
CustomerId customerId = new CustomerId((UUID) row.get("customerId"));
EntityId ownerId = !customerId.isNullUid() ? customerId : TenantId.fromUUID(tenantId);
DeviceProfileId profileId = new DeviceProfileId((UUID) row.get("profileId"));
return ProfileEntityIdInfo.create(tenantId, ownerId, profileId, id);
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\DefaultNativeDeviceRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysMessageService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysMessage sysMessage = sysMessageService.getById(id);
return Result.ok(sysMessage);
}
/**
* 导出excel
*
* @param request
*/
@GetMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysMessage sysMessage) {
|
return super.exportXls(request,sysMessage,SysMessage.class, "推送消息模板");
}
/**
* excel导入
*
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importExcel")
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysMessage.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\controller\SysMessageController.java
| 2
|
请完成以下Java代码
|
public class WFEventAudit
{
int id;
@NonNull
WFEventAuditType eventType;
@Builder.Default
@NonNull
final OrgId orgId = OrgId.ANY;
final WFProcessId wfProcessId;
@Nullable
final WFNodeId wfNodeId;
@NonNull
final TableRecordReference documentRef;
@NonNull
final WFResponsibleId wfResponsibleId;
@Nullable
UserId userId;
|
@NonNull
WFState wfState;
@Nullable
String textMsg;
@NonNull
@Builder.Default
Instant created = SystemTime.asInstant();
@NonNull
@Builder.Default
Duration elapsedTime = Duration.ZERO;
@Nullable
String attributeName;
@Nullable
String attributeValueOld;
@Nullable
String attributeValueNew;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFEventAudit.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WSService implements BpmnInterfaceImplementation {
protected String name;
protected String location;
protected Map<String, WSOperation> operations;
protected String wsdlLocation;
protected SyncWebServiceClient client;
public WSService(String name, String location, String wsdlLocation) {
this.name = name;
this.location = location;
this.operations = new HashMap<String, WSOperation>();
this.wsdlLocation = wsdlLocation;
}
public WSService(String name, String location, SyncWebServiceClient client) {
this.name = name;
this.location = location;
this.operations = new HashMap<String, WSOperation>();
this.client = client;
}
public void addOperation(WSOperation operation) {
|
this.operations.put(operation.getName(), operation);
}
SyncWebServiceClient getClient() {
if (this.client == null) {
// TODO refactor to use configuration
SyncWebServiceClientFactory factory = (SyncWebServiceClientFactory) ReflectUtil.instantiate(
ProcessEngineConfigurationImpl.DEFAULT_WS_SYNC_FACTORY
);
this.client = factory.create(this.wsdlLocation);
}
return this.client;
}
/**
* {@inheritDoc}
*/
public String getName() {
return this.name;
}
public String getLocation() {
return this.location;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\webservice\WSService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void handleEvent(@NonNull final MSV3UserChangedBatchEvent batchEvent)
{
final String mfSyncToken = batchEvent.getId();
//
// Update/Delete
{
final AtomicInteger countUpdated = new AtomicInteger();
for (final MSV3UserChangedEvent event : batchEvent.getEvents())
{
handleEvent(event, mfSyncToken);
countUpdated.incrementAndGet();
}
logger.debug("Updated/Deleted {} users", countUpdated);
}
//
// Delete
if (batchEvent.isDeleteAllOtherUsers())
{
final long countDeleted = usersRepo.deleteInBatchByMfSyncTokenNot(mfSyncToken);
logger.debug("Deleted {} users", countDeleted);
}
}
private void handleEvent(@NonNull final MSV3UserChangedEvent event, final String mfSyncToken)
{
if (event.getChangeType() == ChangeType.CREATED_OR_UPDATED)
{
final String username = event.getUsername();
JpaUser user = usersRepo.findByMfMSV3UserId(event.getMsv3MetasfreshUserId().getId());
if (user == null)
{
|
user = new JpaUser();
user.setMfMSV3UserId(event.getMsv3MetasfreshUserId().getId());
}
user.setMfUsername(username);
user.setMfPassword(event.getPassword());
user.setMfBpartnerId(event.getBpartnerId());
user.setMfBpartnerLocationId(event.getBpartnerLocationId());
user.setMfSyncToken(mfSyncToken);
usersRepo.save(user);
}
else if (event.getChangeType() == ChangeType.DELETED)
{
usersRepo.deleteByMfMSV3UserId(event.getMsv3MetasfreshUserId().getId());
}
else
{
throw new IllegalArgumentException("Unknown change type: " + event);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\security\MSV3ServerAuthenticationService.java
| 2
|
请完成以下Java代码
|
public String toBooleanString()
{
return StringUtils.ofBoolean(toBooleanOrNull());
}
public void ifPresent(@NonNull final BooleanConsumer action)
{
if (this == TRUE)
{
action.accept(true);
}
else if (this == FALSE)
{
action.accept(false);
}
|
}
public void ifTrue(@NonNull final Runnable action)
{
if (this == TRUE)
{
action.run();
}
}
public <U> Optional<U> map(@NonNull final BooleanFunction<? extends U> mapper)
{
return isPresent() ? Optional.ofNullable(mapper.apply(isTrue())) : Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalBoolean.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the versionNum property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersionNum() {
return versionNum;
}
/**
* Sets the value of the versionNum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersionNum(String value) {
this.versionNum = value;
}
/**
* Gets the value of the serviceCodeListDirVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceCodeListDirVersion() {
return serviceCodeListDirVersion;
}
/**
* Sets the value of the serviceCodeListDirVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceCodeListDirVersion(String value) {
this.serviceCodeListDirVersion = value;
}
/**
* Gets the value of the codedCharacterEncoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodedCharacterEncoding() {
return codedCharacterEncoding;
}
/**
* Sets the value of the codedCharacterEncoding property.
*
* @param value
* allowed object is
|
* {@link String }
*
*/
public void setCodedCharacterEncoding(String value) {
this.codedCharacterEncoding = value;
}
/**
* Gets the value of the releaseNum property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReleaseNum() {
return releaseNum;
}
/**
* Sets the value of the releaseNum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReleaseNum(String value) {
this.releaseNum = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SyntaxIdentifierType.java
| 2
|
请完成以下Java代码
|
public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) {
log.trace("[{}] Received RPC command to device", sessionId);
this.rpcHandler.onToDeviceRpcRequest(toDeviceRequest, this.sessionInfo);
}
@Override
public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) {
this.rpcHandler.onToServerRpcResponse(toServerResponse);
}
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
log.info("[{}] operationComplete", future);
}
@Override
public void onResourceUpdate(TransportProtos.ResourceUpdateMsg resourceUpdateMsgOpt) {
if (ResourceType.LWM2M_MODEL.name().equals(resourceUpdateMsgOpt.getResourceType())) {
this.handler.onResourceUpdate(resourceUpdateMsgOpt);
}
|
}
@Override
public void onResourceDelete(TransportProtos.ResourceDeleteMsg resourceDeleteMsgOpt) {
if (ResourceType.LWM2M_MODEL.name().equals(resourceDeleteMsgOpt.getResourceType())) {
this.handler.onResourceDelete(resourceDeleteMsgOpt);
}
}
@Override
public void onDeviceDeleted(DeviceId deviceId) {
log.trace("[{}] Device on delete", deviceId);
this.handler.onDeviceDelete(deviceId);
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mSessionMsgListener.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.