instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public UUID createOrder(final Product product) {
final Order order = new Order(UUID.randomUUID(), product);
orderRepository.save(order);
return order.getId();
}
@Override
public void addProduct(final UUID id, final Product product) {
final Order order = getOrder(id);
order.addOrder(product);
orderRepository.save(order);
}
@Override
public void completeOrder(final UUID id) {
final Order order = getOrder(id);
|
order.complete();
orderRepository.save(order);
}
@Override
public void deleteProduct(final UUID id, final UUID productId) {
final Order order = getOrder(id);
order.removeOrder(productId);
orderRepository.save(order);
}
private Order getOrder(UUID id) {
return orderRepository
.findById(id)
.orElseThrow(() -> new RuntimeException("Order with given id doesn't exist"));
}
}
|
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\service\DomainOrderService.java
| 2
|
请完成以下Java代码
|
private void addToTabs(final I_AD_Column column)
{
final int adTableId = column.getAD_Table_ID();
queryBL.createQueryBuilder(I_AD_Tab.class, column)
.addEqualsFilter(I_AD_Tab.COLUMNNAME_AD_Table_ID, adTableId)
.create()
.stream(I_AD_Tab.class)
.forEach(tab -> createAD_Field(tab, column));
}
private void createAD_Field(final I_AD_Tab tab, final I_AD_Column column)
{
final String fieldEntityType = null; // auto
final I_AD_Field field;
try
{
final boolean displayedIfNotIDColumn = true; // actually doesn't matter because PK probably is an ID column anyways
|
field = AD_Tab_CreateFields.createADField(tab, column, displayedIfNotIDColumn, fieldEntityType);
// log
final I_AD_Window window = tab.getAD_Window();
addLog("@Created@ " + window + " -> " + tab + " -> " + field);
}
catch (final Exception ex)
{
logger.warn("Failed creating AD_Field for {} in {}", column, tab, ex);
addLog("@Error@ creating AD_Field for {} in {}: {}", column, tab, ex.getLocalizedMessage());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\TablePrimaryKeyGenerator.java
| 1
|
请完成以下Java代码
|
public Quantity subtractFrom(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.subtract(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.subtract(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
|
public IssuingToleranceSpec convertQty(@NonNull final UnaryOperator<Quantity> qtyConverter)
{
if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qtyConv = qtyConverter.apply(qty);
if (qtyConv.equals(qty))
{
return this;
}
return toBuilder().qty(qtyConv).build();
}
else
{
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IssuingToleranceSpec.java
| 1
|
请完成以下Java代码
|
public static List<DictModel> getDictList(){
List<DictModel> list = new ArrayList<>();
DictModel dictModel = null;
for(RangeDateEnum e: RangeDateEnum.values()){
dictModel = new DictModel();
dictModel.setValue(e.key);
dictModel.setText(e.title);
list.add(dictModel);
}
return list;
}
/**
* 根据key 获取范围时间值
* @param key
* @return
*/
public static Date[] getRangeArray(String key){
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
Date[] array = new Date[2];
boolean flag = false;
if(JT.key.equals(key)){
//今天
} else if(ZT.key.equals(key)){
//昨天
calendar1.add(Calendar.DAY_OF_YEAR, -1);
calendar2.add(Calendar.DAY_OF_YEAR, -1);
} else if(QT.key.equals(key)){
//前天
calendar1.add(Calendar.DAY_OF_YEAR, -2);
calendar2.add(Calendar.DAY_OF_YEAR, -2);
} else if(BZ.key.equals(key)){
//本周
calendar1.set(Calendar.DAY_OF_WEEK, 2);
calendar2.add(Calendar.WEEK_OF_MONTH,1);
calendar2.add(Calendar.DAY_OF_WEEK,-1);
} else if(SZ.key.equals(key)){
//本周一减一周
calendar1.set(Calendar.DAY_OF_WEEK, 2);
calendar1.add(Calendar.WEEK_OF_MONTH, -1);
// 本周一减一天
calendar2.set(Calendar.DAY_OF_WEEK, 2);
calendar2.add(Calendar.DAY_OF_WEEK,-1);
} else if(BY.key.equals(key)){
//本月
calendar1.set(Calendar.DAY_OF_MONTH, 1);
calendar2.set(Calendar.DAY_OF_MONTH, 1);
calendar2.add(Calendar.MONTH, 1);
|
calendar2.add(Calendar.DAY_OF_MONTH, -1);
} else if(SY.key.equals(key)){
//本月第一天减一月
calendar1.set(Calendar.DAY_OF_MONTH, 1);
calendar1.add(Calendar.MONTH, -1);
//本月第一天减一天
calendar2.set(Calendar.DAY_OF_MONTH, 1);
calendar2.add(Calendar.DAY_OF_MONTH, -1);
} else if (SEVENDAYS.key.equals(key)){
//七日第一天
calendar1.setTime(new Date());
calendar1.add(Calendar.DATE, -7);
}else{
flag = true;
}
if(flag){
return null;
}
// 开始时间00:00:00 结束时间23:59:59
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
calendar2.set(Calendar.HOUR, 23);
calendar2.set(Calendar.MINUTE, 59);
calendar2.set(Calendar.SECOND, 59);
calendar2.set(Calendar.MILLISECOND, 999);
array[0] = calendar1.getTime();
array[1] = calendar2.getTime();
return array;
}
public String getKey(){
return this.key;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\enums\RangeDateEnum.java
| 1
|
请完成以下Java代码
|
public class Person implements KryoSerializable {
private String name = "John Doe";
private int age = 18;
private Date birthDate = new Date(933191282821L);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
|
@Override
public void write(Kryo kryo, Output output) {
output.writeString(name);
output.writeLong(birthDate.getTime());
output.writeInt(age);
}
@Override
public void read(Kryo kryo, Input input) {
name = input.readString();
birthDate = new Date(input.readLong());
age = input.readInt();
}
}
|
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\libraries\kryo\Person.java
| 1
|
请完成以下Java代码
|
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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 Benchmark Data.
@param PA_BenchmarkData_ID
Performance Benchmark Data Point
*/
public void setPA_BenchmarkData_ID (int PA_BenchmarkData_ID)
{
if (PA_BenchmarkData_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, Integer.valueOf(PA_BenchmarkData_ID));
}
/** Get Benchmark Data.
@return Performance Benchmark Data Point
*/
public int getPA_BenchmarkData_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_BenchmarkData_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Benchmark getPA_Benchmark() throws RuntimeException
{
return (I_PA_Benchmark)MTable.get(getCtx(), I_PA_Benchmark.Table_Name)
.getPO(getPA_Benchmark_ID(), get_TrxName()); }
/** Set Benchmark.
@param PA_Benchmark_ID
Performance Benchmark
*/
public void setPA_Benchmark_ID (int PA_Benchmark_ID)
{
if (PA_Benchmark_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID));
}
/** Get Benchmark.
@return Performance Benchmark
*/
public int getPA_Benchmark_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_BenchmarkData.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Kursart (default).
@param C_ConversionType_Default_ID Kursart (default) */
@Override
public void setC_ConversionType_Default_ID (int C_ConversionType_Default_ID)
{
if (C_ConversionType_Default_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ConversionType_Default_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ConversionType_Default_ID, Integer.valueOf(C_ConversionType_Default_ID));
}
/** Get Kursart (default).
@return Kursart (default) */
@Override
public int getC_ConversionType_Default_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_Default_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ConversionType getC_ConversionType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class);
}
@Override
public void setC_ConversionType(org.compiere.model.I_C_ConversionType C_ConversionType)
{
set_ValueFromPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class, C_ConversionType);
}
/** Set Kursart.
@param C_ConversionType_ID
Kursart
*/
@Override
public void setC_ConversionType_ID (int C_ConversionType_ID)
{
if (C_ConversionType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, Integer.valueOf(C_ConversionType_ID));
}
/** Get Kursart.
@return Kursart
*/
@Override
|
public int getC_ConversionType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType_Default.java
| 1
|
请完成以下Java代码
|
public void setManual_Check_User_ID (int Manual_Check_User_ID)
{
if (Manual_Check_User_ID < 1)
set_Value (COLUMNNAME_Manual_Check_User_ID, null);
else
set_Value (COLUMNNAME_Manual_Check_User_ID, Integer.valueOf(Manual_Check_User_ID));
}
/** Get Benutzer für manuelle Prüfung.
@return Benutzer für die Benachrichtigung zur manuellen Prüfung
*/
@Override
public int getManual_Check_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Manual_Check_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kennwort.
@param Password Kennwort */
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Kennwort.
@return Kennwort */
@Override
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Grund der Anfrage.
@param RequestReason Grund der Anfrage */
@Override
public void setRequestReason (java.lang.String RequestReason)
{
set_Value (COLUMNNAME_RequestReason, RequestReason);
}
/** Get Grund der Anfrage.
@return Grund der Anfrage */
@Override
public java.lang.String getRequestReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestReason);
}
/** Set REST API URL.
@param RestApiBaseURL REST API URL */
@Override
public void setRestApiBaseURL (java.lang.String RestApiBaseURL)
{
set_Value (COLUMNNAME_RestApiBaseURL, RestApiBaseURL);
}
/** Get REST API URL.
@return REST API URL */
@Override
public java.lang.String getRestApiBaseURL ()
|
{
return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL);
}
/** Set Creditpass-Prüfung wiederholen .
@param RetryAfterDays Creditpass-Prüfung wiederholen */
@Override
public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays)
{
set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays);
}
/** Get Creditpass-Prüfung wiederholen .
@return Creditpass-Prüfung wiederholen */
@Override
public java.math.BigDecimal getRetryAfterDays ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java
| 1
|
请完成以下Java代码
|
private void cancelDataForExecution(ExecutionEntity executionEntity, String deleteReason) {
boolean isActive = executionEntity.isActive();
deleteExecutionEntity(executionEntity, deleteReason);
cancelUserTask(executionEntity, deleteReason);
if (
isActive &&
executionEntity.getCurrentFlowElement() != null &&
!(executionEntity.getCurrentFlowElement() instanceof UserTask) &&
!(executionEntity.getCurrentFlowElement() instanceof SequenceFlow)
) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createActivityCancelledEvent(executionEntity, deleteReason)
);
}
}
// OTHER METHODS
@Override
public void updateProcessInstanceLockTime(String processInstanceId) {
Date expirationTime = getClock().getCurrentTime();
int lockMillis = getAsyncExecutor().getAsyncJobLockTimeInMillis();
GregorianCalendar lockCal = new GregorianCalendar();
lockCal.setTime(expirationTime);
lockCal.add(Calendar.MILLISECOND, lockMillis);
Date lockDate = lockCal.getTime();
executionDataManager.updateProcessInstanceLockTime(processInstanceId, lockDate, expirationTime);
}
@Override
public void clearProcessInstanceLockTime(String processInstanceId) {
executionDataManager.clearProcessInstanceLockTime(processInstanceId);
}
@Override
public String updateProcessInstanceBusinessKey(ExecutionEntity executionEntity, String businessKey) {
if (executionEntity.isProcessInstanceType() && businessKey != null) {
|
executionEntity.setBusinessKey(businessKey);
getHistoryManager().updateProcessBusinessKeyInHistory(executionEntity);
if (getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, executionEntity)
);
}
return businessKey;
}
return null;
}
public ExecutionDataManager getExecutionDataManager() {
return executionDataManager;
}
public void setExecutionDataManager(ExecutionDataManager executionDataManager) {
this.executionDataManager = executionDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public Quantity of(final int qty, @NonNull final UomId repoId)
{
return of(BigDecimal.valueOf(qty), repoId);
}
@Nullable
public static BigDecimal toBigDecimalOrNull(@Nullable final Quantity quantity)
{
return toBigDecimalOr(quantity, null);
}
@NonNull
public static BigDecimal toBigDecimalOrZero(@Nullable final Quantity quantity)
{
return toBigDecimalOr(quantity, BigDecimal.ZERO);
}
@Contract(value = "null, null -> null; _, !null -> !null; !null, _ -> !null", pure = true)
@Nullable
private static BigDecimal toBigDecimalOr(@Nullable final Quantity quantity, @Nullable final BigDecimal defaultValue)
{
if (quantity == null)
{
return defaultValue;
}
return quantity.toBigDecimal();
}
public static class QuantityDeserializer extends StdDeserializer<Quantity>
{
private static final long serialVersionUID = -5406622853902102217L;
public QuantityDeserializer()
{
super(Quantity.class);
}
@Override
public Quantity deserialize(final JsonParser p, final DeserializationContext ctx) throws IOException
{
final JsonNode node = p.getCodec().readTree(p);
final String qtyStr = node.get("qty").asText();
final int uomRepoId = (Integer)node.get("uomId").numberValue();
final String sourceQtyStr;
final int sourceUomRepoId;
if (node.has("sourceQty"))
{
sourceQtyStr = node.get("sourceQty").asText();
sourceUomRepoId = (Integer)node.get("sourceUomId").numberValue();
}
else
{
sourceQtyStr = qtyStr;
sourceUomRepoId = uomRepoId;
}
return Quantitys.of(
new BigDecimal(qtyStr), UomId.ofRepoId(uomRepoId),
new BigDecimal(sourceQtyStr), UomId.ofRepoId(sourceUomRepoId));
}
}
public static class QuantitySerializer extends StdSerializer<Quantity>
|
{
private static final long serialVersionUID = -8292209848527230256L;
public QuantitySerializer()
{
super(Quantity.class);
}
@Override
public void serialize(final Quantity value, final JsonGenerator gen, final SerializerProvider provider) throws IOException
{
gen.writeStartObject();
final String qtyStr = value.toBigDecimal().toString();
final int uomId = value.getUomId().getRepoId();
gen.writeFieldName("qty");
gen.writeString(qtyStr);
gen.writeFieldName("uomId");
gen.writeNumber(uomId);
final String sourceQtyStr = value.getSourceQty().toString();
final int sourceUomId = value.getSourceUomId().getRepoId();
if (!qtyStr.equals(sourceQtyStr) || uomId != sourceUomId)
{
gen.writeFieldName("sourceQty");
gen.writeString(sourceQtyStr);
gen.writeFieldName("sourceUomId");
gen.writeNumber(sourceUomId);
}
gen.writeEndObject();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantitys.java
| 1
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCurrentDevice() {
return currentDevice;
}
public void setCurrentDevice(String currentDevice) {
|
this.currentDevice = currentDevice;
}
@Override
public String toString() {
return new StringJoiner(", ", User.class.getSimpleName() + "[", "]").add("id=" + id)
.add("email='" + email + "'")
.add("password='" + password + "'")
.add("currentDevice='" + currentDevice + "'")
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof User))
return false;
User user = (User) o;
return email.equals(user.email);
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\ignorable\fields\User.java
| 1
|
请完成以下Java代码
|
public class ConnectorVariableScope extends AbstractVariableScope {
private static final long serialVersionUID = 1L;
protected AbstractVariableScope parent;
protected VariableStore<SimpleVariableInstance> variableStore;
public ConnectorVariableScope(AbstractVariableScope parent) {
this.parent = parent;
this.variableStore = new VariableStore<SimpleVariableInstance>();
}
public String getVariableScopeKey() {
return "connector";
}
protected VariableStore<CoreVariableInstance> getVariableStore() {
return (VariableStore) variableStore;
}
@Override
protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() {
return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE;
}
@Override
protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() {
|
return Collections.emptyList();
}
public AbstractVariableScope getParentVariableScope() {
return parent;
}
public void writeToRequest(ConnectorRequest<?> request) {
for (CoreVariableInstance variable : variableStore.getVariables()) {
request.setRequestParameter(variable.getName(), variable.getTypedValue(true).getValue());
}
}
public void readFromResponse(ConnectorResponse response) {
Map<String, Object> responseParameters = response.getResponseParameters();
for (Entry<String, Object> entry : responseParameters.entrySet()) {
setVariableLocal(entry.getKey(), entry.getValue());
}
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ConnectorVariableScope.java
| 1
|
请完成以下Java代码
|
public void setSubscribeDate (Timestamp SubscribeDate)
{
if (SubscribeDate == null)
SubscribeDate = new Timestamp(System.currentTimeMillis());
log.debug("" + SubscribeDate);
super.setSubscribeDate(SubscribeDate);
super.setOptOutDate(null);
setIsActive(true);
} // setSubscribeDate
/**
* Subscribe
* User action only.
*/
public void subscribe()
{
setSubscribeDate(null);
if (!isActive())
setIsActive(true);
} // subscribe
/**
* Subscribe.
* User action only.
* @param subscribe subscribe
*/
public void subscribe (boolean subscribe)
{
if (subscribe)
setSubscribeDate(null);
else
setOptOutDate(null);
} // subscribe
/**
* Is Subscribed.
* Active is set internally,
* the opt out date is set by the user via the web UI.
* @return true if subscribed
*/
public boolean isSubscribed()
{
return isActive() && getOptOutDate() == null;
} // isSubscribed
/**
* String representation
* @return info
|
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer ("MContactInterest[")
.append("R_InterestArea_ID=").append(getR_InterestArea_ID())
.append(",AD_User_ID=").append(getAD_User_ID())
.append(",Subscribed=").append(isSubscribed())
.append ("]");
return sb.toString ();
} // toString
/**************************************************************************
* @param args ignored
*/
public static void main (String[] args)
{
org.compiere.Adempiere.startup(true);
int R_InterestArea_ID = 1000002;
int AD_User_ID = 1000002;
MContactInterest ci = MContactInterest.get(Env.getCtx(), R_InterestArea_ID, AD_User_ID, false, null);
ci.subscribe();
ci.save();
//
ci = MContactInterest.get(Env.getCtx(), R_InterestArea_ID, AD_User_ID, false, null);
} // main
} // MContactInterest
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContactInterest.java
| 1
|
请完成以下Java代码
|
public void setProcessDef(ProcessDefinitionEntity processDef) {
this.processDef = processDef;
this.processDefId = processDef.getId();
}
public void fireHistoricIdentityLinkEvent(final HistoryEventType eventType) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = processEngineConfiguration.getHistoryLevel();
if(historyLevel.isHistoryEventProduced(eventType, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
HistoryEvent event = null;
if (HistoryEvent.IDENTITY_LINK_ADD.equals(eventType.getEventName())) {
event = producer.createHistoricIdentityLinkAddEvent(IdentityLinkEntity.this);
} else if (HistoryEvent.IDENTITY_LINK_DELETE.equals(eventType.getEventName())) {
event = producer.createHistoricIdentityLinkDeleteEvent(IdentityLinkEntity.this);
}
return event;
}
});
}
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (processDefId != null) {
referenceIdAndClass.put(processDefId, ProcessDefinitionEntity.class);
}
|
if (taskId != null) {
referenceIdAndClass.put(taskId, TaskEntity.class);
}
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", type=" + type
+ ", userId=" + userId
+ ", groupId=" + groupId
+ ", taskId=" + taskId
+ ", processDefId=" + processDefId
+ ", task=" + task
+ ", processDef=" + processDef
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityLinkEntity.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=89
# mybatis
mybatis.type-aliases-package=cn.codesheep.springbt_mybatis_sqlserver.entity
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
## -------------------------------------------------
## SqlServer Դ
spring.datasource.url=jdbc:sqlserver://xxxx:1433;databasename=Ming
|
Li
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=xxxx
spring.datasource.password=xxxx
|
repos\Spring-Boot-In-Action-master\springbt_mybatis_sqlserver\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public IntentEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return innerQuery.count();
}
@Override
public IntentEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return IntentEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
|
public List<IntentEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<IntentEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<IntentEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(IntentEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Selected winners count.
@param RfQ_SelectedWinners_Count Selected winners count */
@Override
public void setRfQ_SelectedWinners_Count (int RfQ_SelectedWinners_Count)
{
throw new IllegalArgumentException ("RfQ_SelectedWinners_Count is virtual column"); }
/** Get Selected winners count.
@return Selected winners count */
@Override
public int getRfQ_SelectedWinners_Count ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_SelectedWinners_Count);
if (ii == null)
|
return 0;
return ii.intValue();
}
/** Set Selected winners Qty.
@param RfQ_SelectedWinners_QtySum Selected winners Qty */
@Override
public void setRfQ_SelectedWinners_QtySum (java.math.BigDecimal RfQ_SelectedWinners_QtySum)
{
throw new IllegalArgumentException ("RfQ_SelectedWinners_QtySum is virtual column"); }
/** Get Selected winners Qty.
@return Selected winners Qty */
@Override
public java.math.BigDecimal getRfQ_SelectedWinners_QtySum ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RfQ_SelectedWinners_QtySum);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Use line quantity.
@param UseLineQty Use line quantity */
@Override
public void setUseLineQty (boolean UseLineQty)
{
set_Value (COLUMNNAME_UseLineQty, Boolean.valueOf(UseLineQty));
}
/** Get Use line quantity.
@return Use line quantity */
@Override
public boolean isUseLineQty ()
{
Object oo = get_Value(COLUMNNAME_UseLineQty);
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.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseProcessDefinitionResource {
@Autowired
protected RestResponseFactory restResponseFactory;
@Autowired
protected RepositoryService repositoryService;
@Autowired(required=false)
protected BpmnRestApiInterceptor restApiInterceptor;
/**
* Returns the {@link ProcessDefinition} that is requested and calls the access interceptor.
* Throws the right exceptions when bad request was made or definition was not found.
*/
protected ProcessDefinition getProcessDefinitionFromRequest(String processDefinitionId) {
ProcessDefinition processDefinition = getProcessDefinitionFromRequestWithoutAccessCheck(processDefinitionId);
if (restApiInterceptor != null) {
restApiInterceptor.accessProcessDefinitionById(processDefinition);
}
|
return processDefinition;
}
/**
* Returns the {@link ProcessDefinition} that is requested without calling the access interceptor
* Throws the right exceptions when bad request was made or definition was not found.
*/
protected ProcessDefinition getProcessDefinitionFromRequestWithoutAccessCheck(String processDefinitionId) {
ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId);
if (processDefinition == null) {
throw new FlowableObjectNotFoundException("Could not find a process definition with id '" + processDefinitionId + "'.", ProcessDefinition.class);
}
return processDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\BaseProcessDefinitionResource.java
| 2
|
请完成以下Java代码
|
protected void setInternalValueNumberInitial(final BigDecimal value)
{
throw new UnsupportedOperationException("Setting initial value not supported");
}
@Override
public boolean isNew()
{
return InterfaceWrapperHelper.isNew(attributeInstance);
}
@Override
protected void setInternalValueDate(Date value)
{
attributeInstance.setValueDate(TimeUtil.asTimestamp(value));
}
@Override
protected Date getInternalValueDate()
{
return attributeInstance.getValueDate();
}
@Override
protected void setInternalValueDateInitial(Date value)
{
throw new UnsupportedOperationException("Setting initial value not supported");
}
@Override
protected Date getInternalValueDateInitial()
{
return null;
}
/**
* @return {@code PROPAGATIONTYPE_NoPropagation}.
*/
@Override
public String getPropagationType()
{
return X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation;
}
/**
* @return {@link NullAggregationStrategy#instance}.
*/
@Override
public IAttributeAggregationStrategy retrieveAggregationStrategy()
{
return NullAggregationStrategy.instance;
}
/**
* @return {@link NullSplitterStrategy#instance}.
*/
@Override
public IAttributeSplitterStrategy retrieveSplitterStrategy()
{
return NullSplitterStrategy.instance;
}
/**
* @return {@link CopyHUAttributeTransferStrategy#instance}.
*/
@Override
|
public IHUAttributeTransferStrategy retrieveTransferStrategy()
{
return CopyHUAttributeTransferStrategy.instance;
}
/**
* @return {@code true}.
*/
@Override
public boolean isReadonlyUI()
{
return true;
}
/**
* @return {@code true}.
*/
@Override
public boolean isDisplayedUI()
{
return true;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
/**
* @return our attribute instance's {@code M_Attribute_ID}.
*/
@Override
public int getDisplaySeqNo()
{
return attributeInstance.getM_Attribute_ID();
}
/**
* @return {@code true}
*/
@Override
public boolean isUseInASI()
{
return true;
}
/**
* @return {@code false}, since no HU-PI attribute is involved.
*/
@Override
public boolean isDefinedByTemplate()
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java
| 1
|
请完成以下Java代码
|
/* package */final class FacetSideAction<ModelType> extends ToggableSideAction
{
public static final <ModelType> FacetSideAction<ModelType> cast(final ISideAction action)
{
Check.assumeNotNull(action, "action not null");
@SuppressWarnings("unchecked")
final FacetSideAction<ModelType> facetAction = (FacetSideAction<ModelType>)action;
return facetAction;
}
private final IFacet<ModelType> facet;
private final ISideActionExecuteDelegate executeDelegate;
public FacetSideAction(final IFacet<ModelType> facet, final ISideActionExecuteDelegate executeDelegate)
{
super(facet.getId());
Check.assumeNotNull(facet, "facet not null");
this.facet = facet;
Check.assumeNotNull(executeDelegate, "executeDelegate not null");
this.executeDelegate = executeDelegate;
}
|
/** @return underlying facet; never returns null */
public final IFacet<ModelType> getFacet()
{
return facet;
}
/** @return underlying facet's ID */
public final String getFacetId()
{
return facet.getId();
}
@Override
public String getDisplayName()
{
return facet.getDisplayName();
}
@Override
public void execute()
{
executeDelegate.execute(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\sideactions\impl\FacetSideAction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){
logger.error("biz exception!the reason is:{}",e.getErrorMsg());
return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
}
/**
* process NUllException
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =NullPointerException.class)
@ResponseBody
public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){
logger.error("null exception!the reason is:",e);
return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
|
}
/**
* unkown Exception
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public ResultBody exceptionHandler(HttpServletRequest req, Exception e){
logger.error("unkown Exception!the reason is:",e);
return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
}
}
|
repos\springboot-demo-master\Exception\src\main\java\com\et\exception\config\GlobalExceptionHandler.java
| 2
|
请完成以下Java代码
|
public <X> JacksonJsonSerde<X> copyWithType(TypeReference<? super X> newTargetType) {
return new JacksonJsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
/**
* Copies this serde with same configuration, except new target java type is used.
* @param newTargetType java type forced for serialization, and used as default for deserialization, not null
* @param <X> new deserialization result type and serialization source type
* @return new instance of serde with type changes
*/
public <X> JacksonJsonSerde<X> copyWithType(JavaType newTargetType) {
return new JacksonJsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
// Fluent API
/**
* Designate this Serde for serializing/deserializing keys (default is values).
* @return the serde.
*/
public JacksonJsonSerde<T> forKeys() {
this.jsonSerializer.forKeys();
this.jsonDeserializer.forKeys();
return this;
}
/**
* Configure the serializer to not add type information.
* @return the serde.
*/
public JacksonJsonSerde<T> noTypeInfo() {
this.jsonSerializer.noTypeInfo();
return this;
}
/**
|
* Don't remove type information headers after deserialization.
* @return the serde.
*/
public JacksonJsonSerde<T> dontRemoveTypeHeaders() {
this.jsonDeserializer.dontRemoveTypeHeaders();
return this;
}
/**
* Ignore type information headers and use the configured target class.
* @return the serde.
*/
public JacksonJsonSerde<T> ignoreTypeHeaders() {
this.jsonDeserializer.ignoreTypeHeaders();
return this;
}
/**
* Use the supplied {@link JacksonJavaTypeMapper}.
* @param mapper the mapper.
* @return the serde.
*/
public JacksonJsonSerde<T> typeMapper(JacksonJavaTypeMapper mapper) {
this.jsonSerializer.setTypeMapper(mapper);
this.jsonDeserializer.setTypeMapper(mapper);
return this;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JacksonJsonSerde.java
| 1
|
请完成以下Java代码
|
private void updateInvokeRate()
{
// getting local copies to ensure that the values we work with aren't changed by other threads
// while this method executes
final BigDecimal intervalLastInvokeLocal = this.intervalLastInvoke;
final long invokeCountLocal = invokeCount.get();
if (invokeCountLocal < 2)
{
// need at least two 'plusOne()' invocations to get a rate
invokeRate = BigDecimal.ZERO;
}
else if (intervalLastInvokeLocal.signum() == 0)
{
// omit division by zero
invokeRate = new BigDecimal(Long.MAX_VALUE);
}
else
{
invokeRate = new BigDecimal("1000")
.setScale(2, BigDecimal.ROUND_HALF_UP)
.divide(intervalLastInvokeLocal, RoundingMode.HALF_UP)
.abs(); // be tolerant against intervalLastChange < 0
|
}
}
@Override
public long getInvokeCount()
{
return invokeCount.get();
}
@Override
public BigDecimal getInvokeRate()
{
return invokeRate;
}
@Override
public long getGauge()
{
return gauge.get();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\api\impl\Meter.java
| 1
|
请完成以下Java代码
|
public static SqlComposedKey extractComposedKey(
final DocumentId recordId,
final List<? extends SqlEntityFieldBinding> keyFields)
{
final int count = keyFields.size();
if (count < 1)
{
throw new AdempiereException("Invalid composed key: " + keyFields);
}
final List<Object> composedKeyParts = recordId.toComposedKeyParts();
if (composedKeyParts.size() != count)
{
throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size());
}
final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder();
final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder();
for (int i = 0; i < count; i++)
{
final SqlEntityFieldBinding keyField = keyFields.get(i);
|
final String keyColumnName = keyField.getColumnName();
keyColumnNames.add(keyColumnName);
final Object valueObj = composedKeyParts.get(i);
@Nullable final Object valueConv = DataTypes.convertToValueClass(
keyColumnName,
valueObj,
keyField.getWidgetType(),
keyField.getSqlValueClass(),
null);
if (!JSONNullValue.isNull(valueConv))
{
values.put(keyColumnName, valueConv);
}
}
return SqlComposedKey.of(keyColumnNames.build(), values.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
private final Map<Long, User> userMap = new HashMap<>();
@GetMapping(path = "/user/{id}")
public User getUser(@PathVariable("id") long userId){
LOGGER.info("Getting user Details for user Id {}", userId);
return userMap.get(userId);
}
@PostConstruct
private void setupRepo() {
User user1 = getUser(100001, "user1");
userMap.put(100001L, user1);
|
User user2 = getUser(100002, "user2");
userMap.put(100002L, user2);
User user3 = getUser(100003, "user3");
userMap.put(100003L, user3);
User user4 = getUser(100004, "user4");
userMap.put(100004L, user4);
}
private static User getUser(int id, String name) {
User user = new User();
user.setId(id);
user.setName(name);
return user;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-3\spring-backend-service\src\main\java\com\baeldung\userservice\controller\UserController.java
| 2
|
请完成以下Java代码
|
static @Nullable PemSslStore load(@Nullable PemSslStoreDetails details, ResourceLoader resourceLoader) {
if (details == null || details.isEmpty()) {
return null;
}
return new LoadedPemSslStore(details, resourceLoader);
}
/**
* Factory method that can be used to create a new {@link PemSslStore} with the given
* values.
* @param type the key store type
* @param certificates the certificates for this store
* @param privateKey the private key
* @return a new {@link PemSslStore} instance
*/
static PemSslStore of(@Nullable String type, List<X509Certificate> certificates, @Nullable PrivateKey privateKey) {
return of(type, null, null, certificates, privateKey);
}
/**
* Factory method that can be used to create a new {@link PemSslStore} with the given
* values.
* @param certificates the certificates for this store
* @param privateKey the private key
* @return a new {@link PemSslStore} instance
*/
static PemSslStore of(List<X509Certificate> certificates, @Nullable PrivateKey privateKey) {
return of(null, null, null, certificates, privateKey);
}
/**
* Factory method that can be used to create a new {@link PemSslStore} with the given
* values.
* @param type the key store type
* @param alias the alias used when setting entries in the {@link KeyStore}
* @param password the password used
* {@link KeyStore#setKeyEntry(String, java.security.Key, char[], java.security.cert.Certificate[])
* setting key entries} in the {@link KeyStore}
* @param certificates the certificates for this store
* @param privateKey the private key
* @return a new {@link PemSslStore} instance
*/
static PemSslStore of(@Nullable String type, @Nullable String alias, @Nullable String password,
List<X509Certificate> certificates, @Nullable PrivateKey privateKey) {
Assert.notEmpty(certificates, "'certificates' must not be empty");
return new PemSslStore() {
@Override
public @Nullable String type() {
return type;
}
@Override
|
public @Nullable String alias() {
return alias;
}
@Override
public @Nullable String password() {
return password;
}
@Override
public List<X509Certificate> certificates() {
return certificates;
}
@Override
public @Nullable PrivateKey privateKey() {
return privateKey;
}
};
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemSslStore.java
| 1
|
请完成以下Java代码
|
public String getMessage() {
return message;
}
@Override
public int getLine() {
return line;
}
@Override
public int getColumn() {
return column;
}
@Override
public String getMainElementId() {
return mainElementId;
}
|
@Override
public List<String> getElementIds() {
return elementIds;
}
public String toString() {
StringBuilder string = new StringBuilder();
if (line > 0) {
string.append(" | line " + line);
}
if (column > 0) {
string.append(" | column " + column);
}
return string.toString();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\xml\ProblemImpl.java
| 1
|
请完成以下Java代码
|
public void prepare() {
List<Person> friends=new ArrayList<Person>();
friends.add(createAPerson("小明",null));
friends.add(createAPerson("Tony",null));
friends.add(createAPerson("陈小二",null));
p=createAPerson("邵同学",friends);
}
@TearDown
public void shutdown() {
}
private Person createAPerson(String name,List<Person> friends) {
Person newPerson=new Person();
newPerson.setName(name);
|
newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last"));
newPerson.setAge(24);
List<String> hobbies=new ArrayList<String>();
hobbies.add("篮球");
hobbies.add("游泳");
hobbies.add("coding");
newPerson.setHobbies(hobbies);
Map<String,String> clothes=new HashMap<String, String>();
clothes.put("coat", "Nike");
clothes.put("trousers", "adidas");
clothes.put("shoes", "安踏");
newPerson.setClothes(clothes);
newPerson.setFriends(friends);
return newPerson;
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\JsonSerializeBenchmark.java
| 1
|
请完成以下Java代码
|
public boolean isChanged()
{
return m_changed;
} // isChanged
/**
* Is First Row - (zero based)
*
* @return true if first row
*/
public boolean isFirstRow()
{
if (m_totalRows == 0)
{
return true;
}
return m_currentRow == 0;
} // isFirstRow
/**
* Is Last Row - (zero based)
*
* @return true if last row
*/
public boolean isLastRow()
{
if (m_totalRows == 0)
{
return true;
}
return m_currentRow == m_totalRows - 1;
} // isLastRow
/**
* Set Changed Column
*
* @param col column
* @param columnName column name
*/
public void setChangedColumn(final int col, final String columnName)
{
m_changedColumn = col;
m_columnName = columnName;
} // setChangedColumn
/**
* Get Changed Column
*
* @return changed column
*/
public int getChangedColumn()
{
return m_changedColumn;
} // getChangedColumn
/**
* Get Column Name
*
* @return column name
*/
public String getColumnName()
{
return m_columnName;
} // getColumnName
/**
* Set Confirmed toggle
*
* @param confirmed confirmed
*/
public void setConfirmed(final boolean confirmed)
{
m_confirmed = confirmed;
} // setConfirmed
/**
* Is Confirmed (e.g. user has seen it)
*
* @return true if confirmed
*/
public boolean isConfirmed()
{
return m_confirmed;
} // isConfirmed
public void setCreated(final Integer createdBy, final Timestamp created)
{
|
this.createdBy = createdBy;
this.created = created;
}
public void setUpdated(final Integer updatedBy, final Timestamp updated)
{
this.updatedBy = updatedBy;
this.updated = updated;
}
public void setAdTableId(final int adTableId)
{
this.adTableId = adTableId;
this.recordId = null;
}
public void setSingleKeyRecord(final int adTableId, @NonNull final String keyColumnName, final int recordId)
{
setRecord(adTableId, ComposedRecordId.singleKey(keyColumnName, recordId));
}
public void setRecord(final int adTableId, @NonNull final ComposedRecordId recordId)
{
Check.assumeGreaterThanZero(adTableId, "adTableId");
this.adTableId = adTableId;
this.recordId = recordId;
}
public OptionalInt getSingleRecordId()
{
if (recordId == null)
{
return OptionalInt.empty();
}
return recordId.getSingleRecordId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\DataStatusEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Person save(Person person) {
Person p = personRepository.save(person);
logger.info("为id、key为:" + p.getId() + "数据做了缓存");
return p;
}
@Override
@CacheEvict(value = "people", key = "#id")//2
public void remove(Long id) {
logger.info("删除了id、key为" + id + "的数据缓存");
//这里不做实际删除操作
}
@Override
@CacheEvict(value = "people", allEntries = true)//2
public void removeAll() {
logger.info("删除了所有缓存的数据缓存");
//这里不做实际删除操作
}
@Override
@Cacheable(value = "'people' + ':' + #person.id", key = "#person.id", depict = "用户信息缓存", enableFirstCache = false,
firstCache = @FirstCache(expireTime = 4, timeUnit = TimeUnit.MINUTES),
|
secondaryCache = @SecondaryCache(expireTime = 15, preloadTime = 8, forceRefresh = true, timeUnit = TimeUnit.HOURS))
public Person findOne(Person person) {
Person p = personRepository.findOne(Example.of(person));
logger.info("为id、key为:" + p.getId() + "数据做了缓存");
return p;
}
@Override
@Cacheable(value = "people1", key = "#person.id", depict = "用户信息缓存1", enableFirstCache = false,
firstCache = @FirstCache(expireTime = 4,timeUnit = TimeUnit.MINUTES, expireMode = ExpireMode.ACCESS),
secondaryCache = @SecondaryCache(expireTime = 15, preloadTime = 8, forceRefresh = true))
public Person findOne1(Person person) {
Person p = personRepository.findOne(Example.of(person));
logger.info("为id、key为:" + p.getId() + "数据做了缓存");
return p;
}
}
|
repos\spring-boot-student-master\spring-boot-student-layering-cache\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(RestResponseStatusExceptionResolver.class);
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
try {
if (ex instanceof IllegalArgumentException) {
return handleIllegalArgument(
(IllegalArgumentException) ex, request, response, handler);
}
} catch (Exception handlerException) {
logger.warn("Handling of [{}] resulted in Exception", ex.getClass().getName(), handlerException);
}
return null;
}
private ModelAndView handleIllegalArgument(IllegalArgumentException ex,
final HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
final String accept = request.getHeader(HttpHeaders.ACCEPT);
response.sendError(HttpServletResponse.SC_CONFLICT);
response.setHeader("ContentType", accept);
final ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("error", prepareErrorResponse(accept));
return modelAndView;
}
/** Prepares error object based on the provided accept type.
* @param accept The Accept header present in the request.
* @return The response to return
* @throws JsonProcessingException
|
*/
private String prepareErrorResponse(String accept) throws JsonProcessingException {
final Map<String, String> error = new HashMap<>();
error.put("Error", "Application specific error message");
final String response;
if(MediaType.APPLICATION_JSON_VALUE.equals(accept)) {
response = new ObjectMapper().writeValueAsString(error);
} else {
response = new XmlMapper().writeValueAsString(error);
}
return response;
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\error\RestResponseStatusExceptionResolver.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isIncludeCaseVariables() {
return includeCaseVariables;
}
public boolean isIncludeIdentityLinks() {
return includeIdentityLinks;
}
public boolean isBothCandidateAndAssigned() {
return bothCandidateAndAssigned;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getDescriptionLikeIgnoreCase() {
return descriptionLikeIgnoreCase;
}
public String getAssigneeLikeIgnoreCase() {
return assigneeLikeIgnoreCase;
}
public String getOwnerLikeIgnoreCase() {
return ownerLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public boolean isOrActive() {
return orActive;
}
public boolean isUnassigned() {
return unassigned;
}
public boolean isNoDelegationState() {
return noDelegationState;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionKeyLike() {
return caseDefinitionKeyLike;
}
public String getCaseDefinitionKeyLikeIgnoreCase() {
return caseDefinitionKeyLikeIgnoreCase;
}
public Collection<String> getCaseDefinitionKeys() {
return caseDefinitionKeys;
}
public boolean isExcludeSubtasks() {
return excludeSubtasks;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
|
}
@Override
public List<Task> list() {
cachedCandidateGroups = null;
return super.list();
}
@Override
public List<Task> listPage(int firstResult, int maxResults) {
cachedCandidateGroups = null;
return super.listPage(firstResult, maxResults);
}
@Override
public long count() {
cachedCandidateGroups = null;
return super.count();
}
public List<List<String>> getSafeCandidateGroups() {
return safeCandidateGroups;
}
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) {
this.safeCandidateGroups = safeCandidateGroups;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeScopeIds() {
return safeScopeIds;
}
public void setSafeScopeIds(List<List<String>> safeScopeIds) {
this.safeScopeIds = safeScopeIds;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public DomainUrl getDomainUrl() {
return domainUrl;
}
public void setDomainUrl(DomainUrl domainUrl) {
this.domainUrl = domainUrl;
}
public String getSignUrls() {
return signUrls;
}
public void setSignUrls(String signUrls) {
this.signUrls = signUrls;
}
public String getFileViewDomain() {
return fileViewDomain;
}
public void setFileViewDomain(String fileViewDomain) {
this.fileViewDomain = fileViewDomain;
}
public String getUploadType() {
return uploadType;
}
public void setUploadType(String uploadType) {
|
this.uploadType = uploadType;
}
public WeiXinPay getWeiXinPay() {
return weiXinPay;
}
public void setWeiXinPay(WeiXinPay weiXinPay) {
this.weiXinPay = weiXinPay;
}
public BaiduApi getBaiduApi() {
return baiduApi;
}
public void setBaiduApi(BaiduApi baiduApi) {
this.baiduApi = baiduApi;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\JeecgBaseConfig.java
| 2
|
请完成以下Spring Boot application配置
|
management:
endpoints.web.exposure.include: '*'
endpoint.health.show-details: always
spring:
application:
name: kafka-monitoring
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: baeldung-app-1
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.value.default.type: com.baeldung.kafka.monitoring.ArticleCommentAddedEvent
|
spring.json.trusted.packages: com.baeldung.kafka.monitoring
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
|
repos\tutorials-master\spring-kafka-4\src\main\resources\application-monitoring.yml
| 2
|
请完成以下Java代码
|
public String getResourceName() {
return resourceName;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public boolean hasGraphicalNotation() {
return isGraphicalNotationDefined;
}
public boolean isGraphicalNotationDefined() {
return hasGraphicalNotation();
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public String getDiagramResourceName() {
return diagramResourceName;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
|
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String getDecisionType() {
return decisionType;
}
@Override
public void setDecisionType(String decisionType) {
this.decisionType = decisionType;
}
@Override
public String toString() {
return "DecisionEntity[" + id + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DecisionEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalBusinessKey
{
@NonNull
Type type;
@NonNull
String rawValue;
@Nullable
ExternalReferenceValueAndSystem externalReferenceValueAndSystem;
private ExternalBusinessKey(
@NonNull final Type type,
@NonNull final String rawValue,
@Nullable final ExternalReferenceValueAndSystem externalReferenceValueAndSystem)
{
if (Type.EXTERNAL_REFERENCE.equals(type) && externalReferenceValueAndSystem == null)
{
throw new AdempiereException("ExternalReferenceValueAndSystem cannot be null for type: EXTERNAL_REFERENCE!")
.appendParametersToMessage()
.setParameter("rawValue", rawValue)
.setParameter("type", type);
}
this.type = type;
this.rawValue = rawValue;
this.externalReferenceValueAndSystem = externalReferenceValueAndSystem;
}
@NonNull
public static ExternalBusinessKey of(@NonNull final String identifier)
{
final Matcher externalBusinessKeyMatcher = Type.EXTERNAL_REFERENCE.pattern.matcher(identifier);
if (externalBusinessKeyMatcher.matches())
{
final ExternalReferenceValueAndSystem valueAndSystem = ExternalReferenceValueAndSystem.builder()
.externalSystem(externalBusinessKeyMatcher.group(1))
.value(externalBusinessKeyMatcher.group(2))
.build();
|
return new ExternalBusinessKey(Type.EXTERNAL_REFERENCE, identifier, valueAndSystem);
}
else
{
return new ExternalBusinessKey(Type.VALUE, identifier, null);
}
}
@NonNull
public ExternalReferenceValueAndSystem asExternalValueAndSystem()
{
Check.assume(Type.EXTERNAL_REFERENCE.equals(type),
"The type of this instance needs to be {}; this={}", Type.EXTERNAL_REFERENCE, this);
Check.assumeNotNull(externalReferenceValueAndSystem,
"externalReferenceValueAndSystem cannot be null to EXTERNAL_REFERENCE type!");
return externalReferenceValueAndSystem;
}
@NonNull
public String asValue()
{
Check.assume(Type.VALUE.equals(type),
"The type of this instance needs to be {}; this={}", Type.VALUE, this);
return rawValue;
}
@AllArgsConstructor
@Getter
public enum Type
{
VALUE(Pattern.compile("(.*?)")),
EXTERNAL_REFERENCE(Pattern.compile("(?:^ext-)([a-zA-Z0-9]+)-(.+)"));
private final Pattern pattern;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalBusinessKey.java
| 2
|
请完成以下Java代码
|
public String getBatchJobDefinitionId() {
return batchJobDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Date getRemovalTime() {
return removalTime;
}
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
public static HistoricBatchDto fromBatch(HistoricBatch historicBatch) {
|
HistoricBatchDto dto = new HistoricBatchDto();
dto.id = historicBatch.getId();
dto.type = historicBatch.getType();
dto.totalJobs = historicBatch.getTotalJobs();
dto.batchJobsPerSeed = historicBatch.getBatchJobsPerSeed();
dto.invocationsPerBatchJob = historicBatch.getInvocationsPerBatchJob();
dto.seedJobDefinitionId = historicBatch.getSeedJobDefinitionId();
dto.monitorJobDefinitionId = historicBatch.getMonitorJobDefinitionId();
dto.batchJobDefinitionId = historicBatch.getBatchJobDefinitionId();
dto.tenantId = historicBatch.getTenantId();
dto.createUserId = historicBatch.getCreateUserId();
dto.startTime = historicBatch.getStartTime();
dto.endTime = historicBatch.getEndTime();
dto.removalTime = historicBatch.getRemovalTime();
dto.executionStartTime = historicBatch.getExecutionStartTime();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchDto.java
| 1
|
请完成以下Java代码
|
public void setC_BPartner_To_ID (final int C_BPartner_To_ID)
{
if (C_BPartner_To_ID < 1)
set_Value (COLUMNNAME_C_BPartner_To_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_To_ID, C_BPartner_To_ID);
}
@Override
public int getC_BPartner_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_To_ID);
}
@Override
public void setDate_OrgChange (final java.sql.Timestamp Date_OrgChange)
{
set_Value (COLUMNNAME_Date_OrgChange, Date_OrgChange);
}
@Override
|
public java.sql.Timestamp getDate_OrgChange()
{
return get_ValueAsTimestamp(COLUMNNAME_Date_OrgChange);
}
@Override
public void setIsCloseInvoiceCandidate (final boolean IsCloseInvoiceCandidate)
{
set_Value (COLUMNNAME_IsCloseInvoiceCandidate, IsCloseInvoiceCandidate);
}
@Override
public boolean isCloseInvoiceCandidate()
{
return get_ValueAsBoolean(COLUMNNAME_IsCloseInvoiceCandidate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgChange_History.java
| 1
|
请完成以下Java代码
|
public ImmutableSet<String> getFieldNames()
{
return columnsByName.keySet();
}
public Stream<ClassViewColumnDescriptor> streamColumns()
{
return columnsByName.values().stream();
}
public ClassViewColumnDescriptor getColumnByName(@NonNull final String fieldName)
{
final ClassViewColumnDescriptor column = columnsByName.get(fieldName);
if (column == null)
{
throw new AdempiereException("No column found for " + fieldName + " in " + this);
}
return column;
}
}
@Value
@Builder(toBuilder = true)
private static class ClassViewColumnDescriptor
{
@NonNull String fieldName;
@NonNull
@Getter(AccessLevel.NONE)
FieldReference fieldReference;
@NonNull ITranslatableString caption;
@Nullable
ITranslatableString description;
@NonNull DocumentFieldWidgetType widgetType;
@Nullable
ReferenceId listReferenceId;
@Nullable
WidgetSize widgetSize;
@NonNull ViewEditorRenderMode editorRenderMode;
boolean allowSorting;
@NonNull ImmutableMap<JSONViewDataType, ClassViewColumnLayoutDescriptor> layoutsByViewType;
@NonNull ImmutableSet<MediaType> restrictToMediaTypes;
boolean allowZoomInfo;
public DisplayMode getDisplayMode(final JSONViewDataType viewType)
{
final ClassViewColumnLayoutDescriptor layout = layoutsByViewType.get(viewType);
return layout != null ? layout.getDisplayMode() : DisplayMode.HIDDEN;
}
public int getSeqNo(final JSONViewDataType viewType)
{
final ClassViewColumnLayoutDescriptor layout = layoutsByViewType.get(viewType);
if (layout == null)
{
return Integer.MAX_VALUE;
}
final int seqNo = layout.getSeqNo();
return seqNo >= 0 ? seqNo : Integer.MAX_VALUE;
}
public Field getField()
{
|
return fieldReference.getField();
}
public boolean isSupportZoomInto() {return allowZoomInfo && widgetType.isSupportZoomInto();}
}
@Getter
private enum DisplayMode
{
DISPLAYED(true, false),
HIDDEN(false, false),
DISPLAYED_BY_SYSCONFIG(true, true),
HIDDEN_BY_SYSCONFIG(false, true),
;
private final boolean displayed;
private final boolean configuredBySysConfig;
DisplayMode(final boolean displayed, final boolean configuredBySysConfig)
{
this.displayed = displayed;
this.configuredBySysConfig = configuredBySysConfig;
}
}
@Value
@Builder
private static class ClassViewColumnLayoutDescriptor
{
@NonNull JSONViewDataType viewType;
DisplayMode displayMode;
int seqNo;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\annotation\ViewColumnHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void validateSignature(HttpServletRequest request) throws IllegalArgumentException {
try {
log.debug("开始签名验证: {} {}", request.getMethod(), request.getRequestURI());
HttpServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
//获取全部参数(包括URL和body上的)
SortedMap<String, String> allParams = HttpUtils.getAllParams(requestWrapper);
log.debug("提取参数: {}", allParams);
//对参数进行签名验证
String headerSign = request.getHeader(CommonConstant.X_SIGN);
String xTimestamp = request.getHeader(CommonConstant.X_TIMESTAMP);
if(oConvertUtils.isEmpty(xTimestamp)){
log.error("Sign签名校验失败,时间戳为空!");
throw new IllegalArgumentException("Sign签名校验失败,请求参数不完整!");
}
//客户端时间
Long clientTimestamp = Long.parseLong(xTimestamp);
int length = 14;
int length1000 = 1000;
//1.校验签名时间(兼容X_TIMESTAMP的新老格式)
if (xTimestamp.length() == length) {
//a. X_TIMESTAMP格式是 yyyyMMddHHmmss (例子:20220308152143)
long currentTimestamp = DateUtils.getCurrentTimestamp();
long timeDiff = currentTimestamp - clientTimestamp;
log.debug("时间戳验证(yyyyMMddHHmmss): 时间差{}秒", timeDiff);
if (timeDiff > MAX_EXPIRE) {
log.error("时间戳已过期: {}秒 > {}秒", timeDiff, MAX_EXPIRE);
throw new IllegalArgumentException("签名验证失败,请求时效性验证失败!");
|
}
} else {
//b. X_TIMESTAMP格式是 时间戳 (例子:1646552406000)
long currentTime = System.currentTimeMillis();
long timeDiff = currentTime - clientTimestamp;
long maxExpireMs = MAX_EXPIRE * length1000;
log.debug("时间戳验证(Unix): 时间差{}ms", timeDiff);
if (timeDiff > maxExpireMs) {
log.error("时间戳已过期: {}ms > {}ms", timeDiff, maxExpireMs);
throw new IllegalArgumentException("签名验证失败,请求时效性验证失败!");
}
}
//2.校验签名
boolean isSigned = SignUtil.verifySign(allParams,headerSign);
if (isSigned) {
log.debug("签名验证通过");
} else {
log.error("签名验证失败, 参数: {}", allParams);
throw new IllegalArgumentException("Sign签名校验失败!");
}
} catch (IllegalArgumentException e) {
// 重新抛出签名验证异常
throw e;
} catch (Exception e) {
// 包装其他异常(如IOException)
log.error("签名验证异常: {}", e.getMessage());
throw new IllegalArgumentException("Sign签名校验失败:" + e.getMessage());
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\interceptor\SignAuthInterceptor.java
| 2
|
请完成以下Java代码
|
public boolean isNotEmpty() {
return !this.value.isEmpty();
}
@Override
public int length() {
return this.value.length();
}
@Override
public char charAt(int index) {
return this.value.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return this.value.subSequence(start, end);
}
|
public String[] split(String regex) {
return this.value.split(regex);
}
/**
* @return 原始字符串
*/
public String get() {
return this.value;
}
@Override
public String toString() {
return this.value;
}
}
|
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DocOutboundLogId implements RepoIdAware
{
@JsonCreator
public static DocOutboundLogId ofRepoId(final int repoId)
{
return new DocOutboundLogId(repoId);
}
@Nullable
public static DocOutboundLogId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new DocOutboundLogId(repoId) : null;
}
public static int toRepoId(final DocOutboundLogId id)
{
return id != null ? id.getRepoId() : -1;
|
}
int repoId;
private DocOutboundLogId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Doc_Outbound_Log");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\DocOutboundLogId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean sendTag() {
for (String tag : new String[]{"yunai", "yutou", "tudou"}) {
// 创建 Message
Demo01Message message = new Demo01Message()
.setId(new Random().nextInt());
// 创建 Spring Message 对象
Message<Demo01Message> springMessage = MessageBuilder.withPayload(message)
.setHeader(MessageConst.PROPERTY_TAGS, tag) // 设置 Tag
.build();
// 发送消息
mySource.demo01Output().send(springMessage);
}
return true;
}
@GetMapping("/send_transaction")
public boolean sendTransaction() {
// 创建 Message
Demo01Message message = new Demo01Message()
.setId(new Random().nextInt());
// 创建 Spring Message 对象
Args args = new Args().setArgs1(1).setArgs2("2");
Message<Demo01Message> springMessage = MessageBuilder.withPayload(message)
.setHeader("args", JSON.toJSONString(args))
.build();
// 发送消息
return mySource.demo01Output().send(springMessage);
}
public static class Args {
private Integer args1;
private String args2;
public Integer getArgs1() {
return args1;
}
|
public Args setArgs1(Integer args1) {
this.args1 = args1;
return this;
}
public String getArgs2() {
return args2;
}
public Args setArgs2(String args2) {
this.args2 = args2;
return this;
}
@Override
public String toString() {
return "Args{" +
"args1=" + args1 +
", args2='" + args2 + '\'' +
'}';
}
}
}
|
repos\SpringBoot-Labs-master\labx-06-spring-cloud-stream-rocketmq\labx-06-sca-stream-rocketmq-producer-transaction\src\main\java\cn\iocoder\springcloudalibaba\labx6\rocketmqdemo\producerdemo\controller\Demo01Controller.java
| 2
|
请完成以下Java代码
|
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 Expense Type.
@param S_ExpenseType_ID
Expense report type
*/
public void setS_ExpenseType_ID (int S_ExpenseType_ID)
{
if (S_ExpenseType_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, Integer.valueOf(S_ExpenseType_ID));
}
/** Get Expense Type.
@return Expense report type
*/
public int getS_ExpenseType_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_S_ExpenseType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ExpenseType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class DefaultJmsListenerContainerFactoryConfigurer
extends AbstractJmsListenerContainerFactoryConfigurer<DefaultJmsListenerContainerFactory> {
private @Nullable JtaTransactionManager transactionManager;
/**
* Set the {@link JtaTransactionManager} to use or {@code null} if the JTA support
* should not be used.
* @param transactionManager the {@link JtaTransactionManager}
*/
void setTransactionManager(@Nullable JtaTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
|
public void configure(DefaultJmsListenerContainerFactory factory, ConnectionFactory connectionFactory) {
super.configure(factory, connectionFactory);
PropertyMapper map = PropertyMapper.get();
JmsProperties.Listener listenerProperties = getJmsProperties().getListener();
Session sessionProperties = listenerProperties.getSession();
map.from(this.transactionManager).to(factory::setTransactionManager);
if (this.transactionManager == null && sessionProperties.getTransacted() == null) {
factory.setSessionTransacted(true);
}
map.from(listenerProperties::formatConcurrency).to(factory::setConcurrency);
map.from(listenerProperties::getReceiveTimeout).as(Duration::toMillis).to(factory::setReceiveTimeout);
map.from(listenerProperties::getMaxMessagesPerTask).to(factory::setMaxMessagesPerTask);
}
}
|
repos\spring-boot-main\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\DefaultJmsListenerContainerFactoryConfigurer.java
| 2
|
请完成以下Java代码
|
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
OAuth2AccessToken.TokenType accessTokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue()
.equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) {
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
}
long expiresIn = 0;
if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) {
try {
expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
} catch (NumberFormatException ex) {
}
}
Set<String> scopes = Collections.emptySet();
if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " "))
.collect(Collectors.toSet());
|
}
String refreshToken = tokenResponseParameters.get(OAuth2ParameterNames.REFRESH_TOKEN);
Map<String, Object> additionalParameters = new LinkedHashMap<>();
tokenResponseParameters.entrySet()
.stream()
.filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
.forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));
return OAuth2AccessTokenResponse.withToken(accessToken)
.tokenType(accessTokenType)
.expiresIn(expiresIn)
.scopes(scopes)
.refreshToken(refreshToken)
.additionalParameters(additionalParameters)
.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2request\CustomTokenResponseConverter.java
| 1
|
请完成以下Java代码
|
public boolean isTemplateAttribute(final I_M_HU_PI_Attribute huPIAttribute)
{
logger.trace("Checking if {} is a template attribute", huPIAttribute);
//
// If the PI attribute is from template then it's a template attribute
final HuPackingInstructionsVersionId piVersionId = HuPackingInstructionsVersionId.ofRepoId(huPIAttribute.getM_HU_PI_Version_ID());
if (piVersionId.isTemplate())
{
if (!huPIAttribute.isActive())
{
logger.trace("Considering {} NOT a template attribute because even if it is direct template attribute it's INACTIVE", huPIAttribute);
return false;
}
else
{
logger.trace("Considering {} a template attribute because it is direct template attribute", huPIAttribute);
return true;
}
}
//
// Get the Template PI attributes and search if this attribute is defined there.
final AttributeId attributeId = AttributeId.ofRepoId(huPIAttribute.getM_Attribute_ID());
final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute);
final PIAttributes templatePIAttributes = retrieveDirectPIAttributes(ctx, HuPackingInstructionsVersionId.TEMPLATE);
if (templatePIAttributes.hasActiveAttribute(attributeId))
{
logger.trace("Considering {} a template attribute because we found M_Attribute_ID={} in template attributes", huPIAttribute, attributeId);
return true;
}
//
|
// Not a template attribute
logger.trace("Considering {} NOT a template attribute", huPIAttribute);
return false;
}
@Override
public void deleteByVersionId(@NonNull final HuPackingInstructionsVersionId versionId)
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_PI_Attribute.class)
.addEqualsFilter(I_M_HU_PI_Attribute.COLUMN_M_HU_PI_Version_ID, versionId)
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUPIAttributesDAO.java
| 1
|
请完成以下Java代码
|
private static ProjectType toProjectType(@NonNull final I_C_ProjectType record)
{
return ProjectType.builder()
.id(ProjectTypeId.ofRepoId(record.getC_ProjectType_ID()))
.projectCategory(ProjectCategory.ofCode(record.getProjectCategory()))
.docSequenceId(DocSequenceId.ofRepoIdOrNull(record.getAD_Sequence_ProjectValue_ID()))
.build();
}
@NonNull
public ProjectTypeId getFirstIdByProjectCategoryAndOrg(
@NonNull final ProjectCategory projectCategory,
@NonNull final OrgId orgId,
final boolean onlyCurrentOrg)
{
final ProjectTypeId projectTypeId = getFirstIdByProjectCategoryAndOrgOrNull(projectCategory, orgId, onlyCurrentOrg);
if (projectTypeId == null)
{
throw new AdempiereException("@NotFound@ @C_ProjectType_ID@")
.appendParametersToMessage()
.setParameter("ProjectCategory", projectCategory)
.setParameter("AD_Org_ID", orgId.getRepoId());
}
return projectTypeId;
}
@Nullable
public ProjectTypeId getFirstIdByProjectCategoryAndOrgOrNull(
@NonNull final ProjectCategory projectCategory,
@NonNull final OrgId orgId,
final boolean onlyCurrentOrg)
{
|
final IQueryBuilder<I_C_ProjectType> builder = queryBL.createQueryBuilderOutOfTrx(I_C_ProjectType.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_ProjectType.COLUMNNAME_ProjectCategory, projectCategory.getCode())
.orderByDescending(I_C_ProjectType.COLUMNNAME_AD_Org_ID)
.orderBy(I_C_ProjectType.COLUMNNAME_C_ProjectType_ID);
if (onlyCurrentOrg)
{
builder.addInArrayFilter(I_C_ProjectType.COLUMNNAME_AD_Org_ID, orgId);
}
else
{
builder.addInArrayFilter(I_C_ProjectType.COLUMNNAME_AD_Org_ID, OrgId.ANY, orgId);
}
return builder
.create()
.firstId(ProjectTypeId::ofRepoIdOrNull);
}
public I_C_ProjectType getByName(final @NonNull String projectTypeValue)
{
return queryBL.createQueryBuilderOutOfTrx(I_C_ProjectType.class)
.addEqualsFilter(I_C_ProjectType.COLUMNNAME_Name, projectTypeValue)
.create()
.firstOnlyNotNull(I_C_ProjectType.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectTypeRepository.java
| 1
|
请完成以下Java代码
|
abstract class AbstractGatewayServerResponse extends GatewayErrorHandlingServerResponse
implements GatewayServerResponse {
private static final Set<HttpMethod> SAFE_METHODS = Set.of(HttpMethod.GET, HttpMethod.HEAD);
private HttpStatusCode statusCode;
private final HttpHeaders headers;
private final MultiValueMap<String, Cookie> cookies;
protected AbstractGatewayServerResponse(HttpStatusCode statusCode, HttpHeaders headers,
MultiValueMap<String, Cookie> cookies) {
this.statusCode = statusCode;
this.headers = HttpHeaders.copyOf(headers);
this.cookies = new LinkedMultiValueMap<>(cookies);
}
@Override
public final HttpStatusCode statusCode() {
return this.statusCode;
}
@Override
public void setStatusCode(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
@Override
public final HttpHeaders headers() {
return this.headers;
}
@Override
public MultiValueMap<String, Cookie> cookies() {
return this.cookies;
}
@Override
public @Nullable ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response, Context context)
throws ServletException, IOException {
try {
writeStatusAndHeaders(response);
|
long lastModified = headers().getLastModified();
ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
if (SAFE_METHODS.contains(httpMethod)
&& servletWebRequest.checkNotModified(headers().getETag(), lastModified)) {
return null;
}
else {
return writeToInternal(request, response, context);
}
}
catch (Throwable throwable) {
return handleError(throwable, request, response, context);
}
}
private void writeStatusAndHeaders(HttpServletResponse response) {
response.setStatus(this.statusCode.value());
writeHeaders(response);
writeCookies(response);
}
private void writeHeaders(HttpServletResponse servletResponse) {
this.headers.forEach((headerName, headerValues) -> {
for (String headerValue : headerValues) {
servletResponse.addHeader(headerName, headerValue);
}
});
// HttpServletResponse exposes some headers as properties: we should include those
// if not already present
if (servletResponse.getContentType() == null && this.headers.getContentType() != null) {
servletResponse.setContentType(this.headers.getContentType().toString());
}
if (servletResponse.getCharacterEncoding() == null && this.headers.getContentType() != null
&& this.headers.getContentType().getCharset() != null) {
servletResponse.setCharacterEncoding(this.headers.getContentType().getCharset().name());
}
}
private void writeCookies(HttpServletResponse servletResponse) {
this.cookies.values().stream().flatMap(Collection::stream).forEach(servletResponse::addCookie);
}
protected abstract @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response,
Context context) throws Exception;
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\AbstractGatewayServerResponse.java
| 1
|
请完成以下Java代码
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
Jwt jwt = getJwt(bearer);
AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt);
Assert.notNull(token, "token cannot be null");
if (token.getDetails() == null) {
token.setDetails(bearer.getDetails());
}
this.logger.debug("Authenticated token");
return token;
}
private Jwt getJwt(BearerTokenAuthenticationToken bearer) {
try {
return this.jwtDecoder.decode(bearer.getToken());
}
catch (BadJwtException failed) {
this.logger.debug("Failed to authenticate since the JWT was invalid");
throw new InvalidBearerTokenException(failed.getMessage(), failed);
}
catch (JwtException failed) {
|
throw new AuthenticationServiceException(failed.getMessage(), failed);
}
}
@Override
public boolean supports(Class<?> authentication) {
return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication);
}
public void setJwtAuthenticationConverter(
Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter) {
Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null");
this.jwtAuthenticationConverter = jwtAuthenticationConverter;
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtAuthenticationProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String toString() {
return "CommentCollectionResource [taskComments=" + taskComments + "]";
}
}
/**
* Inner class to perform the de-serialization of the comments array
*
* @author anilallewar
*
*/
class CommentsCollectionDeserializer extends JsonDeserializer<CommentCollectionResource> {
@Override
public CommentCollectionResource deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
CommentCollectionResource commentArrayResource = new CommentCollectionResource();
CommentResource commentResource = null;
|
JsonNode jsonNode = jp.readValueAsTree();
for (JsonNode childNode : jsonNode) {
if (childNode.has(CommentResource.JP_TASKID)) {
commentResource = new CommentResource();
commentResource.setTaskId(childNode.get(CommentResource.JP_TASKID).asText());
commentResource.setComment(childNode.get(CommentResource.JP_COMMENT).asText());
commentResource.setPosted(new Date(childNode.get(CommentResource.JP_POSTED).asLong()));
commentArrayResource.addComment(commentResource);
}
}
return commentArrayResource;
}
}
|
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\model\CommentCollectionResource.java
| 2
|
请完成以下Java代码
|
public Optional<TemplateDefinition> findAssigneeTemplateForTask(String taskUUID) {
return templates.findAssigneeTemplateForTask(taskUUID);
}
public Optional<TemplateDefinition> findCandidateTemplateForTask(String taskUUID) {
return templates.findCandidateTemplateForTask(taskUUID);
}
public VariableDefinition getProperty(String propertyUUID) {
return properties != null ? properties.get(propertyUUID) : null;
}
public VariableDefinition getPropertyByName(String name) {
if (properties != null) {
for (Map.Entry<String, VariableDefinition> variableDefinition : properties.entrySet()) {
if (variableDefinition.getValue() != null) {
if (Objects.equals(variableDefinition.getValue().getName(), name)) {
return variableDefinition.getValue();
}
}
}
}
return null;
}
public boolean hasMapping(String taskId) {
return mappings.get(taskId) != null;
}
public boolean shouldMapAllInputs(String elementId) {
ProcessVariablesMapping processVariablesMapping = mappings.get(elementId);
return (
processVariablesMapping.getMappingType() != null &&
(processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_INPUTS) ||
processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL))
);
}
public boolean shouldMapAllOutputs(String elementId) {
ProcessVariablesMapping processVariablesMapping = mappings.get(elementId);
return (
|
processVariablesMapping.getMappingType() != null &&
(processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_OUTPUTS) ||
processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL))
);
}
public TemplatesDefinition getTemplates() {
return templates;
}
public void setTemplates(TemplatesDefinition templates) {
this.templates = templates;
}
public Map<String, AssignmentDefinition> getAssignments() {
return assignments;
}
public void setAssignments(Map<String, AssignmentDefinition> assignments) {
this.assignments = assignments;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\Extension.java
| 1
|
请完成以下Java代码
|
public void retryServiceWithRecovery(String sql) throws SQLException {
if (StringUtils.isEmpty(sql)) {
logger.info("throw SQLException in method retryServiceWithRecovery()");
throw new SQLException();
}
}
@Override
public void retryServiceWithCustomization(String sql) throws SQLException {
if (StringUtils.isEmpty(sql)) {
logger.info("throw SQLException in method retryServiceWithCustomization()");
// Correctly throws SQLException to trigger the 2 retry attempts
throw new SQLException();
}
}
@Override
public void retryServiceWithExternalConfiguration(String sql) throws SQLException {
if (StringUtils.isEmpty(sql)) {
logger.info("throw SQLException in method retryServiceWithExternalConfiguration()");
throw new SQLException();
}
}
@Override
public void recover(SQLException e, String sql) {
|
logger.info("In recover method");
}
@Override
public void templateRetryService() {
logger.info("throw RuntimeException in method templateRetryService()");
throw new RuntimeException();
}
// **NEW Implementation for Concurrency Limit**
@Override
@ConcurrencyLimit(5)
public void concurrentLimitService() {
// The ConcurrencyLimit aspect will wrap this method.
logger.info("Concurrency Limit Active. Current Thread: " + Thread.currentThread().getName());
// Simulate a time-consuming task to observe throttling
try {
Thread.sleep(1000); // Correctly blocks to hold the lock
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
logger.info("Concurrency Limit Released. Current Thread: " + Thread.currentThread().getName());
}
}
|
repos\tutorials-master\spring-scheduling\src\main\java\com\baeldung\springretry\MyServiceImpl.java
| 1
|
请完成以下Java代码
|
public void sendMail() throws Exception {
Session session = getSession();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
message.setContent(getMultipart(msg));
Transport.send(message);
}
public void sendMailToMultipleRecipients() throws Exception {
Session session = getSession();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com, to1@gmail.com"));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("to2@gmail.com, to3@gmail.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
message.setContent(getMultipart(msg));
Transport.send(message);
}
private Multipart getMultipart(String msg) throws Exception {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";
MimeBodyPart mimeBodyPartWithStyledText = new MimeBodyPart();
mimeBodyPartWithStyledText.setContent(msgStyled, "text/html; charset=utf-8");
|
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(getFile());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
multipart.addBodyPart(mimeBodyPartWithStyledText);
multipart.addBodyPart(attachmentBodyPart);
return multipart;
}
private Session getSession() {
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
return session;
}
private File getFile() throws Exception {
URI uri = this.getClass()
.getClassLoader()
.getResource("attachment.txt")
.toURI();
return new File(uri);
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\mail\EmailService.java
| 1
|
请完成以下Java代码
|
public class RestErrorResponse {
private Object subject;
private String message;
public RestErrorResponse() {
}
public RestErrorResponse(String message) {
this.message = message;
}
public RestErrorResponse(Object subject, String message) {
this.subject = subject;
this.message = message;
}
public Object getSubject() {
|
return subject;
}
public void setSubject(Object subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\exceptionhandling\rest\exceptions\RestErrorResponse.java
| 1
|
请完成以下Java代码
|
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
@Override
public org.compiere.model.I_AD_User getSupervisor() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSupervisor(org.compiere.model.I_AD_User Supervisor)
{
set_ValueFromPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class, Supervisor);
}
/** Set Vorgesetzter.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
@Override
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Vorgesetzter.
@return Supervisor for this user/organization - used for escalation and approval
*/
@Override
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* WeekDay AD_Reference_ID=167
* Reference name: Weekdays
*/
public static final int WEEKDAY_AD_Reference_ID=167;
/** Sonntag = 7 */
public static final String WEEKDAY_Sonntag = "7";
/** Montag = 1 */
public static final String WEEKDAY_Montag = "1";
/** Dienstag = 2 */
public static final String WEEKDAY_Dienstag = "2";
/** Mittwoch = 3 */
|
public static final String WEEKDAY_Mittwoch = "3";
/** Donnerstag = 4 */
public static final String WEEKDAY_Donnerstag = "4";
/** Freitag = 5 */
public static final String WEEKDAY_Freitag = "5";
/** Samstag = 6 */
public static final String WEEKDAY_Samstag = "6";
/** Set Day of the Week.
@param WeekDay
Day of the Week
*/
@Override
public void setWeekDay (java.lang.String WeekDay)
{
set_Value (COLUMNNAME_WeekDay, WeekDay);
}
/** Get Day of the Week.
@return Day of the Week
*/
@Override
public java.lang.String getWeekDay ()
{
return (java.lang.String)get_Value(COLUMNNAME_WeekDay);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean bufferEmpty()
{
return bufferHead == -1;
}
public boolean stackEmpty()
{
return stack.size() == 0;
}
public int bufferSize()
{
if (bufferHead < 0)
return 0;
return (maxSentenceSize - bufferHead + 1);
}
public int stackSize()
{
return stack.size();
}
public int rightMostModifier(int index)
{
return (rightMostArcs[index] == 0 ? -1 : rightMostArcs[index]);
}
public int leftMostModifier(int index)
{
return (leftMostArcs[index] == 0 ? -1 : leftMostArcs[index]);
}
/**
* @param head
* @return the current index of dependents
*/
public int valence(int head)
{
return rightValency(head) + leftValency(head);
}
/**
* @param head
* @return the current index of right modifiers
*/
public int rightValency(int head)
{
return rightValency[head];
}
/**
* @param head
* @return the current index of left modifiers
*/
public int leftValency(int head)
{
return leftValency[head];
}
public int getHead(int index)
{
if (arcs[index] != null)
return arcs[index].headIndex;
return -1;
}
public int getDependent(int index)
{
if (arcs[index] != null)
return arcs[index].relationId;
return -1;
}
public void setMaxSentenceSize(int maxSentenceSize)
{
this.maxSentenceSize = maxSentenceSize;
}
|
public void incrementBufferHead()
{
if (bufferHead == maxSentenceSize)
bufferHead = -1;
else
bufferHead++;
}
public void setBufferHead(int bufferHead)
{
this.bufferHead = bufferHead;
}
@Override
public State clone()
{
State state = new State(arcs.length - 1);
state.stack = new ArrayDeque<Integer>(stack);
for (int dependent = 0; dependent < arcs.length; dependent++)
{
if (arcs[dependent] != null)
{
Edge head = arcs[dependent];
state.arcs[dependent] = head;
int h = head.headIndex;
if (rightMostArcs[h] != 0)
{
state.rightMostArcs[h] = rightMostArcs[h];
state.rightValency[h] = rightValency[h];
state.rightDepLabels[h] = rightDepLabels[h];
}
if (leftMostArcs[h] != 0)
{
state.leftMostArcs[h] = leftMostArcs[h];
state.leftValency[h] = leftValency[h];
state.leftDepLabels[h] = leftDepLabels[h];
}
}
}
state.rootIndex = rootIndex;
state.bufferHead = bufferHead;
state.maxSentenceSize = maxSentenceSize;
state.emptyFlag = emptyFlag;
return state;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\State.java
| 2
|
请完成以下Java代码
|
public void warn(final int WindowNo, final Throwable e)
{
final String AD_Message = "Error";
final String message = buildErrorMessage(e);
logger.warn(message, e);
warn(WindowNo, AD_Message, message);
}
@Override
public void error(final int WindowNo, final Throwable e)
{
final String AD_Message = "Error";
final String message = buildErrorMessage(e);
// Log the error to console
// NOTE: we need to do that because in case something went wrong we need the stacktrace to debug the actual issue
// Before removing this please consider that you need to provide an alternative from where the support guys can grab their detailed exception info.
logger.warn(message, e);
error(WindowNo, AD_Message, message);
}
protected final String buildErrorMessage(final Throwable e)
{
String message = e == null ? "@UnknownError@" : e.getLocalizedMessage();
if (Check.isEmpty(message, true) && e != null)
{
message = e.toString();
}
return message;
}
@Override
public Thread createUserThread(final Runnable runnable, final String threadName)
{
final Thread thread;
if (threadName == null)
{
thread = new Thread(runnable);
}
else
{
thread = new Thread(runnable, threadName);
}
thread.setDaemon(true);
return thread;
}
@Override
public final void executeLongOperation(final Object component, final Runnable runnable)
{
invoke()
.setParentComponent(component)
.setLongOperation(true)
.setOnFail(OnFail.ThrowException) // backward compatibility
.invoke(runnable);
}
|
@Override
public void invokeLater(final int windowNo, final Runnable runnable)
{
invoke()
.setParentComponentByWindowNo(windowNo)
.setInvokeLater(true)
.setOnFail(OnFail.ThrowException) // backward compatibility
.invoke(runnable);
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}.
*/
@Deprecated
@Override
public void hideBusyDialog()
{
// nothing
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#disableServerPush()}.
*/
@Deprecated
@Override
public void disableServerPush()
{
// nothing
}
/**
* This method throws an UnsupportedOperationException.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#infoNoWait(int, String)}.
* @throws UnsupportedOperationException
*/
@Deprecated
@Override
public void infoNoWait(int WindowNo, String AD_Message)
{
throw new UnsupportedOperationException("not implemented");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInstance.java
| 1
|
请完成以下Java代码
|
public class BeanManagerLookup {
/** holds a local beanManager if no jndi is available */
public static BeanManager localInstance;
/** provide a custom jndi lookup name */
public static String jndiName;
public static BeanManager getBeanManager() {
if (localInstance != null) {
return localInstance;
}
return lookupBeanManagerInJndi();
}
private static BeanManager lookupBeanManagerInJndi() {
if (jndiName != null) {
try {
return (BeanManager) InitialContext.doLookup(jndiName);
} catch (NamingException e) {
throw new FlowableException("Could not lookup beanmanager in jndi using name: '" + jndiName + "'.", e);
|
}
}
try {
// in an application server
return (BeanManager) InitialContext.doLookup("java:comp/BeanManager");
} catch (NamingException e) {
// silently ignore
}
try {
// in a servlet container
return (BeanManager) InitialContext.doLookup("java:comp/env/BeanManager");
} catch (NamingException e) {
// silently ignore
}
throw new FlowableException("Could not lookup beanmanager in jndi. If no jndi is available, set the beanmanger to the 'localInstance' property of this class.");
}
}
|
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\util\BeanManagerLookup.java
| 1
|
请完成以下Java代码
|
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Occupation_AdditionalSpecialization_ID (final int AD_User_Occupation_AdditionalSpecialization_ID)
{
if (AD_User_Occupation_AdditionalSpecialization_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public int getAD_User_Occupation_AdditionalSpecialization_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public org.compiere.model.I_CRM_Occupation getCRM_Occupation()
{
return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class);
}
|
@Override
public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation)
{
set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation);
}
@Override
public void setCRM_Occupation_ID (final int CRM_Occupation_ID)
{
if (CRM_Occupation_ID < 1)
set_Value (COLUMNNAME_CRM_Occupation_ID, null);
else
set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID);
}
@Override
public int getCRM_Occupation_ID()
{
return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_AdditionalSpecialization.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public boolean isInserted() {
return isInserted;
}
@Override
public void setInserted(boolean isInserted) {
this.isInserted = isInserted;
}
@Override
public boolean isUpdated() {
return isUpdated;
}
@Override
public void setUpdated(boolean isUpdated) {
this.isUpdated = isUpdated;
}
@Override
public boolean isDeleted() {
return isDeleted;
}
|
@Override
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public Object getOriginalPersistentState() {
return originalPersistentState;
}
@Override
public void setOriginalPersistentState(Object persistentState) {
this.originalPersistentState = persistentState;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntityNoRevision.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getContentType(){
return contentType;
}
public int getStatusCode() {
return statusCode;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public void setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
|
public String getExceptionMsg() {
return exceptionMsg;
}
public Exception getException() {
return exception;
}
public boolean isSuccess(){
return statusCode==200;
}
public boolean isError(){
return exception!=null;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpResult.java
| 2
|
请完成以下Java代码
|
public class UserOperationLogContext {
protected String operationId;
protected String userId;
protected List<UserOperationLogContextEntry> entries;
public UserOperationLogContext() {
this.entries = new ArrayList<UserOperationLogContextEntry>();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
|
public String getOperationId() {
return operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public void addEntry(UserOperationLogContextEntry entry) {
entries.add(entry);
}
public List<UserOperationLogContextEntry> getEntries() {
return entries;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContext.java
| 1
|
请完成以下Java代码
|
public int getES_FTS_Config_Field_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_Field_ID);
}
@Override
public de.metas.elasticsearch.model.I_ES_FTS_Filter getES_FTS_Filter()
{
return get_ValueAsPO(COLUMNNAME_ES_FTS_Filter_ID, de.metas.elasticsearch.model.I_ES_FTS_Filter.class);
}
@Override
public void setES_FTS_Filter(final de.metas.elasticsearch.model.I_ES_FTS_Filter ES_FTS_Filter)
{
set_ValueFromPO(COLUMNNAME_ES_FTS_Filter_ID, de.metas.elasticsearch.model.I_ES_FTS_Filter.class, ES_FTS_Filter);
}
@Override
public void setES_FTS_Filter_ID (final int ES_FTS_Filter_ID)
{
if (ES_FTS_Filter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, ES_FTS_Filter_ID);
}
@Override
public int getES_FTS_Filter_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_ID);
}
@Override
public void setES_FTS_Filter_JoinColumn_ID (final int ES_FTS_Filter_JoinColumn_ID)
{
if (ES_FTS_Filter_JoinColumn_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, ES_FTS_Filter_JoinColumn_ID);
}
|
@Override
public int getES_FTS_Filter_JoinColumn_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_JoinColumn_ID);
}
@Override
public void setIsNullable (final boolean IsNullable)
{
set_Value (COLUMNNAME_IsNullable, IsNullable);
}
@Override
public boolean isNullable()
{
return get_ValueAsBoolean(COLUMNNAME_IsNullable);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Filter_JoinColumn.java
| 1
|
请完成以下Java代码
|
public void indented(Runnable runnable) {
indent();
runnable.run();
outdent();
}
/**
* Increase the indentation level.
*/
private void indent() {
this.level++;
refreshIndent();
}
/**
* Decrease the indentation level.
*/
private void outdent() {
this.level--;
refreshIndent();
}
private void refreshIndent() {
this.indent = this.indentStrategy.apply(this.level);
}
|
@Override
public void write(char[] chars, int offset, int length) {
try {
if (this.prependIndent) {
this.out.write(this.indent.toCharArray(), 0, this.indent.length());
this.prependIndent = false;
}
this.out.write(chars, offset, length);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void flush() throws IOException {
this.out.flush();
}
@Override
public void close() throws IOException {
this.out.close();
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriter.java
| 1
|
请完成以下Java代码
|
public abstract class TreeCheckingMode {
protected DefaultTreeCheckingModel model;
// TODO: implementare Strategy in questo modo: TreeCheckingMode classe
// interna al TreeCheckingModel, con un metodo getModel() protetto,
// utile
// alle sottoclassi
TreeCheckingMode(DefaultTreeCheckingModel model) {
this.model = model;
}
/**
* Checks the specified path and propagates the checking according to
* the strategy
*
* @param path the path to be added.
*/
public abstract void checkPath(TreePath path);
/**
* Unchecks the specified path and propagates the checking according to
* the strategy
*
* @param path the path to be removed.
*/
public abstract void uncheckPath(TreePath path);
|
/**
* Update the check of the given path after the insertion of some of its
* children, according to the strategy
*
* @param path
*/
public abstract void updateCheckAfterChildrenInserted(TreePath path);
/**
* Update the check of the given path after the removal of some of its
* children, according to the strategy
*
* @param path
*/
public abstract void updateCheckAfterChildrenRemoved(TreePath path);
/**
* Update the check of the given path after the structure change,
* according to the strategy
*
* @param path
*/
public abstract void updateCheckAfterStructureChanged(TreePath path);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\TreeCheckingMode.java
| 1
|
请完成以下Java代码
|
public final void addCtxProvider(final IRecordTextProvider ctxProvider)
{
Check.assumeNotNull(ctxProvider, "ctx provider not null");
ctxProviders.addIfAbsent(ctxProvider);
}
public void setDefaultCtxProvider(final IRecordTextProvider defaultCtxProvider)
{
Check.assumeNotNull(defaultCtxProvider, "defaultCtxProvider not null");
this.defaultCtxProvider = defaultCtxProvider;
}
@Override
public Optional<String> getTextMessageIfApplies(final ITableRecordReference referencedRecord)
{
// take the providers one by one and see if any of them applies to the given referenced record
for (final IRecordTextProvider ctxProvider : ctxProviders)
{
|
final Optional<String> textMessage = ctxProvider.getTextMessageIfApplies(referencedRecord);
if (textMessage != null && textMessage.isPresent())
{
return textMessage;
}
}
// Fallback to default provider
final Optional<String> textMessage = defaultCtxProvider.getTextMessageIfApplies(referencedRecord);
// guard against development issues (usually the text message shall never be null)
if (textMessage == null)
{
new AdempiereException("Possible development issue. " + defaultCtxProvider + " returned null for " + referencedRecord)
.throwIfDeveloperModeOrLogWarningElse(logger);
return Optional.absent();
}
return textMessage;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\spi\impl\CompositeRecordTextProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class NullType implements VariableType {
public static final String TYPE_NAME = "null";
private static final long serialVersionUID = 1L;
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
|
@Override
public Object getValue(ValueFields valueFields) {
return null;
}
@Override
public boolean isAbleToStore(Object value) {
return (value == null);
}
@Override
public void setValue(Object value, ValueFields valueFields) {
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\NullType.java
| 2
|
请完成以下Java代码
|
private Collection<GrantedAuthority> getGrantedAuthorityCollection(Object value) {
Collection<GrantedAuthority> result = new ArrayList<>();
addGrantedAuthorityCollection(result, value);
return result;
}
/**
* Convert the given value to a collection of Granted Authorities, adding the result
* to the given result collection.
* @param value The value to convert to a GrantedAuthority Collection
*/
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object value) {
if (value == null) {
return;
}
if (value instanceof Collection<?>) {
addGrantedAuthorityCollection(result, (Collection<?>) value);
}
else if (value instanceof Object[]) {
addGrantedAuthorityCollection(result, (Object[]) value);
}
else if (value instanceof String) {
addGrantedAuthorityCollection(result, (String) value);
}
else if (value instanceof GrantedAuthority) {
result.add((GrantedAuthority) value);
}
else {
throw new IllegalArgumentException("Invalid object type: " + value.getClass().getName());
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Collection<?> value) {
for (Object elt : value) {
addGrantedAuthorityCollection(result, elt);
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object[] value) {
for (Object aValue : value) {
addGrantedAuthorityCollection(result, aValue);
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, String value) {
StringTokenizer tokenizer = new StringTokenizer(value, this.stringSeparator, false);
while (tokenizer.hasMoreTokens()) {
|
String token = tokenizer.nextToken();
if (StringUtils.hasText(token)) {
result.add(new SimpleGrantedAuthority(token));
}
}
}
/**
*
* @see org.springframework.security.core.authority.mapping.MappableAttributesRetriever#getMappableAttributes()
*/
@Override
public Set<String> getMappableAttributes() {
return this.mappableAttributes;
}
/**
* @return Returns the stringSeparator.
*/
public String getStringSeparator() {
return this.stringSeparator;
}
/**
* @param stringSeparator The stringSeparator to set.
*/
public void setStringSeparator(String stringSeparator) {
Assert.notNull(stringSeparator, "stringSeparator cannot be null");
this.stringSeparator = stringSeparator;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\MapBasedAttributes2GrantedAuthoritiesMapper.java
| 1
|
请完成以下Java代码
|
public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_InOutLine_ID()));
}
/** Set Movement Quantity.
@param MovementQty
Quantity of a product moved.
|
*/
public void setMovementQty (BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Movement Quantity.
@return Quantity of a product moved.
*/
public BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLineMA.java
| 1
|
请完成以下Java代码
|
public static DistributionJobId ofDDOrderId(final @NonNull DDOrderId ddOrderId)
{
return new DistributionJobId(ddOrderId);
}
@JsonCreator
public static DistributionJobId ofJson(final @NonNull Object json)
{
final DDOrderId ddOrderId = RepoIdAwares.ofObject(json, DDOrderId.class, DDOrderId::ofRepoId);
return ofDDOrderId(ddOrderId);
}
public static DistributionJobId ofWFProcessId(final WFProcessId wfProcessId)
{
final DDOrderId ddOrderId = wfProcessId.getRepoIdAssumingApplicationId(DistributionMobileApplication.APPLICATION_ID, DDOrderId::ofRepoId);
return ofDDOrderId(ddOrderId);
}
@JsonValue
public String toString()
{
|
return toJson();
}
@NonNull
private String toJson()
{
return String.valueOf(ddOrderId.getRepoId());
}
public DDOrderId toDDOrderId() {return ddOrderId;}
public WFProcessId toWFProcessId() {return WFProcessId.ofIdPart(DistributionMobileApplication.APPLICATION_ID, ddOrderId);}
public static boolean equals(DistributionJobId id1, DistributionJobId id2) {return Objects.equals(id1, id2);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJobId.java
| 1
|
请完成以下Java代码
|
public class IntegerRestVariableConverter implements RestVariableConverter {
@Override
public String getRestTypeName() {
return "integer";
}
@Override
public Class<?> getVariableType() {
return Integer.class;
}
@Override
public Object getVariableValue(EngineRestVariable result) {
if (result.getValue() != null) {
if (!(result.getValue() instanceof Number)) {
throw new FlowableIllegalArgumentException("Converter can only convert integers");
}
return ((Number) result.getValue()).intValue();
}
return null;
|
}
@Override
public void convertVariableValue(Object variableValue, EngineRestVariable result) {
if (variableValue != null) {
if (!(variableValue instanceof Integer)) {
throw new FlowableIllegalArgumentException("Converter can only convert integers");
}
result.setValue(variableValue);
} else {
result.setValue(null);
}
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\IntegerRestVariableConverter.java
| 1
|
请完成以下Java代码
|
public static DocSubType ofCode(@NonNull final String code)
{
return index.ofCode(code);
}
@NonNull
public static DocSubType ofNullableCode(@Nullable final String code)
{
final DocSubType docSubType = index.ofNullableCode(code);
return docSubType != null ? docSubType : DocSubType.NONE;
}
public static boolean equals(@NonNull final DocSubType o1, @NonNull final DocSubType o2) { return Objects.equals(o1, o2); }
@JsonValue
public String getCode()
{
return code;
|
}
@Nullable
public String getNullableCode()
{
return isAnyOrNone() ? null : code;
}
public boolean isAny() { return ANY.equals(this); }
public boolean isNone() { return NONE.equals(this); }
public boolean isAnyOrNone() { return isAny() || isNone(); }
public boolean IsInterimInvoice() { return DownPayment.equals(this); }
public boolean isPrepay() { return PrepayOrder.equals(this); }
public boolean isCallOrder() { return CallOrder.equals(this); }
public boolean isFrameAgreement() { return FrameAgrement.equals(this); }
public boolean isMediated() { return Mediated.equals(this); }
public boolean isRequisition() { return Requisition.equals(this); }
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\DocSubType.java
| 1
|
请完成以下Java代码
|
private Quantity retrieveReservableQuantity(@NonNull final ProductId productId)
{
final RetrieveHUsQtyRequest request = WEBUI_C_OrderLineSO_Util.createHuQuantityRequest(
streamSelectedHUIds(Select.ALL), productId);
return huReservationService.retrieveReservableQty(request);
}
@Override
protected String doIt()
{
final SalesOrderLine salesOrderLine = WEBUI_C_OrderLineSO_Util.retrieveSalesOrderLine(getView(), salesOrderLineRepository).get();
final ImmutableList<HuId> selectedHuIds = streamSelectedHUIds(Select.ALL)
.collect(ImmutableList.toImmutableList());
if (selectedHuIds.isEmpty())
{
throw new AdempiereException("@NoSelection@");
|
}
final Quantity qtyToReserve = Quantity.of(qtyToReserveBD, salesOrderLine.getOrderedQty().getUOM());
final ReserveHUsRequest reservationRequest = ReserveHUsRequest
.builder()
.huIds(selectedHuIds)
.productId(salesOrderLine.getProductId())
.qtyToReserve(qtyToReserve)
.documentRef(HUReservationDocRef.ofSalesOrderLineId(salesOrderLine.getId().getOrderLineId()))
.build();
huReservationService.makeReservation(reservationRequest);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\hu\reservation\process\WEBUI_C_OrderLineSO_Make_HUReservation.java
| 1
|
请完成以下Java代码
|
public IAttributeStorageFactory createHUAttributeStorageFactory(@NonNull final IHUStorageFactory huStorageFactory)
{
return createHUAttributeStorageFactory(huStorageFactory, HUAttributesDAO.instance);
}
@Override
public IAttributeStorageFactory createHUAttributeStorageFactory(
@NonNull final IHUStorageFactory huStorageFactory,
@NonNull final IHUAttributesDAO huAttributesDAO)
{
final IAttributeStorageFactory factory = prepareHUAttributeStorageFactory(huAttributesDAO);
factory.setHUStorageFactory(huStorageFactory);
return factory;
}
@Override
public IAttributeStorageFactory prepareHUAttributeStorageFactory(@NonNull final IHUAttributesDAO huAttributesDAO)
{
final CompositeAttributeStorageFactory factory = new CompositeAttributeStorageFactory();
factory.setHUAttributesDAO(huAttributesDAO);
factory.addAttributeStorageFactoryClasses(attributeStorageFactories);
for (final IAttributeStorageListener attributeStorageListener : attributeStorageListeners)
{
factory.addAttributeStorageListener(attributeStorageListener);
}
return factory;
}
@Override
public void addAttributeStorageFactory(@NonNull final Class<? extends IAttributeStorageFactory> attributeStorageFactoryClass)
{
|
final boolean added = attributeStorageFactories.addIfAbsent(attributeStorageFactoryClass);
if (added)
{
logger.info("Registered: {}", attributeStorageFactoryClass);
}
else
{
logger.warn("Already registered: {}", attributeStorageFactoryClass);
}
}
@Override
public void addAttributeStorageListener(@NonNull final IAttributeStorageListener attributeStorageListener)
{
attributeStorageListeners.add(attributeStorageListener);
logger.info("Registered: {}", attributeStorageListener);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AttributeStorageFactoryService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RabbitConfig {
/**
* Direct Exchange 示例的配置类
*/
public static class DirectExchangeDemoConfiguration {
// 创建 Queue
@Bean
public Queue demo07Queue() {
return QueueBuilder.durable(Demo07Message.QUEUE) // durable: 是否持久化
.exclusive() // exclusive: 是否排它
.autoDelete() // autoDelete: 是否自动删除
.deadLetterExchange(Demo07Message.EXCHANGE)
.deadLetterRoutingKey(Demo07Message.DEAD_ROUTING_KEY)
.build();
}
// 创建 Dead Queue
@Bean
public Queue demo07DeadQueue() {
return new Queue(Demo07Message.DEAD_QUEUE, // Queue 名字
true, // durable: 是否持久化
false, // exclusive: 是否排它
false); // autoDelete: 是否自动删除
}
// 创建 Direct Exchange
@Bean
public DirectExchange demo07Exchange() {
return new DirectExchange(Demo07Message.EXCHANGE,
true, // durable: 是否持久化
false); // exclusive: 是否排它
|
}
// 创建 Binding
// Exchange:Demo07Message.EXCHANGE
// Routing key:Demo07Message.ROUTING_KEY
// Queue:Demo07Message.QUEUE
@Bean
public Binding demo07Binding() {
return BindingBuilder.bind(demo07Queue()).to(demo07Exchange()).with(Demo07Message.ROUTING_KEY);
}
// 创建 Dead Binding
// Exchange:Demo07Message.EXCHANGE
// Routing key:Demo07Message.DEAD_ROUTING_KEY
// Queue:Demo07Message.DEAD_QUEUE
@Bean
public Binding demo07DeadBinding() {
return BindingBuilder.bind(demo07DeadQueue()).to(demo07Exchange()).with(Demo07Message.DEAD_ROUTING_KEY);
}
}
}
|
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-consume-retry\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
| 2
|
请完成以下Java代码
|
public static Builder builder()
{
return new Builder();
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
public BPartnerId getBPartnerId()
{
return bpartnerId;
}
public BankAccountId getBPartnerBankAccountId()
{
return bpBankAccountId;
}
public static final class Builder
{
private String paymentRule;
@Getter private @Nullable InvoiceId invoiceId;
@Getter private @Nullable OrderId orderId;
@Getter private @Nullable OrderPayScheduleId orderPayScheduleId;
private Boolean isSOTrx;
private BPartnerId bpartnerId;
private @Nullable BankAccountId bpBankAccountId;
// Amounts
private BigDecimal _openAmt;
private BigDecimal _discountAmt;
PaySelectionLineCandidate build()
{
return new PaySelectionLineCandidate(this);
}
public String getPaymentRule()
{
Check.assumeNotNull(paymentRule, "paymentRule not null");
return paymentRule;
}
public Builder setPaymentRule(final String paymentRule)
{
this.paymentRule = paymentRule;
return this;
}
public Builder setInvoiceId(final @Nullable InvoiceId invoiceId)
{
this.invoiceId = invoiceId;
return this;
}
public Builder setOrderPayScheduleId(final @Nullable OrderPayScheduleId orderPayScheduleId)
{
this.orderPayScheduleId = orderPayScheduleId;
return this;
}
public Builder setOrderId(final @Nullable OrderId orderId)
{
this.orderId = orderId;
return this;
}
public Builder setIsSOTrx(final boolean isSOTrx)
{
this.isSOTrx = isSOTrx;
return this;
}
public boolean isSOTrx()
{
return isSOTrx;
}
public BPartnerId getBPartnerId()
{
|
return bpartnerId;
}
public Builder setBPartnerId(final BPartnerId bpartnerId)
{
this.bpartnerId = bpartnerId;
return this;
}
public @Nullable BankAccountId getBPartnerBankAccountId()
{
return bpBankAccountId;
}
public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId)
{
this.bpBankAccountId = bpBankAccountId;
return this;
}
public BigDecimal getOpenAmt()
{
return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO);
}
public Builder setOpenAmt(final BigDecimal openAmt)
{
this._openAmt = openAmt;
return this;
}
public BigDecimal getPayAmt()
{
final BigDecimal openAmt = getOpenAmt();
final BigDecimal discountAmt = getDiscountAmt();
return openAmt.subtract(discountAmt);
}
public BigDecimal getDiscountAmt()
{
return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO);
}
public Builder setDiscountAmt(final BigDecimal discountAmt)
{
this._discountAmt = discountAmt;
return this;
}
public BigDecimal getDifferenceAmt()
{
final BigDecimal openAmt = getOpenAmt();
final BigDecimal payAmt = getPayAmt();
final BigDecimal discountAmt = getDiscountAmt();
return openAmt.subtract(payAmt).subtract(discountAmt);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Language {
@Id
@Column(name = "iso_code")
private String isoCode;
public Language() {
}
public Language(final String isoCode) {
this.isoCode = isoCode;
}
public String getIsoCode() {
return isoCode;
}
public void setIsoCode(final String isoCode) {
this.isoCode = isoCode;
}
@Override
public String toString() {
return "Language{" +
"isoCode='" + isoCode + '\'' +
'}';
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
|
if (o == null || getClass() != o.getClass()) {
return false;
}
final Language language = (Language) o;
return Objects.equals(isoCode, language.isoCode);
}
@Override
public int hashCode() {
return isoCode != null ? isoCode.hashCode() : 0;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query-3\src\main\java\com\baeldung\spring\data\jpa\spel\entity\Language.java
| 2
|
请完成以下Java代码
|
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);
}
@Override
public void setPercentage (final @Nullable BigDecimal Percentage)
{
set_Value (COLUMNNAME_Percentage, Percentage);
}
@Override
public BigDecimal getPercentage()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceActual (final @Nullable BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
@Override
public BigDecimal getPriceActual()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceEntered (final @Nullable BigDecimal PriceEntered)
{
set_Value (COLUMNNAME_PriceEntered, PriceEntered);
}
@Override
public BigDecimal getPriceEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPrice_UOM_ID (final int Price_UOM_ID)
{
if (Price_UOM_ID < 1)
set_Value (COLUMNNAME_Price_UOM_ID, null);
else
set_Value (COLUMNNAME_Price_UOM_ID, Price_UOM_ID);
}
@Override
public int getPrice_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Price_UOM_ID);
}
@Override
|
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInPriceUOM (final @Nullable BigDecimal QtyEnteredInPriceUOM)
{
set_Value (COLUMNNAME_QtyEnteredInPriceUOM, QtyEnteredInPriceUOM);
}
@Override
public BigDecimal getQtyEnteredInPriceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInPriceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Detail.java
| 1
|
请完成以下Java代码
|
public void setTotalLines (final @Nullable BigDecimal TotalLines)
{
set_Value (COLUMNNAME_TotalLines, TotalLines);
}
@Override
public BigDecimal getTotalLines()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLines);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalLinesWithSurchargeAmt (final @Nullable BigDecimal TotalLinesWithSurchargeAmt)
{
set_Value (COLUMNNAME_TotalLinesWithSurchargeAmt, TotalLinesWithSurchargeAmt);
}
@Override
public BigDecimal getTotalLinesWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLinesWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalTaxBaseAmt (final @Nullable BigDecimal TotalTaxBaseAmt)
{
set_Value (COLUMNNAME_TotalTaxBaseAmt, TotalTaxBaseAmt);
}
@Override
public BigDecimal getTotalTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalTaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVat (final @Nullable BigDecimal TotalVat)
{
set_Value (COLUMNNAME_TotalVat, TotalVat);
}
|
@Override
public BigDecimal getTotalVat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVatWithSurchargeAmt (final BigDecimal TotalVatWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TotalVatWithSurchargeAmt, TotalVatWithSurchargeAmt);
}
@Override
public BigDecimal getTotalVatWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVatWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_v.java
| 1
|
请完成以下Java代码
|
public <MovementLineType extends I_M_MovementLine> List<MovementLineType> retrieveLines(@NonNull final I_M_Movement movement, @NonNull final Class<MovementLineType> movementLineClass)
{
final IQueryBuilder<MovementLineType> queryBuilder = queryBL.createQueryBuilder(movementLineClass, movement);
queryBuilder.getCompositeFilter()
.addEqualsFilter(I_M_MovementLine.COLUMNNAME_M_Movement_ID, movement.getM_Movement_ID());
queryBuilder.orderBy()
.addColumn(I_M_MovementLine.COLUMNNAME_Line, Direction.Ascending, Nulls.Last);
return queryBuilder
.create()
.list(movementLineClass);
}
@Override
public IQueryBuilder<I_M_Movement> retrieveMovementsForInventoryQuery(@NonNull final InventoryId inventoryId)
{
return queryBL.createQueryBuilder(I_M_Movement.class)
.addEqualsFilter(I_M_Movement.COLUMN_M_Inventory_ID, inventoryId);
}
|
@Override
public List<I_M_Movement> retrieveMovementsForDDOrder(final int ddOrderId)
{
return queryBL.createQueryBuilder(I_M_Movement.class)
.addEqualsFilter(I_M_Movement.COLUMN_DD_Order_ID, ddOrderId)
.create()
.list();
}
@Override
public void save(@NonNull final I_M_Movement movement)
{
saveRecord(movement);
}
@Override
public void save(@NonNull final I_M_MovementLine movementLine)
{
saveRecord(movementLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mmovement\api\impl\MovementDAO.java
| 1
|
请完成以下Java代码
|
public HistoricJobLogQuery orderByProcessDefinitionId() {
orderBy(HistoricJobLogQueryProperty.PROCESS_DEFINITION_ID);
return this;
}
public HistoricJobLogQuery orderByProcessDefinitionKey() {
orderBy(HistoricJobLogQueryProperty.PROCESS_DEFINITION_KEY);
return this;
}
public HistoricJobLogQuery orderByDeploymentId() {
orderBy(HistoricJobLogQueryProperty.DEPLOYMENT_ID);
return this;
}
public HistoricJobLogQuery orderPartiallyByOccurrence() {
orderBy(HistoricJobLogQueryProperty.SEQUENCE_COUNTER);
return this;
}
public HistoricJobLogQuery orderByTenantId() {
return orderBy(HistoricJobLogQueryProperty.TENANT_ID);
}
@Override
public HistoricJobLogQuery orderByHostname() {
return orderBy(HistoricJobLogQueryProperty.HOSTNAME);
}
// results //////////////////////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricJobLogManager()
.findHistoricJobLogsCountByQueryCriteria(this);
}
public List<HistoricJobLog> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricJobLogManager()
.findHistoricJobLogsByQueryCriteria(this, page);
}
// getter //////////////////////////////////
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public String getJobId() {
return jobId;
}
public String getJobExceptionMessage() {
return jobExceptionMessage;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public String getJobDefinitionType() {
return jobDefinitionType;
}
|
public String getJobDefinitionConfiguration() {
return jobDefinitionConfiguration;
}
public String[] getActivityIds() {
return activityIds;
}
public String[] getFailedActivityIds() {
return failedActivityIds;
}
public String[] getExecutionIds() {
return executionIds;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getDeploymentId() {
return deploymentId;
}
public JobState getState() {
return state;
}
public String[] getTenantIds() {
return tenantIds;
}
public String getHostname() {
return hostname;
}
// setter //////////////////////////////////
protected void setState(JobState state) {
this.state = state;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() throws Exception {
// 通过 ApplicationContext 获得所有 MessageHandler Bean
applicationContext.getBeansOfType(MessageHandler.class).values() // 获得所有 MessageHandler Bean
.forEach(messageHandler -> handlers.put(messageHandler.getType(), messageHandler)); // 添加到 handlers 中
logger.info("[afterPropertiesSet][消息处理器数量:{}]", handlers.size());
}
/**
* 获得类型对应的 MessageHandler
*
* @param type 类型
* @return MessageHandler
*/
MessageHandler getMessageHandler(String type) {
MessageHandler handler = handlers.get(type);
if (handler == null) {
throw new IllegalArgumentException(String.format("类型(%s) 找不到匹配的 MessageHandler 处理器", type));
}
return handler;
}
/**
* 获得 MessageHandler 处理的消息类
*
* @param handler 处理器
* @return 消息类
*/
static Class<? extends Message> getMessageClass(MessageHandler handler) {
// 获得 Bean 对应的 Class 类名。因为有可能被 AOP 代理过。
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(handler);
// 获得接口的 Type 数组
Type[] interfaces = targetClass.getGenericInterfaces();
Class<?> superclass = targetClass.getSuperclass();
while ((Objects.isNull(interfaces) || 0 == interfaces.length) && Objects.nonNull(superclass)) { // 此处,是以父类的接口为准
interfaces = superclass.getGenericInterfaces();
superclass = targetClass.getSuperclass();
}
if (Objects.nonNull(interfaces)) {
|
// 遍历 interfaces 数组
for (Type type : interfaces) {
// 要求 type 是泛型参数
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// 要求是 MessageHandler 接口
if (Objects.equals(parameterizedType.getRawType(), MessageHandler.class)) {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// 取首个元素
if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
return (Class<Message>) actualTypeArguments[0];
} else {
throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler));
}
}
}
}
}
throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler));
}
}
|
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-common\src\main\java\cn\iocoder\springboot\lab67\nettycommondemo\dispatcher\MessageHandlerContainer.java
| 1
|
请完成以下Java代码
|
private final void assertUniqueIds(final List<?> records)
{
if (records == null || records.isEmpty())
{
return;
}
if (records.size() == 1)
{
// ofc it's unique ID
return;
}
final Set<Integer> ids = new HashSet<Integer>();
for (final Object record : records)
{
final POJOWrapper wrapper = POJOWrapper.getWrapper(record);
final int recordId = wrapper.getId();
if (!ids.add(recordId))
{
throw new RuntimeException("Duplicate ID found when retrieving from database"
+"\n ID="+recordId
+"\n Records: "+records);
}
}
}
private final String toString(final List<Object> records)
{
final StringBuilder sb = new StringBuilder();
for (final Object record : records)
{
if (sb.length() > 0)
{
sb.append("\n\n");
}
sb.append("Record: ").append(record);
final Throwable trackingStackTrace = InterfaceWrapperHelper.getDynAttribute(record, DYNATTR_TrackingStackTrace);
if (trackingStackTrace != null)
{
sb.append("\nTrack stacktrace: ").append(Util.dumpStackTraceToString(trackingStackTrace));
}
}
return sb.toString();
}
private static final class RecordInfo
|
{
private final WeakList<Object> records = new WeakList<>();
public void add(final Object recordToAdd)
{
for (final Object record : records.hardList())
{
if (record == recordToAdd)
{
return;
}
}
records.add(recordToAdd);
}
public List<Object> getRecords()
{
return records.hardList();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOLookupMapInstancesTracker.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private <T> T getBeanOrNull(Class<T> type) {
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
return context.getBeanProvider(type).getIfUnique();
}
@SuppressWarnings("unchecked")
private RequestMatcher createDefaultSavedRequestMatcher(H http) {
RequestMatcher notFavIcon = new NegatedRequestMatcher(getFaviconRequestMatcher());
RequestMatcher notXRequestedWith = new NegatedRequestMatcher(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
RequestMatcher notWebSocket = new NegatedRequestMatcher(
new RequestHeaderRequestMatcher("Upgrade", "websocket"));
boolean isCsrfEnabled = http.getConfigurer(CsrfConfigurer.class) != null;
List<RequestMatcher> matchers = new ArrayList<>();
if (isCsrfEnabled) {
RequestMatcher getRequests = getRequestMatcherBuilder().matcher(HttpMethod.GET, "/**");
matchers.add(0, getRequests);
}
matchers.add(notFavIcon);
matchers.add(notMatchingMediaType(http, MediaType.APPLICATION_JSON));
matchers.add(notXRequestedWith);
matchers.add(notMatchingMediaType(http, MediaType.MULTIPART_FORM_DATA));
matchers.add(notMatchingMediaType(http, MediaType.TEXT_EVENT_STREAM));
matchers.add(notWebSocket);
return new AndRequestMatcher(matchers);
}
|
private RequestMatcher notMatchingMediaType(H http, MediaType mediaType) {
ContentNegotiationStrategy contentNegotiationStrategy = http.getSharedObject(ContentNegotiationStrategy.class);
if (contentNegotiationStrategy == null) {
contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
}
MediaTypeRequestMatcher mediaRequest = new MediaTypeRequestMatcher(contentNegotiationStrategy, mediaType);
mediaRequest.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
return new NegatedRequestMatcher(mediaRequest);
}
private RequestMatcher getFaviconRequestMatcher() {
return getRequestMatcherBuilder().matcher("/favicon.*");
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\RequestCacheConfigurer.java
| 2
|
请完成以下Java代码
|
public I_M_HU packToSingleHU(
@NonNull final IHUContext huContext,
@NonNull final HuId pickFromHUId,
@NonNull final ProductId productId,
@NonNull final Quantity qtyPicked,
@NonNull final PickingCandidateId pickingCandidateId)
{
final PackToInfo packToInfo = getPackToInfo(pickingCandidateId);
final boolean checkIfAlreadyPacked = isOnlyOnePickingCandidatePackedTo(packToInfo);
final List<I_M_HU> packedToHUs = packToHUsProducer.packToHU(
PackToHUsProducer.PackToHURequest.builder()
.huContext(huContext)
.pickFromHUId(pickFromHUId)
.packToInfo(packToInfo)
.productId(productId)
.qtyPicked(qtyPicked)
.catchWeight(null)
.documentRef(pickingCandidateId.toTableRecordReference())
.checkIfAlreadyPacked(checkIfAlreadyPacked)
.createInventoryForMissingQty(false)
.build()
)
.getAllTURecords();
if (packedToHUs.isEmpty())
{
throw new AdempiereException("Nothing was packed from " + pickFromHUId);
}
else if (packedToHUs.size() != 1)
{
final String packedHUsDisplayStr = packedToHUs.stream().map(hu -> String.valueOf(hu.getM_HU_ID())).collect(Collectors.joining(", "));
throw new AdempiereException("More than one HU was packed from " + pickFromHUId + ": " + packedHUsDisplayStr)
.appendParametersToMessage()
.setParameter("qtyPicked", qtyPicked);
}
else
{
return CollectionUtils.singleElement(packedToHUs);
}
|
}
private PackToInfo getPackToInfo(final PickingCandidateId pickingCandidateId)
{
final PackToInfo packToInfo = packToInfos.get(pickingCandidateId);
if (packToInfo == null)
{
throw new AdempiereException("No Pack To Infos computed for " + pickingCandidateId);
}
return packToInfo;
}
private boolean isOnlyOnePickingCandidatePackedTo(final PackToInfo packToInfo)
{
return pickingCandidateIdsByPackToInfo.get(packToInfo).size() == 1;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ProcessPickingCandidatesCommand.java
| 1
|
请完成以下Java代码
|
public Set<Object> keySet()
{
return getDelegate().keySet();
}
@Override
public Set<java.util.Map.Entry<Object, Object>> entrySet()
{
return getDelegate().entrySet();
}
@Override
public Collection<Object> values()
{
return getDelegate().values();
}
@Override
public boolean equals(Object o)
{
return getDelegate().equals(o);
}
@SuppressWarnings("deprecation")
@Override
public void save(OutputStream out, String comments)
{
getDelegate().save(out, comments);
}
@Override
public int hashCode()
{
return getDelegate().hashCode();
}
@Override
public void store(Writer writer, String comments) throws IOException
{
getDelegate().store(writer, comments);
}
@Override
public void store(OutputStream out, String comments) throws IOException
{
getDelegate().store(out, comments);
}
@Override
public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException
{
getDelegate().loadFromXML(in);
}
@Override
public void storeToXML(OutputStream os, String comment) throws IOException
|
{
getDelegate().storeToXML(os, comment);
}
@Override
public void storeToXML(OutputStream os, String comment, String encoding) throws IOException
{
getDelegate().storeToXML(os, comment, encoding);
}
@Override
public String getProperty(String key)
{
return getDelegate().getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue)
{
return getDelegate().getProperty(key, defaultValue);
}
@Override
public Enumeration<?> propertyNames()
{
return getDelegate().propertyNames();
}
@Override
public Set<String> stringPropertyNames()
{
return getDelegate().stringPropertyNames();
}
@Override
public void list(PrintStream out)
{
getDelegate().list(out);
}
@Override
public void list(PrintWriter out)
{
getDelegate().list(out);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ConfigDataLocation[] split(String delimiter) {
Assert.state(!this.value.isEmpty(), "Unable to split empty locations");
String[] values = StringUtils.delimitedListToStringArray(toString(), delimiter);
ConfigDataLocation[] result = new ConfigDataLocation[values.length];
for (int i = 0; i < values.length; i++) {
int index = i;
ConfigDataLocation configDataLocation = of(values[index]);
result[i] = configDataLocation.withOrigin(getOrigin());
}
return result;
}
/**
* Create a new {@link ConfigDataLocation} with a specific {@link Origin}.
* @param origin the origin to set
* @return a new {@link ConfigDataLocation} instance.
*/
ConfigDataLocation withOrigin(@Nullable Origin origin) {
return new ConfigDataLocation(this.optional, this.value, origin);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConfigDataLocation other = (ConfigDataLocation) obj;
return this.value.equals(other.value);
}
|
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() {
return (!this.optional) ? this.value : OPTIONAL_PREFIX + this.value;
}
/**
* Factory method to create a new {@link ConfigDataLocation} from a string.
* @param location the location string
* @return the {@link ConfigDataLocation} (which may be empty)
*/
public static ConfigDataLocation of(@Nullable String location) {
boolean optional = location != null && location.startsWith(OPTIONAL_PREFIX);
String value = (location != null && optional) ? location.substring(OPTIONAL_PREFIX.length()) : location;
return (StringUtils.hasText(value)) ? new ConfigDataLocation(optional, value, null) : EMPTY;
}
static boolean isNotEmpty(@Nullable ConfigDataLocation location) {
return (location != null) && !location.getValue().isEmpty();
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocation.java
| 2
|
请完成以下Java代码
|
public void setC_PricingRule_ID (int C_PricingRule_ID)
{
if (C_PricingRule_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PricingRule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PricingRule_ID, Integer.valueOf(C_PricingRule_ID));
}
/** Get Pricing Rule.
@return Pricing Rule */
@Override
public int getC_PricingRule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_PricingRule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
|
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\pricing\model\X_C_PricingRule.java
| 1
|
请完成以下Java代码
|
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty();
}
private static ServerHttpHeadersWriter createDelegate(CrossOriginEmbedderPolicy embedderPolicy) {
StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(EMBEDDER_POLICY, embedderPolicy.getPolicy());
return builder.build();
}
public enum CrossOriginEmbedderPolicy {
UNSAFE_NONE("unsafe-none"),
REQUIRE_CORP("require-corp"),
|
CREDENTIALLESS("credentialless");
private final String policy;
CrossOriginEmbedderPolicy(String policy) {
this.policy = policy;
}
public String getPolicy() {
return this.policy;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\CrossOriginEmbedderPolicyServerHttpHeadersWriter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ForecastDeletedHandler implements MaterialEventHandler<ForecastDeletedEvent>
{
@NonNull
private final CandidateRepositoryRetrieval candidateRepositoryRetrieval;
@NonNull
private final CandidateChangeService candidateChangeHandler;
@Override
public Collection<Class<? extends ForecastDeletedEvent>> getHandledEventType()
{
return ImmutableList.of(ForecastDeletedEvent.class);
}
@Override
public void handleEvent(@NonNull final ForecastDeletedEvent event)
{
deleteCandidates(event);
}
|
private void deleteCandidates(@NonNull final ForecastDeletedEvent event)
{
event.getForecast().getForecastLines().forEach(this::deleteCandidates);
}
private void deleteCandidates(@NonNull final ForecastLine forecastLine)
{
final CandidatesQuery query = CandidatesQuery
.builder()
.type(CandidateType.STOCK_UP)
.businessCase(CandidateBusinessCase.FORECAST)
.demandDetailsQuery(DemandDetailsQuery.ofForecastLineId(forecastLine.getForecastLineId()))
.build();
candidateRepositoryRetrieval.retrieveOrderedByDateAndSeqNo(query)
.forEach(candidateChangeHandler::onCandidateDelete);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\foreacast\ForecastDeletedHandler.java
| 2
|
请完成以下Java代码
|
private void printRunningTotal (PrintData pd, int levelNo, int rowNo)
{
if (m_runningTotalLines < 1)
{
return;
}
log.debug("(" + m_runningTotalLines + ") - Row=" + rowNo
+ ", mod=" + rowNo % m_runningTotalLines);
if (rowNo % m_runningTotalLines != 0)
{
return;
}
log.debug("Row=" + rowNo);
PrintDataColumn pdc = null;
int start = 0;
if (rowNo == 0)
{
start = 1;
}
for (int rt = start; rt < 2; rt++)
{
pd.addRow (true, levelNo);
// get sum columns
for (int c = 0; c < pd.getColumnInfo().length; c++)
{
pdc = pd.getColumnInfo()[c];
if (c == 0)
{
String title = "RunningTotal";
pd.addNode(new PrintDataElement(pdc.getColumnName(),
title, DisplayType.String, false, rt==0, pdc.getFormatPattern())); // page break
}
else if (m_group.isFunctionColumn(pdc.getColumnName(), PrintDataFunction.F_SUM))
{
|
pd.addNode(new PrintDataElement(pdc.getColumnName(),
m_group.getValue(PrintDataGroup.TOTAL, pdc.getColumnName(), PrintDataFunction.F_SUM),
PrintDataFunction.getFunctionDisplayType(PrintDataFunction.F_SUM,
pdc.getDisplayType()), false, false, pdc.getFormatPattern()));
}
} // for all sum columns
} // two lines
} // printRunningTotal
} // DataEngine
/**
* Table Reference Info
*/
class TableReference
{
/** Table Name */
public String TableName;
/** Key Column */
public String KeyColumn;
/** Display Column */
public String DisplayColumn;
/** Displayed */
public boolean IsValueDisplayed = false;
/** Translated */
public boolean IsTranslated = false;
} // TableReference
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\DataEngine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Representation getRepresentation() {
return this.representation;
}
public static class Gridfs {
/**
* GridFS database name.
*/
private @Nullable String database;
/**
* GridFS bucket name.
*/
private @Nullable String bucket;
public @Nullable String getDatabase() {
return this.database;
}
public void setDatabase(@Nullable String database) {
this.database = database;
}
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
}
public static class Representation {
|
/**
* Representation to use when converting a BigDecimal.
*/
private @Nullable BigDecimalRepresentation bigDecimal = BigDecimalRepresentation.UNSPECIFIED;
public @Nullable BigDecimalRepresentation getBigDecimal() {
return this.bigDecimal;
}
public void setBigDecimal(@Nullable BigDecimalRepresentation bigDecimal) {
this.bigDecimal = bigDecimal;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoProperties.java
| 2
|
请完成以下Java代码
|
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getTriggerEventType() {
return triggerEventType;
}
public void setTriggerEventType(String triggerEventType) {
this.triggerEventType = triggerEventType;
}
public boolean isSendSynchronously() {
return sendSynchronously;
}
public void setSendSynchronously(boolean sendSynchronously) {
this.sendSynchronously = sendSynchronously;
}
public List<IOParameter> getEventInParameters() {
return eventInParameters;
}
public void setEventInParameters(List<IOParameter> eventInParameters) {
this.eventInParameters = eventInParameters;
}
public List<IOParameter> getEventOutParameters() {
return eventOutParameters;
}
public void setEventOutParameters(List<IOParameter> eventOutParameters) {
this.eventOutParameters = eventOutParameters;
}
@Override
|
public SendEventServiceTask clone() {
SendEventServiceTask clone = new SendEventServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(SendEventServiceTask otherElement) {
super.setValues(otherElement);
setEventType(otherElement.getEventType());
setTriggerEventType(otherElement.getTriggerEventType());
setSendSynchronously(otherElement.isSendSynchronously());
eventInParameters = new ArrayList<>();
if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventInParameters()) {
eventInParameters.add(parameter.clone());
}
}
eventOutParameters = new ArrayList<>();
if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventOutParameters()) {
eventOutParameters.add(parameter.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SendEventServiceTask.java
| 1
|
请完成以下Java代码
|
public NotFoundException cannotFindResource(String resourcePath) {
return new NotFoundException(exceptionMessage(
"024",
"Unable to find resource at path {}", resourcePath));
}
public IllegalStateException notInsideCommandContext(String operation) {
return new IllegalStateException(exceptionMessage(
"025",
"Operation {} requires active command context. No command context active on thread {}.", operation, Thread.currentThread()));
}
public ProcessEngineException exceptionWhileParsingCycleExpresison(String duedateDescription, Exception e) {
return new ProcessEngineException(exceptionMessage(
"026",
"Exception while parsing cycle expression '{}': {}", duedateDescription, e.getMessage()), e);
}
public ProcessEngineException exceptionWhileResolvingDuedate(String duedate, Exception e) {
return new ProcessEngineException(exceptionMessage(
"027",
"Exception while resolving duedate '{}': {}", duedate, e.getMessage()), e);
}
public Exception cannotParseDuration(String expressions) {
return new ProcessEngineException(exceptionMessage(
"028",
"Cannot parse duration '{}'.", expressions));
}
public void logParsingRetryIntervals(String intervals, Exception e) {
logWarn(
"029",
"Exception while parsing retry intervals '{}'", intervals, e.getMessage(), e);
}
public void logJsonException(Exception e) {
logDebug(
"030",
"Exception while parsing JSON: {}", e.getMessage(), e);
}
public void logAccessExternalSchemaNotSupported(Exception e) {
logDebug(
"031",
"Could not restrict external schema access. "
+ "This indicates that this is not supported by your JAXP implementation: {}",
|
e.getMessage());
}
public void logMissingPropertiesFile(String file) {
logWarn("032", "Could not find the '{}' file on the classpath. " +
"If you have removed it, please restore it.", file);
}
public ProcessEngineException exceptionDuringFormParsing(String cause, String resourceName) {
return new ProcessEngineException(
exceptionMessage("033", "Could not parse Camunda Form resource {}. Cause: {}", resourceName, cause));
}
public void debugCouldNotResolveCallableElement(
String callingProcessDefinitionId,
String activityId,
Throwable cause) {
logDebug("046", "Could not resolve a callable element for activity {} in process {}. Reason: {}",
activityId,
callingProcessDefinitionId,
cause.getMessage());
}
public ProcessEngineException exceptionWhileSettingXxeProcessing(Throwable cause) {
return new ProcessEngineException(exceptionMessage(
"047",
"Exception while configuring XXE processing: {}", cause.getMessage()), cause);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EngineUtilLogger.java
| 1
|
请完成以下Java代码
|
public td getTopLeft()
{
return m_topLeft;
} // getTopLeft
/**
* Get Table Data Right (no class set)
* @return table data
*/
public td getTopRight()
{
return m_topRight;
} // getTopRight
/**
* String representation
* @return String
*/
@Override
public String toString()
{
return m_html.toString();
} // toString
/**
* Output Document
* @param out out
*/
public void output (OutputStream out)
|
{
m_html.output(out);
} // output
/**
* Output Document
* @param out out
*/
public void output (PrintWriter out)
{
m_html.output(out);
} // output
/**
* Add Popup Center
* @param nowrap set nowrap in td
* @return null or center single td
*/
public td addPopupCenter(boolean nowrap)
{
if (m_table == null)
return null;
//
td center = new td ("popupCenter", AlignType.CENTER, AlignType.MIDDLE, nowrap);
center.setColSpan(2);
m_table.addElement(new tr()
.addElement(center));
return center;
} // addPopupCenter
} // WDoc
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebDoc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SyncRfQPriceChangeEvent implements IConfirmableDTO
{
String uuid;
boolean deleted;
long syncConfirmationId;
String product_uuid;
String rfq_uuid;
BigDecimal price;
@Builder(toBuilder = true)
@JsonCreator
private SyncRfQPriceChangeEvent(
@JsonProperty("uuid") final String uuid,
@JsonProperty("deleted") final boolean deleted,
@JsonProperty("syncConfirmationId") final long syncConfirmationId,
@JsonProperty("product_uuid") final String product_uuid,
@JsonProperty("rfq_uuid") final String rfq_uuid,
@JsonProperty("price") final BigDecimal price)
|
{
this.uuid = uuid;
this.deleted = deleted;
this.syncConfirmationId = syncConfirmationId;
this.product_uuid = product_uuid;
this.rfq_uuid = rfq_uuid;
this.price = price;
}
@Override
public IConfirmableDTO withNotDeleted()
{
return toBuilder().deleted(false).build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncRfQPriceChangeEvent.java
| 2
|
请完成以下Java代码
|
private static class BalanceBuilder
{
private Money debit;
private Money credit;
public void add(@NonNull Balance balance)
{
add(balance.getDebit(), balance.getCredit());
}
public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder)
{
add(balanceBuilder.debit, balanceBuilder.credit);
return this;
}
public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd)
{
if (debitToAdd != null)
{
this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd;
|
}
if (creditToAdd != null)
{
this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd;
}
}
public Optional<Balance> build()
{
return debit != null || credit != null
? Optional.of(new Balance(debit, credit))
: Optional.empty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java
| 1
|
请完成以下Java代码
|
public String localDateTimeFormatyMd(LocalDateTime localDateTime) {
return DFY_MD.format(localDateTime);
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
*
* @param localDateTime /
|
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) {
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) {
return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime));
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\DateUtil.java
| 1
|
请完成以下Java代码
|
public Map<String, String> initParams() {
initParams.put(DISABLED_PARAM, null);
initParams.put(OPTION_PARAM, null);
initParams.put(VALUE_PARAM, null);
return initParams;
}
public void parseParams() {
String disabled = initParams.get(DISABLED_PARAM);
if (ServletFilterUtil.isEmpty(disabled)) {
setDisabled(false);
} else {
setDisabled(Boolean.parseBoolean(disabled));
}
String value = initParams.get(VALUE_PARAM);
String option = initParams.get(OPTION_PARAM);
if (!isDisabled()) {
if (!ServletFilterUtil.isEmpty(value) && !ServletFilterUtil.isEmpty(option)) {
throw new ProcessEngineException(this.getClass().getSimpleName() + ": cannot set both " + VALUE_PARAM + " and " + OPTION_PARAM + ".");
}
if (!ServletFilterUtil.isEmpty(value)) {
setValue(value);
} else if (!ServletFilterUtil.isEmpty(option)) {
setValue(parseValue(option).getHeaderValue());
} else {
setValue(HEADER_DEFAULT_VALUE.getHeaderValue());
}
}
|
}
protected XssProtectionOption parseValue(String optionValue) {
for (XssProtectionOption option : XssProtectionOption.values()) {
if (option.getName().equalsIgnoreCase(optionValue)) {
return option;
}
}
throw new ProcessEngineException(this.getClass().getSimpleName() + ": cannot set non-existing option " + optionValue + " for " + OPTION_PARAM + ".");
}
public String getHeaderName() {
return HEADER_NAME;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\XssProtectionProvider.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.