instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class ReverseIterator {
/**
* Iterate using the for loop.
*
* @param list the list
*/
public void iterateUsingForLoop(final List<String> list) {
for (int i = list.size(); i-- > 0; ) {
System.out.println(list.get(i));
}
}
/**
* Iterate using the Java {@link ListIterator}.
*
* @param list the list
*/
public void iterateUsingListIterator(final List<String> list) {
final ListIterator listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
/**
* Iterate using Java {@link Collections} API.
*
* @param list the list
*/
public void iterateUsingCollections(final List<String> list) {
Collections.reverse(list);
for (final String item : list) {
System.out.println(item);
}
}
/**
* Iterate using Apache Commons {@link ReverseListIterator}.
*
|
* @param list the list
*/
public void iterateUsingApacheReverseListIterator(final List<String> list) {
final ReverseListIterator listIterator = new ReverseListIterator(list);
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
/**
* Iterate using Guava {@link Lists} API.
*
* @param list the list
*/
public void iterateUsingGuava(final List<String> list) {
final List<String> reversedList = Lists.reverse(list);
for (final String item : reversedList) {
System.out.println(item);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\ReverseIterator.java
| 1
|
请完成以下Java代码
|
public String getDisplay()
{
return m_text.getText();
} // getDisplay
/**
* ActionListener - Button - Start Dialog
* @param e ActionEvent
*/
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == mDelete)
{
m_value = null; // create new
}
//
final VLocationDialog ld = new VLocationDialog(SwingUtils.getFrame(this), Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Location"), m_value);
ld.setVisible(true);
Object oldValue = getValue();
m_value = ld.getValue();
//
if (e.getSource() == mDelete)
;
else if (!ld.isChanged())
return;
// Data Binding
try
{
int C_Location_ID = 0;
if (m_value != null)
C_Location_ID = m_value.getC_Location_ID();
Integer ii = new Integer(C_Location_ID);
if (C_Location_ID > 0)
fireVetoableChange(m_columnName, oldValue, ii);
setValue(ii);
if (ii.equals(oldValue) && m_GridTab != null && m_GridField != null)
{
// force Change - user does not realize that embedded object is already saved.
m_GridTab.processFieldChange(m_GridField);
}
}
catch (PropertyVetoException pve)
{
log.error("VLocation.actionPerformed", pve);
}
} // actionPerformed
/**
* Action Listener Interface
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
m_text.addActionListener(listener);
} // addActionListener
@Override
public synchronized void addMouseListener(MouseListener l)
{
m_text.addMouseListener(l);
}
/**
* Set Field/WindowNo for ValuePreference (NOP)
|
* @param mField Model Field
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_GridField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField()
{
return m_GridField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VLocation
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocation.java
| 1
|
请完成以下Java代码
|
public class SumQueryAggregateColumnBuilder<SourceModelType, TargetModelType> implements IQueryAggregateColumnBuilder<SourceModelType, TargetModelType, BigDecimal>
{
private final ICompositeQueryFilter<SourceModelType> filters;
private ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute;
private final ModelColumn<SourceModelType, ?> _amountColumn;
/* package */SumQueryAggregateColumnBuilder(final ModelColumn<SourceModelType, ?> amountColumn)
{
super();
Check.assumeNotNull(amountColumn, "amountColumn not null");
this._amountColumn = amountColumn;
filters = CompositeQueryFilter.newInstance(amountColumn.getModelClass());
}
private String getAmountColumnName()
{
return _amountColumn.getColumnName();
}
@Override
public ICompositeQueryFilter<SourceModelType> filter()
{
return this.filters;
}
@Override
public String getSql(final Properties ctx, final List<Object> sqlParamsOut)
{
final List<IQueryFilter<SourceModelType>> nonSqlFilters = filters.getNonSqlFilters();
Check.assume(nonSqlFilters == null || nonSqlFilters.isEmpty(), "Non-SQL filters are not supported: {}", nonSqlFilters);
final String sqlWhereClause = filters.getSqlFiltersWhereClause();
final String sql = "COALESCE(SUM(CASE WHEN (" + sqlWhereClause + ") THEN " + getAmountColumnName() + " ELSE 0 END), 0)";
final List<Object> sqlWhereClauseParams = filters.getSqlFiltersParams(ctx);
sqlParamsOut.addAll(sqlWhereClauseParams);
return sql;
}
@Override
public SumQueryAggregateColumnBuilder<SourceModelType, TargetModelType> setDynAttribute(final ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute)
{
this.dynAttribute = dynAttribute;
return this;
}
@Override
public ModelDynAttributeAccessor<TargetModelType, BigDecimal> getDynAttribute()
{
Check.assumeNotNull(dynAttribute, "dynAttribute not null");
return dynAttribute;
|
}
@Override
public IAggregator<BigDecimal, SourceModelType> createAggregator(final TargetModelType targetModel)
{
Check.assumeNotNull(targetModel, "targetModel not null");
return new IAggregator<BigDecimal, SourceModelType>()
{
private final ICompositeQueryFilter<SourceModelType> filters = SumQueryAggregateColumnBuilder.this.filters.copy();
private final ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute = SumQueryAggregateColumnBuilder.this.dynAttribute;
private BigDecimal sum = BigDecimal.ZERO;
@Override
public void add(final SourceModelType model)
{
if (filters.accept(model))
{
final Optional<BigDecimal> value = InterfaceWrapperHelper.getValue(model, getAmountColumnName());
if (value.isPresent())
{
sum = sum.add(value.get());
}
}
// Update target model's dynamic attribute
dynAttribute.setValue(targetModel, sum);
}
@Override
public BigDecimal getValue()
{
return sum;
}
};
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\SumQueryAggregateColumnBuilder.java
| 1
|
请完成以下Java代码
|
public class BPMNTimerImpl extends BPMNElementImpl implements BPMNTimer {
private TimerPayload timerPayload;
public BPMNTimerImpl() {}
public BPMNTimerImpl(String elementId) {
this.setElementId(elementId);
}
public TimerPayload getTimerPayload() {
return timerPayload;
}
public void setTimerPayload(TimerPayload timerPayload) {
this.timerPayload = timerPayload;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((timerPayload == null) ? 0 : timerPayload.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
|
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
BPMNTimerImpl other = (BPMNTimerImpl) obj;
if (timerPayload == null) {
if (other.timerPayload != null) return false;
} else if (!timerPayload.equals(other.timerPayload)) return false;
return true;
}
@Override
public String toString() {
return (
"BPMNActivityImpl{" +
", elementId='" +
getElementId() +
'\'' +
", timerPayload='" +
(timerPayload != null ? timerPayload.toString() : null) +
'\'' +
'}'
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNTimerImpl.java
| 1
|
请完成以下Java代码
|
public void setM_Warehouse_PickingGroup_ID (int M_Warehouse_PickingGroup_ID)
{
if (M_Warehouse_PickingGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_PickingGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_PickingGroup_ID, Integer.valueOf(M_Warehouse_PickingGroup_ID));
}
/** Get Warehouse Picking Group.
@return Warehouse Picking Group */
@Override
public int getM_Warehouse_PickingGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_PickingGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
|
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_PickingGroup.java
| 1
|
请完成以下Java代码
|
public LookupValuesList notOrdered()
{
return ordered(false);
}
public LookupValuesPage pageByOffsetAndLimit(final int offset, final int limit)
{
final int size = valuesById.size();
final int lastIndex = size - 1;
final int pageFirstIndex = Math.max(offset, 0);
final int pageLastIndex = limit > 0 ? Math.min(pageFirstIndex + limit - 1, lastIndex) : lastIndex;
if (pageFirstIndex == 0 && pageLastIndex == lastIndex)
{
return LookupValuesPage.allValues(this);
}
final ImmutableList<LookupValue> pageValues = valuesById.values()
.asList()
.subList(pageFirstIndex, pageLastIndex + 1);
final boolean hasMoreValues = pageLastIndex < lastIndex;
|
return LookupValuesPage.builder()
.totalRows(OptionalInt.of(size))
.firstRow(pageFirstIndex)
.values(LookupValuesList.fromCollection(pageValues)
.ordered(isOrdered()))
.hasMoreResults(OptionalBoolean.ofBoolean(hasMoreValues))
.build();
}
public ImmutableMap<Object, LookupValue> toMap()
{
// NOTE: might throw exception in case there are multiple lookup values with same ID
return Maps.uniqueIndex(valuesById.values(), LookupValue::getId);
}
public static LookupValuesList of(@NonNull final LookupValue lookupValue)
{
final ImmutableListMultimap<Object, LookupValue> valuesById = ImmutableListMultimap.of(lookupValue.getId(), lookupValue);
final boolean ordered = true;
return new LookupValuesList(valuesById, ordered, DebugProperties.EMPTY);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValuesList.java
| 1
|
请完成以下Java代码
|
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setExportSequenceNumber (final int ExportSequenceNumber)
{
set_Value (COLUMNNAME_ExportSequenceNumber, ExportSequenceNumber);
}
@Override
public int getExportSequenceNumber()
{
return get_ValueAsInt(COLUMNNAME_ExportSequenceNumber);
}
/**
* ExportStatus AD_Reference_ID=541161
* Reference name: API_ExportStatus
*/
public static final int EXPORTSTATUS_AD_Reference_ID=541161;
/** PENDING = PENDING */
public static final String EXPORTSTATUS_PENDING = "PENDING";
/** EXPORTED = EXPORTED */
public static final String EXPORTSTATUS_EXPORTED = "EXPORTED";
/** EXPORTED_AND_FORWARDED = EXPORTED_AND_FORWARDED */
public static final String EXPORTSTATUS_EXPORTED_AND_FORWARDED = "EXPORTED_AND_FORWARDED";
/** EXPORTED_FORWARD_ERROR = EXPORTED_FORWARD_ERROR */
public static final String EXPORTSTATUS_EXPORTED_FORWARD_ERROR = "EXPORTED_FORWARD_ERROR";
/** EXPORT_ERROR = EXPORT_ERROR */
public static final String EXPORTSTATUS_EXPORT_ERROR = "EXPORT_ERROR";
/** DONT_EXPORT = DONT_EXPORT */
public static final String EXPORTSTATUS_DONT_EXPORT = "DONT_EXPORT";
@Override
public void setExportStatus (final java.lang.String ExportStatus)
{
set_Value (COLUMNNAME_ExportStatus, ExportStatus);
}
@Override
public java.lang.String getExportStatus()
{
return get_ValueAsString(COLUMNNAME_ExportStatus);
|
}
@Override
public void setForwardedData (final @Nullable java.lang.String ForwardedData)
{
set_Value (COLUMNNAME_ForwardedData, ForwardedData);
}
@Override
public java.lang.String getForwardedData()
{
return get_ValueAsString(COLUMNNAME_ForwardedData);
}
@Override
public void setM_ShipmentSchedule_ExportAudit_ID (final int M_ShipmentSchedule_ExportAudit_ID)
{
if (M_ShipmentSchedule_ExportAudit_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, M_ShipmentSchedule_ExportAudit_ID);
}
@Override
public int getM_ShipmentSchedule_ExportAudit_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID);
}
@Override
public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI)
{
set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI);
}
@Override
public java.lang.String getTransactionIdAPI()
{
return get_ValueAsString(COLUMNNAME_TransactionIdAPI);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit.java
| 1
|
请完成以下Java代码
|
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
|
repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\gen\UserRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void configure()
{
//@formatter:off
from(fileEndpointConfig.getBPartnerFileEndpoint())
.id(routeId)
.streamCache("true")
.log("Business Partner Sync Route Started with Id=" + routeId)
.process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest))
.split(body().tokenize("\n"))
.streaming()
.process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest))
.filter(new SkipFirstLinePredicate())
.doTry()
.unmarshal(new BindyCsvDataFormat(BPartnerRow.class))
.process(getBPartnerUpsertProcessor()).id(UPSERT_BPARTNER_PROCESSOR_ID)
.choice()
.when(bodyAs(BPUpsertCamelRequest.class).isNull())
.log(LoggingLevel.INFO, "Nothing to do! No bpartner to upsert!")
.otherwise()
.log(LoggingLevel.DEBUG, "Calling metasfresh-api to upsert Business Partners: ${body}")
.to("{{" + MF_UPSERT_BPARTNER_V2_CAMEL_URI + "}}").id(UPSERT_BPARTNER_ENDPOINT_ID)
|
.endChoice()
.end()
.endDoTry()
.doCatch(Throwable.class)
.to(direct(ERROR_WRITE_TO_ADISSUE))
.end()
.end();
//@formatter:on
}
@NonNull
private BPartnerUpsertProcessor getBPartnerUpsertProcessor()
{
return BPartnerUpsertProcessor.builder()
.externalSystemRequest(enabledByExternalSystemRequest)
.pInstanceLogger(pInstanceLogger)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\bpartner\GetBPartnerFromFileRouteBuilder.java
| 2
|
请完成以下Java代码
|
public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setScrappedQty (final @Nullable BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
@Override
public BigDecimal getScrappedQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ScrappedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSetupTimeReal (final @Nullable BigDecimal SetupTimeReal)
{
set_Value (COLUMNNAME_SetupTimeReal, SetupTimeReal);
}
|
@Override
public BigDecimal getSetupTimeReal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SetupTimeReal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector.java
| 1
|
请完成以下Java代码
|
public void setAuthorizationProxyFactory(AuthorizationProxyFactory authorizationProxyFactory) {
Assert.notNull(authorizationProxyFactory, "authorizationProxyFactory cannot be null");
this.authorizationProxyFactory = authorizationProxyFactory;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* {@inheritDoc}
*/
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
public void setPointcut(Pointcut pointcut) {
this.pointcut = pointcut;
}
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
|
return true;
}
static final class MethodReturnTypePointcut extends StaticMethodMatcherPointcut {
private final Predicate<Class<?>> returnTypeMatches;
MethodReturnTypePointcut(Predicate<Class<?>> returnTypeMatches) {
this.returnTypeMatches = returnTypeMatches;
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return this.returnTypeMatches.test(method.getReturnType());
}
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\AuthorizeReturnObjectMethodInterceptor.java
| 1
|
请完成以下Java代码
|
public ReplenishInfo getBy(@NonNull final ReplenishInfo.Identifier identifier)
{
final ProductId productId = identifier.getProductId();
final I_M_Replenish replenishRecord = getRecordByIdentifier(identifier).orElse(null);
final UomId uomId = productBL.getStockUOMId(productId);
final StockQtyAndUOMQty min;
final StockQtyAndUOMQty max;
final boolean highPriority;
if (replenishRecord == null)
{
min = StockQtyAndUOMQtys.createZero(productId, uomId);
max = StockQtyAndUOMQtys.createZero(productId, uomId);
highPriority = false;
}
else
{
min = StockQtyAndUOMQtys.createConvert(replenishRecord.getLevel_Min(), productId, uomId);
max = NumberUtils.zeroToNull(replenishRecord.getLevel_Max()) == null ? min : StockQtyAndUOMQtys.createConvert(replenishRecord.getLevel_Max(), productId, uomId);
highPriority = replenishRecord.isHighPriority();
}
return ReplenishInfo.builder()
.identifier(identifier)
.min(min)
.max(max)
.highPriority(highPriority)
.build();
}
public void save(@NonNull final ReplenishInfo replenishInfo)
{
final I_M_Replenish replenishRecord = getRecordByIdentifier(replenishInfo.getIdentifier())
.orElseGet(() -> initNewRecord(replenishInfo.getIdentifier()));
final BigDecimal levelMin = replenishInfo.getMin().getStockQty().toBigDecimal();
final BigDecimal levelMax = replenishInfo.getMax().getStockQty().toBigDecimal();
replenishRecord.setLevel_Min(levelMin);
replenishRecord.setLevel_Max(levelMax.compareTo(levelMin) ==0 ? null : levelMax);
saveRecord(replenishRecord);
}
|
@NonNull
private I_M_Replenish initNewRecord(@NonNull final ReplenishInfo.Identifier identifier)
{
final I_M_Replenish replenishRecord = InterfaceWrapperHelper.newInstance(I_M_Replenish.class);
replenishRecord.setM_Product_ID(identifier.getProductId().getRepoId());
replenishRecord.setM_Warehouse_ID(identifier.getWarehouseId().getRepoId());
return replenishRecord;
}
@NonNull
private Optional<I_M_Replenish> getRecordByIdentifier(@NonNull final ReplenishInfo.Identifier identifier)
{
// if locator has been provided, give preference to replenish rules that are specific to that locator
final IQueryOrderBy locatorPreferenceOrderBy = queryBL.createQueryOrderByBuilder(I_M_Replenish.class)
.addColumn(I_M_Replenish.COLUMNNAME_M_Locator_ID, Ascending, identifier.getLocatorId() != null ? Last : First)
.createQueryOrderBy();
return queryBL.createQueryBuilder(I_M_Replenish.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Replenish.COLUMNNAME_M_Product_ID, identifier.getProductId())
.addEqualsFilter(I_M_Replenish.COLUMNNAME_M_Warehouse_ID, identifier.getWarehouseId())
.addInArrayFilter(I_M_Replenish.COLUMNNAME_M_Locator_ID, identifier.getLocatorId(), null)
.create()
.setOrderBy(locatorPreferenceOrderBy)
.firstOnlyOptional(I_M_Replenish.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\replenish\ReplenishInfoRepository.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException
{
return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name)
.getPO(getRef_OrderLine_ID(), get_TrxName()); }
/** Set Referenced Order Line.
@param Ref_OrderLine_ID
Reference to corresponding Sales/Purchase Order
*/
public void setRef_OrderLine_ID (int Ref_OrderLine_ID)
{
if (Ref_OrderLine_ID < 1)
set_Value (COLUMNNAME_Ref_OrderLine_ID, null);
else
set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID));
}
/** Get Referenced Order Line.
@return Reference to corresponding Sales/Purchase Order
*/
public int getRef_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ressourcenzuordnung.
@param S_ResourceAssignment_ID
Ressourcenzuordnung
|
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_Value (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Ressourcenzuordnung.
@return Ressourcenzuordnung
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java
| 1
|
请完成以下Java代码
|
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public Integer getProcessDefinitionVersion() {
return processDefinitionVersion;
}
public void setProcessDefinitionVersion(Integer processDefinitionVersion) {
this.processDefinitionVersion = processDefinitionVersion;
}
public String getCaseDefinitionName() {
return caseDefinitionName;
}
public void setCaseDefinitionName(String caseDefinitionName) {
this.caseDefinitionName = caseDefinitionName;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public void setCaseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public void setCaseExecutionId(String caseExecutionId) {
this.caseExecutionId = caseExecutionId;
}
public void setId(String id) {
|
this.id = id;
}
public String getId() {
return id;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public long getSequenceCounter() {
return sequenceCounter;
}
public void setSequenceCounter(long sequenceCounter) {
this.sequenceCounter = sequenceCounter;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
// persistent object implementation ///////////////
public Object getPersistentState() {
// events are immutable
return HistoryEvent.class;
}
// state inspection
public boolean isEventOfType(HistoryEventType type) {
return type.getEventName().equals(eventType);
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void fetchAuthorAsDtoClassNative() {
List<AuthorDto> authors = authorRepository.fetchAsDtoNative();
authors.forEach(a -> System.out.println("Author{id=" + a.getId()
+ ", name=" + a.getName() + ", genre=" + a.getGenre()
+ ", age=" + a.getAge() + "}"));
briefOverviewOfPersistentContextContent();
}
@Transactional(readOnly = true)
public void fetchAuthorByGenreAsDtoClassQueryBuilderMechanism() {
List<AuthorDto> authors = authorRepository.findBy();
authors.forEach(a -> System.out.println("Author{id=" + a.getId()
+ ", name=" + a.getName() + ", genre=" + a.getGenre()
+ ", age=" + a.getAge() + "}"));
briefOverviewOfPersistentContextContent();
}
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
|
// getEntitiesByKey() will be removed and probably replaced with #iterateEntities()
Map<EntityKey, Object> entitiesByKey = persistenceContext.getEntitiesByKey();
entitiesByKey.forEach((key, value) -> System.out.println(key + ": " + value));
for (Object entry : entitiesByKey.values()) {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
};
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinDtoAllFields\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public User createUser(User user) {
user.setId(null);
return userDao.save(user);
}
public void deleteUser(String id) {
this.userDao.findById(id)
.ifPresent(user -> this.userDao.delete(user));
}
public void updateUser(String id, User user) {
this.userDao.findById(id)
.ifPresent(
u -> {
u.setName(user.getName());
u.setAge(user.getAge());
u.setDescription(user.getDescription());
this.userDao.save(u);
}
);
}
public List<User> getUserByAge(Integer from, Integer to) {
return this.userDao.findByAgeBetween(from, to);
}
public List<User> getUserByName(String name) {
return this.userDao.findByNameEquals(name);
}
public List<User> getUserByDescription(String description) {
return this.userDao.findByDescriptionIsLike(description);
|
}
public Page<User> getUserByCondition(int size, int page, User user) {
Query query = new Query();
Criteria criteria = new Criteria();
if (!StringUtils.isEmpty(user.getName())) {
criteria.and("name").is(user.getName());
}
if (!StringUtils.isEmpty(user.getDescription())) {
criteria.and("description").regex(user.getDescription());
}
query.addCriteria(criteria);
Sort sort = new Sort(Sort.Direction.DESC, "age");
Pageable pageable = PageRequest.of(page, size, sort);
List<User> users = template.find(query.with(pageable), User.class);
return PageableExecutionUtils.getPage(users, pageable, () -> template.count(query, User.class));
}
}
|
repos\SpringAll-master\56.Spring-Boot-MongoDB-crud\src\main\java\com\example\mongodb\service\UserService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void saveTs(TenantId tenantId, EdgeId edgeId, List<TsKvEntry> statsEntries) {
try {
ListenableFuture<TimeseriesSaveResult> future = tsService.save(
tenantId,
edgeId,
statsEntries,
TimeUnit.DAYS.toSeconds(edgesStatsTtlDays)
);
Futures.addCallback(future, new FutureCallback<>() {
@Override
public void onSuccess(TimeseriesSaveResult result) {
log.debug("Successfully saved edge time-series stats: {} for edge: {}", statsEntries, edgeId);
}
|
@Override
public void onFailure(Throwable t) {
log.warn("Failed to save edge time-series stats for edge: {}", edgeId, t);
}
}, MoreExecutors.directExecutor());
} finally {
statsCounterService.clear(edgeId);
}
}
private BasicTsKvEntry entry(long ts, String key, long value) {
return new BasicTsKvEntry(ts, new LongDataEntry(key, value));
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\stats\EdgeStatsService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
|
public Date getReachedBefore() {
return reachedBefore;
}
public void setReachedBefore(Date reachedBefore) {
this.reachedBefore = reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public void setReachedAfter(Date reachedAfter) {
this.reachedAfter = reachedAfter;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\milestone\HistoricMilestoneInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
public Thread newThread(Runnable r)
{
String threadName = namePrefix + threadNumber.getAndIncrement();
final Thread t = new Thread(group, r, threadName, 0); // stackSize=0
if (t.isDaemon() != daemon)
{
t.setDaemon(daemon);
}
if (t.getPriority() != Thread.NORM_PRIORITY)
{
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
/**
* @return the daemon
*/
public boolean isDaemon()
{
return daemon;
}
public static final class Builder
{
private String threadNamePrefix;
private boolean daemon = false;
private Builder()
{
super();
}
public CustomizableThreadFactory build()
{
return new CustomizableThreadFactory(this);
}
public Builder setThreadNamePrefix(String threadNamePrefix)
{
this.threadNamePrefix = threadNamePrefix;
return this;
}
|
private final String getThreadNamePrefix()
{
Check.assumeNotEmpty(threadNamePrefix, "threadNamePrefix not empty");
return threadNamePrefix;
}
/**
* Decides if the threads shall be daemon threads or user threads.
*
* @param daemon the daemon to set
*/
public Builder setDaemon(boolean daemon)
{
this.daemon = daemon;
return this;
}
private final boolean isDaemon()
{
return daemon;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\CustomizableThreadFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteBatch(String batchId) {
getBatchEntityManager().delete(batchId);
}
@Override
public BatchPartEntity getBatchPart(String id) {
return getBatchPartEntityManager().findById(id);
}
@Override
public List<BatchPart> findBatchPartsByBatchId(String batchId) {
return getBatchPartEntityManager().findBatchPartsByBatchId(batchId);
}
@Override
public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) {
return getBatchPartEntityManager().findBatchPartsByBatchIdAndStatus(batchId, status);
}
@Override
public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) {
return getBatchPartEntityManager().findBatchPartsByScopeIdAndType(scopeId, scopeType);
}
@Override
public BatchPart createBatchPart(Batch batch, String status, String scopeId, String subScopeId, String scopeType) {
return getBatchPartEntityManager().createBatchPart((BatchEntity) batch, status, scopeId, subScopeId, scopeType);
}
@Override
public BatchPart completeBatchPart(String batchPartId, String status, String resultJson) {
|
return getBatchPartEntityManager().completeBatchPart(batchPartId, status, resultJson);
}
@Override
public Batch completeBatch(String batchId, String status) {
return getBatchEntityManager().completeBatch(batchId, status);
}
public Batch createBatch(BatchBuilder batchBuilder) {
return getBatchEntityManager().createBatch(batchBuilder);
}
public BatchEntityManager getBatchEntityManager() {
return configuration.getBatchEntityManager();
}
public BatchPartEntityManager getBatchPartEntityManager() {
return configuration.getBatchPartEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchServiceImpl.java
| 2
|
请完成以下Java代码
|
protected BatchElementConfiguration collectInstances(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
HistoricProcessInstanceQuery instanceQuery = builder.getQuery();
if (instanceQuery != null) {
elementConfiguration.addDeploymentMappings(((HistoricProcessInstanceQueryImpl) instanceQuery).listDeploymentIdMappings());
}
List<String> instanceIds = builder.getIds();
if (!CollectionUtil.isEmpty(instanceIds)) {
HistoricProcessInstanceQueryImpl query = new HistoricProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(instanceIds));
elementConfiguration.addDeploymentMappings(commandContext.runWithoutAuthorization(query::listDeploymentIdMappings));
}
return elementConfiguration;
}
protected BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) {
return new SetRemovalTimeBatchConfiguration(elementConfiguration.getIds(), elementConfiguration.getMappings())
.setHierarchical(builder.isHierarchical())
.setHasRemovalTime(hasRemovalTime())
.setRemovalTime(builder.getRemovalTime())
.setUpdateInChunks(builder.isUpdateInChunks())
.setChunkSize(builder.getChunkSize());
}
protected boolean hasRemovalTime() {
return builder.getMode() == Mode.ABSOLUTE_REMOVAL_TIME ||
builder.getMode() == Mode.CLEARED_REMOVAL_TIME;
|
}
protected void writeUserOperationLog(CommandContext commandContext, int numInstances) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("mode", null, builder.getMode()));
propertyChanges.add(new PropertyChange("removalTime", null, builder.getRemovalTime()));
propertyChanges.add(new PropertyChange("hierarchical", null, builder.isHierarchical()));
propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances));
propertyChanges.add(new PropertyChange("async", null, true));
propertyChanges.add(new PropertyChange("updateInChunks", null, builder.isUpdateInChunks()));
propertyChanges.add(new PropertyChange("chunkSize", null, builder.getChunkSize()));
commandContext.getOperationLogManager()
.logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_SET_REMOVAL_TIME, propertyChanges);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\removaltime\SetRemovalTimeToHistoricProcessInstancesCmd.java
| 1
|
请完成以下Java代码
|
public VariableType getVariableType() {
return variableType;
}
@Override
public void setVariableType(VariableType variableType) {
this.variableType = variableType;
}
@Override
public Long getLongValue() {
return longValue;
}
@Override
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
@Override
public Double getDoubleValue() {
return doubleValue;
}
@Override
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
@Override
public String getTextValue() {
return textValue;
}
@Override
public void setTextValue(String textValue) {
this.textValue = textValue;
}
@Override
public String getTextValue2() {
return textValue2;
}
@Override
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
@Override
public Object getCachedValue() {
return cachedValue;
}
@Override
public void setCachedValue(Object cachedValue) {
this.cachedValue = cachedValue;
}
// common methods ///////////////////////////////////////////////////////////////
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricDetailVariableInstanceUpdateEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
@Override
public String getScopeId() {
return null;
}
@Override
public String getSubScopeId() {
return null;
}
@Override
public String getScopeType() {
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public EventSubscriptionBuilder configuration(String configuration) {
this.configuration = configuration;
return this;
}
@Override
public EventSubscription create() {
return eventSubscriptionService.createEventSubscription(this);
}
@Override
public String getEventType() {
return eventType;
}
@Override
public String getEventName() {
return eventName;
}
@Override
public Signal getSignal() {
return signal;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public String getSubScopeId() {
return subScopeId;
|
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getScopeDefinitionKey() {
return scopeDefinitionKey;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getConfiguration() {
return configuration;
}
}
|
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java
| 2
|
请完成以下Java代码
|
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* bean、array、List、Map --> json
*
* @param obj
* @return json string
* @throws Exception
*/
public static String writeValueAsString(Object obj) {
try {
return getInstance().writeValueAsString(obj);
} catch (JsonGenerationException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* string --> bean、Map、List(array)
*
* @param jsonStr
* @param clazz
* @return obj
* @throws Exception
*/
public static <T> T readValue(String jsonStr, Class<T> clazz) {
try {
return getInstance().readValue(jsonStr, clazz);
} catch (JsonParseException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
|
logger.error(e.getMessage(), e);
}
return null;
}
/**
* string --> List<Bean>...
*
* @param jsonStr
* @param parametrized
* @param parameterClasses
* @param <T>
* @return
*/
public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) {
try {
JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses);
return getInstance().readValue(jsonStr, javaType);
} catch (JsonParseException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\JacksonUtil.java
| 1
|
请完成以下Java代码
|
private void printArchive(final I_C_Doc_Outbound_Log_Line logLine)
{
if (logLine == null)
{
//nothing to do
return;
}
final int archiveRecordId = logLine.getAD_Archive_ID();
if (archiveRecordId <= 0)
{
//nothing to do
return;
}
final I_AD_Archive archive = archiveDAO.retrieveArchive(ArchiveId.ofRepoId(archiveRecordId), I_AD_Archive.class);
if (archive == null)
{
//nothing to do
return;
}
final HardwareTrayId hwTrayId = HardwareTrayId.ofRepoIdOrNull(hwPrinterId, hwTrayRecordId);
final PrintArchiveParameters printArchiveParameters = PrintArchiveParameters.builder()
.archive(archive)
.printOutputFacade(printOutputFacade)
.hwPrinterId(hwPrinterId)
.hwTrayId(hwTrayId)
.enforceEnqueueToPrintQueue(true)
.build();
printingQueueBL.printArchive(printArchiveParameters);
}
@Override
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
final SelectionSize selectionSize = context.getSelectionSize();
if (selectionSize.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
private final Iterator<I_C_Doc_Outbound_Log> retrieveSelectedDocOutboundLogs()
{
final IQueryFilter<I_C_Doc_Outbound_Log> filter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final Stream<I_C_Doc_Outbound_Log> stream = queryBL
.createQueryBuilder(I_C_Doc_Outbound_Log.class)
.addOnlyActiveRecordsFilter()
.filter(filter)
.create()
.iterateAndStream();
return stream.iterator();
}
protected I_C_Doc_Outbound_Log_Line retrieveDocumentLogLine(final I_C_Doc_Outbound_Log log)
{
final I_C_Doc_Outbound_Log_Line logLine = docOutboundDAO.retrieveCurrentPDFArchiveLogLineOrNull(log);
return logLine;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Doc_Outbound_Log_PrintSelected.java
| 1
|
请完成以下Java代码
|
public boolean isJoinOr()
{
return !and;
}
@Override
public String getSql()
{
if (!isPureSql())
{
throw new IllegalStateException("Cannot get SQL for a filter which is not pure SQL: " + this);
}
return getSqlFiltersWhereClause();
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
if (!isPureSql())
{
throw new IllegalStateException("Cannot get SQL Parameters for a filter which is not pure SQL: " + this);
}
return getSqlFiltersParams(ctx);
}
@Override
public ISqlQueryFilter asSqlQueryFilter()
{
if (!isPureSql())
{
throw new IllegalStateException("Cannot convert to pure SQL filter when this filter is not pure SQL: " + this);
}
return this;
}
|
@Override
public ISqlQueryFilter asPartialSqlQueryFilter()
{
return partialSqlQueryFilter;
}
@Override
public IQueryFilter<T> asPartialNonSqlFilterOrNull()
{
final List<IQueryFilter<T>> nonSqlFilters = getNonSqlFiltersToUse();
if (nonSqlFilters == null || nonSqlFilters.isEmpty())
{
return null;
}
return partialNonSqlQueryFilter;
}
@Override
public CompositeQueryFilter<T> allowSqlFilters(final boolean allowSqlFilters)
{
if (this._allowSqlFilters == allowSqlFilters)
{
return this;
}
this._allowSqlFilters = allowSqlFilters;
_compiled = false;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryFilter.java
| 1
|
请完成以下Java代码
|
public void setIsReplicationTrxFinished (final boolean IsReplicationTrxFinished)
{
set_Value (COLUMNNAME_IsReplicationTrxFinished, IsReplicationTrxFinished);
}
@Override
public boolean isReplicationTrxFinished()
{
return get_ValueAsBoolean(COLUMNNAME_IsReplicationTrxFinished);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
|
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrx.java
| 1
|
请完成以下Java代码
|
public String getToUser() {
return toUser;
}
public ChatSendToOneRequest setToUser(String toUser) {
this.toUser = toUser;
return this;
}
public String getMsgId() {
return msgId;
}
public ChatSendToOneRequest setMsgId(String msgId) {
this.msgId = msgId;
return this;
}
public String getContent() {
return content;
}
|
public ChatSendToOneRequest setContent(String content) {
this.content = content;
return this;
}
@Override
public String toString() {
return "ChatSendToOneRequest{" +
"toUser='" + toUser + '\'' +
", msgId='" + msgId + '\'' +
", content='" + content + '\'' +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-client\src\main\java\cn\iocoder\springboot\lab67\nettyclientdemo\message\chat\ChatSendToOneRequest.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty() {
return size() == 0;
}
public int size() {
return size;
}
public void add(S element) {
Node<S> newTail = new Node<>(element);
if (head == null) {
tail = newTail;
head = tail;
} else {
tail.next = newTail;
tail = newTail;
}
++size;
}
public void remove(S element) {
if (isEmpty()) {
return;
}
Node<S> previous = null;
Node<S> current = head;
while (current != null) {
if (Objects.equals(element, current.element)) {
Node<S> next = current.next;
if (isFistNode(current)) {
head = next;
} else if (isLastNode(current)) {
previous.next = null;
} else {
Node<S> next1 = current.next;
previous.next = next1;
}
--size;
break;
}
previous = current;
current = current.next;
}
}
public void removeLast() {
if (isEmpty()) {
return;
} else if (size() == 1) {
tail = null;
|
head = null;
} else {
Node<S> secondToLast = null;
Node<S> last = head;
while (last.next != null) {
secondToLast = last;
last = last.next;
}
secondToLast.next = null;
}
--size;
}
public boolean contains(S element) {
if (isEmpty()) {
return false;
}
Node<S> current = head;
while (current != null) {
if (Objects.equals(element, current.element))
return true;
current = current.next;
}
return false;
}
private boolean isLastNode(Node<S> node) {
return tail == node;
}
private boolean isFistNode(Node<S> node) {
return head == node;
}
public static class Node<T> {
private T element;
private Node<T> next;
public Node(T element) {
this.element = element;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\linkedlistremove\SinglyLinkedList.java
| 1
|
请完成以下Java代码
|
protected EventSubscriptionQuery createNewQuery(ProcessEngine engine) {
return engine.getRuntimeService().createEventSubscriptionQuery();
}
@Override
protected void applyFilters(EventSubscriptionQuery query) {
if (eventSubscriptionId != null) {
query.eventSubscriptionId(eventSubscriptionId);
}
if (eventName != null) {
query.eventName(eventName);
}
if (eventType != null) {
query.eventType(eventType);
}
if (executionId != null) {
query.executionId(executionId);
}
if (processInstanceId != null) {
query.processInstanceId(processInstanceId);
}
if (activityId != null) {
query.activityId(activityId);
}
|
if (tenantIdIn != null && !tenantIdIn.isEmpty()) {
query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) {
query.includeEventSubscriptionsWithoutTenantId();
}
}
@Override
protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_CREATED)) {
query.orderByCreated();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionQueryDto.java
| 1
|
请完成以下Java代码
|
public void setC_Customer_Retention_ID (int C_Customer_Retention_ID)
{
if (C_Customer_Retention_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Customer_Retention_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Customer_Retention_ID, Integer.valueOf(C_Customer_Retention_ID));
}
/** Get C_Customer_Retention_ID.
@return C_Customer_Retention_ID */
@Override
public int getC_Customer_Retention_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Customer_Retention_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* CustomerRetention AD_Reference_ID=540937
* Reference name: C_BPartner_TimeSpan_List
*/
public static final int CUSTOMERRETENTION_AD_Reference_ID=540937;
|
/** Neukunde = N */
public static final String CUSTOMERRETENTION_Neukunde = "N";
/** Stammkunde = S */
public static final String CUSTOMERRETENTION_Stammkunde = "S";
/** Set Customer Retention.
@param CustomerRetention Customer Retention */
@Override
public void setCustomerRetention (java.lang.String CustomerRetention)
{
set_Value (COLUMNNAME_CustomerRetention, CustomerRetention);
}
/** Get Customer Retention.
@return Customer Retention */
@Override
public java.lang.String getCustomerRetention ()
{
return (java.lang.String)get_Value(COLUMNNAME_CustomerRetention);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customer_Retention.java
| 1
|
请完成以下Java代码
|
public java.lang.String getGO_AuthUsername ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_AuthUsername);
}
/** Set Request Sender ID.
@param GO_RequestSenderId Request Sender ID */
@Override
public void setGO_RequestSenderId (java.lang.String GO_RequestSenderId)
{
set_Value (COLUMNNAME_GO_RequestSenderId, GO_RequestSenderId);
}
/** Get Request Sender ID.
@return Request Sender ID */
@Override
public java.lang.String getGO_RequestSenderId ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_RequestSenderId);
}
/** Set Request Username.
@param GO_RequestUsername Request Username */
@Override
public void setGO_RequestUsername (java.lang.String GO_RequestUsername)
{
set_Value (COLUMNNAME_GO_RequestUsername, GO_RequestUsername);
}
/** Get Request Username.
@return Request Username */
@Override
public java.lang.String getGO_RequestUsername ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_RequestUsername);
}
/** Set GO Shipper Configuration.
@param GO_Shipper_Config_ID GO Shipper Configuration */
@Override
public void setGO_Shipper_Config_ID (int GO_Shipper_Config_ID)
{
if (GO_Shipper_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_GO_Shipper_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GO_Shipper_Config_ID, Integer.valueOf(GO_Shipper_Config_ID));
}
/** Get GO Shipper Configuration.
@return GO Shipper Configuration */
@Override
public int getGO_Shipper_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GO_Shipper_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set GO URL.
@param GO_URL GO URL */
@Override
public void setGO_URL (java.lang.String GO_URL)
{
set_Value (COLUMNNAME_GO_URL, GO_URL);
}
/** Get GO URL.
@return GO URL */
@Override
public java.lang.String getGO_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_URL);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
|
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_Shipper_Config.java
| 1
|
请完成以下Java代码
|
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
});
}
/**
* Check if a user is authenticated.
*
* @return true if the user is authenticated, false otherwise
*/
public static boolean isAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)))
.orElse(false);
}
|
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the isUserInRole() method in the Servlet API
*
* @param authority the authority to check
* @return true if the current user has the authority, false otherwise
*/
public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)))
.orElse(false);
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\SecurityUtils.java
| 1
|
请完成以下Java代码
|
private static ITabCallout copyAndInitialize(final Collection<Object> tabCalloutsList, @Nullable final ICalloutRecord calloutRecord)
{
final CompositeTabCallout.Builder tabCalloutsBuilder = CompositeTabCallout.builder();
for (final Object tabCalloutObj : tabCalloutsList)
{
if (tabCalloutObj instanceof Class)
{
try
{
final Class<?> tabCalloutClass = (Class<?>)tabCalloutObj;
final ITabCallout tabCalloutInstance = Util.newInstance(ITabCallout.class, tabCalloutClass);
if (tabCalloutInstance instanceof IStatefulTabCallout)
{
((IStatefulTabCallout)tabCalloutInstance).onInit(calloutRecord);
}
tabCalloutsBuilder.addTabCallout(tabCalloutInstance);
}
catch (final Exception e)
{
logger.warn("Failed to initialize {}. Ignored.", tabCalloutObj, e);
}
}
else if (tabCalloutObj instanceof ITabCallout)
{
final ITabCallout tabCallout = (ITabCallout)tabCalloutObj;
tabCalloutsBuilder.addTabCallout(tabCallout);
}
else
{
logger.warn("Unknown callout type {}. Ignored.", tabCalloutObj);
}
}
return tabCalloutsBuilder.build();
}
|
@Override
public void registerTabCalloutForTable(
@NonNull final String tableName,
@NonNull final Class<? extends ITabCallout> tabCalloutClass)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
tableName2tabCalloutClasses.put(tableName, tabCalloutClass);
logger.info("Registered tab callout {} for table {}", tabCalloutClass, tableName);
}
@Override
public void unregisterTabCalloutForTable(
@NonNull final String tableName,
@NonNull final Class<? extends ITabCallout> tabCalloutClass)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
tableName2tabCalloutClasses.remove(tableName, tabCalloutClass);
logger.info("Unregistered tab callout {} for table {}", tabCalloutClass, tableName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\api\impl\TabCalloutFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToMany(mappedBy="department")
private List<DeptEmployee> employees;
public Department(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
|
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DeptEmployee> getEmployees() {
return employees;
}
public void setEmployees(List<DeptEmployee> employees) {
this.employees = employees;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\entities\Department.java
| 2
|
请完成以下Spring Boot application配置
|
# \u5355\u4E2A Memcached \u914D\u7F6E
memcached.servers=192.168.0.161:11211
# \u591A\u4E2A Memcached \u914D\u7F6E
# memcached.servers=192.168.0.161:11211 192.168.0.162:11211 192.168.0.163:11211
# \u8FDE\u63A5\
|
u6C60
memcached.poolSize=10
#\u64CD\u4F5C\u8D85\u65F6\u65F6\u95F4
memcached.opTimeout=6000
|
repos\spring-boot-leaning-master\2.x_42_courses\第 4-1 课:Spring Boot 操作 Memcache\spring-boot-memcache\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Map<String, String> selectProperties(Map<String, String> allProperties, boolean selectFoxProperties) {
Map<String, String> result = null;
if (selectFoxProperties) {
result = new HashMap<String, String>();
String isAutoSchemaUpdate = allProperties.get(PROP_IS_AUTO_SCHEMA_UPDATE);
String isActivateJobExecutor = allProperties.get(PROP_IS_ACTIVATE_JOB_EXECUTOR);
String isIdentityUsed = allProperties.get(PROP_IS_IDENTITY_USED);
String dbTablePrefix = allProperties.get(PROP_DB_TABLE_PREFIX);
String jobExecutorAcquisitionName = allProperties.get(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
if (isAutoSchemaUpdate != null) {
result.put(PROP_IS_AUTO_SCHEMA_UPDATE, isAutoSchemaUpdate);
}
if (isActivateJobExecutor != null) {
result.put(PROP_IS_ACTIVATE_JOB_EXECUTOR, isActivateJobExecutor);
}
if (isIdentityUsed != null) {
result.put(PROP_IS_IDENTITY_USED, isIdentityUsed);
|
}
if (dbTablePrefix != null) {
result.put(PROP_DB_TABLE_PREFIX, dbTablePrefix);
}
if (jobExecutorAcquisitionName != null) {
result.put(PROP_JOB_EXECUTOR_ACQUISITION_NAME, jobExecutorAcquisitionName);
}
} else {
result = new HashMap<String, String>(allProperties);
result.remove(PROP_IS_AUTO_SCHEMA_UPDATE);
result.remove(PROP_IS_ACTIVATE_JOB_EXECUTOR);
result.remove(PROP_IS_IDENTITY_USED);
result.remove(PROP_DB_TABLE_PREFIX);
result.remove(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
}
return result;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\config\ManagedProcessEngineMetadata.java
| 2
|
请完成以下Java代码
|
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
//results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobCountByQueryCriteria(this);
}
@Override
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobsByQueryCriteria(this, page);
}
@Override
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findDeploymentIdMappingsByQueryCriteria(this);
}
//getters //////////////////////////////////////////
public Set<String> getIds() {
return ids;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public String getExecutionId() {
|
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public boolean getAcquired() {
return acquired;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java
| 1
|
请完成以下Java代码
|
public BigDecimal getParameterAsBigDecimal()
{
return toBigDecimal(m_Parameter);
}
@Nullable
public BigDecimal getParameter_ToAsBigDecimal()
{
return toBigDecimal(m_Parameter_To);
}
@Nullable
private static BigDecimal toBigDecimal(@Nullable final Object value)
{
if (value == null)
{
|
return null;
}
else if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((Integer)value);
}
else
{
return new BigDecimal(value.toString());
}
}
} // ProcessInfoParameter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java
| 1
|
请完成以下Java代码
|
public final boolean permitAll() {
return true;
}
@Override
public final boolean denyAll() {
return false;
}
@Override
public final boolean isAnonymous() {
return trustResolver.isAnonymous(authentication);
}
@Override
public final boolean isAuthenticated() {
return !isAnonymous();
}
@Override
public final boolean isRememberMe() {
return trustResolver.isRememberMe(authentication);
}
@Override
public final boolean isFullyAuthenticated() {
return !trustResolver.isAnonymous(authentication) && !trustResolver.isRememberMe(authentication);
}
public Object getPrincipal() {
return authentication.getPrincipal();
}
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
}
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
this.roleHierarchy = roleHierarchy;
}
public void setDefaultRolePrefix(String defaultRolePrefix) {
this.defaultRolePrefix = defaultRolePrefix;
}
private Set<String> getAuthoritySet() {
if (roles == null) {
Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
if (roleHierarchy != null) {
userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities);
}
roles = AuthorityUtils.authorityListToSet(userAuthorities);
}
return roles;
}
@Override
public boolean hasPermission(Object target, Object permission) {
return permissionEvaluator.hasPermission(authentication, target, permission);
}
@Override
public boolean hasPermission(Object targetId, String targetType, Object permission) {
return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission);
}
public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) {
this.permissionEvaluator = permissionEvaluator;
}
private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
|
if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) {
return role;
}
if (role.startsWith(defaultRolePrefix)) {
return role;
}
return defaultRolePrefix + role;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
}
@Override
public Object getThis() {
return this;
}
@Override
public void setFilterObject(Object obj) {
this.filterObject = obj;
}
@Override
public void setReturnObject(Object obj) {
this.returnObject = obj;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java
| 1
|
请完成以下Java代码
|
private void ack(MessageAndChannel mac) {
try {
mac.channel.basicAck(mac.message.getMessageProperties()
.getDeliveryTag(), false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private int tryGetRetryCountOrFail(MessageAndChannel mac, Throwable originalError) throws Throwable {
MessageProperties props = mac.message.getMessageProperties();
String xRetriedCountHeader = (String) props.getHeader("x-retried-count");
final int xRetriedCount = xRetriedCountHeader == null ? 0 : Integer.valueOf(xRetriedCountHeader);
if (retryQueues.retriesExhausted(xRetriedCount)) {
mac.channel.basicReject(props.getDeliveryTag(), false);
throw originalError;
}
return xRetriedCount;
}
private void sendToNextRetryQueue(MessageAndChannel mac, int retryCount) throws Exception {
String retryQueueName = retryQueues.getQueueName(retryCount);
|
rabbitTemplate.convertAndSend(retryQueueName, mac.message, m -> {
MessageProperties props = m.getMessageProperties();
props.setExpiration(String.valueOf(retryQueues.getTimeToWait(retryCount)));
props.setHeader("x-retried-count", String.valueOf(retryCount + 1));
props.setHeader("x-original-exchange", props.getReceivedExchange());
props.setHeader("x-original-routing-key", props.getReceivedRoutingKey());
return m;
});
mac.channel.basicReject(mac.message.getMessageProperties()
.getDeliveryTag(), false);
}
private class MessageAndChannel {
private Message message;
private Channel channel;
private MessageAndChannel(Message message, Channel channel) {
this.message = message;
this.channel = channel;
}
}
}
|
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RetryQueuesInterceptor.java
| 1
|
请完成以下Java代码
|
public class OrgIdAccessList
{
public static final OrgIdAccessList ALL = new OrgIdAccessList(true, ImmutableSet.of()); // NOTE: new instance to make sure it's unique
public static final OrgIdAccessList TABLE_ALL = new OrgIdAccessList(true, ImmutableSet.of()); // NOTE: new instance to make sure it's unique;
@Getter
private final boolean any;
private final ImmutableSet<OrgId> orgIds;
private OrgIdAccessList(final boolean any, final Set<OrgId> orgIds)
{
this.any = any;
this.orgIds = ImmutableSet.copyOf(orgIds);
}
public static OrgIdAccessList ofSet(final Set<OrgId> orgIds)
{
return new OrgIdAccessList(false, orgIds);
}
private void assertNotAny()
{
if (any)
{
|
throw new AdempiereException("Assumed not an ANY org access list: " + this);
}
}
public Iterator<OrgId> iterator()
{
assertNotAny();
return orgIds.iterator();
}
public boolean contains(@NonNull final OrgId orgId)
{
return any || orgIds.contains(orgId);
}
public ImmutableSet<OrgId> toSet()
{
assertNotAny();
return orgIds;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\OrgIdAccessList.java
| 1
|
请完成以下Java代码
|
public class MemoryLocalityCosts {
private static final int[] intArray = new int[1_000_000];
private static final Integer[] integerArray = new Integer[1_000_000];
static {
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
intArray[i-1] = i;
integerArray[i-1] = i;
});
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntArraySequential() {
Arrays.stream(intArray).reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntArrayParallel() {
Arrays.stream(intArray).parallel().reduce(0, Integer::sum);
}
|
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntegerArraySequential() {
Arrays.stream(integerArray).reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntegerArrayParallel() {
Arrays.stream(integerArray).parallel().reduce(0, Integer::sum);
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\parallel\MemoryLocalityCosts.java
| 1
|
请完成以下Java代码
|
public static boolean[][] setupAbacus(int[] A, int m) {
boolean[][] abacus = new boolean[A.length][m];
for (int i = 0; i < abacus.length; i++) {
int number = A[i];
for (int j = 0; j < abacus[0].length && j < number; j++) {
abacus[A.length - 1 - i][j] = true;
}
}
return abacus;
}
public static void dropBeads(boolean[][] abacus, int[] A, int m) {
for (int i = 1; i < A.length; i++) {
for (int j = m - 1; j >= 0; j--) {
if (abacus[i][j] == true) {
int x = i;
while (x > 0 && abacus[x - 1][j] == false) {
boolean temp = abacus[x - 1][j];
abacus[x - 1][j] = abacus[x][j];
abacus[x][j] = temp;
x--;
}
}
}
}
|
}
public static void transformToList(boolean[][] abacus, int[] A) {
int index = 0;
for (int i = abacus.length - 1; i >= 0; i--) {
int beads = 0;
for (int j = 0; j < abacus[0].length && abacus[i][j] == true; j++) {
beads++;
}
A[index++] = beads;
}
}
public static void sort(int[] A) {
int m = findMax(A);
boolean[][] abacus = setupAbacus(A, m);
dropBeads(abacus, A, m);
// transform abacus into sorted list
transformToList(abacus, A);
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting-3\src\main\java\com\baeldung\algorithms\gravitysort\GravitySort.java
| 1
|
请完成以下Java代码
|
public void cusToExistingCU(@NonNull final List<I_M_HU> sourceCuHUs, @NonNull final I_M_HU targetCU)
{
sourceCuHUs.forEach(sourceCU -> cuToExistingCU(sourceCU, targetCU));
}
private void cuToExistingCU(@NonNull final I_M_HU sourceCuHU, @NonNull final I_M_HU targetHU)
{
trxManager.runInThreadInheritedTrx(() -> cuToExistingCU_InTrx(sourceCuHU, targetHU));
}
private void cuToExistingCU_InTrx(
@NonNull final I_M_HU sourceCuHU,
@NonNull final I_M_HU targetHU)
{
final IMutableHUContext huContextWithOrgId = huContextFactory.createMutableHUContext(InterfaceWrapperHelper.getContextAware(targetHU));
final List<IHUProductStorage> productStorages = huContext.getHUStorageFactory()
.getStorage(targetHU)
.getProductStorages();
if (productStorages.size() > 1)
{
throw new AdempiereException("CUs with more than one product are not supported!");
}
final IAllocationSource source = HUListAllocationSourceDestination
|
.of(sourceCuHU, AllocationStrategyType.UNIFORM)
.setDestroyEmptyHUs(true);
final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU, AllocationStrategyType.UNIFORM);
final IHUProductStorage sourceProductStorage = getSingleProductStorage(sourceCuHU);
final ProductId targetHUProductId = productStorages.isEmpty()
? sourceProductStorage.getProductId()
: productStorages.get(0).getProductId();
Check.assume(sourceProductStorage.getProductId().equals(targetHUProductId), "Source and Target HU productId must match!");
HULoader.of(source, destination)
.load(AllocationUtils.builder()
.setHUContext(huContextWithOrgId)
.setDateAsToday()
.setProduct(sourceProductStorage.getProductId())
.setQuantity(sourceProductStorage.getQtyInStockingUOM())
.setFromReferencedModel(sourceCuHU)
.setForceQtyAllocation(true)
.create());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\HUTransformService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void buildAndAttachRouteContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
if (request.getAdPInstanceId() != null)
{
exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue());
processLogger.logMessage("Shopware6:ExportStock process started!" + Instant.now(), request.getAdPInstanceId().getValue());
}
final String clientId = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_ID);
final String clientSecret = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_SECRET);
final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH);
final PInstanceLogger pInstanceLogger = PInstanceLogger.builder()
.processLogger(processLogger)
.pInstanceId(request.getAdPInstanceId())
.build();
final ShopwareClient shopwareClient = ShopwareClient.of(clientId, clientSecret, basePath, pInstanceLogger);
final JsonAvailableForSales jsonAvailableForSales = getJsonAvailableForSales(request);
final ExportStockRouteContext exportStockRouteContext = ExportStockRouteContext.builder()
.shopwareClient(shopwareClient)
.jsonAvailableForSales(jsonAvailableForSales)
.build();
exchange.setProperty(ROUTE_PROPERTY_EXPORT_STOCK_CONTEXT, exportStockRouteContext);
|
}
@NonNull
private JsonAvailableForSales getJsonAvailableForSales(@NonNull final JsonExternalSystemRequest request)
{
try
{
return objectMapper.readValue(request.getParameters().get(ExternalSystemConstants.PARAM_JSON_AVAILABLE_FOR_SALES), JsonAvailableForSales.class);
}
catch (final IOException e)
{
throw new RuntimeException("Unable to deserialize JsonAvailableStock", e);
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\stock\ExportStockRouteBuilder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class HistoricVariableInstanceResponse {
protected String id;
protected String caseInstanceId;
protected String caseInstanceUrl;
protected String taskId;
protected String planItemInstanceId;
protected RestVariable variable;
@ApiModelProperty(example = "14")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "5")
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/5")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
|
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
@ApiModelProperty(example = "6")
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public RestVariable getVariable() {
return variable;
}
public void setVariable(RestVariable variable) {
this.variable = variable;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceResponse.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 7001
spring:
application:
name: jeecg-system
cloud:
nacos:
config:
server-addr: @config.server-addr@
group: @config.group@
namespace: @config.namespace@
username: @config.username@
password: @config.password@
discovery:
server-addr: ${spring.cloud.nacos.config.server-addr}
group: @config.group@
namespace: @config.namespace@
username: @config.username@
password: @config.password@
config:
import:
- optional:classpath:config/application-liteflow.yml
- optional:nacos:jeecg.yaml
- optional:nacos:jeecg-@profile.name@.yaml
# #shardingjdbc数
|
据源
# datasource:
# dynamic:
# datasource:
# sharding-db:
# driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
# url: jdbc:shardingsphere:nacos:sharding.yaml?serverAddr=@config.server-addr@&namespace=@config.namespace@&group=@config.group@
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-system-cloud-start\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
private static BooleanWithReason validatePaymentTermWithSchedules(@NonNull final List<PaySchedule> schedules)
{
if (schedules.isEmpty())
{
return BooleanWithReason.TRUE;
}
else
{
final Percent totalPercent = schedules.stream().map(PaySchedule::getPercentage).reduce(Percent.ZERO, Percent::add);
if (!totalPercent.isOneHundred())
{
return BooleanWithReason.falseBecause("Total percent must be exactly 100%, but it was: " + totalPercent);
}
return BooleanWithReason.TRUE;
}
}
|
public boolean isValid() {return valid.isTrue();}
public PaymentTermBreak getBreakById(final @NonNull PaymentTermBreakId id)
{
Check.assumeNotEmpty(breaksById, "Payment term does not support breaks: {}", this);
final PaymentTermBreak paymentTermBreak = breaksById.get(id);
if (paymentTermBreak == null)
{
throw new AdempiereException("No break found for id: " + id);
}
return paymentTermBreak;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\PaymentTerm.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getTimerLockWaitTime() {
return timerLockWaitTime;
}
public void setTimerLockWaitTime(Duration timerLockWaitTime) {
this.timerLockWaitTime = timerLockWaitTime;
}
public Duration getTimerLockPollRate() {
return timerLockPollRate;
}
public void setTimerLockPollRate(Duration timerLockPollRate) {
this.timerLockPollRate = timerLockPollRate;
}
public Duration getTimerLockForceAcquireAfter() {
return timerLockForceAcquireAfter;
}
public void setTimerLockForceAcquireAfter(Duration timerLockForceAcquireAfter) {
this.timerLockForceAcquireAfter = timerLockForceAcquireAfter;
}
public Duration getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
|
public void setResetExpiredJobsInterval(Duration resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobExecutorConfiguration.java
| 2
|
请完成以下Java代码
|
public class TodoAppClient {
ObjectMapper objectMapper = new ObjectMapper();
Gson gson = new GsonBuilder().create();
public String sampleApiRequest() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/todos"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
return response.body();
}
public Todo syncGson() throws Exception {
String response = sampleApiRequest();
List<Todo> todo = gson.fromJson(response, new TypeToken<List<Todo>>() {
}.getType());
return todo.get(1);
}
public Todo syncJackson() throws Exception {
String response = sampleApiRequest();
Todo[] todo = objectMapper.readValue(response, Todo[].class);
return todo[1];
}
public Todo asyncJackson() throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/todos"))
.build();
TodoAppClient todoAppClient = new TodoAppClient();
List<Todo> todo = HttpClient.newHttpClient()
.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(todoAppClient::readValueJackson)
.get();
return todo.get(1);
}
|
public Todo asyncGson() throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/todos"))
.build();
TodoAppClient todoAppClient = new TodoAppClient();
List<Todo> todo = HttpClient.newHttpClient()
.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(todoAppClient::readValueGson)
.get();
return todo.get(1);
}
List<Todo> readValueJackson(String content) {
try {
return objectMapper.readValue(content, new TypeReference<List<Todo>>() {
});
} catch (IOException ioe) {
throw new CompletionException(ioe);
}
}
List<Todo> readValueGson(String content) {
return gson.fromJson(content, new TypeToken<List<Todo>>() {
}.getType());
}
}
|
repos\tutorials-master\core-java-modules\core-java-11-3\src\main\java\com\baeldung\httppojo\TodoAppClient.java
| 1
|
请完成以下Java代码
|
public static final class ThrowMessagBuilder implements INameStage, IBuildStage {
private String name;
private Optional<Map<String, Object>> payload = Optional.empty();
private Optional<String> businessKey = Optional.empty();
private Optional<String> correlationKey = Optional.empty();
private ThrowMessagBuilder() {}
@Override
public IBuildStage name(String name) {
this.name = name;
return this;
}
@Override
public IBuildStage payload(Optional<Map<String, Object>> payload) {
this.payload = payload;
return this;
}
|
@Override
public IBuildStage businessKey(Optional<String> businessKey) {
this.businessKey = businessKey;
return this;
}
@Override
public IBuildStage correlationKey(Optional<String> correlationKey) {
this.correlationKey = correlationKey;
return this;
}
@Override
public ThrowMessage build() {
return new ThrowMessage(this);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\delegate\ThrowMessage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String , Object> map;
private List<Object> list;
private Dog dog;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
|
this.map = map;
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Person\":{" );
sb.append( "\"lastName\":\"" )
.append( lastName ).append( '\"' );
sb.append( ",\"age\":" )
.append( age );
sb.append( ",\"boss\":" )
.append( boss );
sb.append( ",\"birth\":\"" )
.append( birth ).append( '\"' );
sb.append( ",\"map\":" )
.append( map );
sb.append( ",\"list\":" )
.append( list );
sb.append( ",\"dog\":" )
.append( dog );
sb.append( "}}" );
return sb.toString();
}
}
|
repos\SpringBootLearning-master (1)\springboot-config\src\main\java\com\gf\entity\Person.java
| 2
|
请完成以下Java代码
|
public void addPreDefaultResolver(ELResolver elResolver) {
if (this.preDefaultResolvers == null) {
this.preDefaultResolvers = new ArrayList<>();
}
this.preDefaultResolvers.add(elResolver);
}
public ELResolver getJsonNodeResolver() {
return jsonNodeResolver;
}
public void setJsonNodeResolver(ELResolver jsonNodeResolver) {
// When the bean resolver is modified we need to reset the el resolver
this.staticElResolver = null;
this.jsonNodeResolver = jsonNodeResolver;
}
public void addPostDefaultResolver(ELResolver elResolver) {
if (this.postDefaultResolvers == null) {
this.postDefaultResolvers = new ArrayList<>();
}
this.postDefaultResolvers.add(elResolver);
}
|
public void addPreBeanResolver(ELResolver elResolver) {
if (this.preBeanResolvers == null) {
this.preBeanResolvers = new ArrayList<>();
}
this.preBeanResolvers.add(elResolver);
}
public ELResolver getBeanResolver() {
return beanResolver;
}
public void setBeanResolver(ELResolver beanResolver) {
// When the bean resolver is modified we need to reset the el resolver
this.staticElResolver = null;
this.beanResolver = beanResolver;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\DefaultExpressionManager.java
| 1
|
请完成以下Java代码
|
protected Object getValue(ValueFields valueFields, CommandContext commandContext) {
String multiInstanceRootId = valueFields.getTextValue();
String type = valueFields.getTextValue2();
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
ExecutionEntityManager executionEntityManager = processEngineConfiguration.getExecutionEntityManager();
ExecutionEntity multiInstanceRootExecution = executionEntityManager.findById(multiInstanceRootId);
if (multiInstanceRootExecution == null) {
// We used to have a bug where we would create this variable type for a parallel multi instance with no instances.
// Therefore, if the multi instance root execution is null it means that we have no active, nor completed instances.
return 0;
}
List<? extends ExecutionEntity> childExecutions = multiInstanceRootExecution.getExecutions();
int nrOfActiveInstances = (int) childExecutions.stream().filter(execution -> execution.isActive()
&& !(execution.getCurrentFlowElement() instanceof BoundaryEvent)).count();
if (ParallelMultiInstanceLoopVariable.COMPLETED_INSTANCES.equals(type)) {
|
Object nrOfInstancesValue = multiInstanceRootExecution.getVariable(NUMBER_OF_INSTANCES);
int nrOfInstances = (Integer) (nrOfInstancesValue != null ? nrOfInstancesValue : 0);
return nrOfInstances - nrOfActiveInstances;
} else if (ParallelMultiInstanceLoopVariable.ACTIVE_INSTANCES.equals(type)) {
return nrOfActiveInstances;
} else {
//TODO maybe throw exception
return 0;
}
}
@Override
public boolean isReadOnly() {
return true;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\variable\ParallelMultiInstanceLoopVariableType.java
| 1
|
请完成以下Java代码
|
public class ProductService {
@Autowired
ProductRepository productRepository;
@Transactional
public Mono<Order> handleOrder(Order order) {
log.info("Handle order invoked with: {}", order);
return Flux.fromIterable(order.getLineItems())
.flatMap(l -> productRepository.findById(l.getProductId()))
.flatMap(p -> {
int q = order.getLineItems()
.stream()
.filter(l -> l.getProductId()
.equals(p.getId()))
.findAny()
.get()
.getQuantity();
if (p.getStock() >= q) {
p.setStock(p.getStock() - q);
return productRepository.save(p);
} else {
return Mono.error(new RuntimeException("Product is out of stock: " + p.getId()));
}
})
.then(Mono.just(order.setOrderStatus(OrderStatus.SUCCESS)));
|
}
@Transactional
public Mono<Order> revertOrder(Order order) {
log.info("Revert order invoked with: {}", order);
return Flux.fromIterable(order.getLineItems())
.flatMap(l -> productRepository.findById(l.getProductId()))
.flatMap(p -> {
int q = order.getLineItems()
.stream()
.filter(l -> l.getProductId()
.equals(p.getId()))
.collect(Collectors.toList())
.get(0)
.getQuantity();
p.setStock(p.getStock() + q);
return productRepository.save(p);
})
.then(Mono.just(order.setOrderStatus(OrderStatus.SUCCESS)));
}
public Flux<Product> getProducts() {
return productRepository.findAll();
}
}
|
repos\tutorials-master\reactive-systems\inventory-service\src\main\java\com\baeldung\reactive\service\ProductService.java
| 1
|
请完成以下Java代码
|
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Size X.
@param SizeX
X (horizontal) dimension size
*/
public void setSizeX (BigDecimal SizeX)
{
set_Value (COLUMNNAME_SizeX, SizeX);
}
/** Get Size X.
@return X (horizontal) dimension size
*/
|
public BigDecimal getSizeX ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeX);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Size Y.
@param SizeY
Y (vertical) dimension size
*/
public void setSizeY (BigDecimal SizeY)
{
set_Value (COLUMNNAME_SizeY, SizeY);
}
/** Get Size Y.
@return Y (vertical) dimension size
*/
public BigDecimal getSizeY ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeY);
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_AD_PrintPaper.java
| 1
|
请完成以下Java代码
|
public int getUVP_Price_List_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UVP_Price_List_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_PriceList getZBV_Price_List() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class);
}
@Override
public void setZBV_Price_List(org.compiere.model.I_M_PriceList ZBV_Price_List)
{
set_ValueFromPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class, ZBV_Price_List);
}
/** Set Price List ZBV.
@param ZBV_Price_List_ID Price List ZBV */
|
@Override
public void setZBV_Price_List_ID (int ZBV_Price_List_ID)
{
if (ZBV_Price_List_ID < 1)
set_Value (COLUMNNAME_ZBV_Price_List_ID, null);
else
set_Value (COLUMNNAME_ZBV_Price_List_ID, Integer.valueOf(ZBV_Price_List_ID));
}
/** Get Price List ZBV.
@return Price List ZBV */
@Override
public int getZBV_Price_List_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ZBV_Price_List_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_Product.java
| 1
|
请完成以下Java代码
|
public class OmsOrderOperateHistory implements Serializable {
private Long id;
@ApiModelProperty(value = "订单id")
private Long orderId;
@ApiModelProperty(value = "操作人:用户;系统;后台管理员")
private String operateMan;
@ApiModelProperty(value = "操作时间")
private Date createTime;
@ApiModelProperty(value = "订单状态:0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单")
private Integer orderStatus;
@ApiModelProperty(value = "备注")
private String note;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOperateMan() {
return operateMan;
}
public void setOperateMan(String operateMan) {
this.operateMan = operateMan;
|
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", orderId=").append(orderId);
sb.append(", operateMan=").append(operateMan);
sb.append(", createTime=").append(createTime);
sb.append(", orderStatus=").append(orderStatus);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderOperateHistory.java
| 1
|
请完成以下Java代码
|
public int getM_HU_Item_Storage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID);
}
@Override
public void setM_HU_Item_Storage_Snapshot_ID (final int M_HU_Item_Storage_Snapshot_ID)
{
if (M_HU_Item_Storage_Snapshot_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, M_HU_Item_Storage_Snapshot_ID);
}
@Override
public int getM_HU_Item_Storage_Snapshot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_Snapshot_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
|
}
@Override
public void setQty (final 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 setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java
| 1
|
请完成以下Java代码
|
private String digest(String salt, CharSequence rawPassword) {
if (rawPassword == null) {
rawPassword = "";
}
String saltedPassword = rawPassword + salt;
byte[] saltedPasswordBytes = Utf8.encode(saltedPassword);
Md4 md4 = new Md4();
md4.update(saltedPasswordBytes, 0, saltedPasswordBytes.length);
byte[] digest = md4.digest();
String encoded = encodedNonNullPassword(digest);
return salt + encoded;
}
private String encodedNonNullPassword(byte[] digest) {
if (this.encodeHashAsBase64) {
return Utf8.decode(Base64.getEncoder().encode(digest));
}
return new String(Hex.encode(digest));
}
/**
* Takes a previously encoded password and compares it with a rawpassword after mixing
* in the salt and encoding that value
* @param rawPassword plain text password
|
* @param encodedPassword previously encoded password
* @return true or false
*/
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
String salt = extractSalt(encodedPassword);
String rawPasswordEncoded = digest(salt, rawPassword);
return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded);
}
private String extractSalt(String prefixEncodedPassword) {
int start = prefixEncodedPassword.indexOf(PREFIX);
if (start != 0) {
return "";
}
int end = prefixEncodedPassword.indexOf(SUFFIX, start);
if (end < 0) {
return "";
}
return prefixEncodedPassword.substring(start, end + 1);
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Md4PasswordEncoder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuditResource {
private final AuditEventService auditEventService;
public AuditResource(AuditEventService auditEventService) {
this.auditEventService = auditEventService;
}
/**
* GET /audits : get a page of AuditEvents.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
*/
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) {
Page<AuditEvent> page = auditEventService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /audits : get a page of AuditEvents between the fromDate and toDate.
*
* @param fromDate the start of the time period of AuditEvents to get
* @param toDate the end of the time period of AuditEvents to get
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
*/
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
@RequestParam(value = "fromDate") LocalDate fromDate,
@RequestParam(value = "toDate") LocalDate toDate,
Pageable pageable) {
Page<AuditEvent> page = auditEventService.findByDates(
|
fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(),
toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(),
pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /audits/:id : get an AuditEvent by id.
*
* @param id the id of the entity to get
* @return the ResponseEntity with status 200 (OK) and the AuditEvent in body, or status 404 (Not Found)
*/
@GetMapping("/{id:.+}")
public ResponseEntity<AuditEvent> get(@PathVariable Long id) {
return ResponseUtil.wrapOrNotFound(auditEventService.find(id));
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\AuditResource.java
| 2
|
请完成以下Java代码
|
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Attribute Search.
@param M_AttributeSearch_ID
Common Search Attribute
*/
public void setM_AttributeSearch_ID (int M_AttributeSearch_ID)
{
if (M_AttributeSearch_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, Integer.valueOf(M_AttributeSearch_ID));
}
/** Get Attribute Search.
@return Common Search Attribute
*/
public int getM_AttributeSearch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSearch_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSearch.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class RandomUtil {
private static final int DEF_COUNT = 20;
private RandomUtil() {
}
/**
* Generate a password.
*
* @return the generated password
*/
public static String generatePassword() {
return RandomStringUtils.randomAlphanumeric(DEF_COUNT);
}
/**
|
* Generate an activation key.
*
* @return the generated activation key
*/
public static String generateActivationKey() {
return RandomStringUtils.randomNumeric(DEF_COUNT);
}
/**
* Generate a reset key.
*
* @return the generated reset key
*/
public static String generateResetKey() {
return RandomStringUtils.randomNumeric(DEF_COUNT);
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\util\RandomUtil.java
| 2
|
请完成以下Java代码
|
protected DeploymentEntityManager getDeploymentEntityManager() {
return getProcessEngineConfiguration().getDeploymentEntityManager();
}
protected ResourceEntityManager getResourceEntityManager() {
return getProcessEngineConfiguration().getResourceEntityManager();
}
protected ByteArrayEntityManager getByteArrayEntityManager() {
return getProcessEngineConfiguration().getByteArrayEntityManager();
}
protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionEntityManager();
}
protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionInfoEntityManager();
}
protected ModelEntityManager getModelEntityManager() {
return getProcessEngineConfiguration().getModelEntityManager();
}
protected ExecutionEntityManager getExecutionEntityManager() {
return getProcessEngineConfiguration().getExecutionEntityManager();
|
}
protected ActivityInstanceEntityManager getActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getActivityInstanceEntityManager();
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow);
}
@Override
public int getPP_Order_Workflow_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID);
}
@Override
public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID)
{
if (PP_Order_Workflow_ID < 1)
set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null);
else
set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty(final @Nullable BigDecimal Qty)
{
set_Value(COLUMNNAME_Qty, Qty);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNo(final int SeqNo)
{
set_Value(COLUMNNAME_SeqNo, SeqNo);
|
}
@Override
public java.lang.String getSpecification()
{
return get_ValueAsString(COLUMNNAME_Specification);
}
@Override
public void setSpecification(final @Nullable java.lang.String Specification)
{
set_Value(COLUMNNAME_Specification, Specification);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setYield(final @Nullable BigDecimal Yield)
{
set_Value(COLUMNNAME_Yield, Yield);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java
| 1
|
请完成以下Java代码
|
public DefaultOutputEntry getDefaultOutputEntry() {
return defaultOutputEntryChild.getChild(this);
}
public void setDefaultOutputEntry(DefaultOutputEntry defaultOutputEntry) {
defaultOutputEntryChild.setChild(this, defaultOutputEntry);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OutputClause.class, DMN_ELEMENT_OUTPUT_CLAUSE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<OutputClause>() {
public OutputClause newInstance(ModelTypeInstanceContext instanceContext) {
return new OutputClauseImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAME)
.build();
|
typeRefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_REF)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
outputValuesChild = sequenceBuilder.element(OutputValues.class)
.build();
defaultOutputEntryChild = sequenceBuilder.element(DefaultOutputEntry.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OutputClauseImpl.java
| 1
|
请完成以下Java代码
|
public List<?> queryForMovies() {
EntityManager em = HibernateOperations.getEntityManager();
List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
.setParameter(1, "English")
.getResultList();
return movies;
}
/**
* Method to illustrate the usage of find() method.
* @param movieId
* @return Movie
*/
public Movie getMovie(Long movieId) {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = em.find(Movie.class, Long.valueOf(movieId));
return movie;
}
/**
* Method to illustrate the usage of merge() function.
*/
public void mergeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
|
Movie movie = getMovie(1L);
em.detach(movie);
movie.setLanguage("Italian");
em.getTransaction()
.begin();
em.merge(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the usage of remove() function.
*/
public void removeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = em.find(Movie.class, Long.valueOf(1L));
em.remove(movie);
em.getTransaction()
.commit();
}
}
|
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\operations\HibernateOperations.java
| 1
|
请完成以下Java代码
|
public Long zadd(final String key, final Map<String, Double> scoreMembers) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.zadd(key, scoreMembers);
} catch (Exception ex) {
log.error("Exception caught in zadd", ex);
}
return 0L;
}
public List<String> zrange(final String key, final long start, final long stop) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.zrange(key, start, stop);
} catch (Exception ex) {
log.error("Exception caught in zrange", ex);
}
return new ArrayList<>();
}
public String mset(final HashMap<String, String> keysValues) {
try (Jedis jedis = jedisPool.getResource()) {
ArrayList<String> keysValuesArrayList = new ArrayList<>();
keysValues.forEach((key, value) -> {
keysValuesArrayList.add(key);
keysValuesArrayList.add(value);
});
return jedis.mset((keysValuesArrayList.toArray(new String[keysValues.size()])));
} catch (Exception ex) {
log.error("Exception caught in mset", ex);
}
return null;
}
public Set<String> keys(final String pattern) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(pattern);
} catch (Exception ex) {
log.error("Exception caught in keys", ex);
}
return new HashSet<String>();
}
|
public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) {
return new RedisIterator(jedisPool, initialScanCount, pattern, strategy);
}
public void flushAll() {
try (Jedis jedis = jedisPool.getResource()) {
jedis.flushAll();
} catch (Exception ex) {
log.error("Exception caught in flushAll", ex);
}
}
public void destroyInstance() {
jedisPool = null;
instance = null;
}
}
|
repos\tutorials-master\persistence-modules\redis\src\main\java\com\baeldung\redis_scan\client\RedisClient.java
| 1
|
请完成以下Java代码
|
public class C_Async_Batch
{
private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class);
private final IAsyncBatchListeners asyncBatchListeners = Services.get(IAsyncBatchListeners.class);
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE,
ifColumnsChanged = I_C_Async_Batch.COLUMNNAME_Processed)
public void updateProcessed(final I_C_Async_Batch asyncBatch)
{
//
// Our batch was processed right now => notify user by sending email
if (asyncBatch.isProcessed()
&& isNotificationType(asyncBatch, X_C_Async_Batch_Type.NOTIFICATIONTYPE_AsyncBatchProcessed))
{
asyncBatchListeners.notify(asyncBatch);
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE,
ifColumnsChanged = { I_C_Async_Batch.COLUMNNAME_CountProcessed, I_C_Async_Batch.COLUMNNAME_LastProcessed_WorkPackage_ID })
public void updateCountProcessed(final I_C_Async_Batch asyncBatch)
|
{
//
// Our batch was not processed => notify user with note when workpackage processed
if (!asyncBatch.isProcessed()
&& isNotificationType(asyncBatch, X_C_Async_Batch_Type.NOTIFICATIONTYPE_WorkpackageProcessed))
{
asyncBatchListeners.notify(asyncBatch);
}
}
private boolean isNotificationType(@NonNull final I_C_Async_Batch asyncBatch, @NonNull final String expectedNotificationType)
{
final String notificationType = asyncBatchBL.getAsyncBatchType(asyncBatch).map(AsyncBatchType::getNotificationType).orElse(null);
return Objects.equals(notificationType, expectedNotificationType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\C_Async_Batch.java
| 1
|
请完成以下Java代码
|
public List<String> getValuesInArray(JSONArray jsonArray, String key) {
List<String> accumulatedValues = new ArrayList<>();
for (Object obj : jsonArray) {
if (obj instanceof JSONArray) {
accumulatedValues.addAll(getValuesInArray((JSONArray)obj, key));
} else if (obj instanceof JSONObject) {
accumulatedValues.addAll(getValuesInObject((JSONObject)obj, key));
}
}
return accumulatedValues;
}
/**
* Among all the values associated with the given key, get the N-th value
*
* @param jsonObject JSONObject instance in which to search the key
* @param key Key we're interested in
* @param N Index of the value to get
*
* @return N-th value associated with the key, or null if the key is absent or
* the number of values associated with the key is less than N
*/
|
public String getNthValue(JSONObject jsonObject, String key, int N) {
List<String> values = getValuesInObject(jsonObject, key);
return (values.size() >= N) ? values.get(N - 1) : null;
}
/**
* Count the number of values associated with the given key
*
* @param jsonObject JSONObject instance in which to count the key
* @param key Key we're interested in
*
* @return The number of values associated with the given key
*/
public int getCount(JSONObject jsonObject, String key) {
List<String> values = getValuesInObject(jsonObject, key);
return values.size();
}
}
|
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonvaluegetter\JSONObjectValueGetter.java
| 1
|
请完成以下Java代码
|
public DeviceProfileId getId() {
return super.getId();
}
@Schema(description = "Timestamp of the profile creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
@Schema(description = "Used to mark the default profile. Default profile is used when the device profile is not specified during device creation.")
public boolean isDefault() {
return isDefault;
}
@Schema(description = "Complex JSON object that includes addition device profile configuration (transport, alarm rules, etc).")
public DeviceProfileData getProfileData() {
if (profileData != null) {
return profileData;
} else {
if (profileDataBytes != null) {
try {
profileData = mapper.readValue(new ByteArrayInputStream(profileDataBytes), DeviceProfileData.class);
|
} catch (IOException e) {
log.warn("Can't deserialize device profile data: ", e);
return null;
}
return profileData;
} else {
return null;
}
}
}
public void setProfileData(DeviceProfileData data) {
this.profileData = data;
try {
this.profileDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize device profile data: ", e);
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\DeviceProfile.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Builder
{
@Nullable
private String noNameHeaderPrefix = DEFAULT_UnknownHeaderPrefix;
private boolean considerNullStringAsNull = false;
private boolean considerEmptyStringAsNull = false;
private String rowNumberMapKey = null;
private boolean discardRepeatingHeaders = false;
private boolean useTypeColumn = true;
private Builder()
{
super();
}
public ExcelToMapListConverter build()
{
return new ExcelToMapListConverter(this);
}
/**
* Sets the header prefix to be used if the header columns is null or black.
*
* Set it to <code>null</code> to turn it off and get rid of columns without header.
*
* @see #setDiscardNoNameHeaders()
*/
public Builder setNoNameHeaderPrefix(@Nullable final String noNameHeaderPrefix)
{
this.noNameHeaderPrefix = noNameHeaderPrefix;
return this;
}
public Builder setDiscardNoNameHeaders()
{
setNoNameHeaderPrefix(null);
return this;
}
/**
* Sets if a cell value which is a null string (i.e. {@link ExcelToMapListConverter#NULLStringMarker}) shall be considered as <code>null</code>.
*/
public Builder setConsiderNullStringAsNull(final boolean considerNullStringAsNull)
{
this.considerNullStringAsNull = considerNullStringAsNull;
return this;
}
public Builder setConsiderEmptyStringAsNull(final boolean considerEmptyStringAsNull)
{
this.considerEmptyStringAsNull = considerEmptyStringAsNull;
return this;
}
public Builder setRowNumberMapKey(final String rowNumberMapKey)
{
|
this.rowNumberMapKey = rowNumberMapKey;
return this;
}
/**
* Sets if we shall detect repeating headers and discard them.
*/
public Builder setDiscardRepeatingHeaders(final boolean discardRepeatingHeaders)
{
this.discardRepeatingHeaders = discardRepeatingHeaders;
return this;
}
/**
* If enabled, the XLS converter will look for first not null column and it will expect to have one of the codes from {@link RowType}.
* If no row type would be found, the row would be ignored entirely.
*
* task 09045
*/
public Builder setUseRowTypeColumn(final boolean useTypeColumn)
{
this.useTypeColumn = useTypeColumn;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelToMapListConverter.java
| 2
|
请完成以下Java代码
|
public void setAD_OrgTo_ID (final int AD_OrgTo_ID)
{
if (AD_OrgTo_ID < 1)
set_Value (COLUMNNAME_AD_OrgTo_ID, null);
else
set_Value (COLUMNNAME_AD_OrgTo_ID, AD_OrgTo_ID);
}
@Override
public int getAD_OrgTo_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_OrgTo_ID);
}
@Override
public void setC_BPartner_From_ID (final int C_BPartner_From_ID)
{
if (C_BPartner_From_ID < 1)
set_Value (COLUMNNAME_C_BPartner_From_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_From_ID, C_BPartner_From_ID);
}
@Override
public int getC_BPartner_From_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_From_ID);
}
@Override
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 boolean remove(Object o)
{
return termFrequencyMap.remove(o) != null;
}
@Override
public boolean containsAll(Collection<?> c)
{
for (Object o : c)
{
if (!contains(o))
return false;
}
return true;
}
@Override
public boolean addAll(Collection<? extends TermFrequency> c)
{
for (TermFrequency termFrequency : c)
{
add(termFrequency);
}
return !c.isEmpty();
}
@Override
public boolean removeAll(Collection<?> c)
{
for (Object o : c)
{
if (!remove(o))
return false;
}
return true;
}
@Override
public boolean retainAll(Collection<?> c)
{
return termFrequencyMap.values().retainAll(c);
}
@Override
public void clear()
{
termFrequencyMap.clear();
}
/**
* 提取关键词(非线程安全)
*
* @param termList
* @param size
* @return
*/
@Override
public List<String> getKeywords(List<Term> termList, int size)
{
clear();
add(termList);
|
Collection<TermFrequency> topN = top(size);
List<String> r = new ArrayList<String>(topN.size());
for (TermFrequency termFrequency : topN)
{
r.add(termFrequency.getTerm());
}
return r;
}
/**
* 提取关键词(线程安全)
*
* @param document 文档内容
* @param size 希望提取几个关键词
* @return 一个列表
*/
public static List<String> getKeywordList(String document, int size)
{
return new TermFrequencyCounter().getKeywords(document, size);
}
@Override
public String toString()
{
final int max = 100;
return top(Math.min(max, size())).toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TermFrequencyCounter.java
| 1
|
请完成以下Java代码
|
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);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public org.compiere.util.KeyNamePair getKeyNamePair()
{
return new org.compiere.util.KeyNamePair(get_ID(), getName());
}
/** Set Sql ORDER BY.
@param OrderByClause
Fully qualified ORDER BY clause
*/
@Override
public void setOrderByClause (java.lang.String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
@Override
public java.lang.String getOrderByClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OrderByClause);
}
/** Set Other SQL Clause.
@param OtherClause
Other SQL Clause
*/
@Override
public void setOtherClause (java.lang.String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
@Override
public java.lang.String getOtherClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OtherClause);
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
|
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set ShowInMenu.
@param ShowInMenu ShowInMenu */
@Override
public void setShowInMenu (boolean ShowInMenu)
{
set_Value (COLUMNNAME_ShowInMenu, Boolean.valueOf(ShowInMenu));
}
/** Get ShowInMenu.
@return ShowInMenu */
@Override
public boolean isShowInMenu ()
{
Object oo = get_Value(COLUMNNAME_ShowInMenu);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<UserOnline> list() {
List<UserOnline> list = new ArrayList<>();
Collection<Session> sessions = sessionDAO.getActiveSessions();
for (Session session : sessions) {
UserOnline userOnline = new UserOnline();
User user = new User();
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
continue;
} else {
principalCollection = (SimplePrincipalCollection) session
.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
user = (User) principalCollection.getPrimaryPrincipal();
userOnline.setUsername(user.getUserName());
userOnline.setUserId(user.getId().toString());
}
userOnline.setId((String) session.getId());
userOnline.setHost(session.getHost());
userOnline.setStartTimestamp(session.getStartTimestamp());
userOnline.setLastAccessTime(session.getLastAccessTime());
Long timeout = session.getTimeout();
if (timeout == 0l) {
userOnline.setStatus("离线");
} else {
|
userOnline.setStatus("在线");
}
userOnline.setTimeout(timeout);
list.add(userOnline);
}
return list;
}
@Override
public boolean forceLogout(String sessionId) {
Session session = sessionDAO.readSession(sessionId);
session.setTimeout(0);
return true;
}
}
|
repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\service\impl\SessionServiceImpl.java
| 2
|
请完成以下Java代码
|
public class X_PP_ComponentGenerator_Param extends org.compiere.model.PO implements I_PP_ComponentGenerator_Param, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1661195109L;
/** Standard Constructor */
public X_PP_ComponentGenerator_Param (final Properties ctx, final int PP_ComponentGenerator_Param_ID, @Nullable final String trxName)
{
super (ctx, PP_ComponentGenerator_Param_ID, trxName);
}
/** Load Constructor */
public X_PP_ComponentGenerator_Param (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setParamValue (final java.lang.String ParamValue)
{
set_Value (COLUMNNAME_ParamValue, ParamValue);
}
@Override
public java.lang.String getParamValue()
{
return get_ValueAsString(COLUMNNAME_ParamValue);
}
@Override
public org.compiere.model.I_PP_ComponentGenerator getPP_ComponentGenerator()
{
return get_ValueAsPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class);
}
@Override
public void setPP_ComponentGenerator(final org.compiere.model.I_PP_ComponentGenerator PP_ComponentGenerator)
{
set_ValueFromPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class, PP_ComponentGenerator);
}
@Override
public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID)
|
{
if (PP_ComponentGenerator_ID < 1)
set_Value (COLUMNNAME_PP_ComponentGenerator_ID, null);
else
set_Value (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID);
}
@Override
public int getPP_ComponentGenerator_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID);
}
@Override
public void setPP_ComponentGenerator_Param_ID (final int PP_ComponentGenerator_Param_ID)
{
if (PP_ComponentGenerator_Param_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, PP_ComponentGenerator_Param_ID);
}
@Override
public int getPP_ComponentGenerator_Param_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_Param_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator_Param.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Father {
@Id
@GeneratedValue
private Long id;
private String name;
private String surname;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Father father = (Father) o;
return Objects.equals(id, father.id) &&
Objects.equals(name, father.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
|
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\entity\Father.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Authority implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(length = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
|
}
Authority authority = (Authority) o;
return !(name != null ? !name.equals(authority.name) : authority.name != null);
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public String toString() {
return "Authority{" +
"name='" + name + '\'' +
"}";
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\Authority.java
| 2
|
请完成以下Java代码
|
public PMMBalanceSegment build()
{
return new PMMBalanceSegment(this);
}
public Builder setC_BPartner_ID(final int C_BPartner_ID)
{
this.C_BPartner_ID = C_BPartner_ID;
return this;
}
public Builder setM_Product_ID(final int M_Product_ID)
{
this.M_Product_ID = M_Product_ID;
return this;
}
public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
|
this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID;
return this;
}
// public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID)
// {
// this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID;
// return this;
// }
public Builder setC_Flatrate_DataEntry_ID(final int C_Flatrate_DataEntry_ID)
{
this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceSegment.java
| 1
|
请完成以下Java代码
|
protected boolean afterDelete (boolean success)
{
if (success)
delete_Tree(MTree_Base.TREETYPE_Menu);
return success;
} // afterDelete
/**
* FR [ 1966326 ]
* get Menu ID
* @param String Menu Name
* @return int retValue
*/
public static int getMenu_ID(String menuName) {
int retValue = 0;
String SQL = "SELECT AD_Menu_ID FROM AD_Menu WHERE Name = ?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(SQL, null);
pstmt.setString(1, menuName);
rs = pstmt.executeQuery();
|
if (rs.next())
retValue = rs.getInt(1);
}
catch (SQLException e)
{
s_log.error(SQL, e);
retValue = -1;
}
finally
{
DB.close(rs, pstmt);
}
return retValue;
}
} // MMenu
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMenu.java
| 1
|
请完成以下Java代码
|
public class FlowableCmmnServices {
private CmmnEngine cmmnEngine;
public void setCmmnEngine(CmmnEngine cmmnEngine) {
this.cmmnEngine = cmmnEngine;
}
@Produces
@Named
@ApplicationScoped
public CmmnEngine cmmnEngine() {
return cmmnEngine;
}
@Produces
@Named
@ApplicationScoped
public CmmnRuntimeService cmmnRuntimeService() {
return cmmnEngine().getCmmnRuntimeService();
}
@Produces
@Named
@ApplicationScoped
public CmmnTaskService cmmnTaskService() {
return cmmnEngine().getCmmnTaskService();
}
@Produces
@Named
@ApplicationScoped
public CmmnRepositoryService cmmnRepositoryService() {
|
return cmmnEngine().getCmmnRepositoryService();
}
@Produces
@Named
@ApplicationScoped
public DynamicCmmnService dynamicCmmnService() {
return cmmnEngine().getDynamicCmmnService();
}
@Produces
@Named
@ApplicationScoped
public CmmnHistoryService cmmnHistoryService() {
return cmmnEngine().getCmmnHistoryService();
}
@Produces
@Named
@ApplicationScoped
public CmmnManagementService cmmnManagementService() {
return cmmnEngine().getCmmnManagementService();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-cdi\src\main\java\org\flowable\cdi\impl\util\FlowableCmmnServices.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/secured/socket").setViewName("socket");
registry.addViewController("/secured/success").setViewName("success");
registry.addViewController("/denied").setViewName("denied");
}
@Bean
public UrlBasedViewResolver viewResolver() {
final UrlBasedViewResolver bean = new UrlBasedViewResolver();
bean.setPrefix("/WEB-INF/jsp/");
bean.setSuffix(".jsp");
bean.setViewClass(JstlView.class);
return bean;
}
|
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
// View H2
@Bean(initMethod="start", destroyMethod="stop")
public Server h2Console () throws SQLException {
return Server.createWebServer("-web","-webAllowOthers","-webDaemon","-webPort", "8084");
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\config\AppConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MscExecutorService implements Service<MscExecutorService>, ExecutorService {
private static Logger log = Logger.getLogger(MscExecutorService.class.getName());
protected final Supplier<EnhancedQueueExecutor> managedQueueSupplier;
protected final Consumer<ExecutorService> provider;
private long lastWarningLogged = System.currentTimeMillis();
public MscExecutorService(Supplier<EnhancedQueueExecutor> managedQueueSupplier, Consumer<ExecutorService> provider) {
this.managedQueueSupplier = managedQueueSupplier;
this.provider = provider;
}
@Override
public MscExecutorService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
@Override
public void start(StartContext context) throws StartException {
provider.accept(this);
}
@Override
public void stop(StopContext context) {
provider.accept(null);
}
@Override
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new ExecuteJobsRunnable(jobIds, processEngine);
}
@Override
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunningWork(runnable);
} else {
return scheduleShortRunningWork(runnable);
}
}
protected boolean scheduleShortRunningWork(Runnable runnable) {
|
EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
try {
EnhancedQueueExecutor.execute(runnable);
return true;
} catch (Exception e) {
// we must be able to schedule this
log.log(Level.WARNING, "Cannot schedule long running work.", e);
}
return false;
}
protected boolean scheduleLongRunningWork(Runnable runnable) {
final EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
boolean rejected = false;
try {
EnhancedQueueExecutor.execute(runnable);
} catch (RejectedExecutionException e) {
rejected = true;
} catch (Exception e) {
// if it fails for some other reason, log a warning message
long now = System.currentTimeMillis();
// only log every 60 seconds to prevent log flooding
if((now-lastWarningLogged) >= (60*1000)) {
log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e);
} else {
log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e);
}
}
return !rejected;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getPlanItemDefinitionId() {
return planItemDefinitionId;
}
public void setPlanItemDefinitionId(String planItemDefinitionId) {
this.planItemDefinitionId = planItemDefinitionId;
}
public String getPlanItemDefinitionType() {
return planItemDefinitionType;
}
public void setPlanItemDefinitionType(String planItemDefinitionType) {
this.planItemDefinitionType = planItemDefinitionType;
}
public List<String> getPlanItemDefinitionTypes() {
return planItemDefinitionTypes;
}
public void setPlanItemDefinitionTypes(List<String> planItemDefinitionTypes) {
this.planItemDefinitionTypes = planItemDefinitionTypes;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedBefore() {
return createdBefore;
}
public void setCreatedBefore(Date createdBefore) {
this.createdBefore = createdBefore;
}
public Date getCreatedAfter() {
return createdAfter;
}
public void setCreatedAfter(Date createdAfter) {
this.createdAfter = createdAfter;
}
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public Boolean getIncludeEnded() {
return includeEnded;
}
public void setIncludeEnded(Boolean includeEnded) {
this.includeEnded = includeEnded;
|
}
public Boolean getIncludeLocalVariables() {
return includeLocalVariables;
}
public void setIncludeLocalVariables(boolean includeLocalVariables) {
this.includeLocalVariables = includeLocalVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public void setCaseInstanceIds(Set<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceQueryRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Category() {
}
public Category(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
|
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\cloneentity\Category.java
| 2
|
请完成以下Java代码
|
public class MultipleResourcesProjectContributor implements ProjectContributor {
private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private final String rootResource;
private final Predicate<String> executable;
/**
* Create a new instance with the {@code rootResource} to use to locate resources to
* copy to the project structure.
* @param rootResource the root resource path
* @see PathMatchingResourcePatternResolver#getResources(String)
*/
public MultipleResourcesProjectContributor(String rootResource) {
this(rootResource, (filename) -> false);
}
public MultipleResourcesProjectContributor(String rootResource, Predicate<String> executable) {
this.rootResource = StringUtils.trimTrailingCharacter(rootResource, '/');
this.executable = executable;
}
@Override
public void contribute(Path projectRoot) throws IOException {
Resource root = this.resolver.getResource(this.rootResource);
Resource[] resources = this.resolver.getResources(this.rootResource + "/**");
for (Resource resource : resources) {
if (resource.isReadable()) {
String filename = extractFileName(root.getURI(), resource.getURI());
Path output = projectRoot.resolve(filename);
if (!Files.exists(output)) {
Files.createDirectories(output.getParent());
|
Files.createFile(output);
}
FileCopyUtils.copy(resource.getInputStream(), Files.newOutputStream(output));
// TODO Set executable using NIO
output.toFile().setExecutable(this.executable.test(filename));
}
}
}
private String extractFileName(URI root, URI resource) {
String candidate = resource.toString().substring(root.toString().length());
return StringUtils.trimLeadingCharacter(candidate, '/');
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\contributor\MultipleResourcesProjectContributor.java
| 1
|
请完成以下Java代码
|
public UpdateExternalTaskRetriesBuilder externalTaskQuery(ExternalTaskQuery externalTaskQuery) {
this.externalTaskQuery = externalTaskQuery;
return this;
}
public UpdateExternalTaskRetriesBuilder processInstanceQuery(ProcessInstanceQuery processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
return this;
}
public UpdateExternalTaskRetriesBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
return this;
}
public void set(int retries) {
this.retries = retries;
commandExecutor.execute(new SetExternalTasksRetriesCmd(this));
}
@Override
public Batch setAsync(int retries) {
this.retries = retries;
return commandExecutor.execute(new SetExternalTasksRetriesBatchCmd(this));
}
public int getRetries() {
return retries;
}
public List<String> getExternalTaskIds() {
|
return externalTaskIds;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public ExternalTaskQuery getExternalTaskQuery() {
return externalTaskQuery;
}
public ProcessInstanceQuery getProcessInstanceQuery() {
return processInstanceQuery;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateExternalTaskRetriesBuilderImpl.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.M
|
ySQL8Dialect
spring.datasource.initialization-mode=always
spring.datasource.platform=mysql
spring.jpa.open-in-view=false
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootAssignSequentialNumber\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient newClient = client.getHttpClient()
.newBuilder()
.addInterceptor(interceptor)
.readTimeout(0, TimeUnit.SECONDS)
.build();
client.setHttpClient(newClient);
CoreV1Api api = new CoreV1Api(client);
String fs = createSelector(args);
V1PodList items = api.listPodForAllNamespaces(null, null, fs, null, null, null, null, null, 10, false);
items.getItems()
.stream()
.map((pod) -> pod.getMetadata().getName() )
.forEach((name) -> System.out.println("name=" + name));
|
}
private static String createSelector(String[] args) {
StringBuilder b = new StringBuilder();
for( int i = 0 ; i < args.length; i++ ) {
if( b.length() > 0 ) {
b.append(',');
}
b.append(args[i]);
}
return b.toString();
}
}
|
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\ListPodsWithFieldSelectors.java
| 1
|
请完成以下Java代码
|
public Criteria andRecentOrderTimeNotIn(List<Date> values) {
addCriterion("recent_order_time not in", values, "recentOrderTime");
return (Criteria) this;
}
public Criteria andRecentOrderTimeBetween(Date value1, Date value2) {
addCriterion("recent_order_time between", value1, value2, "recentOrderTime");
return (Criteria) this;
}
public Criteria andRecentOrderTimeNotBetween(Date value1, Date value2) {
addCriterion("recent_order_time not between", value1, value2, "recentOrderTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
|
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberStatisticsInfoExample.java
| 1
|
请完成以下Java代码
|
public void println(long l) throws IOException {
trackContentLength(l);
trackContentLengthLn();
this.delegate.println(l);
}
@Override
public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
|
this.delegate.setWriteListener(writeListener);
}
@Override
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\OnCommittedResponseWrapper.java
| 1
|
请完成以下Java代码
|
public void printMessage() {
System.out.println("invoked by this");
}
public void printInstance(Keyword thisKeyword) {
System.out.println(thisKeyword);
}
public Keyword getCurrentInstance() {
return this;
}
class ThisInnerClass {
boolean isInnerClass = true;
|
public ThisInnerClass() {
Keyword thisKeyword = Keyword.this;
String outerString = Keyword.this.name;
System.out.println(this.isInnerClass);
}
}
@Override
public String toString() {
return "KeywordTest{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-types-3\src\main\java\com\baeldung\thiskeyword\Keyword.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
datasource:
url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
username: root
password: root
druid:
initial-size: 5 #连接池初始化大小
min-idle: 10 #最小空闲连接数
max-active: 20 #最大连接数
web-stat-filter:
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #不统计这些请求数据
stat-view-servlet: #访问监控网页的登录用户名和密码
login-username: druid
login-password: druid
redis:
host: localhost # Redis服务器地址
database: 0 # Redis数据库索引(默认为0)
port: 6379 # Redis服务器连接端口
password: # Redis服务器连接密码(默认为空)
timeout:
|
300ms # 连接超时时间(毫秒)
minio:
endpoint: http://localhost:9000 #MinIO服务所在地址
bucketName: mall #存储桶名称
accessKey: minioadmin #访问的key
secretKey: minioadmin #访问的秘钥
logging:
level:
root: info
com.macro.mall: debug
logstash:
host: localhost
enableInnerLog: false
|
repos\mall-master\mall-admin\src\main\resources\application-dev.yml
| 2
|
请完成以下Java代码
|
public class FlowableIdmEventBuilder {
/**
* @param type
* type of event
* @return an {@link FlowableEvent} that doesn't have it's execution context-fields filled, as the event is a global event, independent of any running execution.
*/
public static FlowableEvent createGlobalEvent(FlowableIdmEventType type) {
FlowableIdmEventImpl newEvent = new FlowableIdmEventImpl(type);
return newEvent;
}
/**
* @param type
* type of event
* @param entity
* the entity this event targets
|
* @return an {@link FlowableEntityEvent}. In case an execution context is active, the execution related event fields will be populated. If not, execution details will be retrieved from the
* {@link Object} if possible.
*/
public static FlowableEntityEvent createEntityEvent(FlowableIdmEventType type, Object entity) {
FlowableIdmEntityEventImpl newEvent = new FlowableIdmEntityEventImpl(entity, type);
return newEvent;
}
public static FlowableIdmMembershipEvent createMembershipEvent(FlowableIdmEventType type, String groupId, String userId) {
FlowableIdmMembershipEventImpl newEvent = new FlowableIdmMembershipEventImpl(type);
newEvent.setUserId(userId);
newEvent.setGroupId(groupId);
return newEvent;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\delegate\event\impl\FlowableIdmEventBuilder.java
| 1
|
请完成以下Java代码
|
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.GRSSignum;
}
@Override
protected String getExternalCommand()
{
return EXTERNAL_SYSTEM_COMMAND_EXPORT_BPARTNER;
}
@Override
@NonNull
protected Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final BPartnerId bPartnerId)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId);
final boolean isVendor = bPartner.isVendor();
final boolean isCustomer = bPartner.isCustomer();
if (!isCustomer && !isVendor)
{
return Optional.empty();
}
final ImmutableList<ExternalSystemParentConfig> grsParentConfigs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum);
return Optional.of(grsParentConfigs.stream()
.filter(ExternalSystemParentConfig::isActive)
.map(ExternalSystemParentConfig::getChildConfig)
.map(ExternalSystemGRSSignumConfig::cast)
.filter(grsConfig -> (grsConfig.isAutoSendVendors() && isVendor) || (grsConfig.isAutoSendCustomers() && isCustomer))
.map(IExternalSystemChildConfig::getId)
.collect(ImmutableSet.toImmutableSet()));
}
@NonNull
private static Optional<String> getJsonExportDirectorySettings(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig)
{
if (!grsSignumConfig.isCreateBPartnerFolders())
{
return Optional.empty();
}
|
if (Check.isBlank(grsSignumConfig.getBPartnerExportDirectories()) || Check.isBlank(grsSignumConfig.getBasePathForExportDirectories()))
{
throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!")
.appendParametersToMessage()
.setParameter("ExternalSystem_Config_GRSSignum_ID", grsSignumConfig.getId());
}
final List<String> directories = Arrays
.stream(grsSignumConfig.getBPartnerExportDirectories().split(","))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList());
final JsonExportDirectorySettings exportDirectorySettings = JsonExportDirectorySettings.builder()
.basePath(grsSignumConfig.getBasePathForExportDirectories())
.directories(directories)
.build();
try
{
final String serializedExportDirectorySettings = JsonObjectMapperHolder.sharedJsonObjectMapper()
.writeValueAsString(exportDirectorySettings);
return Optional.of(serializedExportDirectorySettings);
}
catch (final JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportBPartnerToGRSService.java
| 1
|
请完成以下Java代码
|
public String getProcessInstanceId() {
return ScopeTypes.BPMN.equals(scopeType) ? scopeId : null;
}
public void setProcessInstanceId(String processInstanceId) {
setScopeType(ScopeTypes.BPMN);
setScopeId(processInstanceId);
}
@Override
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
|
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\event\FlowableEngineEventImpl.java
| 1
|
请完成以下Java代码
|
public static InstanceExchangeFilterFunction logfileAcceptWorkaround() {
return (instance, request, next) -> {
if (request.attribute(ATTRIBUTE_ENDPOINT).map(Endpoint.LOGFILE::equals).orElse(false)) {
List<MediaType> newAcceptHeaders = Stream
.concat(request.headers().getAccept().stream(), Stream.of(MediaType.ALL))
.toList();
request = ClientRequest.from(request).headers((h) -> h.setAccept(newAcceptHeaders)).build();
}
return next.exchange(request);
};
}
/**
* Creates the {@link InstanceExchangeFilterFunction} that could handle cookies during
* requests and responses to/from applications.
* @param store the cookie store to use
* @return the new filter function
*/
public static InstanceExchangeFilterFunction handleCookies(final PerInstanceCookieStore store) {
return (instance, request, next) -> {
// we need an absolute URL to be able to deal with cookies
if (request.url().isAbsolute()) {
return next.exchange(enrichRequestWithStoredCookies(instance.getId(), request, store))
.map((response) -> storeCookiesFromResponse(instance.getId(), request, response, store));
}
return next.exchange(request);
|
};
}
private static ClientRequest enrichRequestWithStoredCookies(final InstanceId instId, final ClientRequest request,
final PerInstanceCookieStore store) {
final MultiValueMap<String, String> storedCookies = store.get(instId, request.url(), request.headers());
if (CollectionUtils.isEmpty(storedCookies)) {
log.trace("No cookies found for request [url={}]", request.url());
return request;
}
log.trace("Cookies found for request [url={}]", request.url());
return ClientRequest.from(request).cookies((cm) -> cm.addAll(storedCookies)).build();
}
private static ClientResponse storeCookiesFromResponse(final InstanceId instId, final ClientRequest request,
final ClientResponse response, final PerInstanceCookieStore store) {
final HttpHeaders headers = response.headers().asHttpHeaders();
log.trace("Searching for cookies in header values of response [url={},headerValues={}]", request.url(),
headers);
store.put(instId, request.url(), headers);
return response;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\InstanceExchangeFilterFunctions.java
| 1
|
请完成以下Java代码
|
public class Producer implements Runnable {
private static final Logger log = Logger.getLogger(Producer.class.getCanonicalName());
private static final AtomicInteger idSequence = new AtomicInteger(0);
private boolean running = false;
private final DataQueue dataQueue;
public Producer(DataQueue dataQueue) {
this.dataQueue = dataQueue;
}
@Override
public void run() {
running = true;
produce();
}
public void stop() {
running = false;
}
public void produce() {
while (running) {
if (dataQueue.isFull()) {
try {
dataQueue.waitIsNotFull();
} catch (InterruptedException e) {
log.severe("Error while waiting to Produce messages.");
|
break;
}
}
// avoid spurious wake-up
if (!running) {
break;
}
dataQueue.add(generateMessage());
log.info("Size of the queue is: " + dataQueue.getSize());
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (Math.random() * 100));
}
log.info("Producer Stopped");
}
private Message generateMessage() {
Message message = new Message(idSequence.incrementAndGet(), Math.random());
log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n",
Thread.currentThread().getName(), message.getId(), message.getData()));
return message;
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\Producer.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.